(apropos): Restore autoload cookie. Fix error
[emacs.git] / lispintro / emacs-lisp-intro.texi
blobbc1602179a64a3cdc4bee76cee40365d836c5d61
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 @c Printed copies are available for $30 each.@*
241 ISBN 1-882114-43-4
243 Permission is granted to copy, distribute and/or modify this document
244 under the terms of the GNU Free Documentation License, Version 1.1 or
245 any later version published by the Free Software Foundation; there
246 being no Invariant Section, with the Front-Cover Texts being ``A GNU
247 Manual'', and with the Back-Cover Texts as in (a) below.  A copy of
248 the license is included in the section entitled ``GNU Free
249 Documentation License''.
251 (a) The FSF's Back-Cover Text is: ``You have freedom to copy and
252 modify this GNU Manual, like GNU software.  Copies published by the
253 Free Software Foundation raise funds for GNU development.''
254 @end copying
256 @c half title; two lines here, so do not use `shorttitlepage'
257 @tex
258 {\begingroup%
259     \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
260         \endgroup}%
261 {\begingroup\hbox{}\vskip 0.25in \chaprm%
262         \centerline{Programming in Emacs Lisp}%
263         \endgroup\page\hbox{}\page}
264 @end tex
266 @titlepage
267 @sp 6
268 @center @titlefont{An Introduction to}
269 @sp 2
270 @center @titlefont{Programming in Emacs Lisp}
271 @sp 2
272 @center Second Edition
273 @sp 4
274 @center by Robert J. Chassell
276 @page
277 @vskip 0pt plus 1filll
278 @insertcopying
279 @end titlepage
281 @iftex
282 @headings off
283 @evenheading @thispage @| @| @thischapter
284 @oddheading @thissection @| @| @thispage
285 @end iftex
287 @ifnothtml
289 @c Keep T.O.C. short by tightening up.
290 @ifset largebook
291 @tex
292 \global\parskip 2pt plus 1pt
293 \global\advance\baselineskip by -1pt
294 @end tex
295 @end ifset
297 @shortcontents
298 @contents
300 @ifset largebook
301 @tex
302 \global\parskip 6pt plus 1pt
303 \global\advance\baselineskip by 1pt
304 @end tex
305 @end ifset
307 @end ifnothtml
309 @c >>>> Set pageno appropriately <<<<
311 @c The first page of the Preface is a roman numeral; it is the first
312 @c right handed page after the Table of Contents; hence the following
313 @c setting must be for an odd negative number.
315 @c if largebook, there are 8 pages in Table of Contents
316 @ifset largebook
317 @iftex
318 @pageno = -9
319 @end iftex
320 @end ifset
322 @c if smallbook, there are 10 pages in Table of Contents
323 @ifclear largebook
324 @iftex
325 @pageno = -11
326 @end iftex
327 @end ifclear
329 @ifnottex
330 @node Top, Preface, (dir), (dir)
331 @top An Introduction to Programming in Emacs Lisp
333 @insertcopying
335 This master menu first lists each chapter and index; then it lists
336 every node in every chapter.
337 @end ifnottex
339 @menu
340 * Preface::                     What to look for.
341 * List Processing::             What is Lisp?
342 * Practicing Evaluation::       Running several programs.
343 * Writing Defuns::              How to write function definitions.
344 * Buffer Walk Through::         Exploring a few buffer-related functions.
345 * More Complex::                A few, even more complex functions.
346 * Narrowing & Widening::        Restricting your and Emacs attention to
347                                     a region.
348 * car cdr & cons::              Fundamental functions in Lisp.
349 * Cutting & Storing Text::      Removing text and saving it.
350 * List Implementation::         How lists are implemented in the computer.
351 * Yanking::                     Pasting stored text.
352 * Loops & Recursion::           How to repeat a process.
353 * Regexp Search::               Regular expression searches.
354 * Counting Words::              A review of repetition and regexps.
355 * Words in a defun::            Counting words in a @code{defun}.
356 * Readying a Graph::            A prototype graph printing function.
357 * Emacs Initialization::        How to write a @file{.emacs} file.
358 * Debugging::                   How to run the Emacs Lisp debuggers.
359 * Conclusion::                  Now you have the basics.
360 * the-the::                     An appendix: how to find reduplicated words.
361 * Kill Ring::                   An appendix: how the kill ring works.
362 * Full Graph::                  How to create a graph with labelled axes.
363 * GNU Free Documentation License::
364 * Index::
365 * About the Author::
367 @detailmenu
368  --- The Detailed Node Listing ---
370 Preface
372 * Why::                         Why learn Emacs Lisp?
373 * On Reading this Text::        Read, gain familiarity, pick up habits....
374 * Who You Are::                 For whom this is written.
375 * Lisp History::
376 * Note for Novices::            You can read this as a novice.
377 * Thank You::
379 List Processing
381 * Lisp Lists::                  What are lists?
382 * Run a Program::               Any list in Lisp is a program ready to run.
383 * Making Errors::               Generating an error message.
384 * Names & Definitions::         Names of symbols and function definitions.
385 * Lisp Interpreter::            What the Lisp interpreter does.
386 * Evaluation::                  Running a program.
387 * Variables::                   Returning a value from a variable.
388 * Arguments::                   Passing information to a function.
389 * set & setq::                  Setting the value of a variable.
390 * Summary::                     The major points.
391 * Error Message Exercises::
393 Lisp Lists
395 * Numbers Lists::               List have numbers, other lists, in them.
396 * Lisp Atoms::                  Elemental entities.
397 * Whitespace in Lists::         Formating lists to be readable.
398 * Typing Lists::                How GNU Emacs helps you type lists.
400 The Lisp Interpreter
402 * Complications::               Variables, Special forms, Lists within.
403 * Byte Compiling::              Specially processing code for speed.
405 Evaluation
407 * Evaluating Inner Lists::      Lists within lists...
409 Variables
411 * fill-column Example::
412 * Void Function::               The error message for a symbol
413                                   without a function.
414 * Void Variable::               The error message for a symbol without a value.
416 Arguments
418 * Data types::                  Types of data passed to a function.
419 * Args as Variable or List::    An argument can be the value
420                                   of a variable or list.
421 * Variable Number of Arguments::  Some functions may take a
422                                   variable number of arguments.
423 * Wrong Type of Argument::      Passing an argument of the wrong type
424                                   to a function.
425 * message::                     A useful function for sending messages.
427 Setting the Value of a Variable
429 * Using set::                   Setting values.
430 * Using setq::                  Setting a quoted value.
431 * Counting::                    Using @code{setq} to count.
433 Practicing Evaluation
435 * How to Evaluate::             Typing editing commands or @kbd{C-x C-e}
436                                   causes evaluation.
437 * Buffer Names::                Buffers and files are different.
438 * Getting Buffers::             Getting a buffer itself, not merely its name.
439 * Switching Buffers::           How to change to another buffer.
440 * Buffer Size & Locations::     Where point is located and the size of
441                                 the buffer.
442 * Evaluation Exercise::
444 How To Write Function Definitions
446 * Primitive Functions::
447 * defun::                       The @code{defun} special form.
448 * Install::                     Install a function definition.
449 * Interactive::                 Making a function interactive.
450 * Interactive Options::         Different options for @code{interactive}.
451 * Permanent Installation::      Installing code permanently.
452 * let::                         Creating and initializing local variables.
453 * if::                          What if?
454 * else::                        If--then--else expressions.
455 * Truth & Falsehood::           What Lisp considers false and true.
456 * save-excursion::              Keeping track of point, mark, and buffer.
457 * Review::
458 * defun Exercises::
460 Install a Function Definition
462 * Effect of installation::
463 * Change a defun::              How to change a function definition.
465 Make a Function Interactive
467 * Interactive multiply-by-seven::  An overview.
468 * multiply-by-seven in detail::  The interactive version.
470 @code{let}
472 * Prevent confusion::
473 * Parts of let Expression::
474 * Sample let Expression::
475 * Uninitialized let Variables::
477 The @code{if} Special Form
479 * if in more detail::
480 * type-of-animal in detail::    An example of an @code{if} expression.
482 Truth and Falsehood in Emacs Lisp
484 * nil explained::               @code{nil} has two meanings.
486 @code{save-excursion}
488 * Point and mark::              A review of various locations.
489 * Template for save-excursion::
491 A Few Buffer--Related Functions
493 * Finding More::                How to find more information.
494 * simplified-beginning-of-buffer::  Shows @code{goto-char},
495                                 @code{point-min}, and @code{push-mark}.
496 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
497 * append-to-buffer::            Uses @code{save-excursion} and
498                                 @code{insert-buffer-substring}.
499 * Buffer Related Review::       Review.
500 * Buffer Exercises::
502 The Definition of @code{mark-whole-buffer}
504 * mark-whole-buffer overview::
505 * Body of mark-whole-buffer::   Only three lines of code.
507 The Definition of @code{append-to-buffer}
509 * append-to-buffer overview::
510 * append interactive::          A two part interactive expression.
511 * append-to-buffer body::       Incorporates a @code{let} expression.
512 * append save-excursion::       How the @code{save-excursion} works.
514 A Few More Complex Functions
516 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
517 * insert-buffer::               Read-only, and with @code{or}.
518 * beginning-of-buffer::         Shows @code{goto-char},
519                                 @code{point-min}, and @code{push-mark}.
520 * Second Buffer Related Review::
521 * optional Exercise::
523 The Definition of @code{insert-buffer}
525 * insert-buffer code::
526 * insert-buffer interactive::   When you can read, but not write.
527 * insert-buffer body::          The body has an @code{or} and a @code{let}.
528 * if & or::                     Using an @code{if} instead of an @code{or}.
529 * Insert or::                   How the @code{or} expression works.
530 * Insert let::                  Two @code{save-excursion} expressions.
532 The Interactive Expression in @code{insert-buffer}
534 * Read-only buffer::            When a buffer cannot be modified.
535 * b for interactive::           An existing buffer or else its name.
537 Complete Definition of @code{beginning-of-buffer}
539 * Optional Arguments::
540 * beginning-of-buffer opt arg::  Example with optional argument.
541 * beginning-of-buffer complete::
543 @code{beginning-of-buffer} with an Argument
545 * Disentangle beginning-of-buffer::
546 * Large buffer case::
547 * Small buffer case::
549 Narrowing and Widening
551 * Narrowing advantages::        The advantages of narrowing
552 * save-restriction::            The @code{save-restriction} special form.
553 * what-line::                   The number of the line that point is on.
554 * narrow Exercise::
556 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
558 * Strange Names::               An historical aside: why the strange names?
559 * car & cdr::                   Functions for extracting part of a list.
560 * cons::                        Constructing a list.
561 * nthcdr::                      Calling @code{cdr} repeatedly.
562 * nth::
563 * setcar::                      Changing the first element of a list.
564 * setcdr::                      Changing the rest of a list.
565 * cons Exercise::
567 @code{cons}
569 * Build a list::
570 * length::                      How to find the length of a list.
572 Cutting and Storing Text
574 * Storing Text::                Text is stored in a list.
575 * zap-to-char::                 Cutting out text up to a character.
576 * kill-region::                 Cutting text out of a region.
577 * Digression into C::           Minor note on C programming language macros.
578 * defvar::                      How to give a variable an initial value.
579 * copy-region-as-kill::         A definition for copying text.
580 * cons & search-fwd Review::
581 * search Exercises::
583 @code{zap-to-char}
585 * Complete zap-to-char::        The complete implementation.
586 * zap-to-char interactive::     A three part interactive expression.
587 * zap-to-char body::            A short overview.
588 * search-forward::              How to search for a string.
589 * progn::                       The @code{progn} special form.
590 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
592 @code{kill-region}
594 * Complete kill-region::        The function definition.
595 * condition-case::              Dealing with a problem.
596 * delete-and-extract-region::   Doing the work.
598 Initializing a Variable with @code{defvar}
600 * See variable current value::
601 * defvar and asterisk::         An old-time convention.
603 @code{copy-region-as-kill}
605 * Complete copy-region-as-kill::  The complete function definition.
606 * copy-region-as-kill body::    The body of @code{copy-region-as-kill}.
608 The Body of @code{copy-region-as-kill}
610 * last-command & this-command::
611 * kill-append function::
612 * kill-new function::
614 How Lists are Implemented
616 * Lists diagrammed::
617 * Symbols as Chest::            Exploring a powerful metaphor.
618 * List Exercise::
620 Yanking Text Back
622 * Kill Ring Overview::          The kill ring is a list.
623 * kill-ring-yank-pointer::      The @code{kill-ring-yank-pointer} variable.
624 * yank nthcdr Exercises::
626 Loops and Recursion
628 * while::                       Causing a stretch of code to repeat.
629 * dolist dotimes::
630 * Recursion::                   Causing a function to call itself.
631 * Looping exercise::
633 @code{while}
635 * Looping with while::          Repeat so long as test returns true.
636 * Loop Example::                A @code{while} loop that uses a list.
637 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
638 * Incrementing Loop::           A loop with an incrementing counter.
639 * Decrementing Loop::           A loop with a decrementing counter.
641 A Loop with an Incrementing Counter
643 * Incrementing Example::        Counting pebbles in a triangle.
644 * Inc Example parts::           The parts of the function definition.
645 * Inc Example altogether::      Putting the function definition together.
647 Loop with a Decrementing Counter
649 * Decrementing Example::        More pebbles on the beach.
650 * Dec Example parts::           The parts of the function definition.
651 * Dec Example altogether::      Putting the function definition together.
653 Save your time: @code{dolist} and @code{dotimes}
655 * dolist::
656 * dotimes::
658 Recursion
660 * Building Robots::             Same model, different serial number ...
661 * Recursive Definition Parts::  Walk until you stop ...
662 * Recursion with list::         Using a list as the test whether to recurse.
663 * Recursive triangle function::
664 * Recursion with cond::
665 * Recursive Patterns::          Often used templates.
666 * No Deferment::                Don't store up work ...
667 * No deferment solution::
669 Recursion in Place of a Counter
671 * Recursive Example arg of 1 or 2::
672 * Recursive Example arg of 3 or 4::
674 Recursive Patterns
676 * Every::
677 * Accumulate::
678 * Keep::
680 Regular Expression Searches
682 * sentence-end::                The regular expression for @code{sentence-end}.
683 * re-search-forward::           Very similar to @code{search-forward}.
684 * forward-sentence::            A straightforward example of regexp search.
685 * forward-paragraph::           A somewhat complex example.
686 * etags::                       How to create your own @file{TAGS} table.
687 * Regexp Review::
688 * re-search Exercises::
690 @code{forward-sentence}
692 * Complete forward-sentence::
693 * fwd-sentence while loops::    Two @code{while} loops.
694 * fwd-sentence re-search::      A regular expression search.
696 @code{forward-paragraph}: a Goldmine of Functions
698 * forward-paragraph in brief::  Key parts of the function definition.
699 * fwd-para let::                The @code{let*} expression.
700 * fwd-para while::              The forward motion @code{while} loop.
701 * fwd-para between paragraphs::  Movement between paragraphs.
702 * fwd-para within paragraph::   Movement within paragraphs.
703 * fwd-para no fill prefix::     When there is no fill prefix.
704 * fwd-para with fill prefix::   When there is a fill prefix.
705 * fwd-para summary::            Summary of @code{forward-paragraph} code.
707 Counting: Repetition and Regexps
709 * Why Count Words::
710 * count-words-region::          Use a regexp, but find a problem.
711 * recursive-count-words::       Start with case of no words in region.
712 * Counting Exercise::
714 The @code{count-words-region} Function
716 * Design count-words-region::   The definition using a @code{while} loop.
717 * Whitespace Bug::              The Whitespace Bug in @code{count-words-region}.
719 Counting Words in a @code{defun}
721 * Divide and Conquer::
722 * Words and Symbols::           What to count?
723 * Syntax::                      What constitutes a word or symbol?
724 * count-words-in-defun::        Very like @code{count-words}.
725 * Several defuns::              Counting several defuns in a file.
726 * Find a File::                 Do you want to look at a file?
727 * lengths-list-file::           A list of the lengths of many definitions.
728 * Several files::               Counting in definitions in different files.
729 * Several files recursively::   Recursively counting in different files.
730 * Prepare the data::            Prepare the data for display in a graph.
732 Count Words in @code{defuns} in Different Files
734 * lengths-list-many-files::     Return a list of the lengths of defuns.
735 * append::                      Attach one list to another.
737 Prepare the Data for Display in a Graph
739 * Sorting::                     Sorting lists.
740 * Files List::                  Making a list of files.
741 * Counting function definitions::
743 Readying a Graph
745 * Columns of a graph::
746 * graph-body-print::            How to print the body of a graph.
747 * recursive-graph-body-print::
748 * Printed Axes::
749 * Line Graph Exercise::
751 Your @file{.emacs} File
753 * Default Configuration::
754 * Site-wide Init::              You can write site-wide init files.
755 * defcustom::                   Emacs will write code for you.
756 * Beginning a .emacs File::     How to write a @code{.emacs file}.
757 * Text and Auto-fill::          Automatically wrap lines.
758 * Mail Aliases::                Use abbreviations for email addresses.
759 * Indent Tabs Mode::            Don't use tabs with @TeX{}
760 * Keybindings::                 Create some personal keybindings.
761 * Keymaps::                     More about key binding.
762 * Loading Files::               Load (i.e., evaluate) files automatically.
763 * Autoload::                    Make functions available.
764 * Simple Extension::            Define a function; bind it to a key.
765 * X11 Colors::                  Colors in version 19 in X.
766 * Miscellaneous::
767 * Mode Line::                   How to customize your mode line.
769 Debugging
771 * debug::                       How to use the built-in debugger.
772 * debug-on-entry::              Start debugging when you call a function.
773 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
774 * edebug::                      How to use Edebug, a source level debugger.
775 * Debugging Exercises::
777 Handling the Kill Ring
779 * rotate-yank-pointer::         Move a pointer along a list and around.
780 * yank::                        Paste a copy of a clipped element.
781 * yank-pop::                    Insert first element pointed to.
783 The @code{rotate-yank-pointer} Function
785 * Understanding rotate-yk-ptr::
786 * rotate-yk-ptr body::          The body of @code{rotate-yank-pointer}.
788 The Body of @code{rotate-yank-pointer}
790 * Digression concerning error::  How to mislead humans, but not computers.
791 * rotate-yk-ptr else-part::     The else-part of the @code{if} expression.
792 * Remainder Function::          The remainder, @code{%}, function.
793 * rotate-yk-ptr remainder::     Using @code{%} in @code{rotate-yank-pointer}.
794 * kill-rng-yk-ptr last elt::    Pointing to the last element.
796 @code{yank}
798 * rotate-yk-ptr arg::           Pass the argument to @code{rotate-yank-pointer}.
799 * rotate-yk-ptr negative arg::  Pass a negative argument.
801 A Graph with Labelled Axes
803 * Labelled Example::
804 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
805 * print-Y-axis::                Print a label for the vertical axis.
806 * print-X-axis::                Print a horizontal label.
807 * Print Whole Graph::           The function to print a complete graph.
809 The @code{print-Y-axis} Function
811 * Height of label::             What height for the Y axis?
812 * Compute a Remainder::         How to compute the remainder of a division.
813 * Y Axis Element::              Construct a line for the Y axis.
814 * Y-axis-column::               Generate a list of Y axis labels.
815 * print-Y-axis Penultimate::    A not quite final version.
817 The @code{print-X-axis} Function
819 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
820 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
822 Printing the Whole Graph
824 * The final version::           A few changes.
825 * Test print-graph::            Run a short test.
826 * Graphing words in defuns::    Executing the final code.
827 * lambda::                      How to write an anonymous function.
828 * mapcar::                      Apply a function to elements of a list.
829 * Another Bug::                 Yet another bug @dots{} most insidious.
830 * Final printed graph::         The graph itself!
832 @end detailmenu
833 @end menu
835 @node Preface, List Processing, Top, Top
836 @comment  node-name,  next,  previous,  up
837 @unnumbered Preface
839 Most of the GNU Emacs integrated environment is written in the programming
840 language called Emacs Lisp.  The code written in this programming
841 language is the software---the sets of instructions---that tell the
842 computer what to do when you give it commands.  Emacs is designed so
843 that you can write new code in Emacs Lisp and easily install it as an
844 extension to the editor.
846 (GNU Emacs is sometimes called an ``extensible editor'', but it does
847 much more than provide editing capabilities.  It is better to refer to
848 Emacs as an ``extensible computing environment''.  However, that
849 phrase is quite a mouthful.  It is easier to refer to Emacs simply as
850 an editor.  Moreover, everything you do in Emacs---find the Mayan date
851 and phases of the moon, simplify polynomials, debug code, manage
852 files, read letters, write books---all these activities are kinds of
853 editing in the most general sense of the word.)
855 @menu
856 * Why::                         Why learn Emacs Lisp?
857 * On Reading this Text::        Read, gain familiarity, pick up habits....
858 * Who You Are::                 For whom this is written.
859 * Lisp History::
860 * Note for Novices::            You can read this as a novice.
861 * Thank You::
862 @end menu
864 @node Why, On Reading this Text, Preface, Preface
865 @ifnottex
866 @unnumberedsec Why Study Emacs Lisp?
867 @end ifnottex
869 Although Emacs Lisp is usually thought of in association only with Emacs,
870 it is a full computer programming language.  You can use Emacs Lisp as
871 you would any other programming language.
873 Perhaps you want to understand programming; perhaps you want to extend
874 Emacs; or perhaps you want to become a programmer.  This introduction to
875 Emacs Lisp is designed to get you started: to guide you in learning the
876 fundamentals of programming, and more importantly, to show you how you
877 can teach yourself to go further.
879 @node On Reading this Text, Who You Are, Why, Preface
880 @comment  node-name,  next,  previous,  up
881 @unnumberedsec On Reading this Text
883 All through this document, you will see little sample programs you can
884 run inside of Emacs.  If you read this document in Info inside of GNU
885 Emacs, you can run the programs as they appear.  (This is easy to do and
886 is explained when the examples are presented.)  Alternatively, you can
887 read this introduction as a printed book while sitting beside a computer
888 running Emacs.  (This is what I like to do; I like printed books.)  If
889 you don't have a running Emacs beside you, you can still read this book,
890 but in this case, it is best to treat it as a novel or as a travel guide
891 to a country not yet visited: interesting, but not the same as being
892 there.
894 Much of this introduction is dedicated to walk-throughs or guided tours
895 of code used in GNU Emacs.  These tours are designed for two purposes:
896 first, to give you familiarity with real, working code (code you use
897 every day); and, second, to give you familiarity with the way Emacs
898 works.  It is interesting to see how a working environment is
899 implemented.
900 Also, I
901 hope that you will pick up the habit of browsing through source code.
902 You can learn from it and mine it for ideas.  Having GNU Emacs is like
903 having a dragon's cave of treasures.
905 In addition to learning about Emacs as an editor and Emacs Lisp as a
906 programming language, the examples and guided tours will give you an
907 opportunity to get acquainted with Emacs as a Lisp programming
908 environment.  GNU Emacs supports programming and provides tools that
909 you will want to become comfortable using, such as @kbd{M-.} (the key
910 which invokes the @code{find-tag} command).  You will also learn about
911 buffers and other objects that are part of the environment.
912 Learning about these features of Emacs is like learning new routes
913 around your home town.
915 @ignore
916 In addition, I have written several programs as extended examples.
917 Although these are examples, the programs are real.  I use them.
918 Other people use them.  You may use them.  Beyond the fragments of
919 programs used for illustrations, there is very little in here that is
920 `just for teaching purposes'; what you see is used.  This is a great
921 advantage of Emacs Lisp: it is easy to learn to use it for work.
922 @end ignore
924 Finally, I hope to convey some of the skills for using Emacs to
925 learn aspects of programming that you don't know.  You can often use
926 Emacs to help you understand what puzzles you or to find out how to do
927 something new.  This self-reliance is not only a pleasure, but an
928 advantage.
930 @node Who You Are, Lisp History, On Reading this Text, Preface
931 @comment  node-name,  next,  previous,  up
932 @unnumberedsec For Whom This is Written
934 This text is written as an elementary introduction for people who are
935 not programmers.  If you are a programmer, you may not be satisfied with
936 this primer.  The reason is that you may have become expert at reading
937 reference manuals and be put off by the way this text is organized.
939 An expert programmer who reviewed this text said to me:
941 @quotation
942 @i{I prefer to learn from reference manuals.  I ``dive into'' each
943 paragraph, and ``come up for air'' between paragraphs.}
945 @i{When I get to the end of a paragraph, I assume that that subject is
946 done, finished, that I know everything I need (with the
947 possible exception of the case when the next paragraph starts talking
948 about it in more detail).  I expect that a well written reference manual
949 will not have a lot of redundancy, and that it will have excellent
950 pointers to the (one) place where the information I want is.}
951 @end quotation
953 This introduction is not written for this person!
955 Firstly, I try to say everything at least three times: first, to
956 introduce it; second, to show it in context; and third, to show it in a
957 different context, or to review it.
959 Secondly, I hardly ever put all the information about a subject in one
960 place, much less in one paragraph.  To my way of thinking, that imposes
961 too heavy a burden on the reader.  Instead I try to explain only what
962 you need to know at the time.  (Sometimes I include a little extra
963 information so you won't be surprised later when the additional
964 information is formally introduced.)
966 When you read this text, you are not expected to learn everything the
967 first time.  Frequently, you need only make, as it were, a `nodding
968 acquaintance' with some of the items mentioned.  My hope is that I have
969 structured the text and given you enough hints that you will be alert to
970 what is important, and concentrate on it.
972 You will need to ``dive into'' some paragraphs; there is no other way
973 to read them.  But I have tried to keep down the number of such
974 paragraphs.  This book is intended as an approachable hill, rather than
975 as a daunting mountain.
977 This introduction to @cite{Programming in Emacs Lisp} has a companion
978 document,
979 @iftex
980 @cite{The GNU Emacs Lisp Reference Manual}.
981 @end iftex
982 @ifnottex
983 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
984 Emacs Lisp Reference Manual}.
985 @end ifnottex
986 The reference manual has more detail than this introduction.  In the
987 reference manual, all the information about one topic is concentrated
988 in one place.  You should turn to it if you are like the programmer
989 quoted above.  And, of course, after you have read this
990 @cite{Introduction}, you will find the @cite{Reference Manual} useful
991 when you are writing your own programs.
993 @node Lisp History, Note for Novices, Who You Are, Preface
994 @unnumberedsec Lisp History
995 @cindex Lisp history
997 Lisp was first developed in the late 1950s at the Massachusetts
998 Institute of Technology for research in artificial intelligence.  The
999 great power of the Lisp language makes it superior for other purposes as
1000 well, such as writing editor commands and integrated environments.
1002 @cindex Maclisp
1003 @cindex Common Lisp
1004 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1005 in the 1960s.  It is somewhat inspired by Common Lisp, which became a
1006 standard in the 1980s.  However, Emacs Lisp is much simpler than Common
1007 Lisp.  (The standard Emacs distribution contains an optional extensions
1008 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1010 @node Note for Novices, Thank You, Lisp History, Preface
1011 @comment  node-name,  next,  previous,  up
1012 @unnumberedsec A Note for Novices
1014 If you don't know GNU Emacs, you can still read this document
1015 profitably.  However, I recommend you learn Emacs, if only to learn to
1016 move around your computer screen.  You can teach yourself how to use
1017 Emacs with the on-line tutorial.  To use it, type @kbd{C-h t}.  (This
1018 means you press and release the @key{CTRL} key and the @kbd{h} at the
1019 same time, and then press and release @kbd{t}.)
1021 Also, I often refer to one of Emacs' standard commands by listing the
1022 keys which you press to invoke the command and then giving the name of
1023 the command in parentheses, like this: @kbd{M-C-\}
1024 (@code{indent-region}).  What this means is that the
1025 @code{indent-region} command is customarily invoked by typing
1026 @kbd{M-C-\}.  (You can, if you wish, change the keys that are typed to
1027 invoke the command; this is called @dfn{rebinding}.  @xref{Keymaps, ,
1028 Keymaps}.)  The abbreviation @kbd{M-C-\} means that you type your
1029 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1030 (On many modern keyboards the @key{META} key is labelled
1031 @key{ALT}.)
1032 Sometimes a combination like this is called a keychord, since it is
1033 similar to the way you play a chord on a piano.  If your keyboard does
1034 not have a @key{META} key, the @key{ESC} key prefix is used in place
1035 of it.  In this case, @kbd{M-C-\} means that you press and release your
1036 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1037 the same time.  But usually @kbd{M-C-\} means press the @key{CTRL} key
1038 along with the key that is labelled @key{ALT} and, at the same time,
1039 press the @key{\} key.
1041 In addition to typing a lone keychord, you can prefix what you type
1042 with @kbd{C-u}, which is called the `universal argument'.  The
1043 @kbd{C-u} keychord passes an argument to the subsequent command.
1044 Thus, to indent a region of plain text by 6 spaces, mark the region,
1045 and then type @w{@kbd{C-u 6 M-C-\}}.  (If you do not specify a number,
1046 Emacs either passes the number 4 to the command or otherwise runs the
1047 command differently than it would otherwise.)  @xref{Arguments, ,
1048 Numeric Arguments, emacs, The GNU Emacs Manual}.
1050 If you are reading this in Info using GNU Emacs, you can read through
1051 this whole document just by pressing the space bar, @key{SPC}.
1052 (To learn about Info, type @kbd{C-h i} and then select Info.)
1054 A note on terminology:  when I use the word Lisp alone, I often am
1055 referring to the various dialects of Lisp in general, but when I speak
1056 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1058 @node Thank You,  , Note for Novices, Preface
1059 @comment  node-name,  next,  previous,  up
1060 @unnumberedsec Thank You
1062 My thanks to all who helped me with this book.  My especial thanks to
1063 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1064 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1065 Stallman}, and @w{Melissa Weisshaus}.  My thanks also go to both
1066 @w{Philip Johnson} and @w{David Stampe} for their patient
1067 encouragement.  My mistakes are my own.
1069 @flushright
1070 Robert J. Chassell
1071 @end flushright
1073 @c ================ Beginning of main text ================
1075 @c Start main text on right-hand (verso) page
1077 @tex
1078 \par\vfill\supereject
1079 \headings off
1080 \ifodd\pageno
1081     \par\vfill\supereject
1082 \else
1083     \par\vfill\supereject
1084     \page\hbox{}\page
1085     \par\vfill\supereject
1087 @end tex
1089 @iftex
1090 @headings off
1091 @evenheading @thispage @| @| @thischapter
1092 @oddheading @thissection @| @| @thispage
1093 @pageno = 1
1094 @end iftex
1096 @node List Processing, Practicing Evaluation, Preface, Top
1097 @comment  node-name,  next,  previous,  up
1098 @chapter List Processing
1100 To the untutored eye, Lisp is a strange programming language.  In Lisp
1101 code there are parentheses everywhere.  Some people even claim that the
1102 name stands for `Lots of Isolated Silly Parentheses'.  But the claim is
1103 unwarranted.  Lisp stands for LISt Processing, and the programming
1104 language handles @emph{lists} (and lists of lists) by putting them
1105 between parentheses.  The parentheses mark the boundaries of the list.
1106 Sometimes a list is preceded by a single apostrophe or quotation mark,
1107 @samp{'}.  Lists are the basis of Lisp.
1109 @menu
1110 * Lisp Lists::                  What are lists?
1111 * Run a Program::               Any list in Lisp is a program ready to run.
1112 * Making Errors::               Generating an error message.
1113 * Names & Definitions::         Names of symbols and function definitions.
1114 * Lisp Interpreter::            What the Lisp interpreter does.
1115 * Evaluation::                  Running a program.
1116 * Variables::                   Returning a value from a variable.
1117 * Arguments::                   Passing information to a function.
1118 * set & setq::                  Setting the value of a variable.
1119 * Summary::                     The major points.
1120 * Error Message Exercises::
1121 @end menu
1123 @node Lisp Lists, Run a Program, List Processing, List Processing
1124 @comment  node-name,  next,  previous,  up
1125 @section Lisp Lists
1126 @cindex Lisp Lists
1128 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1129 This list is preceded by a single apostrophe.  It could just as well be
1130 written as follows, which looks more like the kind of list you are likely
1131 to be familiar with:
1133 @smallexample
1134 @group
1135 '(rose
1136   violet
1137   daisy
1138   buttercup)
1139 @end group
1140 @end smallexample
1142 @noindent
1143 The elements of this list are the names of the four different flowers,
1144 separated from each other by whitespace and surrounded by parentheses,
1145 like flowers in a field with a stone wall around them.
1146 @cindex Flowers in a field
1148 @menu
1149 * Numbers Lists::               List have numbers, other lists, in them.
1150 * Lisp Atoms::                  Elemental entities.
1151 * Whitespace in Lists::         Formating lists to be readable.
1152 * Typing Lists::                How GNU Emacs helps you type lists.
1153 @end menu
1155 @node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1156 @ifnottex
1157 @unnumberedsubsec Numbers, Lists inside of Lists
1158 @end ifnottex
1160 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1161 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1162 separated by whitespace.
1164 In Lisp, both data and programs are represented the same way; that is,
1165 they are both lists of words, numbers, or other lists, separated by
1166 whitespace and surrounded by parentheses.  (Since a program looks like
1167 data, one program may easily serve as data for another; this is a very
1168 powerful feature of Lisp.)  (Incidentally, these two parenthetical
1169 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1170 @samp{.} as punctuation marks.)
1172 @need 1200
1173 Here is another list, this time with a list inside of it:
1175 @smallexample
1176 '(this list has (a list inside of it))
1177 @end smallexample
1179 The components of this list are the words @samp{this}, @samp{list},
1180 @samp{has}, and the list @samp{(a list inside of it)}.  The interior
1181 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1182 @samp{of}, @samp{it}.
1184 @node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1185 @comment  node-name,  next,  previous,  up
1186 @subsection Lisp Atoms
1187 @cindex Lisp Atoms
1189 In Lisp, what we have been calling words are called @dfn{atoms}.  This
1190 term comes from the historical meaning of the word atom, which means
1191 `indivisible'.  As far as Lisp is concerned, the words we have been
1192 using in the lists cannot be divided into any smaller parts and still
1193 mean the same thing as part of a program; likewise with numbers and
1194 single character symbols like @samp{+}.  On the other hand, unlike an
1195 atom, a list can be split into parts.  (@xref{car cdr & cons, ,
1196 @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1198 In a list, atoms are separated from each other by whitespace.  They can be
1199 right next to a parenthesis.
1201 @cindex @samp{empty list} defined
1202 Technically speaking, a list in Lisp consists of parentheses surrounding
1203 atoms separated by whitespace or surrounding other lists or surrounding
1204 both atoms and other lists.  A list can have just one atom in it or
1205 have nothing in it at all.  A list with nothing in it looks like this:
1206 @code{()}, and is called the @dfn{empty list}.  Unlike anything else, an
1207 empty list is considered both an atom and a list at the same time.
1209 @cindex Symbolic expressions, introduced
1210 @cindex @samp{expression} defined
1211 @cindex @samp{form} defined
1212 The printed representation of both atoms and lists are called
1213 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1214 The word @dfn{expression} by itself can refer to either the printed
1215 representation, or to the atom or list as it is held internally in the
1216 computer.  Often, people use the term @dfn{expression}
1217 indiscriminately.  (Also, in many texts, the word @dfn{form} is used
1218 as a synonym for expression.)
1220 Incidentally, the atoms that make up our universe were named such when
1221 they were thought to be indivisible; but it has been found that physical
1222 atoms are not indivisible.  Parts can split off an atom or it can
1223 fission into two parts of roughly equal size.  Physical atoms were named
1224 prematurely, before their truer nature was found.  In Lisp, certain
1225 kinds of atom, such as an array, can be separated into parts; but the
1226 mechanism for doing this is different from the mechanism for splitting a
1227 list.  As far as list operations are concerned, the atoms of a list are
1228 unsplittable.
1230 As in English, the meanings of the component letters of a Lisp atom
1231 are different from the meaning the letters make as a word.  For
1232 example, the word for the South American sloth, the @samp{ai}, is
1233 completely different from the two words, @samp{a}, and @samp{i}.
1235 There are many kinds of atom in nature but only a few in Lisp: for
1236 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1237 as @samp{+}, @samp{foo}, or @samp{forward-line}.  The words we have
1238 listed in the examples above are all symbols.  In everyday Lisp
1239 conversation, the word ``atom'' is not often used, because programmers
1240 usually try to be more specific about what kind of atom they are dealing
1241 with.  Lisp programming is mostly about symbols (and sometimes numbers)
1242 within lists.  (Incidentally, the preceding three word parenthetical
1243 remark is a proper list in Lisp, since it consists of atoms, which in
1244 this case are symbols, separated by whitespace and enclosed by
1245 parentheses, without any non-Lisp punctuation.)
1247 @need 1250
1248 In addition, text between double quotation marks---even sentences or
1249 paragraphs---is an atom.  Here is an example:
1250 @cindex Text between double quotation marks
1252 @smallexample
1253 '(this list includes "text between quotation marks.")
1254 @end smallexample
1256 @cindex @samp{string} defined
1257 @noindent
1258 In Lisp, all of the quoted text including the punctuation mark and the
1259 blank spaces is a single atom.  This kind of atom is called a
1260 @dfn{string} (for `string of characters') and is the sort of thing that
1261 is used for messages that a computer can print for a human to read.
1262 Strings are a different kind of atom than numbers or symbols and are
1263 used differently.
1265 @node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1266 @comment  node-name,  next,  previous,  up
1267 @subsection Whitespace in Lists
1268 @cindex Whitespace in lists
1270 @need 1200
1271 The amount of whitespace in a list does not matter.  From the point of view
1272 of the Lisp language,
1274 @smallexample
1275 @group
1276 '(this list
1277    looks like this)
1278 @end group
1279 @end smallexample
1281 @need 800
1282 @noindent
1283 is exactly the same as this:
1285 @smallexample
1286 '(this list looks like this)
1287 @end smallexample
1289 Both examples show what to Lisp is the same list, the list made up of
1290 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1291 @samp{this} in that order.
1293 Extra whitespace and newlines are designed to make a list more readable
1294 by humans.  When Lisp reads the expression, it gets rid of all the extra
1295 whitespace (but it needs to have at least one space between atoms in
1296 order to tell them apart.)
1298 Odd as it seems, the examples we have seen cover almost all of what Lisp
1299 lists look like!  Every other list in Lisp looks more or less like one
1300 of these examples, except that the list may be longer and more complex.
1301 In brief, a list is between parentheses, a string is between quotation
1302 marks, a symbol looks like a word, and a number looks like a number.
1303 (For certain situations, square brackets, dots and a few other special
1304 characters may be used; however, we will go quite far without them.)
1306 @node Typing Lists,  , Whitespace in Lists, Lisp Lists
1307 @comment  node-name,  next,  previous,  up
1308 @subsection GNU Emacs Helps You Type Lists
1309 @cindex Help typing lists
1310 @cindex Formatting help
1312 When you type a Lisp expression in GNU Emacs using either Lisp
1313 Interaction mode or Emacs Lisp mode, you have available to you several
1314 commands to format the Lisp expression so it is easy to read.  For
1315 example, pressing the @key{TAB} key automatically indents the line the
1316 cursor is on by the right amount.  A command to properly indent the
1317 code in a region is customarily bound to @kbd{M-C-\}.  Indentation is
1318 designed so that you can see which elements of a list belong to which
1319 list---elements of a sub-list are indented more than the elements of
1320 the enclosing list.
1322 In addition, when you type a closing parenthesis, Emacs momentarily
1323 jumps the cursor back to the matching opening parenthesis, so you can
1324 see which one it is.  This is very useful, since every list you type
1325 in Lisp must have its closing parenthesis match its opening
1326 parenthesis.  (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1327 Manual}, for more information about Emacs' modes.)
1329 @node Run a Program, Making Errors, Lisp Lists, List Processing
1330 @comment  node-name,  next,  previous,  up
1331 @section Run a Program
1332 @cindex Run a program
1333 @cindex Program, running one
1335 @cindex @samp{evaluate} defined
1336 A list in Lisp---any list---is a program ready to run.  If you run it
1337 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1338 of three things: do nothing except return to you the list itself; send
1339 you an error message; or, treat the first symbol in the list as a
1340 command to do something.  (Usually, of course, it is the last of these
1341 three things that you really want!)
1343 @c use code for the single apostrophe, not samp.
1344 The single apostrophe, @code{'}, that I put in front of some of the
1345 example lists in preceding sections is called a @dfn{quote}; when it
1346 precedes a list, it tells Lisp to do nothing with the list, other than
1347 take it as it is written.  But if there is no quote preceding a list,
1348 the first item of the list is special: it is a command for the computer
1349 to obey.  (In Lisp, these commands are called @emph{functions}.)  The list
1350 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1351 understands that the @code{+} is an instruction to do something with the
1352 rest of the list: add the numbers that follow.
1354 @need 1250
1355 If you are reading this inside of GNU Emacs in Info, here is how you can
1356 evaluate such a list:  place your cursor immediately after the right
1357 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1359 @smallexample
1360 (+ 2 2)
1361 @end smallexample
1363 @c use code for the number four, not samp.
1364 @noindent
1365 You will see the number @code{4} appear in the echo area.  (In the
1366 jargon, what you have just done is ``evaluate the list.''  The echo area
1367 is the line at the bottom of the screen that displays or ``echoes''
1368 text.)  Now try the same thing with a quoted list:  place the cursor
1369 right after the following list and type @kbd{C-x C-e}:
1371 @smallexample
1372 '(this is a quoted list)
1373 @end smallexample
1375 @noindent
1376 You will see @code{(this is a quoted list)} appear in the echo area.
1378 @cindex Lisp interpreter, explained
1379 @cindex Interpreter, Lisp, explained
1380 In both cases, what you are doing is giving a command to the program
1381 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1382 interpreter a command to evaluate the expression.  The name of the Lisp
1383 interpreter comes from the word for the task done by a human who comes
1384 up with the meaning of an expression---who ``interprets'' it.
1386 You can also evaluate an atom that is not part of a list---one that is
1387 not surrounded by parentheses; again, the Lisp interpreter translates
1388 from the humanly readable expression to the language of the computer.
1389 But before discussing this (@pxref{Variables}), we will discuss what the
1390 Lisp interpreter does when you make an error.
1392 @node Making Errors, Names & Definitions, Run a Program, List Processing
1393 @comment  node-name,  next,  previous,  up
1394 @section Generate an Error Message
1395 @cindex Generate an error message
1396 @cindex Error message generation
1398 Partly so you won't worry if you do it accidentally, we will now give
1399 a command to the Lisp interpreter that generates an error message.
1400 This is a harmless activity; and indeed, we will often try to generate
1401 error messages intentionally.  Once you understand the jargon, error
1402 messages can be informative.  Instead of being called ``error''
1403 messages, they should be called ``help'' messages.  They are like
1404 signposts to a traveller in a strange country; deciphering them can be
1405 hard, but once understood, they can point the way.
1407 The error message is generated by a built-in GNU Emacs debugger.  We
1408 will `enter the debugger'.  You get out of the debugger by typing @code{q}.
1410 What we will do is evaluate a list that is not quoted and does not
1411 have a meaningful command as its first element.  Here is a list almost
1412 exactly the same as the one we just used, but without the single-quote
1413 in front of it.  Position the cursor right after it and type @kbd{C-x
1414 C-e}:
1416 @smallexample
1417 (this is an unquoted list)
1418 @end smallexample
1420 @noindent
1421 What you see depends on which version of Emacs you are running.  GNU
1422 Emacs version 21 provides more information than version 20 and before.
1423 First, the more recent result of generating an error; then the
1424 earlier, version 20 result.
1426 @need 1250
1427 @noindent
1428 In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1429 you will see the following in it:
1431 @smallexample
1432 @group
1433 ---------- Buffer: *Backtrace* ----------
1434 Debugger entered--Lisp error: (void-function this)
1435   (this is an unquoted list)
1436   eval((this is an unquoted list))
1437   eval-last-sexp-1(nil)
1438   eval-last-sexp(nil)
1439   call-interactively(eval-last-sexp)
1440 ---------- Buffer: *Backtrace* ----------
1441 @end group
1442 @end smallexample
1444 @need 1200
1445 @noindent
1446 Your cursor will be in this window (you may have to wait a few seconds
1447 before it becomes visible).  To quit the debugger and make the
1448 debugger window go away, type:
1450 @smallexample
1452 @end smallexample
1454 @noindent
1455 Please type @kbd{q} right now, so you become confident that you can
1456 get out of the debugger.  Then, type @kbd{C-x C-e} again to re-enter
1459 @cindex @samp{function} defined
1460 Based on what we already know, we can almost read this error message.
1462 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1463 you what Emacs did.  When you typed @kbd{C-x C-e}, you made an
1464 interactive call to the command @code{eval-last-sexp}.  @code{eval} is
1465 an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1466 `symbolic expression'.  The command means `evaluate last symbolic
1467 expression', which is the expression just before your cursor.
1469 Each line above tells you what the Lisp interpreter evaluated next.
1470 The most recent action is at the top.  The buffer is called the
1471 @file{*Backtrace*} buffer because it enables you to track Emacs
1472 backwards.
1474 @need 800
1475 At the top of the @file{*Backtrace*} buffer, you see the line:
1477 @smallexample
1478 Debugger entered--Lisp error: (void-function this)
1479 @end smallexample
1481 @noindent
1482 The Lisp interpreter tried to evaluate the first atom of the list, the
1483 word @samp{this}.  It is this action that generated the error message
1484 @samp{void-function this}.
1486 The message contains the words @samp{void-function} and @samp{this}.
1488 @cindex @samp{function} defined
1489 The word @samp{function} was mentioned once before.  It is a very
1490 important word.  For our purposes, we can define it by saying that a
1491 @dfn{function} is a set of instructions to the computer that tell the
1492 computer to do something.
1494 Now we can begin to understand the error message: @samp{void-function
1495 this}.  The function (that is, the word @samp{this}) does not have a
1496 definition of any set of instructions for the computer to carry out.
1498 The slightly odd word, @samp{void-function}, is designed to cover the
1499 way Emacs Lisp is implemented, which is that when a symbol does not
1500 have a function definition attached to it, the place that should
1501 contain the instructions is `void'.
1503 On the other hand, since we were able to add 2 plus 2 successfully, by
1504 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1505 have a set of instructions for the computer to obey and those
1506 instructions must be to add the numbers that follow the @code{+}.
1508 @need 1250
1509 In GNU Emacs version 20, and in earlier versions, you will see only
1510 one line of error message; it will appear in the echo area and look
1511 like this:
1513 @smallexample
1514 Symbol's function definition is void:@: this
1515 @end smallexample
1517 @noindent
1518 (Also, your terminal may beep at you---some do, some don't; and others
1519 blink.  This is just a device to get your attention.)  The message goes
1520 away as soon as you type another key, even just to move the cursor.
1522 We know the meaning of the word @samp{Symbol}.  It refers to the first
1523 atom of the list, the word @samp{this}.  The word @samp{function}
1524 refers to the instructions that tell the computer what to do.
1525 (Technically, the symbol tells the computer where to find the
1526 instructions, but this is a complication we can ignore for the
1527 moment.)
1529 The error message can be understood: @samp{Symbol's function
1530 definition is void:@: this}.  The symbol (that is, the word
1531 @samp{this}) lacks instructions for the computer to carry out.
1533 @node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1534 @comment  node-name,  next,  previous,  up
1535 @section Symbol Names and Function Definitions
1536 @cindex Symbol names
1538 We can articulate another characteristic of Lisp based on what we have
1539 discussed so far---an important characteristic: a symbol, like
1540 @code{+}, is not itself the set of instructions for the computer to
1541 carry out.  Instead, the symbol is used, perhaps temporarily, as a way
1542 of locating the definition or set of instructions.  What we see is the
1543 name through which the instructions can be found.  Names of people
1544 work the same way.  I can be referred to as @samp{Bob}; however, I am
1545 not the letters @samp{B}, @samp{o}, @samp{b} but am the consciousness
1546 consistently associated with a particular life-form.  The name is not
1547 me, but it can be used to refer to me.
1549 In Lisp, one set of instructions can be attached to several names.
1550 For example, the computer instructions for adding numbers can be
1551 linked to the symbol @code{plus} as well as to the symbol @code{+}
1552 (and are in some dialects of Lisp).  Among humans, I can be referred
1553 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1555 On the other hand, a symbol can have only one function definition
1556 attached to it at a time.  Otherwise, the computer would be confused as
1557 to which definition to use.  If this were the case among people, only
1558 one person in the world could be named @samp{Bob}.  However, the function
1559 definition to which the name refers can be changed readily.
1560 (@xref{Install, , Install a Function Definition}.)
1562 Since Emacs Lisp is large, it is customary to name symbols in a way
1563 that identifies the part of Emacs to which the function belongs.
1564 Thus, all the names for functions that deal with Texinfo start with
1565 @samp{texinfo-} and those for functions that deal with reading mail
1566 start with @samp{rmail-}.
1568 @node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1569 @comment  node-name,  next,  previous,  up
1570 @section The Lisp Interpreter
1571 @cindex Lisp interpreter, what it does
1572 @cindex Interpreter, what it does
1574 Based on what we have seen, we can now start to figure out what the
1575 Lisp interpreter does when we command it to evaluate a list.
1576 First, it looks to see whether there is a quote before the list; if
1577 there is, the interpreter just gives us the list.  On the other
1578 hand, if there is no quote, the interpreter looks at the first element
1579 in the list and sees whether it has a function definition.  If it does,
1580 the interpreter carries out the instructions in the function definition.
1581 Otherwise, the interpreter prints an error message.
1583 This is how Lisp works.  Simple.  There are added complications which we
1584 will get to in a minute, but these are the fundamentals.  Of course, to
1585 write Lisp programs, you need to know how to write function definitions
1586 and attach them to names, and how to do this without confusing either
1587 yourself or the computer.
1589 @menu
1590 * Complications::               Variables, Special forms, Lists within.
1591 * Byte Compiling::              Specially processing code for speed.
1592 @end menu
1594 @node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1595 @ifnottex
1596 @unnumberedsubsec Complications
1597 @end ifnottex
1599 Now, for the first complication.  In addition to lists, the Lisp
1600 interpreter can evaluate a symbol that is not quoted and does not have
1601 parentheses around it.  The Lisp interpreter will attempt to determine
1602 the symbol's value as a @dfn{variable}.  This situation is described
1603 in the section on variables.  (@xref{Variables}.)
1605 @cindex Special form
1606 The second complication occurs because some functions are unusual and do
1607 not work in the usual manner.  Those that don't are called @dfn{special
1608 forms}.  They are used for special jobs, like defining a function, and
1609 there are not many of them.  In the next few chapters, you will be
1610 introduced to several of the more important special forms.
1612 The third and final complication is this: if the function that the
1613 Lisp interpreter is looking at is not a special form, and if it is part
1614 of a list, the Lisp interpreter looks to see whether the list has a list
1615 inside of it.  If there is an inner list, the Lisp interpreter first
1616 figures out what it should do with the inside list, and then it works on
1617 the outside list.  If there is yet another list embedded inside the
1618 inner list, it works on that one first, and so on.  It always works on
1619 the innermost list first.  The interpreter works on the innermost list
1620 first, to evaluate the result of that list.  The result may be
1621 used by the enclosing expression.
1623 Otherwise, the interpreter works left to right, from one expression to
1624 the next.
1626 @node Byte Compiling,  , Complications, Lisp Interpreter
1627 @subsection Byte Compiling
1628 @cindex Byte compiling
1630 One other aspect of interpreting: the Lisp interpreter is able to
1631 interpret two kinds of entity: humanly readable code, on which we will
1632 focus exclusively, and specially processed code, called @dfn{byte
1633 compiled} code, which is not humanly readable.  Byte compiled code
1634 runs faster than humanly readable code.
1636 You can transform humanly readable code into byte compiled code by
1637 running one of the compile commands such as @code{byte-compile-file}.
1638 Byte compiled code is usually stored in a file that ends with a
1639 @file{.elc} extension rather than a @file{.el} extension.  You will
1640 see both kinds of file in the @file{emacs/lisp} directory; the files
1641 to read are those with @file{.el} extensions.
1643 As a practical matter, for most things you might do to customize or
1644 extend Emacs, you do not need to byte compile; and I will not discuss
1645 the topic here.  @xref{Byte Compilation, , Byte Compilation, elisp,
1646 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1647 compilation.
1649 @node Evaluation, Variables, Lisp Interpreter, List Processing
1650 @comment  node-name,  next,  previous,  up
1651 @section Evaluation
1652 @cindex Evaluation
1654 When the Lisp interpreter works on an expression, the term for the
1655 activity is called @dfn{evaluation}.  We say that the interpreter
1656 `evaluates the expression'.  I've used this term several times before.
1657 The word comes from its use in everyday language, `to ascertain the
1658 value or amount of; to appraise', according to @cite{Webster's New
1659 Collegiate Dictionary}.
1661 After evaluating an expression, the Lisp interpreter will most likely
1662 @dfn{return} the value that the computer produces by carrying out the
1663 instructions it found in the function definition, or perhaps it will
1664 give up on that function and produce an error message.  (The interpreter
1665 may also find itself tossed, so to speak, to a different function or it
1666 may attempt to repeat continually what it is doing for ever and ever in
1667 what is called an `infinite loop'.  These actions are less common; and
1668 we can ignore them.)  Most frequently, the interpreter returns a value.
1670 @cindex @samp{side effect} defined
1671 At the same time the interpreter returns a value, it may do something
1672 else as well, such as move a cursor or copy a file; this other kind of
1673 action is called a @dfn{side effect}.  Actions that we humans think are
1674 important, such as printing results, are often ``side effects'' to the
1675 Lisp interpreter.  The jargon can sound peculiar, but it turns out that
1676 it is fairly easy to learn to use side effects.
1678 In summary, evaluating a symbolic expression most commonly causes the
1679 Lisp interpreter to return a value and perhaps carry out a side effect;
1680 or else produce an error.
1682 @menu
1683 * Evaluating Inner Lists::      Lists within lists...
1684 @end menu
1686 @node Evaluating Inner Lists,  , Evaluation, Evaluation
1687 @comment  node-name,  next,  previous,  up
1688 @subsection Evaluating Inner Lists
1689 @cindex Inner list evaluation
1690 @cindex Evaluating inner lists
1692 If evaluation applies to a list that is inside another list, the outer
1693 list may use the value returned by the first evaluation as information
1694 when the outer list is evaluated.  This explains why inner expressions
1695 are evaluated first: the values they return are used by the outer
1696 expressions.
1698 @need 1250
1699 We can investigate this process by evaluating another addition example.
1700 Place your cursor after the following expression and type @kbd{C-x C-e}:
1702 @smallexample
1703 (+ 2 (+ 3 3))
1704 @end smallexample
1706 @noindent
1707 The number 8 will appear in the echo area.
1709 What happens is that the Lisp interpreter first evaluates the inner
1710 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1711 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1712 returns the value 8.  Since there are no more enclosing expressions to
1713 evaluate, the interpreter prints that value in the echo area.
1715 Now it is easy to understand the name of the command invoked by the
1716 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}.  The
1717 letters @code{sexp} are an abbreviation for `symbolic expression', and
1718 @code{eval} is an abbreviation for `evaluate'.  The command means
1719 `evaluate last symbolic expression'.
1721 As an experiment, you can try evaluating the expression by putting the
1722 cursor at the beginning of the next line immediately following the
1723 expression, or inside the expression.
1725 @need 800
1726 Here is another copy of the expression:
1728 @smallexample
1729 (+ 2 (+ 3 3))
1730 @end smallexample
1732 @noindent
1733 If you place the cursor at the beginning of the blank line that
1734 immediately follows the expression and type @kbd{C-x C-e}, you will
1735 still get the value 8 printed in the echo area.  Now try putting the
1736 cursor inside the expression.  If you put it right after the next to
1737 last parenthesis (so it appears to sit on top of the last parenthesis),
1738 you will get a 6 printed in the echo area!  This is because the command
1739 evaluates the expression @code{(+ 3 3)}.
1741 Now put the cursor immediately after a number.  Type @kbd{C-x C-e} and
1742 you will get the number itself.  In Lisp, if you evaluate a number, you
1743 get the number itself---this is how numbers differ from symbols.  If you
1744 evaluate a list starting with a symbol like @code{+}, you will get a
1745 value returned that is the result of the computer carrying out the
1746 instructions in the function definition attached to that name.  If a
1747 symbol by itself is evaluated, something different happens, as we will
1748 see in the next section.
1750 @node Variables, Arguments, Evaluation, List Processing
1751 @comment  node-name,  next,  previous,  up
1752 @section Variables
1753 @cindex Variables
1755 In Emacs Lisp, a symbol can have a value attached to it just as it can
1756 have a function definition attached to it.  The two are different.
1757 The function definition is a set of instructions that a computer will
1758 obey.  A value, on the other hand, is something, such as number or a
1759 name, that can vary (which is why such a symbol is called a variable).
1760 The value of a symbol can be any expression in Lisp, such as a symbol,
1761 number, list, or string.  A symbol that has a value is often called a
1762 @dfn{variable}.
1764 A symbol can have both a function definition and a value attached to
1765 it at the same time.  Or it can have just one or the other.
1766 The two are separate.  This is somewhat similar
1767 to the way the name Cambridge can refer to the city in Massachusetts
1768 and have some information attached to the name as well, such as
1769 ``great programming center''.
1771 @ignore
1772 (Incidentally, in Emacs Lisp, a symbol can have two
1773 other things attached to it, too: a property list and a documentation
1774 string; these are discussed later.)
1775 @end ignore
1777 Another way to think about this is to imagine a symbol as being a chest
1778 of drawers.  The function definition is put in one drawer, the value in
1779 another, and so on.  What is put in the drawer holding the value can be
1780 changed without affecting the contents of the drawer holding the
1781 function definition, and vice-versa.
1783 @menu
1784 * fill-column Example::
1785 * Void Function::               The error message for a symbol
1786                                   without a function.
1787 * Void Variable::               The error message for a symbol without a value.
1788 @end menu
1790 @node fill-column Example, Void Function, Variables, Variables
1791 @ifnottex
1792 @unnumberedsubsec @code{fill-column}, an Example Variable
1793 @end ifnottex
1795 @findex fill-column, @r{an example variable}
1796 @cindex Example variable, @code{fill-column}
1797 @cindex Variable, example of, @code{fill-column}
1798 The variable @code{fill-column} illustrates a symbol with a value
1799 attached to it: in every GNU Emacs buffer, this symbol is set to some
1800 value, usually 72 or 70, but sometimes to some other value.  To find the
1801 value of this symbol, evaluate it by itself.  If you are reading this in
1802 Info inside of GNU Emacs, you can do this by putting the cursor after
1803 the symbol and typing @kbd{C-x C-e}:
1805 @smallexample
1806 fill-column
1807 @end smallexample
1809 @noindent
1810 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1811 area.  This is the value for which @code{fill-column} is set for me as I
1812 write this.  It may be different for you in your Info buffer.  Notice
1813 that the value returned as a variable is printed in exactly the same way
1814 as the value returned by a function carrying out its instructions.  From
1815 the point of view of the Lisp interpreter, a value returned is a value
1816 returned.  What kind of expression it came from ceases to matter once
1817 the value is known.
1819 A symbol can have any value attached to it or, to use the jargon, we can
1820 @dfn{bind} the variable to a value: to a number, such as 72; to a
1821 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1822 oak)}; we can even bind a variable to a function definition.
1824 A symbol can be bound to a value in several ways.  @xref{set & setq, ,
1825 Setting the Value of a Variable}, for information about one way to do
1826 this.
1828 @node Void Function, Void Variable, fill-column Example, Variables
1829 @comment  node-name,  next,  previous,  up
1830 @subsection Error Message for a Symbol Without a Function
1831 @cindex Symbol without function error
1832 @cindex Error for symbol without function
1834 When we evaluated @code{fill-column} to find its value as a variable,
1835 we did not place parentheses around the word.  This is because we did
1836 not intend to use it as a function name.
1838 If @code{fill-column} were the first or only element of a list, the
1839 Lisp interpreter would attempt to find the function definition
1840 attached to it.  But @code{fill-column} has no function definition.
1841 Try evaluating this:
1843 @smallexample
1844 (fill-column)
1845 @end smallexample
1847 @need 1250
1848 @noindent
1849 In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1850 that says:
1852 @smallexample
1853 @group
1854 ---------- Buffer: *Backtrace* ----------
1855 Debugger entered--Lisp error: (void-function fill-column)
1856   (fill-column)
1857   eval((fill-column))
1858   eval-last-sexp-1(nil)
1859   eval-last-sexp(nil)
1860   call-interactively(eval-last-sexp)
1861 ---------- Buffer: *Backtrace* ----------
1862 @end group
1863 @end smallexample
1865 @noindent
1866 (Remember, to quit the debugger and make the debugger window go away,
1867 type @kbd{q} in the @file{*Backtrace*} buffer.)
1869 @need 800
1870 In GNU Emacs 20 and before, you will produce an error message that says:
1872 @smallexample
1873 Symbol's function definition is void:@: fill-column
1874 @end smallexample
1876 @noindent
1877 (The message will go away away as soon as you move the cursor or type
1878 another key.)
1880 @node Void Variable,  , Void Function, Variables
1881 @comment  node-name,  next,  previous,  up
1882 @subsection Error Message for a Symbol Without a Value
1883 @cindex Symbol without value error
1884 @cindex Error for symbol without value
1886 If you attempt to evaluate a symbol that does not have a value bound to
1887 it, you will receive an error message.  You can see this by
1888 experimenting with our 2 plus 2 addition.  In the following expression,
1889 put your cursor right after the @code{+}, before the first number 2,
1890 type @kbd{C-x C-e}:
1892 @smallexample
1893 (+ 2 2)
1894 @end smallexample
1896 @need 1500
1897 @noindent
1898 In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1899 says:
1901 @smallexample
1902 @group
1903 ---------- Buffer: *Backtrace* ----------
1904 Debugger entered--Lisp error: (void-variable +)
1905   eval(+)
1906   eval-last-sexp-1(nil)
1907   eval-last-sexp(nil)
1908   call-interactively(eval-last-sexp)
1909 ---------- Buffer: *Backtrace* ----------
1910 @end group
1911 @end smallexample
1913 @noindent
1914 (As with the other times we entered the debugger, you can quit by
1915 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1917 This backtrace is different from the very first error message we saw,
1918 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1919 In this case, the function does not have a value as a variable; while
1920 in the other error message, the function (the word `this') did not
1921 have a definition.
1923 In this experiment with the @code{+}, what we did was cause the Lisp
1924 interpreter to evaluate the @code{+} and look for the value of the
1925 variable instead of the function definition.  We did this by placing the
1926 cursor right after the symbol rather than after the parenthesis of the
1927 enclosing list as we did before.  As a consequence, the Lisp interpreter
1928 evaluated the preceding s-expression, which in this case was the
1929 @code{+} by itself.
1931 Since @code{+} does not have a value bound to it, just the function
1932 definition, the error message reported that the symbol's value as a
1933 variable was void.
1935 @need 800
1936 In GNU Emacs version 20 and before, your error message will say:
1938 @example
1939 Symbol's value as variable is void:@: +
1940 @end example
1942 @noindent
1943 The meaning is the same as in GNU Emacs 21.
1945 @node Arguments, set & setq, Variables, List Processing
1946 @comment  node-name,  next,  previous,  up
1947 @section Arguments
1948 @cindex Arguments
1949 @cindex Passing information to functions
1951 To see how information is passed to functions, let's look again at
1952 our old standby, the addition of two plus two.  In Lisp, this is written
1953 as follows:
1955 @smallexample
1956 (+ 2 2)
1957 @end smallexample
1959 If you evaluate this expression, the number 4 will appear in your echo
1960 area.  What the Lisp interpreter does is add the numbers that follow
1961 the @code{+}.
1963 @cindex @samp{argument} defined
1964 The numbers added by @code{+} are called the @dfn{arguments} of the
1965 function @code{+}.  These numbers are the information that is given to
1966 or @dfn{passed} to the function.
1968 The word `argument' comes from the way it is used in mathematics and
1969 does not refer to a disputation between two people; instead it refers to
1970 the information presented to the function, in this case, to the
1971 @code{+}.  In Lisp, the arguments to a function are the atoms or lists
1972 that follow the function.  The values returned by the evaluation of
1973 these atoms or lists are passed to the function.  Different functions
1974 require different numbers of arguments; some functions require none at
1975 all.@footnote{It is curious to track the path by which the word `argument'
1976 came to have two different meanings, one in mathematics and the other in
1977 everyday English.  According to the @cite{Oxford English Dictionary},
1978 the word derives from the Latin for @samp{to make clear, prove}; thus it
1979 came to mean, by one thread of derivation, `the evidence offered as
1980 proof', which is to say, `the information offered', which led to its
1981 meaning in Lisp.  But in the other thread of derivation, it came to mean
1982 `to assert in a manner against which others may make counter
1983 assertions', which led to the meaning of the word as a disputation.
1984 (Note here that the English word has two different definitions attached
1985 to it at the same time.  By contrast, in Emacs Lisp, a symbol cannot
1986 have two different function definitions at the same time.)}
1988 @menu
1989 * Data types::                  Types of data passed to a function.
1990 * Args as Variable or List::    An argument can be the value
1991                                   of a variable or list.
1992 * Variable Number of Arguments::  Some functions may take a
1993                                   variable number of arguments.
1994 * Wrong Type of Argument::      Passing an argument of the wrong type
1995                                   to a function.
1996 * message::                     A useful function for sending messages.
1997 @end menu
1999 @node Data types, Args as Variable or List, Arguments, Arguments
2000 @comment  node-name,  next,  previous,  up
2001 @subsection Arguments' Data Types
2002 @cindex Data types
2003 @cindex Types of data
2004 @cindex Arguments' data types
2006 The type of data that should be passed to a function depends on what
2007 kind of information it uses.  The arguments to a function such as
2008 @code{+} must have values that are numbers, since @code{+} adds numbers.
2009 Other functions use different kinds of data for their arguments.
2011 @findex concat
2012 For example, the @code{concat} function links together or unites two or
2013 more strings of text to produce a string.  The arguments are strings.
2014 Concatenating the two character strings @code{abc}, @code{def} produces
2015 the single string @code{abcdef}.  This can be seen by evaluating the
2016 following:
2018 @smallexample
2019 (concat "abc" "def")
2020 @end smallexample
2022 @noindent
2023 The value produced by evaluating this expression is @code{"abcdef"}.
2025 A function such as @code{substring} uses both a string and numbers as
2026 arguments.  The function returns a part of the string, a substring of
2027 the first argument.  This function takes three arguments.  Its first
2028 argument is the string of characters, the second and third arguments are
2029 numbers that indicate the beginning and end of the substring.  The
2030 numbers are a count of the number of characters (including spaces and
2031 punctuations) from the beginning of the string.
2033 @need 800
2034 For example, if you evaluate the following:
2036 @smallexample
2037 (substring "The quick brown fox jumped." 16 19)
2038 @end smallexample
2040 @noindent
2041 you will see @code{"fox"} appear in the echo area.  The arguments are the
2042 string and the two numbers.
2044 Note that the string passed to @code{substring} is a single atom even
2045 though it is made up of several words separated by spaces.  Lisp counts
2046 everything between the two quotation marks as part of the string,
2047 including the spaces.  You can think of the @code{substring} function as
2048 a kind of `atom smasher' since it takes an otherwise indivisible atom
2049 and extracts a part.  However, @code{substring} is only able to extract
2050 a substring from an argument that is a string, not from another type of
2051 atom such as a number or symbol.
2053 @node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2054 @comment  node-name,  next,  previous,  up
2055 @subsection An Argument as the Value of a Variable or List
2057 An argument can be a symbol that returns a value when it is evaluated.
2058 For example, when the symbol @code{fill-column} by itself is evaluated,
2059 it returns a number.  This number can be used in an addition.
2061 @need 1250
2062 Position the cursor after the following expression and type @kbd{C-x
2063 C-e}:
2065 @smallexample
2066 (+ 2 fill-column)
2067 @end smallexample
2069 @noindent
2070 The value will be a number two more than what you get by evaluating
2071 @code{fill-column} alone.  For me, this is 74, because the value of
2072 @code{fill-column} is 72.
2074 As we have just seen, an argument can be a symbol that returns a value
2075 when evaluated.  In addition, an argument can be a list that returns a
2076 value when it is evaluated.  For example, in the following expression,
2077 the arguments to the function @code{concat} are the strings
2078 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2079 @code{(number-to-string (+ 2 fill-column))}.
2081 @c For Emacs 21, need number-to-string
2082 @smallexample
2083 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2084 @end smallexample
2086 @noindent
2087 If you evaluate this expression---and if, as with my Emacs,
2088 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2089 appear in the echo area.  (Note that you must put spaces after the
2090 word @samp{The} and before the word @samp{red} so they will appear in
2091 the final string.  The function @code{number-to-string} converts the
2092 integer that the addition function returns to a string.
2093 @code{number-to-string} is also known as @code{int-to-string}.)
2095 @node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2096 @comment  node-name,  next,  previous,  up
2097 @subsection Variable Number of Arguments
2098 @cindex Variable number of arguments
2099 @cindex Arguments, variable number of
2101 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2102 number of arguments.  (The @code{*} is the symbol for multiplication.)
2103 This can be seen by evaluating each of the following expressions in
2104 the usual way.  What you will see in the echo area is printed in this
2105 text after @samp{@result{}}, which you may read as `evaluates to'.
2107 @need 1250
2108 In the first set, the functions have no arguments:
2110 @smallexample
2111 @group
2112 (+)       @result{} 0
2114 (*)       @result{} 1
2115 @end group
2116 @end smallexample
2118 @need 1250
2119 In this set, the functions have one argument each:
2121 @smallexample
2122 @group
2123 (+ 3)     @result{} 3
2125 (* 3)     @result{} 3
2126 @end group
2127 @end smallexample
2129 @need 1250
2130 In this set, the functions have three arguments each:
2132 @smallexample
2133 @group
2134 (+ 3 4 5) @result{} 12
2136 (* 3 4 5) @result{} 60
2137 @end group
2138 @end smallexample
2140 @node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2141 @comment  node-name,  next,  previous,  up
2142 @subsection Using the Wrong Type Object as an Argument
2143 @cindex Wrong type of argument
2144 @cindex Argument, wrong type of
2146 When a function is passed an argument of the wrong type, the Lisp
2147 interpreter produces an error message.  For example, the @code{+}
2148 function expects the values of its arguments to be numbers.  As an
2149 experiment we can pass it the quoted symbol @code{hello} instead of a
2150 number.  Position the cursor after the following expression and type
2151 @kbd{C-x C-e}:
2153 @smallexample
2154 (+ 2 'hello)
2155 @end smallexample
2157 @noindent
2158 When you do this you will generate an error message.  What has happened
2159 is that @code{+} has tried to add the 2 to the value returned by
2160 @code{'hello}, but the value returned by @code{'hello} is the symbol
2161 @code{hello}, not a number.  Only numbers can be added.  So @code{+}
2162 could not carry out its addition.
2164 @need 1250
2165 In GNU Emacs version 21, you will create and enter a
2166 @file{*Backtrace*} buffer that says:
2168 @noindent
2169 @smallexample
2170 @group
2171 ---------- Buffer: *Backtrace* ----------
2172 Debugger entered--Lisp error:
2173          (wrong-type-argument number-or-marker-p hello)
2174   +(2 hello)
2175   eval((+ 2 (quote hello)))
2176   eval-last-sexp-1(nil)
2177   eval-last-sexp(nil)
2178   call-interactively(eval-last-sexp)
2179 ---------- Buffer: *Backtrace* ----------
2180 @end group
2181 @end smallexample
2183 @need 1250
2184 As usual, the error message tries to be helpful and makes sense after you
2185 learn how to read it.
2187 The first part of the error message is straightforward; it says
2188 @samp{wrong type argument}.  Next comes the mysterious jargon word
2189 @w{@samp{number-or-marker-p}}.  This word is trying to tell you what
2190 kind of argument the @code{+} expected.
2192 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2193 trying to determine whether the information presented it (the value of
2194 the argument) is a number or a marker (a special object representing a
2195 buffer position).  What it does is test to see whether the @code{+} is
2196 being given numbers to add.  It also tests to see whether the
2197 argument is something called a marker, which is a specific feature of
2198 Emacs Lisp.  (In Emacs, locations in a buffer are recorded as markers.
2199 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2200 its position is kept as a marker.  The mark can be considered a
2201 number---the number of characters the location is from the beginning
2202 of the buffer.)  In Emacs Lisp, @code{+} can be used to add the
2203 numeric value of marker positions as numbers.
2205 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2206 practice started in the early days of Lisp programming.  The @samp{p}
2207 stands for `predicate'.  In the jargon used by the early Lisp
2208 researchers, a predicate refers to a function to determine whether some
2209 property is true or false.  So the @samp{p} tells us that
2210 @code{number-or-marker-p} is the name of a function that determines
2211 whether it is true or false that the argument supplied is a number or
2212 a marker.  Other Lisp symbols that end in @samp{p} include @code{zerop},
2213 a function that tests whether its argument has the value of zero, and
2214 @code{listp}, a function that tests whether its argument is a list.
2216 Finally, the last part of the error message is the symbol @code{hello}.
2217 This is the value of the argument that was passed to @code{+}.  If the
2218 addition had been passed the correct type of object, the value passed
2219 would have been a number, such as 37, rather than a symbol like
2220 @code{hello}.  But then you would not have got the error message.
2222 @need 1250
2223 In GNU Emacs version 20 and before, the echo area displays an error
2224 message that says:
2226 @smallexample
2227 Wrong type argument:@: number-or-marker-p, hello
2228 @end smallexample
2230 This says, in different words, the same as the top line of the
2231 @file{*Backtrace*} buffer.
2233 @node message,  , Wrong Type of Argument, Arguments
2234 @comment  node-name,  next,  previous,  up
2235 @subsection The @code{message} Function
2236 @findex message
2238 Like @code{+}, the @code{message} function takes a variable number of
2239 arguments.  It is used to send messages to the user and is so useful
2240 that we will describe it here.
2242 @need 1250
2243 A message is printed in the echo area.  For example, you can print a
2244 message in your echo area by evaluating the following list:
2246 @smallexample
2247 (message "This message appears in the echo area!")
2248 @end smallexample
2250 The whole string between double quotation marks is a single argument
2251 and is printed @i{in toto}.  (Note that in this example, the message
2252 itself will appear in the echo area within double quotes; that is
2253 because you see the value returned by the @code{message} function.  In
2254 most uses of @code{message} in programs that you write, the text will
2255 be printed in the echo area as a side-effect, without the quotes.
2256 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2257 detail}, for an example of this.)
2259 However, if there is a @samp{%s} in the quoted string of characters, the
2260 @code{message} function does not print the @samp{%s} as such, but looks
2261 to the argument that follows the string.  It evaluates the second
2262 argument and prints the value at the location in the string where the
2263 @samp{%s} is.
2265 @need 1250
2266 You can see this by positioning the cursor after the following
2267 expression and typing @kbd{C-x C-e}:
2269 @smallexample
2270 (message "The name of this buffer is: %s." (buffer-name))
2271 @end smallexample
2273 @noindent
2274 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2275 echo area.  The function @code{buffer-name} returns the name of the
2276 buffer as a string, which the @code{message} function inserts in place
2277 of @code{%s}.
2279 To print a value as an integer, use @samp{%d} in the same way as
2280 @samp{%s}.  For example, to print a message in the echo area that
2281 states the value of the @code{fill-column}, evaluate the following:
2283 @smallexample
2284 (message "The value of fill-column is %d." fill-column)
2285 @end smallexample
2287 @noindent
2288 On my system, when I evaluate this list, @code{"The value of
2289 fill-column is 72."} appears in my echo area@footnote{Actually, you
2290 can use @code{%s} to print a number.  It is non-specific.  @code{%d}
2291 prints only the part of a number left of a decimal point, and not
2292 anything that is not a number.}.
2294 If there is more than one @samp{%s} in the quoted string, the value of
2295 the first argument following the quoted string is printed at the
2296 location of the first @samp{%s} and the value of the second argument is
2297 printed at the location of the second @samp{%s}, and so on.
2299 @need 1250
2300 For example, if you evaluate the following,
2302 @smallexample
2303 @group
2304 (message "There are %d %s in the office!"
2305          (- fill-column 14) "pink elephants")
2306 @end group
2307 @end smallexample
2309 @noindent
2310 a rather whimsical message will appear in your echo area.  On my system
2311 it says, @code{"There are 58 pink elephants in the office!"}.
2313 The expression @code{(- fill-column 14)} is evaluated and the resulting
2314 number is inserted in place of the @samp{%d}; and the string in double
2315 quotes, @code{"pink elephants"}, is treated as a single argument and
2316 inserted in place of the @samp{%s}.  (That is to say, a string between
2317 double quotes evaluates to itself, like a number.)
2319 Finally, here is a somewhat complex example that not only illustrates
2320 the computation of a number, but also shows how you can use an
2321 expression within an expression to generate the text that is substituted
2322 for @samp{%s}:
2324 @smallexample
2325 @group
2326 (message "He saw %d %s"
2327          (- fill-column 34)
2328          (concat "red "
2329                  (substring
2330                   "The quick brown foxes jumped." 16 21)
2331                  " leaping."))
2332 @end group
2333 @end smallexample
2335 In this example, @code{message} has three arguments: the string,
2336 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2337 the expression beginning with the function @code{concat}.  The value
2338 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2339 in place of the @samp{%d}; and the value returned by the expression
2340 beginning with @code{concat} is inserted in place of the @samp{%s}.
2342 When I evaluate the expression, the message @code{"He saw 38 red
2343 foxes leaping."} appears in my echo area.
2345 @node set & setq, Summary, Arguments, List Processing
2346 @comment  node-name,  next,  previous,  up
2347 @section Setting the Value of a Variable
2348 @cindex Variable, setting value
2349 @cindex Setting value of variable
2351 @cindex @samp{bind} defined
2352 There are several ways by which a variable can be given a value.  One of
2353 the ways is to use either the function @code{set} or the function
2354 @code{setq}.  Another way is to use @code{let} (@pxref{let}).  (The
2355 jargon for this process is to @dfn{bind} a variable to a value.)
2357 The following sections not only describe how @code{set} and @code{setq}
2358 work but also illustrate how arguments are passed.
2360 @menu
2361 * Using set::                   Setting values.
2362 * Using setq::                  Setting a quoted value.
2363 * Counting::                    Using @code{setq} to count.
2364 @end menu
2366 @node Using set, Using setq, set & setq, set & setq
2367 @comment  node-name,  next,  previous,  up
2368 @subsection Using @code{set}
2369 @findex set
2371 To set the value of the symbol @code{flowers} to the list @code{'(rose
2372 violet daisy buttercup)}, evaluate the following expression by
2373 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2375 @smallexample
2376 (set 'flowers '(rose violet daisy buttercup))
2377 @end smallexample
2379 @noindent
2380 The list @code{(rose violet daisy buttercup)} will appear in the echo
2381 area.  This is what is @emph{returned} by the @code{set} function.  As a
2382 side effect, the symbol @code{flowers} is bound to the list ; that is,
2383 the symbol @code{flowers}, which can be viewed as a variable, is given
2384 the list as its value.  (This process, by the way, illustrates how a
2385 side effect to the Lisp interpreter, setting the value, can be the
2386 primary effect that we humans are interested in.  This is because every
2387 Lisp function must return a value if it does not get an error, but it
2388 will only have a side effect if it is designed to have one.)
2390 After evaluating the @code{set} expression, you can evaluate the symbol
2391 @code{flowers} and it will return the value you just set.  Here is the
2392 symbol.  Place your cursor after it and type @kbd{C-x C-e}.
2394 @smallexample
2395 flowers
2396 @end smallexample
2398 @noindent
2399 When you evaluate @code{flowers}, the list
2400 @code{(rose violet daisy buttercup)} appears in the echo area.
2402 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2403 in front of it, what you will see in the echo area is the symbol itself,
2404 @code{flowers}.  Here is the quoted symbol, so you can try this:
2406 @smallexample
2407 'flowers
2408 @end smallexample
2410 Note also, that when you use @code{set}, you need to quote both
2411 arguments to @code{set}, unless you want them evaluated.  Since we do
2412 not want either argument evaluated, neither the variable
2413 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2414 are quoted.  (When you use @code{set} without quoting its first
2415 argument, the first argument is evaluated before anything else is
2416 done.  If you did this and @code{flowers} did not have a value
2417 already, you would get an error message that the @samp{Symbol's value
2418 as variable is void}; on the other hand, if @code{flowers} did return
2419 a value after it was evaluated, the @code{set} would attempt to set
2420 the value that was returned.  There are situations where this is the
2421 right thing for the function to do; but such situations are rare.)
2423 @node Using setq, Counting, Using set, set & setq
2424 @comment  node-name,  next,  previous,  up
2425 @subsection Using @code{setq}
2426 @findex setq
2428 As a practical matter, you almost always quote the first argument to
2429 @code{set}.  The combination of @code{set} and a quoted first argument
2430 is so common that it has its own name: the special form @code{setq}.
2431 This special form is just like @code{set} except that the first argument
2432 is quoted automatically, so you don't need to type the quote mark
2433 yourself.  Also, as an added convenience, @code{setq} permits you to set
2434 several different variables to different values, all in one expression.
2436 To set the value of the variable @code{carnivores} to the list
2437 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2438 is used:
2440 @smallexample
2441 (setq carnivores '(lion tiger leopard))
2442 @end smallexample
2444 @noindent
2445 This is exactly the same as using @code{set} except the first argument
2446 is automatically quoted by @code{setq}.  (The @samp{q} in @code{setq}
2447 means @code{quote}.)
2449 @need 1250
2450 With @code{set}, the expression would look like this:
2452 @smallexample
2453 (set 'carnivores '(lion tiger leopard))
2454 @end smallexample
2456 Also, @code{setq} can be used to assign different values to
2457 different variables.  The first argument is bound to the value
2458 of the second argument, the third argument is bound to the value of the
2459 fourth argument, and so on.  For example, you could use the following to
2460 assign a list of trees to the symbol @code{trees} and a list of herbivores
2461 to the symbol @code{herbivores}:
2463 @smallexample
2464 @group
2465 (setq trees '(pine fir oak maple)
2466       herbivores '(gazelle antelope zebra))
2467 @end group
2468 @end smallexample
2470 @noindent
2471 (The expression could just as well have been on one line, but it might
2472 not have fit on a page; and humans find it easier to read nicely
2473 formatted lists.)
2475 Although I have been using the term `assign', there is another way of
2476 thinking about the workings of @code{set} and @code{setq}; and that is to
2477 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2478 list.  This latter way of thinking is very common and in forthcoming
2479 chapters we shall come upon at least one symbol that has `pointer' as
2480 part of its name.  The name is chosen because the symbol has a value,
2481 specifically a list, attached to it; or, expressed another way,
2482 the symbol is set to ``point'' to the list.
2484 @node Counting,  , Using setq, set & setq
2485 @comment  node-name,  next,  previous,  up
2486 @subsection Counting
2487 @cindex Counting
2489 Here is an example that shows how to use @code{setq} in a counter.  You
2490 might use this to count how many times a part of your program repeats
2491 itself.  First set a variable to zero; then add one to the number each
2492 time the program repeats itself.  To do this, you need a variable that
2493 serves as a counter, and two expressions: an initial @code{setq}
2494 expression that sets the counter variable to zero; and a second
2495 @code{setq} expression that increments the counter each time it is
2496 evaluated.
2498 @smallexample
2499 @group
2500 (setq counter 0)                ; @r{Let's call this the initializer.}
2502 (setq counter (+ counter 1))    ; @r{This is the incrementer.}
2504 counter                         ; @r{This is the counter.}
2505 @end group
2506 @end smallexample
2508 @noindent
2509 (The text following the @samp{;} are comments.  @xref{Change a
2510 defun, , Change a Function Definition}.)
2512 If you evaluate the first of these expressions, the initializer,
2513 @code{(setq counter 0)}, and then evaluate the third expression,
2514 @code{counter}, the number @code{0} will appear in the echo area.  If
2515 you then evaluate the second expression, the incrementer, @code{(setq
2516 counter (+ counter 1))}, the counter will get the value 1.  So if you
2517 again evaluate @code{counter}, the number @code{1} will appear in the
2518 echo area.  Each time you evaluate the second expression, the value of
2519 the counter will be incremented.
2521 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2522 the Lisp interpreter first evaluates the innermost list; this is the
2523 addition.  In order to evaluate this list, it must evaluate the variable
2524 @code{counter} and the number @code{1}.  When it evaluates the variable
2525 @code{counter}, it receives its current value.  It passes this value and
2526 the number @code{1} to the @code{+} which adds them together.  The sum
2527 is then returned as the value of the inner list and passed to the
2528 @code{setq} which sets the variable @code{counter} to this new value.
2529 Thus, the value of the variable, @code{counter}, is changed.
2531 @node Summary, Error Message Exercises, set & setq, List Processing
2532 @comment  node-name,  next,  previous,  up
2533 @section Summary
2535 Learning Lisp is like climbing a hill in which the first part is the
2536 steepest.  You have now climbed the most difficult part; what remains
2537 becomes easier as you progress onwards.
2539 In summary,
2541 @itemize @bullet
2543 @item
2544 Lisp programs are made up of expressions, which are lists or single atoms.
2546 @item
2547 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2548 surrounded by parentheses.  A list can be empty.
2550 @item
2551 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2552 character symbols like @code{+}, strings of characters between double
2553 quotation marks, or numbers.
2555 @item
2556 A number evaluates to itself.
2558 @item
2559 A string between double quotes also evaluates to itself.
2561 @item
2562 When you evaluate a symbol by itself, its value is returned.
2564 @item
2565 When you evaluate a list, the Lisp interpreter looks at the first symbol
2566 in the list and then at the function definition bound to that symbol.
2567 Then the instructions in the function definition are carried out.
2569 @item
2570 A single-quote, @code{'}, tells the Lisp interpreter that it should
2571 return the following expression as written, and not evaluate it as it
2572 would if the quote were not there.
2574 @item
2575 Arguments are the information passed to a function.  The arguments to a
2576 function are computed by evaluating the rest of the elements of the list
2577 of which the function is the first element.
2579 @item
2580 A function always returns a value when it is evaluated (unless it gets
2581 an error); in addition, it may also carry out some action called a
2582 ``side effect''.  In many cases, a function's primary purpose is to
2583 create a side effect.
2584 @end itemize
2586 @node Error Message Exercises,  , Summary, List Processing
2587 @comment  node-name,  next,  previous,  up
2588 @section Exercises
2590 A few simple exercises:
2592 @itemize @bullet
2593 @item
2594 Generate an error message by evaluating an appropriate symbol that is
2595 not within parentheses.
2597 @item
2598 Generate an error message by evaluating an appropriate symbol that is
2599 between parentheses.
2601 @item
2602 Create a counter that increments by two rather than one.
2604 @item
2605 Write an expression that prints a message in the echo area when
2606 evaluated.
2607 @end itemize
2609 @node Practicing Evaluation, Writing Defuns, List Processing, Top
2610 @comment  node-name,  next,  previous,  up
2611 @chapter Practicing Evaluation
2612 @cindex Practicing evaluation
2613 @cindex Evaluation practice
2615 Before learning how to write a function definition in Emacs Lisp, it is
2616 useful to spend a little time evaluating various expressions that have
2617 already been written.  These expressions will be lists with the
2618 functions as their first (and often only) element.  Since some of the
2619 functions associated with buffers are both simple and interesting, we
2620 will start with those.  In this section, we will evaluate a few of
2621 these.  In another section, we will study the code of several other
2622 buffer-related functions, to see how they were written.
2624 @menu
2625 * How to Evaluate::             Typing editing commands or @kbd{C-x C-e}
2626                                   causes evaluation.
2627 * Buffer Names::                Buffers and files are different.
2628 * Getting Buffers::             Getting a buffer itself, not merely its name.
2629 * Switching Buffers::           How to change to another buffer.
2630 * Buffer Size & Locations::     Where point is located and the size of
2631                                 the buffer.
2632 * Evaluation Exercise::
2633 @end menu
2635 @node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2636 @ifnottex
2637 @unnumberedsec How to Evaluate
2638 @end ifnottex
2640 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2641 command to move the cursor or to scroll the screen, @i{you are evaluating
2642 an expression,} the first element of which is a function.  @i{This is
2643 how Emacs works.}
2645 @cindex @samp{interactive function} defined
2646 @cindex @samp{command} defined
2647 When you type keys, you cause the Lisp interpreter to evaluate an
2648 expression and that is how you get your results.  Even typing plain text
2649 involves evaluating an Emacs Lisp function, in this case, one that uses
2650 @code{self-insert-command}, which simply inserts the character you
2651 typed.  The functions you evaluate by typing keystrokes are called
2652 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2653 interactive will be illustrated in the chapter on how to write function
2654 definitions.  @xref{Interactive, , Making a Function Interactive}.
2656 In addition to typing keyboard commands, we have seen a second way to
2657 evaluate an expression: by positioning the cursor after a list and
2658 typing @kbd{C-x C-e}.  This is what we will do in the rest of this
2659 section.  There are other ways to evaluate an expression as well; these
2660 will be described as we come to them.
2662 Besides being used for practicing evaluation, the functions shown in the
2663 next few sections are important in their own right.  A study of these
2664 functions makes clear the distinction between buffers and files, how to
2665 switch to a buffer, and how to determine a location within it.
2667 @node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2668 @comment  node-name,  next,  previous,  up
2669 @section Buffer Names
2670 @findex buffer-name
2671 @findex buffer-file-name
2673 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2674 the difference between a file and a buffer.  When you evaluate the
2675 following expression, @code{(buffer-name)}, the name of the buffer
2676 appears in the echo area.  When you evaluate @code{(buffer-file-name)},
2677 the name of the file to which the buffer refers appears in the echo
2678 area.  Usually, the name returned by @code{(buffer-name)} is the same as
2679 the name of the file to which it refers, and the name returned by
2680 @code{(buffer-file-name)} is the full path-name of the file.
2682 A file and a buffer are two different entities.  A file is information
2683 recorded permanently in the computer (unless you delete it).  A buffer,
2684 on the other hand, is information inside of Emacs that will vanish at
2685 the end of the editing session (or when you kill the buffer).  Usually,
2686 a buffer contains information that you have copied from a file; we say
2687 the buffer is @dfn{visiting} that file.  This copy is what you work on
2688 and modify.  Changes to the buffer do not change the file, until you
2689 save the buffer.  When you save the buffer, the buffer is copied to the file
2690 and is thus saved permanently.
2692 @need 1250
2693 If you are reading this in Info inside of GNU Emacs, you can evaluate
2694 each of the following expressions by positioning the cursor after it and
2695 typing @kbd{C-x C-e}.
2697 @smallexample
2698 @group
2699 (buffer-name)
2701 (buffer-file-name)
2702 @end group
2703 @end smallexample
2705 @noindent
2706 When I do this, @file{"introduction.texinfo"} is the value returned by
2707 evaluating @code{(buffer-name)}, and
2708 @file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2709 evaluating @code{(buffer-file-name)}.  The former is the name of the
2710 buffer and the latter is the name of the file.  (In the expressions, the
2711 parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2712 @code{buffer-file-name} as functions; without the parentheses, the
2713 interpreter would attempt to evaluate the symbols as variables.
2714 @xref{Variables}.)
2716 In spite of the distinction between files and buffers, you will often
2717 find that people refer to a file when they mean a buffer and vice-versa.
2718 Indeed, most people say, ``I am editing a file,'' rather than saying,
2719 ``I am editing a buffer which I will soon save to a file.''  It is
2720 almost always clear from context what people mean.  When dealing with
2721 computer programs, however, it is important to keep the distinction in mind,
2722 since the computer is not as smart as a person.
2724 @cindex Buffer, history of word
2725 The word `buffer', by the way, comes from the meaning of the word as a
2726 cushion that deadens the force of a collision.  In early computers, a
2727 buffer cushioned the interaction between files and the computer's
2728 central processing unit.  The drums or tapes that held a file and the
2729 central processing unit were pieces of equipment that were very
2730 different from each other, working at their own speeds, in spurts.  The
2731 buffer made it possible for them to work together effectively.
2732 Eventually, the buffer grew from being an intermediary, a temporary
2733 holding place, to being the place where work is done.  This
2734 transformation is rather like that of a small seaport that grew into a
2735 great city: once it was merely the place where cargo was warehoused
2736 temporarily before being loaded onto ships; then it became a business
2737 and cultural center in its own right.
2739 Not all buffers are associated with files.  For example, when you start
2740 an Emacs session by typing the command @code{emacs} alone, without
2741 naming any files, Emacs will start with the @file{*scratch*} buffer on
2742 the screen.  This buffer is not visiting any file.  Similarly, a
2743 @file{*Help*} buffer is not associated with any file.
2745 @cindex @code{nil}, history of word
2746 If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2747 position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2748 expression, the name @code{"*scratch*"} is returned and will appear in
2749 the echo area.  @code{"*scratch*"} is the name of the buffer.  However,
2750 if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2751 evaluate that, @code{nil} will appear in the echo area.  @code{nil} is
2752 from the Latin word for `nothing'; in this case, it means that the
2753 @file{*scratch*} buffer is not associated with any file.  (In Lisp,
2754 @code{nil} is also used to mean `false' and is a synonym for the empty
2755 list, @code{()}.)
2757 Incidentally, if you are in the @file{*scratch*} buffer and want the
2758 value returned by an expression to appear in the @file{*scratch*}
2759 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2760 instead of @kbd{C-x C-e}.  This causes the value returned to appear
2761 after the expression.  The buffer will look like this:
2763 @smallexample
2764 (buffer-name)"*scratch*"
2765 @end smallexample
2767 @noindent
2768 You cannot do this in Info since Info is read-only and it will not allow
2769 you to change the contents of the buffer.  But you can do this in any
2770 buffer you can edit; and when you write code or documentation (such as
2771 this book), this feature is very useful.
2773 @node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2774 @comment  node-name,  next,  previous,  up
2775 @section Getting Buffers
2776 @findex current-buffer
2777 @findex other-buffer
2778 @cindex Getting a buffer
2780 The @code{buffer-name} function returns the @emph{name} of the buffer;
2781 to get the buffer @emph{itself}, a different function is needed: the
2782 @code{current-buffer} function.  If you use this function in code, what
2783 you get is the buffer itself.
2785 A name and the object or entity to which the name refers are different
2786 from each other.  You are not your name.  You are a person to whom
2787 others refer by name.  If you ask to speak to George and someone hands you
2788 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2789 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2790 not be satisfied.  You do not want to speak to the name, but to the
2791 person to whom the name refers.  A buffer is similar: the name of the
2792 scratch buffer is @file{*scratch*}, but the name is not the buffer.  To
2793 get a buffer itself, you need to use a function such as
2794 @code{current-buffer}.
2796 However, there is a slight complication: if you evaluate
2797 @code{current-buffer} in an expression on its own, as we will do here,
2798 what you see is a printed representation of the name of the buffer
2799 without the contents of the buffer.  Emacs works this way for two
2800 reasons: the buffer may be thousands of lines long---too long to be
2801 conveniently displayed; and, another buffer may have the same contents
2802 but a different name, and it is important to distinguish between them.
2804 @need 800
2805 Here is an expression containing the function:
2807 @smallexample
2808 (current-buffer)
2809 @end smallexample
2811 @noindent
2812 If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2813 appears in the echo area.  The special format indicates that the
2814 buffer itself is being returned, rather than just its name.
2816 Incidentally, while you can type a number or symbol into a program, you
2817 cannot do that with the printed representation of a buffer: the only way
2818 to get a buffer itself is with a function such as @code{current-buffer}.
2820 A related function is @code{other-buffer}.  This returns the most
2821 recently selected buffer other than the one you are in currently.  If
2822 you have recently switched back and forth from the @file{*scratch*}
2823 buffer, @code{other-buffer} will return that buffer.
2825 @need 800
2826 You can see this by evaluating the expression:
2828 @smallexample
2829 (other-buffer)
2830 @end smallexample
2832 @noindent
2833 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2834 the name of whatever other buffer you switched back from most
2835 recently@footnote{Actually, by default, if the buffer from which you
2836 just switched is visible to you in another window, @code{other-buffer}
2837 will choose the most recent buffer that you cannot see; this is a
2838 subtlety that I often forget.}.
2840 @node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2841 @comment  node-name,  next,  previous,  up
2842 @section Switching Buffers
2843 @findex switch-to-buffer
2844 @findex set-buffer
2845 @cindex Switching to a buffer
2847 The @code{other-buffer} function actually provides a buffer when it is
2848 used as an argument to a function that requires one.  We can see this
2849 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2850 different buffer.
2852 But first, a brief introduction to the @code{switch-to-buffer}
2853 function.  When you switched back and forth from Info to the
2854 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2855 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2856 rather, to save typing, you probably typed just part of the name, such
2857 as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2858 expand to the full name; and then typed your @kbd{RET} key.} when
2859 prompted in the minibuffer for the name of the buffer to which you
2860 wanted to switch.  The keystrokes, @kbd{C-x b}, cause the Lisp
2861 interpreter to evaluate the interactive function
2862 @code{switch-to-buffer}.  As we said before, this is how Emacs works:
2863 different keystrokes call or run different functions.  For example,
2864 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2865 @code{forward-sentence}, and so on.
2867 By writing @code{switch-to-buffer} in an expression, and giving it a
2868 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2869 does.
2871 @need 1000
2872 Here is the Lisp expression:
2874 @smallexample
2875 (switch-to-buffer (other-buffer))
2876 @end smallexample
2878 @noindent
2879 The symbol @code{switch-to-buffer} is the first element of the list,
2880 so the Lisp interpreter will treat it as a function and carry out the
2881 instructions that are attached to it.  But before doing that, the
2882 interpreter will note that @code{other-buffer} is inside parentheses
2883 and work on that symbol first.  @code{other-buffer} is the first (and
2884 in this case, the only) element of this list, so the Lisp interpreter
2885 calls or runs the function.  It returns another buffer.  Next, the
2886 interpreter runs @code{switch-to-buffer}, passing to it, as an
2887 argument, the other buffer, which is what Emacs will switch to.  If
2888 you are reading this in Info, try this now.  Evaluate the expression.
2889 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2890 expression will move you to your most recent other buffer that you
2891 cannot see.  If you really want to go to your most recently selected
2892 buffer, even if you can still see it, you need to evaluate the
2893 following more complex expression:
2895 @smallexample
2896 (switch-to-buffer (other-buffer (current-buffer) t))
2897 @end smallexample
2899 @c noindent
2900 In this case, the first argument to @code{other-buffer} tells it which
2901 buffer to skip---the current one---and the second argument tells
2902 @code{other-buffer} it is OK to switch to a visible buffer.
2903 In regular use, @code{switch-to-buffer} takes you to an invisible
2904 window since you would most likely use @kbd{C-x o} (@code{other-window})
2905 to go to another visible buffer.}
2907 In the programming examples in later sections of this document, you will
2908 see the function @code{set-buffer} more often than
2909 @code{switch-to-buffer}.  This is because of a difference between
2910 computer programs and humans: humans have eyes and expect to see the
2911 buffer on which they are working on their computer terminals.  This is
2912 so obvious, it almost goes without saying.  However, programs do not
2913 have eyes.  When a computer program works on a buffer, that buffer does
2914 not need to be visible on the screen.
2916 @code{switch-to-buffer} is designed for humans and does two different
2917 things: it switches the buffer to which Emacs' attention is directed; and
2918 it switches the buffer displayed in the window to the new buffer.
2919 @code{set-buffer}, on the other hand, does only one thing: it switches
2920 the attention of the computer program to a different buffer.  The buffer
2921 on the screen remains unchanged (of course, normally nothing happens
2922 there until the command finishes running).
2924 @cindex @samp{call} defined
2925 Also, we have just introduced another jargon term, the word @dfn{call}.
2926 When you evaluate a list in which the first symbol is a function, you
2927 are calling that function.  The use of the term comes from the notion of
2928 the function as an entity that can do something for you if you `call'
2929 it---just as a plumber is an entity who can fix a leak if you call him
2930 or her.
2932 @node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2933 @comment  node-name,  next,  previous,  up
2934 @section Buffer Size and the Location of Point
2935 @cindex Size of buffer
2936 @cindex Buffer size
2937 @cindex Point location
2938 @cindex Location of point
2940 Finally, let's look at several rather simple functions,
2941 @code{buffer-size}, @code{point}, @code{point-min}, and
2942 @code{point-max}.  These give information about the size of a buffer and
2943 the location of point within it.
2945 The function @code{buffer-size} tells you the size of the current
2946 buffer; that is, the function returns a count of the number of
2947 characters in the buffer.
2949 @smallexample
2950 (buffer-size)
2951 @end smallexample
2953 @noindent
2954 You can evaluate this in the usual way, by positioning the
2955 cursor after the expression and typing @kbd{C-x C-e}.
2957 @cindex @samp{point} defined
2958 In Emacs, the current  position of the cursor is called @dfn{point}.
2959 The expression @code{(point)} returns a number that tells you where the
2960 cursor is located as a count of the number of characters from the
2961 beginning of the buffer up to point.
2963 @need 1250
2964 You can see the character count for point in this buffer by evaluating
2965 the following expression in the usual way:
2967 @smallexample
2968 (point)
2969 @end smallexample
2971 @noindent
2972 As I write this, the value of @code{point} is 65724.  The @code{point}
2973 function is frequently used in some of the examples later in this
2974 book.
2976 @need 1250
2977 The value of point depends, of course, on its location within the
2978 buffer.  If you evaluate point in this spot, the number will be larger:
2980 @smallexample
2981 (point)
2982 @end smallexample
2984 @noindent
2985 For me, the value of point in this location is 66043, which means that
2986 there are 319 characters (including spaces) between the two expressions.
2988 @cindex @samp{narrowing} defined
2989 The function @code{point-min} is somewhat similar to @code{point}, but
2990 it returns the value of the minimum permissible value of point in the
2991 current buffer.  This is the number 1 unless @dfn{narrowing} is in
2992 effect.  (Narrowing is a mechanism whereby you can restrict yourself,
2993 or a program, to operations on just a part of a buffer.
2994 @xref{Narrowing & Widening, , Narrowing and Widening}.)  Likewise, the
2995 function @code{point-max} returns the value of the maximum permissible
2996 value of point in the current buffer.
2998 @node Evaluation Exercise,  , Buffer Size & Locations, Practicing Evaluation
2999 @section Exercise
3001 Find a file with which you are working and move towards its middle.
3002 Find its buffer name, file name, length, and your position in the file.
3004 @node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
3005 @comment  node-name,  next,  previous,  up
3006 @chapter How To Write Function Definitions
3007 @cindex Definition writing
3008 @cindex Function definition writing
3009 @cindex Writing a function definition
3011 When the Lisp interpreter evaluates a list, it looks to see whether the
3012 first symbol on the list has a function definition attached to it; or,
3013 put another way, whether the symbol points to a function definition.  If
3014 it does, the computer carries out the instructions in the definition.  A
3015 symbol that has a function definition is called, simply, a function
3016 (although, properly speaking, the definition is the function and the
3017 symbol refers to it.)
3019 @menu
3020 * Primitive Functions::
3021 * defun::                       The @code{defun} special form.
3022 * Install::                     Install a function definition.
3023 * Interactive::                 Making a function interactive.
3024 * Interactive Options::         Different options for @code{interactive}.
3025 * Permanent Installation::      Installing code permanently.
3026 * let::                         Creating and initializing local variables.
3027 * if::                          What if?
3028 * else::                        If--then--else expressions.
3029 * Truth & Falsehood::           What Lisp considers false and true.
3030 * save-excursion::              Keeping track of point, mark, and buffer.
3031 * Review::
3032 * defun Exercises::
3033 @end menu
3035 @node Primitive Functions, defun, Writing Defuns, Writing Defuns
3036 @ifnottex
3037 @unnumberedsec An Aside about Primitive Functions
3038 @end ifnottex
3039 @cindex Primitive functions
3040 @cindex Functions, primitive
3042 @cindex C language primitives
3043 @cindex Primitives written in C
3044 All functions are defined in terms of other functions, except for a few
3045 @dfn{primitive} functions that are written in the C programming
3046 language.  When you write functions' definitions, you will write them in
3047 Emacs Lisp and use other functions as your building blocks.  Some of the
3048 functions you will use will themselves be written in Emacs Lisp (perhaps
3049 by you) and some will be primitives written in C.  The primitive
3050 functions are used exactly like those written in Emacs Lisp and behave
3051 like them.  They are written in C so we can easily run GNU Emacs on any
3052 computer that has sufficient power and can run C.
3054 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3055 distinguish between the use of functions written in C and the use of
3056 functions written in Emacs Lisp.  The difference is irrelevant.  I
3057 mention the distinction only because it is interesting to know.  Indeed,
3058 unless you investigate, you won't know whether an already-written
3059 function is written in Emacs Lisp or C.
3061 @node defun, Install, Primitive Functions, Writing Defuns
3062 @comment  node-name,  next,  previous,  up
3063 @section The @code{defun} Special Form
3064 @findex defun
3065 @cindex Special form of @code{defun}
3067 @cindex @samp{function definition} defined
3068 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3069 it that tells the computer what to do when the function is called.
3070 This code is called the @dfn{function definition} and is created by
3071 evaluating a Lisp expression that starts with the symbol @code{defun}
3072 (which is an abbreviation for @emph{define function}).  Because
3073 @code{defun} does not evaluate its arguments in the usual way, it is
3074 called a @dfn{special form}.
3076 In subsequent sections, we will look at function definitions from the
3077 Emacs source code, such as @code{mark-whole-buffer}.  In this section,
3078 we will describe a simple function definition so you can see how it
3079 looks.  This function definition uses arithmetic because it makes for a
3080 simple example.  Some people dislike examples using arithmetic; however,
3081 if you are such a person, do not despair.  Hardly any of the code we
3082 will study in the remainder of this introduction involves arithmetic or
3083 mathematics.  The examples mostly involve text in one way or another.
3085 A function definition has up to five parts following the word
3086 @code{defun}:
3088 @enumerate
3089 @item
3090 The name of the symbol to which the function definition should be
3091 attached.
3093 @item
3094 A list of the arguments that will be passed to the function.  If no
3095 arguments will be passed to the function, this is an empty list,
3096 @code{()}.
3098 @item
3099 Documentation describing the function.  (Technically optional, but
3100 strongly recommended.)
3102 @item
3103 Optionally, an expression to make the function interactive so you can
3104 use it by typing @kbd{M-x} and then the name of the function; or by
3105 typing an appropriate key or keychord.
3107 @cindex @samp{body} defined
3108 @item
3109 The code that instructs the computer what to do: the @dfn{body} of the
3110 function definition.
3111 @end enumerate
3113 It is helpful to think of the five parts of a function definition as
3114 being organized in a template, with slots for each part:
3116 @smallexample
3117 @group
3118 (defun @var{function-name} (@var{arguments}@dots{})
3119   "@var{optional-documentation}@dots{}"
3120   (interactive @var{argument-passing-info})     ; @r{optional}
3121   @var{body}@dots{})
3122 @end group
3123 @end smallexample
3125 As an example, here is the code for a function that multiplies its
3126 argument by 7.  (This example is not interactive.  @xref{Interactive,
3127 , Making a Function Interactive}, for that information.)
3129 @smallexample
3130 @group
3131 (defun multiply-by-seven (number)
3132   "Multiply NUMBER by seven."
3133   (* 7 number))
3134 @end group
3135 @end smallexample
3137 This definition begins with a parenthesis and the symbol @code{defun},
3138 followed by the name of the function.
3140 @cindex @samp{argument list} defined
3141 The name of the function is followed by a list that contains the
3142 arguments that will be passed to the function.  This list is called
3143 the @dfn{argument list}.  In this example, the list has only one
3144 element, the symbol, @code{number}.  When the function is used, the
3145 symbol will be bound to the value that is used as the argument to the
3146 function.
3148 Instead of choosing the word @code{number} for the name of the argument,
3149 I could have picked any other name.  For example, I could have chosen
3150 the word @code{multiplicand}.  I picked the word `number' because it
3151 tells what kind of value is intended for this slot; but I could just as
3152 well have chosen the word `multiplicand' to indicate the role that the
3153 value placed in this slot will play in the workings of the function.  I
3154 could have called it @code{foogle}, but that would have been a bad
3155 choice because it would not tell humans what it means.  The choice of
3156 name is up to the programmer and should be chosen to make the meaning of
3157 the function clear.
3159 Indeed, you can choose any name you wish for a symbol in an argument
3160 list, even the name of a symbol used in some other function: the name
3161 you use in an argument list is private to that particular definition.
3162 In that definition, the name refers to a different entity than any use
3163 of the same name outside the function definition.  Suppose you have a
3164 nick-name `Shorty' in your family; when your family members refer to
3165 `Shorty', they mean you.  But outside your family, in a movie, for
3166 example, the name `Shorty' refers to someone else.  Because a name in an
3167 argument list is private to the function definition, you can change the
3168 value of such a symbol inside the body of a function without changing
3169 its value outside the function.  The effect is similar to that produced
3170 by a @code{let} expression.  (@xref{let, , @code{let}}.)
3172 @ignore
3173 Note also that we discuss the word `number' in two different ways: as a
3174 symbol that appears in the code, and as the name of something that will
3175 be replaced by a something else during the evaluation of the function.
3176 In the first case, @code{number} is a symbol, not a number; it happens
3177 that within the function, it is a variable who value is the number in
3178 question, but our primary interest in it is as a symbol.  On the other
3179 hand, when we are talking about the function, our interest is that we
3180 will substitute a number for the word @var{number}.  To keep this
3181 distinction clear, we use different typography for the two
3182 circumstances.  When we talk about this function, or about how it works,
3183 we refer to this number by writing @var{number}.  In the function
3184 itself, we refer to it by writing @code{number}.
3185 @end ignore
3187 The argument list is followed by the documentation string that
3188 describes the function.  This is what you see when you type
3189 @w{@kbd{C-h f}} and the name of a function.  Incidentally, when you
3190 write a documentation string like this, you should make the first line
3191 a complete sentence since some commands, such as @code{apropos}, print
3192 only the first line of a multi-line documentation string.  Also, you
3193 should not indent the second line of a documentation string, if you
3194 have one, because that looks odd when you use @kbd{C-h f}
3195 (@code{describe-function}).  The documentation string is optional, but
3196 it is so useful, it should be included in almost every function you
3197 write.
3199 @findex * @r{(multiplication)}
3200 The third line of the example consists of the body of the function
3201 definition.  (Most functions' definitions, of course, are longer than
3202 this.)  In this function, the body is the list, @code{(* 7 number)}, which
3203 says to multiply the value of @var{number} by 7.  (In Emacs Lisp,
3204 @code{*} is the function for multiplication, just as @code{+} is the
3205 function for addition.)
3207 When you use the @code{multiply-by-seven} function, the argument
3208 @code{number} evaluates to the actual number you want used.  Here is an
3209 example that shows how @code{multiply-by-seven} is used; but don't try
3210 to evaluate this yet!
3212 @smallexample
3213 (multiply-by-seven 3)
3214 @end smallexample
3216 @noindent
3217 The symbol @code{number}, specified in the function definition in the
3218 next section, is given or ``bound to'' the value 3 in the actual use of
3219 the function.  Note that although @code{number} was inside parentheses
3220 in the function definition, the argument passed to the
3221 @code{multiply-by-seven} function is not in parentheses.  The
3222 parentheses are written in the function definition so the computer can
3223 figure out where the argument list ends and the rest of the function
3224 definition begins.
3226 If you evaluate this example, you are likely to get an error message.
3227 (Go ahead, try it!)  This is because we have written the function
3228 definition, but not yet told the computer about the definition---we have
3229 not yet installed (or `loaded') the function definition in Emacs.
3230 Installing a function is the process that tells the Lisp interpreter the
3231 definition of the function.  Installation is described in the next
3232 section.
3234 @node Install, Interactive, defun, Writing Defuns
3235 @comment  node-name,  next,  previous,  up
3236 @section Install a Function Definition
3237 @cindex Install a Function Definition
3238 @cindex Definition installation
3239 @cindex Function definition installation
3241 If you are reading this inside of Info in Emacs, you can try out the
3242 @code{multiply-by-seven} function by first evaluating the function
3243 definition and then evaluating @code{(multiply-by-seven 3)}.  A copy of
3244 the function definition follows.  Place the cursor after the last
3245 parenthesis of the function definition and type @kbd{C-x C-e}.  When you
3246 do this, @code{multiply-by-seven} will appear in the echo area.  (What
3247 this means is that when a function definition is evaluated, the value it
3248 returns is the name of the defined function.)  At the same time, this
3249 action installs the function definition.
3251 @smallexample
3252 @group
3253 (defun multiply-by-seven (number)
3254   "Multiply NUMBER by seven."
3255   (* 7 number))
3256 @end group
3257 @end smallexample
3259 @noindent
3260 By evaluating this @code{defun}, you have just installed
3261 @code{multiply-by-seven} in Emacs.  The function is now just as much a
3262 part of Emacs as @code{forward-word} or any other editing function you
3263 use.  (@code{multiply-by-seven} will stay installed until you quit
3264 Emacs.  To reload code automatically whenever you start Emacs, see
3265 @ref{Permanent Installation, , Installing Code Permanently}.)
3268 @menu
3269 * Effect of installation::
3270 * Change a defun::              How to change a function definition.
3271 @end menu
3273 @node Effect of installation, Change a defun, Install, Install
3274 @ifnottex
3275 @unnumberedsubsec The effect of installation
3276 @end ifnottex
3279 You can see the effect of installing @code{multiply-by-seven} by
3280 evaluating the following sample.  Place the cursor after the following
3281 expression and type @kbd{C-x C-e}.  The number 21 will appear in the
3282 echo area.
3284 @smallexample
3285 (multiply-by-seven 3)
3286 @end smallexample
3288 If you wish, you can read the documentation for the function by typing
3289 @kbd{C-h f} (@code{describe-function}) and then the name of the
3290 function, @code{multiply-by-seven}.  When you do this, a
3291 @file{*Help*} window will appear on your screen that says:
3293 @smallexample
3294 @group
3295 multiply-by-seven:
3296 Multiply NUMBER by seven.
3297 @end group
3298 @end smallexample
3300 @noindent
3301 (To return to a single window on your screen, type @kbd{C-x 1}.)
3303 @node Change a defun,  , Effect of installation, Install
3304 @comment  node-name,  next,  previous,  up
3305 @subsection Change a Function Definition
3306 @cindex Changing a function definition
3307 @cindex Function definition, how to change
3308 @cindex Definition, how to change
3310 If you want to change the code in @code{multiply-by-seven}, just rewrite
3311 it.  To install the new version in place of the old one, evaluate the
3312 function definition again.  This is how you modify code in Emacs.  It is
3313 very simple.
3315 As an example, you can change the @code{multiply-by-seven} function to
3316 add the number to itself seven times instead of multiplying the number
3317 by seven.  It produces the same answer, but by a different path.  At
3318 the same time, we will add a comment to the code; a comment is text
3319 that the Lisp interpreter ignores, but that a human reader may find
3320 useful or enlightening.  The comment is that this is the ``second
3321 version''.
3323 @smallexample
3324 @group
3325 (defun multiply-by-seven (number)       ; @r{Second version.}
3326   "Multiply NUMBER by seven."
3327   (+ number number number number number number number))
3328 @end group
3329 @end smallexample
3331 @cindex Comments in Lisp code
3332 The comment follows a semicolon, @samp{;}.  In Lisp, everything on a
3333 line that follows a semicolon is a comment.  The end of the line is the
3334 end of the comment.  To stretch a comment over two or more lines, begin
3335 each line with a semicolon.
3337 @xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3338 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3339 Reference Manual}, for more about comments.
3341 You can install this version of the @code{multiply-by-seven} function by
3342 evaluating it in the same way you evaluated the first function: place
3343 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3345 In summary, this is how you write code in Emacs Lisp: you write a
3346 function; install it; test it; and then make fixes or enhancements and
3347 install it again.
3349 @node Interactive, Interactive Options, Install, Writing Defuns
3350 @comment  node-name,  next,  previous,  up
3351 @section Make a Function Interactive
3352 @cindex Interactive functions
3353 @findex interactive
3355 You make a function interactive by placing a list that begins with
3356 the special form @code{interactive} immediately after the
3357 documentation.  A user can invoke an interactive function by typing
3358 @kbd{M-x} and then the name of the function; or by typing the keys to
3359 which it is bound, for example, by typing @kbd{C-n} for
3360 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3362 Interestingly, when you call an interactive function interactively,
3363 the value returned is not automatically displayed in the echo area.
3364 This is because you often call an interactive function for its side
3365 effects, such as moving forward by a word or line, and not for the
3366 value returned.  If the returned value were displayed in the echo area
3367 each time you typed a key, it would be very distracting.
3369 @menu
3370 * Interactive multiply-by-seven::  An overview.
3371 * multiply-by-seven in detail::  The interactive version.
3372 @end menu
3374 @node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3375 @ifnottex
3376 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3377 @end ifnottex
3379 Both the use of the special form @code{interactive} and one way to
3380 display a value in the echo area can be illustrated by creating an
3381 interactive version of @code{multiply-by-seven}.
3383 @need 1250
3384 Here is the code:
3386 @smallexample
3387 @group
3388 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3389   "Multiply NUMBER by seven."
3390   (interactive "p")
3391   (message "The result is %d" (* 7 number)))
3392 @end group
3393 @end smallexample
3395 @noindent
3396 You can install this code by placing your cursor after it and typing
3397 @kbd{C-x C-e}.  The name of the function will appear in your echo area.
3398 Then, you can use this code by typing @kbd{C-u} and a number and then
3399 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}.  The phrase
3400 @samp{The result is @dots{}} followed by the product will appear in the
3401 echo area.
3403 Speaking more generally, you invoke a function like this in either of two
3404 ways:
3406 @enumerate
3407 @item
3408 By typing a prefix argument that contains the number to be passed, and
3409 then typing @kbd{M-x} and the name of the function, as with
3410 @kbd{C-u 3 M-x forward-sentence}; or,
3412 @item
3413 By typing whatever key or keychord the function is bound to, as with
3414 @kbd{C-u 3 M-e}.
3415 @end enumerate
3417 @noindent
3418 Both the examples just mentioned work identically to move point forward
3419 three sentences.  (Since @code{multiply-by-seven} is not bound to a key,
3420 it could not be used as an example of key binding.)
3422 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3423 to a key.)
3425 A prefix argument is passed to an interactive function by typing the
3426 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3427 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3428 type @kbd{C-u} without a number, it defaults to 4).
3430 @node multiply-by-seven in detail,  , Interactive multiply-by-seven, Interactive
3431 @comment  node-name,  next,  previous,  up
3432 @subsection An Interactive @code{multiply-by-seven}
3434 Let's look at the use of the special form @code{interactive} and then at
3435 the function @code{message} in the interactive version of
3436 @code{multiply-by-seven}.  You will recall that the function definition
3437 looks like this:
3439 @smallexample
3440 @group
3441 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3442   "Multiply NUMBER by seven."
3443   (interactive "p")
3444   (message "The result is %d" (* 7 number)))
3445 @end group
3446 @end smallexample
3448 In this function, the expression, @code{(interactive "p")}, is a list of
3449 two elements.  The @code{"p"} tells Emacs to pass the prefix argument to
3450 the function and use its value for the argument of the function.
3452 @need 1000
3453 The argument will be a number.  This means that the symbol
3454 @code{number} will be bound to a number in the line:
3456 @smallexample
3457 (message "The result is %d" (* 7 number))
3458 @end smallexample
3460 @need 1250
3461 @noindent
3462 For example, if your prefix argument is 5, the Lisp interpreter will
3463 evaluate the line as if it were:
3465 @smallexample
3466 (message "The result is %d" (* 7 5))
3467 @end smallexample
3469 @noindent
3470 (If you are reading this in GNU Emacs, you can evaluate this expression
3471 yourself.)  First, the interpreter will evaluate the inner list, which
3472 is @code{(* 7 5)}.  This returns a value of 35.  Next, it
3473 will evaluate the outer list, passing the values of the second and
3474 subsequent elements of the list to the function @code{message}.
3476 As we have seen, @code{message} is an Emacs Lisp function especially
3477 designed for sending a one line message to a user.  (@xref{message, , The
3478 @code{message} function}.)
3479 In summary, the @code{message} function prints its first argument in the
3480 echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3481 @samp{%c}.  When it sees one of these control sequences, the function
3482 looks to the second and subsequent arguments and prints the value of the
3483 argument in the location in the string where the control sequence is
3484 located.
3486 In the interactive @code{multiply-by-seven} function, the control string
3487 is @samp{%d}, which requires a number, and the value returned by
3488 evaluating @code{(* 7 5)} is the number 35.  Consequently, the number 35
3489 is printed in place of the @samp{%d} and the message is @samp{The result
3490 is 35}.
3492 (Note that when you call the function @code{multiply-by-seven}, the
3493 message is printed without quotes, but when you call @code{message}, the
3494 text is printed in double quotes.  This is because the value returned by
3495 @code{message} is what appears in the echo area when you evaluate an
3496 expression whose first element is @code{message}; but when embedded in a
3497 function, @code{message} prints the text as a side effect without
3498 quotes.)
3500 @node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3501 @comment  node-name,  next,  previous,  up
3502 @section Different Options for @code{interactive}
3503 @cindex Options for @code{interactive}
3504 @cindex Interactive options
3506 In the example, @code{multiply-by-seven} used @code{"p"} as the
3507 argument to @code{interactive}.  This argument told Emacs to interpret
3508 your typing either @kbd{C-u} followed by a number or @key{META}
3509 followed by a number as a command to pass that number to the function
3510 as its argument.  Emacs has more than twenty characters predefined for
3511 use with @code{interactive}.  In almost every case, one of these
3512 options will enable you to pass the right information interactively to
3513 a function.  (@xref{Interactive Codes, , Code Characters for
3514 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3516 @need 1250
3517 For example, the character @samp{r} causes Emacs to pass the beginning
3518 and end of the region (the current values of point and mark) to the
3519 function as two separate arguments.  It is used as follows:
3521 @smallexample
3522 (interactive "r")
3523 @end smallexample
3525 On the other hand, a @samp{B} tells Emacs to ask for the name of a
3526 buffer that will be passed to the function.  When it sees a @samp{B},
3527 Emacs will ask for the name by prompting the user in the minibuffer,
3528 using a string that follows the @samp{B}, as in @code{"BAppend to
3529 buffer:@: "}.  Not only will Emacs prompt for the name, but Emacs will
3530 complete the name if you type enough of it and press @key{TAB}.
3532 A function with two or more arguments can have information passed to
3533 each argument by adding parts to the string that follows
3534 @code{interactive}.  When you do this, the information is passed to
3535 each argument in the same order it is specified in the
3536 @code{interactive} list.  In the string, each part is separated from
3537 the next part by a @samp{\n}, which is a newline.  For example, you
3538 could follow @code{"BAppend to buffer:@: "} with a @samp{\n}) and an
3539 @samp{r}.  This would cause Emacs to pass the values of point and mark
3540 to the function as well as prompt you for the buffer---three arguments
3541 in all.
3543 In this case, the function definition would look like the following,
3544 where @code{buffer}, @code{start}, and @code{end} are the symbols to
3545 which @code{interactive} binds the buffer and the current values of the
3546 beginning and ending of the region:
3548 @smallexample
3549 @group
3550 (defun @var{name-of-function} (buffer start end)
3551   "@var{documentation}@dots{}"
3552   (interactive "BAppend to buffer:@: \nr")
3553   @var{body-of-function}@dots{})
3554 @end group
3555 @end smallexample
3557 @noindent
3558 (The space after the colon in the prompt makes it look better when you
3559 are prompted.  The @code{append-to-buffer} function looks exactly like
3560 this.  @xref{append-to-buffer, , The Definition of
3561 @code{append-to-buffer}}.)
3563 If a function does not have arguments, then @code{interactive} does not
3564 require any.  Such a function contains the simple expression
3565 @code{(interactive)}.  The @code{mark-whole-buffer} function is like
3566 this.
3568 Alternatively, if the special letter-codes are not right for your
3569 application, you can pass your own arguments to @code{interactive} as
3570 a list.  @xref{interactive, , Using @code{Interactive}, elisp, The
3571 GNU Emacs Lisp Reference Manual}, for more information about this advanced
3572 technique.
3574 @node Permanent Installation, let, Interactive Options, Writing Defuns
3575 @comment  node-name,  next,  previous,  up
3576 @section Install Code Permanently
3577 @cindex Install code permanently
3578 @cindex Permanent code installation
3579 @cindex Code installation
3581 When you install a function definition by evaluating it, it will stay
3582 installed until you quit Emacs.  The next time you start a new session
3583 of Emacs, the function will not be installed unless you evaluate the
3584 function definition again.
3586 At some point, you may want to have code installed automatically
3587 whenever you start a new session of Emacs.  There are several ways of
3588 doing this:
3590 @itemize @bullet
3591 @item
3592 If you have code that is just for yourself, you can put the code for the
3593 function definition in your @file{.emacs} initialization file.  When you
3594 start Emacs, your @file{.emacs} file is automatically evaluated and all
3595 the function definitions within it are installed.
3596 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3598 @item
3599 Alternatively, you can put the function definitions that you want
3600 installed in one or more files of their own and use the @code{load}
3601 function to cause Emacs to evaluate and thereby install each of the
3602 functions in the files.
3603 @xref{Loading Files, , Loading Files}.
3605 @item
3606 On the other hand, if you have code that your whole site will use, it
3607 is usual to put it in a file called @file{site-init.el} that is loaded
3608 when Emacs is built.  This makes the code available to everyone who
3609 uses your machine.  (See the @file{INSTALL} file that is part of the
3610 Emacs distribution.)
3611 @end itemize
3613 Finally, if you have code that everyone who uses Emacs may want, you
3614 can post it on a computer network or send a copy to the Free Software
3615 Foundation.  (When you do this, please license the code and its
3616 documentation under a license that permits other people to run, copy,
3617 study, modify, and redistribute the code and which protects you from
3618 having your work taken from you.)  If you send a copy of your code to
3619 the Free Software Foundation, and properly protect yourself and
3620 others, it may be included in the next release of Emacs.  In large
3621 part, this is how Emacs has grown over the past years, by donations.
3623 @node let, if, Permanent Installation, Writing Defuns
3624 @comment  node-name,  next,  previous,  up
3625 @section @code{let}
3626 @findex let
3628 The @code{let} expression is a special form in Lisp that you will need
3629 to use in most function definitions.
3631 @code{let} is used to attach or bind a symbol to a value in such a way
3632 that the Lisp interpreter will not confuse the variable with a
3633 variable of the same name that is not part of the function.
3635 To understand why the @code{let} special form is necessary, consider
3636 the situation in which you own a home that you generally refer to as
3637 `the house', as in the sentence, ``The house needs painting.''  If you
3638 are visiting a friend and your host refers to `the house', he is
3639 likely to be referring to @emph{his} house, not yours, that is, to a
3640 different house.
3642 If your friend is referring to his house and you think he is referring
3643 to your house, you may be in for some confusion.  The same thing could
3644 happen in Lisp if a variable that is used inside of one function has
3645 the same name as a variable that is used inside of another function,
3646 and the two are not intended to refer to the same value.  The
3647 @code{let} special form prevents this kind of confusion.
3649 @menu
3650 * Prevent confusion::
3651 * Parts of let Expression::
3652 * Sample let Expression::
3653 * Uninitialized let Variables::
3654 @end menu
3656 @node Prevent confusion, Parts of let Expression, let, let
3657 @ifnottex
3658 @unnumberedsubsec @code{let} Prevents Confusion
3659 @end ifnottex
3661 @cindex @samp{local variable} defined
3662 The @code{let} special form prevents confusion.  @code{let} creates a
3663 name for a @dfn{local variable} that overshadows any use of the same
3664 name outside the @code{let} expression.  This is like understanding
3665 that whenever your host refers to `the house', he means his house, not
3666 yours.  (Symbols used in argument lists work the same way.
3667 @xref{defun, , The @code{defun} Special Form}.)
3669 Local variables created by a @code{let} expression retain their value
3670 @emph{only} within the @code{let} expression itself (and within
3671 expressions called within the @code{let} expression); the local
3672 variables have no effect outside the @code{let} expression.
3674 Another way to think about @code{let} is that it is like a @code{setq}
3675 that is temporary and local.  The values set by @code{let} are
3676 automatically undone when the @code{let} is finished.  The setting
3677 only affects expressions that are inside the bounds of the @code{let}
3678 expression.  In computer science jargon, we would say ``the binding of
3679 a symbol is visible only in functions called in the @code{let} form;
3680 in Emacs Lisp, scoping is dynamic, not lexical.''
3682 @code{let} can create more than one variable at once.  Also,
3683 @code{let} gives each variable it creates an initial value, either a
3684 value specified by you, or @code{nil}.  (In the jargon, this is called
3685 `binding the variable to the value'.)  After @code{let} has created
3686 and bound the variables, it executes the code in the body of the
3687 @code{let}, and returns the value of the last expression in the body,
3688 as the value of the whole @code{let} expression.  (`Execute' is a jargon
3689 term that means to evaluate a list; it comes from the use of the word
3690 meaning `to give practical effect to' (@cite{Oxford English
3691 Dictionary}).  Since you evaluate an expression to perform an action,
3692 `execute' has evolved as a synonym to `evaluate'.)
3694 @node Parts of let Expression, Sample let Expression, Prevent confusion, let
3695 @comment  node-name,  next,  previous,  up
3696 @subsection The Parts of a @code{let} Expression
3697 @cindex @code{let} expression, parts of
3698 @cindex Parts of @code{let} expression
3700 @cindex @samp{varlist} defined
3701 A @code{let} expression is a list of three parts.  The first part is
3702 the symbol @code{let}.  The second part is a list, called a
3703 @dfn{varlist}, each element of which is either a symbol by itself or a
3704 two-element list, the first element of which is a symbol.  The third
3705 part of the @code{let} expression is the body of the @code{let}.  The
3706 body usually consists of one or more lists.
3708 @need 800
3709 A template for a @code{let} expression looks like this:
3711 @smallexample
3712 (let @var{varlist} @var{body}@dots{})
3713 @end smallexample
3715 @noindent
3716 The symbols in the varlist are the variables that are given initial
3717 values by the @code{let} special form.  Symbols by themselves are given
3718 the initial value of @code{nil}; and each symbol that is the first
3719 element of a two-element list is bound to the value that is returned
3720 when the Lisp interpreter evaluates the second element.
3722 Thus, a varlist might look like this: @code{(thread (needles 3))}.  In
3723 this case, in a @code{let} expression, Emacs binds the symbol
3724 @code{thread} to an initial value of @code{nil}, and binds the symbol
3725 @code{needles} to an initial value of 3.
3727 When you write a @code{let} expression, what you do is put the
3728 appropriate expressions in the slots of the @code{let} expression
3729 template.
3731 If the varlist is composed of two-element lists, as is often the case,
3732 the template for the @code{let} expression looks like this:
3734 @smallexample
3735 @group
3736 (let ((@var{variable} @var{value})
3737       (@var{variable} @var{value})
3738       @dots{})
3739   @var{body}@dots{})
3740 @end group
3741 @end smallexample
3743 @node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3744 @comment  node-name,  next,  previous,  up
3745 @subsection Sample @code{let} Expression
3746 @cindex Sample @code{let} expression
3747 @cindex @code{let} expression sample
3749 The following expression creates and gives initial values
3750 to the two variables @code{zebra} and @code{tiger}.  The body of the
3751 @code{let} expression is a list which calls the @code{message} function.
3753 @smallexample
3754 @group
3755 (let ((zebra 'stripes)
3756       (tiger 'fierce))
3757   (message "One kind of animal has %s and another is %s."
3758            zebra tiger))
3759 @end group
3760 @end smallexample
3762 Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3764 The two variables are @code{zebra} and @code{tiger}.  Each variable is
3765 the first element of a two-element list and each value is the second
3766 element of its two-element list.  In the varlist, Emacs binds the
3767 variable @code{zebra} to the value @code{stripes}, and binds the
3768 variable @code{tiger} to the value @code{fierce}.  In this example,
3769 both values are symbols preceded by a quote.  The values could just as
3770 well have been another list or a string.  The body of the @code{let}
3771 follows after the list holding the variables.  In this example, the body
3772 is a list that uses the @code{message} function to print a string in
3773 the echo area.
3775 @need 1500
3776 You may evaluate the example in the usual fashion, by placing the
3777 cursor after the last parenthesis and typing @kbd{C-x C-e}.  When you do
3778 this, the following will appear in the echo area:
3780 @smallexample
3781 "One kind of animal has stripes and another is fierce."
3782 @end smallexample
3784 As we have seen before, the @code{message} function prints its first
3785 argument, except for @samp{%s}.  In this example, the value of the variable
3786 @code{zebra} is printed at the location of the first @samp{%s} and the
3787 value of the variable @code{tiger} is printed at the location of the
3788 second @samp{%s}.
3790 @node Uninitialized let Variables,  , Sample let Expression, let
3791 @comment  node-name,  next,  previous,  up
3792 @subsection Uninitialized Variables in a @code{let} Statement
3793 @cindex Uninitialized @code{let} variables
3794 @cindex @code{let} variables uninitialized
3796 If you do not bind the variables in a @code{let} statement to specific
3797 initial values, they will automatically be bound to an initial value of
3798 @code{nil}, as in the following expression:
3800 @smallexample
3801 @group
3802 (let ((birch 3)
3803       pine
3804       fir
3805       (oak 'some))
3806   (message
3807    "Here are %d variables with %s, %s, and %s value."
3808    birch pine fir oak))
3809 @end group
3810 @end smallexample
3812 @noindent
3813 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3815 @need 1250
3816 If you evaluate this expression in the usual way, the following will
3817 appear in your echo area:
3819 @smallexample
3820 "Here are 3 variables with nil, nil, and some value."
3821 @end smallexample
3823 @noindent
3824 In this example, Emacs binds the symbol @code{birch} to the number 3,
3825 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3826 the symbol @code{oak} to the value @code{some}.
3828 Note that in the first part of the @code{let}, the variables @code{pine}
3829 and @code{fir} stand alone as atoms that are not surrounded by
3830 parentheses; this is because they are being bound to @code{nil}, the
3831 empty list.  But @code{oak} is bound to @code{some} and so is a part of
3832 the list @code{(oak 'some)}.  Similarly, @code{birch} is bound to the
3833 number 3 and so is in a list with that number.  (Since a number
3834 evaluates to itself, the number does not need to be quoted.  Also, the
3835 number is printed in the message using a @samp{%d} rather than a
3836 @samp{%s}.)  The four variables as a group are put into a list to
3837 delimit them from the body of the @code{let}.
3839 @node if, else, let, Writing Defuns
3840 @comment  node-name,  next,  previous,  up
3841 @section The @code{if} Special Form
3842 @findex if
3843 @cindex Conditional with @code{if}
3845 A third special form, in addition to @code{defun} and @code{let}, is the
3846 conditional @code{if}.  This form is used to instruct the computer to
3847 make decisions.  You can write function definitions without using
3848 @code{if}, but it is used often enough, and is important enough, to be
3849 included here.  It is used, for example, in the code for the
3850 function @code{beginning-of-buffer}.
3852 The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3853 @emph{then} an expression is evaluated.''  If the test is not true, the
3854 expression is not evaluated.  For example, you might make a decision
3855 such as, ``if it is warm and sunny, then go to the beach!''
3857 @menu
3858 * if in more detail::
3859 * type-of-animal in detail::    An example of an @code{if} expression.
3860 @end menu
3862 @node if in more detail, type-of-animal in detail, if, if
3863 @ifnottex
3864 @unnumberedsubsec @code{if} in more detail
3865 @end ifnottex
3867 @cindex @samp{if-part} defined
3868 @cindex @samp{then-part} defined
3869 An @code{if} expression written in Lisp does not use the word `then';
3870 the test and the action are the second and third elements of the list
3871 whose first element is @code{if}.  Nonetheless, the test part of an
3872 @code{if} expression is often called the @dfn{if-part} and the second
3873 argument is often called the @dfn{then-part}.
3875 Also, when an @code{if} expression is written, the true-or-false-test
3876 is usually written on the same line as the symbol @code{if}, but the
3877 action to carry out if the test is true, the ``then-part'', is written
3878 on the second and subsequent lines.  This makes the @code{if}
3879 expression easier to read.
3881 @smallexample
3882 @group
3883 (if @var{true-or-false-test}
3884     @var{action-to-carry-out-if-test-is-true})
3885 @end group
3886 @end smallexample
3888 @noindent
3889 The true-or-false-test will be an expression that
3890 is evaluated by the Lisp interpreter.
3892 Here is an example that you can evaluate in the usual manner.  The test
3893 is whether the number 5 is greater than the number 4.  Since it is, the
3894 message @samp{5 is greater than 4!} will be printed.
3896 @smallexample
3897 @group
3898 (if (> 5 4)                             ; @r{if-part}
3899     (message "5 is greater than 4!"))   ; @r{then-part}
3900 @end group
3901 @end smallexample
3903 @noindent
3904 (The function @code{>} tests whether its first argument is greater than
3905 its second argument and returns true if it is.)
3906 @findex > (greater than)
3908 Of course, in actual use, the test in an @code{if} expression will not
3909 be fixed for all time as it is by the expression @code{(> 5 4)}.
3910 Instead, at least one of the variables used in the test will be bound to
3911 a value that is not known ahead of time.  (If the value were known ahead
3912 of time, we would not need to run the test!)
3914 For example, the value may be bound to an argument of a function
3915 definition.  In the following function definition, the character of the
3916 animal is a value that is passed to the function.  If the value bound to
3917 @code{characteristic} is @code{fierce}, then the message, @samp{It's a
3918 tiger!} will be printed; otherwise, @code{nil} will be returned.
3920 @smallexample
3921 @group
3922 (defun type-of-animal (characteristic)
3923   "Print message in echo area depending on CHARACTERISTIC.
3924 If the CHARACTERISTIC is the symbol `fierce',
3925 then warn of a tiger."
3926   (if (equal characteristic 'fierce)
3927       (message "It's a tiger!")))
3928 @end group
3929 @end smallexample
3931 @need 1500
3932 @noindent
3933 If you are reading this inside of GNU Emacs, you can evaluate the
3934 function definition in the usual way to install it in Emacs, and then you
3935 can evaluate the following two expressions to see the results:
3937 @smallexample
3938 @group
3939 (type-of-animal 'fierce)
3941 (type-of-animal 'zebra)
3943 @end group
3944 @end smallexample
3946 @c Following sentences rewritten to prevent overfull hbox.
3947 @noindent
3948 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3949 following message printed in the echo area: @code{"It's a tiger!"}; and
3950 when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3951 printed in the echo area.
3953 @node type-of-animal in detail,  , if in more detail, if
3954 @comment  node-name,  next,  previous,  up
3955 @subsection The @code{type-of-animal} Function in Detail
3957 Let's look at the @code{type-of-animal} function in detail.
3959 The function definition for @code{type-of-animal} was written by filling
3960 the slots of two templates, one for a function definition as a whole, and
3961 a second for an @code{if} expression.
3963 @need 1250
3964 The template for every function that is not interactive is:
3966 @smallexample
3967 @group
3968 (defun @var{name-of-function} (@var{argument-list})
3969   "@var{documentation}@dots{}"
3970   @var{body}@dots{})
3971 @end group
3972 @end smallexample
3974 @need 800
3975 The parts of the function that match this template look like this:
3977 @smallexample
3978 @group
3979 (defun type-of-animal (characteristic)
3980   "Print message in echo area depending on CHARACTERISTIC.
3981 If the CHARACTERISTIC is the symbol `fierce',
3982 then warn of a tiger."
3983   @var{body: the} @code{if} @var{expression})
3984 @end group
3985 @end smallexample
3987 The name of function is @code{type-of-animal}; it is passed the value
3988 of one argument.  The argument list is followed by a multi-line
3989 documentation string.  The documentation string is included in the
3990 example because it is a good habit to write documentation string for
3991 every function definition.  The body of the function definition
3992 consists of the @code{if} expression.
3994 @need 800
3995 The template for an @code{if} expression looks like this:
3997 @smallexample
3998 @group
3999 (if @var{true-or-false-test}
4000     @var{action-to-carry-out-if-the-test-returns-true})
4001 @end group
4002 @end smallexample
4004 @need 1250
4005 In the @code{type-of-animal} function, the code for the @code{if}
4006 looks like this:
4008 @smallexample
4009 @group
4010 (if (equal characteristic 'fierce)
4011     (message "It's a tiger!")))
4012 @end group
4013 @end smallexample
4015 @need 800
4016 Here, the true-or-false-test is the expression:
4018 @smallexample
4019 (equal characteristic 'fierce)
4020 @end smallexample
4022 @noindent
4023 In Lisp, @code{equal} is a function that determines whether its first
4024 argument is equal to its second argument.  The second argument is the
4025 quoted symbol @code{'fierce} and the first argument is the value of the
4026 symbol @code{characteristic}---in other words, the argument passed to
4027 this function.
4029 In the first exercise of @code{type-of-animal}, the argument
4030 @code{fierce} is passed to @code{type-of-animal}.  Since @code{fierce}
4031 is equal to @code{fierce}, the expression, @code{(equal characteristic
4032 'fierce)}, returns a value of true.  When this happens, the @code{if}
4033 evaluates the second argument or then-part of the @code{if}:
4034 @code{(message "It's tiger!")}.
4036 On the other hand, in the second exercise of @code{type-of-animal}, the
4037 argument @code{zebra} is passed to @code{type-of-animal}.  @code{zebra}
4038 is not equal to @code{fierce}, so the then-part is not evaluated and
4039 @code{nil} is returned by the @code{if} expression.
4041 @node else, Truth & Falsehood, if, Writing Defuns
4042 @comment  node-name,  next,  previous,  up
4043 @section If--then--else Expressions
4044 @cindex Else
4046 An @code{if} expression may have an optional third argument, called
4047 the @dfn{else-part}, for the case when the true-or-false-test returns
4048 false.  When this happens, the second argument or then-part of the
4049 overall @code{if} expression is @emph{not} evaluated, but the third or
4050 else-part @emph{is} evaluated.  You might think of this as the cloudy
4051 day alternative for the decision `if it is warm and sunny, then go to
4052 the beach, else read a book!''.
4054 The word ``else'' is not written in the Lisp code; the else-part of an
4055 @code{if} expression comes after the then-part.  In the written Lisp, the
4056 else-part is usually written to start on a line of its own and is
4057 indented less than the then-part:
4059 @smallexample
4060 @group
4061 (if @var{true-or-false-test}
4062     @var{action-to-carry-out-if-the-test-returns-true}
4063   @var{action-to-carry-out-if-the-test-returns-false})
4064 @end group
4065 @end smallexample
4067 For example, the following @code{if} expression prints the message @samp{4
4068 is not greater than 5!} when you evaluate it in the usual way:
4070 @smallexample
4071 @group
4072 (if (> 4 5)                             ; @r{if-part}
4073     (message "5 is greater than 4!")    ; @r{then-part}
4074   (message "4 is not greater than 5!")) ; @r{else-part}
4075 @end group
4076 @end smallexample
4078 @noindent
4079 Note that the different levels of indentation make it easy to
4080 distinguish the then-part from the else-part.  (GNU Emacs has several
4081 commands that automatically indent @code{if} expressions correctly.
4082 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4084 We can extend the @code{type-of-animal} function to include an
4085 else-part by simply incorporating an additional part to the @code{if}
4086 expression.
4088 @need 1500
4089 You can see the consequences of doing this if you evaluate the following
4090 version of the @code{type-of-animal} function definition to install it
4091 and then evaluate the two subsequent expressions to pass different
4092 arguments to the function.
4094 @smallexample
4095 @group
4096 (defun type-of-animal (characteristic)  ; @r{Second version.}
4097   "Print message in echo area depending on CHARACTERISTIC.
4098 If the CHARACTERISTIC is the symbol `fierce',
4099 then warn of a tiger;
4100 else say it's not fierce."
4101   (if (equal characteristic 'fierce)
4102       (message "It's a tiger!")
4103     (message "It's not fierce!")))
4104 @end group
4105 @end smallexample
4106 @sp 1
4108 @smallexample
4109 @group
4110 (type-of-animal 'fierce)
4112 (type-of-animal 'zebra)
4114 @end group
4115 @end smallexample
4117 @c Following sentence rewritten to prevent overfull hbox.
4118 @noindent
4119 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4120 following message printed in the echo area: @code{"It's a tiger!"}; but
4121 when you evaluate @code{(type-of-animal 'zebra)}, you will see
4122 @code{"It's not fierce!"}.
4124 (Of course, if the @var{characteristic} were @code{ferocious}, the
4125 message @code{"It's not fierce!"} would be printed; and it would be
4126 misleading!  When you write code, you need to take into account the
4127 possibility that some such argument will be tested by the @code{if} and
4128 write your program accordingly.)
4130 @node Truth & Falsehood, save-excursion, else, Writing Defuns
4131 @comment  node-name,  next,  previous,  up
4132 @section Truth and Falsehood in Emacs Lisp
4133 @cindex Truth and falsehood in Emacs Lisp
4134 @cindex Falsehood and truth in Emacs Lisp
4135 @findex nil
4137 There is an important aspect to the truth test in an @code{if}
4138 expression.  So far, we have spoken of `true' and `false' as values of
4139 predicates as if they were new kinds of Emacs Lisp objects.  In fact,
4140 `false' is just our old friend @code{nil}.  Anything else---anything
4141 at all---is `true'.
4143 The expression that tests for truth is interpreted as @dfn{true}
4144 if the result of evaluating it is a value that is not @code{nil}.  In
4145 other words, the result of the test is considered true if the value
4146 returned is a number such as 47, a string such as @code{"hello"}, or a
4147 symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4148 even a buffer!
4150 @menu
4151 * nil explained::               @code{nil} has two meanings.
4152 @end menu
4154 @node nil explained,  , Truth & Falsehood, Truth & Falsehood
4155 @ifnottex
4156 @unnumberedsubsec An explanation of @code{nil}
4157 @end ifnottex
4159 Before illustrating a test for truth, we need an explanation of @code{nil}.
4161 In Emacs Lisp, the symbol @code{nil} has two meanings.  First, it means the
4162 empty list.  Second, it means false and is the value returned when a
4163 true-or-false-test tests false.  @code{nil} can be written as an empty
4164 list, @code{()}, or as @code{nil}.  As far as the Lisp interpreter is
4165 concerned, @code{()} and @code{nil} are the same.  Humans, however, tend
4166 to use @code{nil} for false and @code{()} for the empty list.
4168 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4169 list---is considered true.  This means that if an evaluation returns
4170 something that is not an empty list, an @code{if} expression will test
4171 true.  For example, if a number is put in the slot for the test, it
4172 will be evaluated and will return itself, since that is what numbers
4173 do when evaluated.  In this conditional, the @code{if} expression will
4174 test true.  The expression tests false only when @code{nil}, an empty
4175 list, is returned by evaluating the expression.
4177 You can see this by evaluating the two expressions in the following examples.
4179 In the first example, the number 4 is evaluated as the test in the
4180 @code{if} expression and returns itself; consequently, the then-part
4181 of the expression is evaluated and returned: @samp{true} appears in
4182 the echo area.  In the second example, the @code{nil} indicates false;
4183 consequently, the else-part of the expression is evaluated and
4184 returned: @samp{false} appears in the echo area.
4186 @smallexample
4187 @group
4188 (if 4
4189     'true
4190   'false)
4191 @end group
4193 @group
4194 (if nil
4195     'true
4196   'false)
4197 @end group
4198 @end smallexample
4200 @need 1250
4201 Incidentally, if some other useful value is not available for a test that
4202 returns true, then the Lisp interpreter will return the symbol @code{t}
4203 for true.  For example, the expression @code{(> 5 4)} returns @code{t}
4204 when evaluated, as you can see by evaluating it in the usual way:
4206 @smallexample
4207 (> 5 4)
4208 @end smallexample
4210 @need 1250
4211 @noindent
4212 On the other hand, this function returns @code{nil} if the test is false.
4214 @smallexample
4215 (> 4 5)
4216 @end smallexample
4218 @node save-excursion, Review, Truth & Falsehood, Writing Defuns
4219 @comment  node-name,  next,  previous,  up
4220 @section @code{save-excursion}
4221 @findex save-excursion
4222 @cindex Region, what it is
4223 @cindex Preserving point, mark, and buffer
4224 @cindex Point, mark, buffer preservation
4225 @findex point
4226 @findex mark
4228 The @code{save-excursion} function is the fourth and final special form
4229 that we will discuss in this chapter.
4231 In Emacs Lisp programs used for editing, the @code{save-excursion}
4232 function is very common.  It saves the location of point and mark,
4233 executes the body of the function, and then restores point and mark to
4234 their previous positions if their locations were changed.  Its primary
4235 purpose is to keep the user from being surprised and disturbed by
4236 unexpected movement of point or mark.
4238 @menu
4239 * Point and mark::              A review of various locations.
4240 * Template for save-excursion::
4241 @end menu
4243 @node Point and mark, Template for save-excursion, save-excursion, save-excursion
4244 @ifnottex
4245 @unnumberedsubsec Point and Mark
4246 @end ifnottex
4248 Before discussing @code{save-excursion}, however, it may be useful
4249 first to review what point and mark are in GNU Emacs.  @dfn{Point} is
4250 the current location of the cursor.  Wherever the cursor
4251 is, that is point.  More precisely, on terminals where the cursor
4252 appears to be on top of a character, point is immediately before the
4253 character.  In Emacs Lisp, point is an integer.  The first character in
4254 a buffer is number one, the second is number two, and so on.  The
4255 function @code{point} returns the current position of the cursor as a
4256 number.  Each buffer has its own value for point.
4258 The @dfn{mark} is another position in the buffer; its value can be set
4259 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}).  If
4260 a mark has been set, you can use the command @kbd{C-x C-x}
4261 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4262 and set the mark to be the previous position of point.  In addition, if
4263 you set another mark, the position of the previous mark is saved in the
4264 mark ring.  Many mark positions can be saved this way.  You can jump the
4265 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4266 times.
4268 The part of the buffer between point and mark is called @dfn{the
4269 region}.  Numerous commands work on the region, including
4270 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4271 @code{print-region}.
4273 The @code{save-excursion} special form saves the locations of point and
4274 mark and restores those positions after the code within the body of the
4275 special form is evaluated by the Lisp interpreter.  Thus, if point were
4276 in the beginning of a piece of text and some code moved point to the end
4277 of the buffer, the @code{save-excursion} would put point back to where
4278 it was before, after the expressions in the body of the function were
4279 evaluated.
4281 In Emacs, a function frequently moves point as part of its internal
4282 workings even though a user would not expect this.  For example,
4283 @code{count-lines-region} moves point.  To prevent the user from being
4284 bothered by jumps that are both unexpected and (from the user's point of
4285 view) unnecessary, @code{save-excursion} is often used to keep point and
4286 mark in the location expected by the user.  The use of
4287 @code{save-excursion} is good housekeeping.
4289 To make sure the house stays clean, @code{save-excursion} restores the
4290 values of point and mark even if something goes wrong in the code inside
4291 of it (or, to be more precise and to use the proper jargon, ``in case of
4292 abnormal exit'').  This feature is very helpful.
4294 In addition to recording the values of point and mark,
4295 @code{save-excursion} keeps track of the current buffer, and restores
4296 it, too.  This means you can write code that will change the buffer and
4297 have @code{save-excursion} switch you back to the original buffer.  This
4298 is how @code{save-excursion} is used in @code{append-to-buffer}.
4299 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4301 @node Template for save-excursion,  , Point and mark, save-excursion
4302 @comment  node-name,  next,  previous,  up
4303 @subsection Template for a @code{save-excursion} Expression
4305 @need 800
4306 The template for code using @code{save-excursion} is simple:
4308 @smallexample
4309 @group
4310 (save-excursion
4311   @var{body}@dots{})
4312 @end group
4313 @end smallexample
4315 @noindent
4316 The body of the function is one or more expressions that will be
4317 evaluated in sequence by the Lisp interpreter.  If there is more than
4318 one expression in the body, the value of the last one will be returned
4319 as the value of the @code{save-excursion} function.  The other
4320 expressions in the body are evaluated only for their side effects; and
4321 @code{save-excursion} itself is used only for its side effect (which
4322 is restoring the positions of point and mark).
4324 @need 1250
4325 In more detail, the template for a @code{save-excursion} expression
4326 looks like this:
4328 @smallexample
4329 @group
4330 (save-excursion
4331   @var{first-expression-in-body}
4332   @var{second-expression-in-body}
4333   @var{third-expression-in-body}
4334    @dots{}
4335   @var{last-expression-in-body})
4336 @end group
4337 @end smallexample
4339 @noindent
4340 An expression, of course, may be a symbol on its own or a list.
4342 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4343 within the body of a @code{let} expression.  It looks like this:
4345 @smallexample
4346 @group
4347 (let @var{varlist}
4348   (save-excursion
4349     @var{body}@dots{}))
4350 @end group
4351 @end smallexample
4353 @node Review, defun Exercises, save-excursion, Writing Defuns
4354 @comment  node-name,  next,  previous,  up
4355 @section Review
4357 In the last few chapters we have introduced a fair number of functions
4358 and special forms.  Here they are described in brief, along with a few
4359 similar functions that have not been mentioned yet.
4361 @table @code
4362 @item eval-last-sexp
4363 Evaluate the last symbolic expression before the current location of
4364 point.  The value is printed in the echo area unless the function is
4365 invoked with an argument; in that case, the output is printed in the
4366 current buffer.  This command is normally bound to @kbd{C-x C-e}.
4368 @item defun
4369 Define function.  This special form has up to five parts: the name,
4370 a template for the arguments that will be passed to the function,
4371 documentation, an optional interactive declaration, and the body of the
4372 definition.
4374 @need 1250
4375 For example:
4377 @smallexample
4378 @group
4379 (defun back-to-indentation ()
4380   "Move point to first visible character on line."
4381   (interactive)
4382   (beginning-of-line 1)
4383   (skip-chars-forward " \t"))
4384 @end group
4385 @end smallexample
4387 @item interactive
4388 Declare to the interpreter that the function can be used
4389 interactively.  This special form may be followed by a string with one
4390 or more parts that pass the information to the arguments of the
4391 function, in sequence.  These parts may also tell the interpreter to
4392 prompt for information.  Parts of the string are separated by
4393 newlines, @samp{\n}.
4395 Common code characters are:
4397 @table @code
4398 @item b
4399 The name of an existing buffer.
4401 @item f
4402 The name of an existing file.
4404 @item p
4405 The numeric prefix argument.  (Note that this `p' is lower case.)
4407 @item r
4408 Point and the mark, as two numeric arguments, smallest first.  This
4409 is the only code letter that specifies two successive arguments
4410 rather than one.
4411 @end table
4413 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4414 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4415 code characters.
4417 @item let
4418 Declare that a list of variables is for use within the body of the
4419 @code{let} and give them an initial value, either @code{nil} or a
4420 specified value; then evaluate the rest of the expressions in the body
4421 of the @code{let} and return the value of the last one.  Inside the
4422 body of the @code{let}, the Lisp interpreter does not see the values of
4423 the variables of the same names that are bound outside of the
4424 @code{let}.
4426 @need 1250
4427 For example,
4429 @smallexample
4430 @group
4431 (let ((foo (buffer-name))
4432       (bar (buffer-size)))
4433   (message
4434    "This buffer is %s and has %d characters."
4435    foo bar))
4436 @end group
4437 @end smallexample
4439 @item save-excursion
4440 Record the values of point and mark and the current buffer before
4441 evaluating the body of this special form.  Restore the values of point
4442 and mark and buffer afterward.
4444 @need 1250
4445 For example,
4447 @smallexample
4448 @group
4449 (message "We are %d characters into this buffer."
4450          (- (point)
4451             (save-excursion
4452               (goto-char (point-min)) (point))))
4453 @end group
4454 @end smallexample
4456 @item if
4457 Evaluate the first argument to the function; if it is true, evaluate
4458 the second argument; else evaluate the third argument, if there is one.
4460 The @code{if} special form is called a @dfn{conditional}.  There are
4461 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4462 commonly used.
4464 @need 1250
4465 For example,
4467 @smallexample
4468 @group
4469 (if (string-equal
4470      (number-to-string 21)
4471      (substring (emacs-version) 10 12))
4472     (message "This is version 21 Emacs")
4473   (message "This is not version 21 Emacs"))
4474 @end group
4475 @end smallexample
4477 @item equal
4478 @itemx eq
4479 Test whether two objects are the same.  @code{equal} uses one meaning
4480 of the word `same' and @code{eq} uses another:  @code{equal} returns
4481 true if the two objects have a similar structure and contents, such as
4482 two copies of the same book.  On the other hand, @code{eq}, returns
4483 true if both arguments are actually the same object.
4484 @findex equal
4485 @findex eq
4487 @need 1250
4488 @item <
4489 @itemx >
4490 @itemx <=
4491 @itemx >=
4492 The @code{<} function tests whether its first argument is smaller than
4493 its second argument.  A corresponding function, @code{>}, tests whether
4494 the first argument is greater than the second.  Likewise, @code{<=}
4495 tests whether the first argument is less than or equal to the second and
4496 @code{>=} tests whether the first argument is greater than or equal to
4497 the second.  In all cases, both arguments must be numbers or markers
4498 (markers indicate positions in buffers).
4500 @item string<
4501 @itemx string-lessp
4502 @itemx string=
4503 @itemx string-equal
4504 The @code{string-lessp} function tests whether its first argument is
4505 smaller than the second argument.  A shorter, alternative name for the
4506 same function (a @code{defalias}) is @code{string<}.
4508 The arguments to @code{string-lessp} must be strings or symbols; the
4509 ordering is lexicographic, so case is significant.  The print names of
4510 symbols are used instead of the symbols themselves.
4512 @cindex @samp{empty string} defined
4513 An empty string, @samp{""}, a string with no characters in it, is
4514 smaller than any string of characters.
4516 @code{string-equal} provides the corresponding test for equality.  Its
4517 shorter, alternative name is @code{string=}.  There are no string test
4518 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4520 @item message
4521 Print a message in the echo area. The first argument is a string that
4522 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4523 arguments that follow the string.  The argument used by @samp{%s} must
4524 be a string or a symbol; the argument used by @samp{%d} must be a
4525 number.  The argument used by @samp{%c} must be an ascii code number;
4526 it will be printed as the character with that @sc{ascii} code.
4528 @item setq
4529 @itemx set
4530 The @code{setq} function sets the value of its first argument to the
4531 value of the second argument.  The first argument is automatically
4532 quoted by @code{setq}.  It does the same for succeeding pairs of
4533 arguments.  Another function, @code{set}, takes only two arguments and
4534 evaluates both of them before setting the value returned by its first
4535 argument to the value returned by its second argument.
4537 @item buffer-name
4538 Without an argument, return the name of the buffer, as a string.
4540 @itemx buffer-file-name
4541 Without an argument, return the name of the file the buffer is
4542 visiting.
4544 @item current-buffer
4545 Return the buffer in which Emacs is active; it may not be
4546 the buffer that is visible on the screen.
4548 @item other-buffer
4549 Return the most recently selected buffer (other than the buffer passed
4550 to @code{other-buffer} as an argument and other than the current
4551 buffer).
4553 @item switch-to-buffer
4554 Select a buffer for Emacs to be active in and display it in the current
4555 window so users can look at it.  Usually bound to @kbd{C-x b}.
4557 @item set-buffer
4558 Switch Emacs' attention to a buffer on which programs will run.  Don't
4559 alter what the window is showing.
4561 @item buffer-size
4562 Return the number of characters in the current buffer.
4564 @item point
4565 Return the value of the current position of the cursor, as an
4566 integer counting the number of characters from the beginning of the
4567 buffer.
4569 @item point-min
4570 Return the minimum permissible value of point in
4571 the current buffer.  This is 1, unless narrowing is in effect.
4573 @item point-max
4574 Return the value of the maximum permissible value of point in the
4575 current buffer.  This is the end of the buffer, unless narrowing is in
4576 effect.
4577 @end table
4579 @need 1500
4580 @node defun Exercises,  , Review, Writing Defuns
4581 @section Exercises
4583 @itemize @bullet
4584 @item
4585 Write a non-interactive function that doubles the value of its
4586 argument, a number.  Make that function interactive.
4588 @item
4589 Write a function that tests whether the current value of
4590 @code{fill-column} is greater than the argument passed to the function,
4591 and if so, prints an appropriate message.
4592 @end itemize
4594 @node Buffer Walk Through, More Complex, Writing Defuns, Top
4595 @comment  node-name,  next,  previous,  up
4596 @chapter A Few Buffer--Related Functions
4598 In this chapter we study in detail several of the functions used in GNU
4599 Emacs.  This is called a ``walk-through''.  These functions are used as
4600 examples of Lisp code, but are not imaginary examples; with the
4601 exception of the first, simplified function definition, these functions
4602 show the actual code used in GNU Emacs.  You can learn a great deal from
4603 these definitions.  The functions described here are all related to
4604 buffers.  Later, we will study other functions.
4606 @menu
4607 * Finding More::                How to find more information.
4608 * simplified-beginning-of-buffer::  Shows @code{goto-char},
4609                                 @code{point-min}, and @code{push-mark}.
4610 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
4611 * append-to-buffer::            Uses @code{save-excursion} and
4612                                 @code{insert-buffer-substring}.
4613 * Buffer Related Review::       Review.
4614 * Buffer Exercises::
4615 @end menu
4617 @node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4618 @section Finding More Information
4620 @findex describe-function, @r{introduced}
4621 @cindex Find function documentation
4622 In this walk-through, I will describe each new function as we come to
4623 it, sometimes in detail and sometimes briefly.  If you are interested,
4624 you can get the full documentation of any Emacs Lisp function at any
4625 time by typing @kbd{C-h f} and then the name of the function (and then
4626 @key{RET}).  Similarly, you can get the full documentation for a
4627 variable by typing @kbd{C-h v} and then the name of the variable (and
4628 then @key{RET}).
4630 @cindex Find source of function
4631 In versions 20 and higher, when a function is written in Emacs Lisp,
4632 @code{describe-function} will also tell you the location of the
4633 function definition.  If you move point over the file name and press
4634 the @key{RET} key, which is this case means @code{help-follow} rather
4635 than `return' or `enter', Emacs will take you directly to the function
4636 definition.
4638 More generally, if you want to see a function in its original source
4639 file, you can use the @code{find-tags} function to jump to it.
4640 @code{find-tags} works with a wide variety of languages, not just
4641 Lisp, and C, and it works with non-programming text as well.  For
4642 example, @code{find-tags} will jump to the various nodes in the
4643 Texinfo source file of this document.
4645 The @code{find-tags} function depends on `tags tables' that record
4646 the locations of the functions, variables, and other items to which
4647 @code{find-tags} jumps.
4649 To use the @code{find-tags} command, type @kbd{M-.}  (i.e., type the
4650 @key{META} key and the period key at the same time, or else type the
4651 @key{ESC} key and then type the period key), and then, at the prompt,
4652 type in the name of the function whose source code you want to see,
4653 such as @code{mark-whole-buffer}, and then type @key{RET}.  Emacs will
4654 switch buffers and display the source code for the function on your
4655 screen.  To switch back to your current buffer, type @kbd{C-x b
4656 @key{RET}}.  (On some keyboards, the @key{META} key is labelled
4657 @key{ALT}.)
4659 @c !!! 21.0.100 tags table location in this paragraph
4660 @cindex TAGS table, specifying
4661 @findex find-tags
4662 Depending on how the initial default values of your copy of Emacs are
4663 set, you may also need to specify the location of your `tags table',
4664 which is a file called @file{TAGS}.  For example, if you are
4665 interested in Emacs sources, the tags table you will most likely want,
4666 if it has already been created for you, will be in a subdirectory of
4667 the @file{/usr/local/share/emacs/} directory; thus you would use the
4668 @code{M-x visit-tags-table} command and specify a pathname such as
4669 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
4670 @file{/usr/local/src/emacs/lisp/TAGS}.  If the tags table has
4671 not already been created, you will have to create it yourself.
4673 @need 1250
4674 To create a @file{TAGS} file in a specific directory, switch to that
4675 directory in Emacs using @kbd{M-x cd} command, or list the directory
4676 with @kbd{C-x d} (@code{dired}).  Then run the compile command, with
4677 @w{@code{etags *.el}} as the command to execute
4679 @smallexample
4680 M-x compile RET etags *.el RET
4681 @end smallexample
4683 For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4685 After you become more familiar with Emacs Lisp, you will find that you will
4686 frequently use @code{find-tags} to navigate your way around source code;
4687 and you will create your own @file{TAGS} tables.
4689 @cindex Library, as term for `file'
4690 Incidentally, the files that contain Lisp code are conventionally
4691 called @dfn{libraries}.  The metaphor is derived from that of a
4692 specialized library, such as a law library or an engineering library,
4693 rather than a general library.  Each library, or file, contains
4694 functions that relate to a particular topic or activity, such as
4695 @file{abbrev.el} for handling abbreviations and other typing
4696 shortcuts, and @file{help.el} for on-line help.  (Sometimes several
4697 libraries provide code for a single activity, as the various
4698 @file{rmail@dots{}} files provide code for reading electronic mail.)
4699 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4700 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4701 by topic keywords.''
4703 @node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4704 @comment  node-name,  next,  previous,  up
4705 @section A Simplified @code{beginning-of-buffer} Definition
4706 @findex simplified-beginning-of-buffer
4708 The @code{beginning-of-buffer} command is a good function to start with
4709 since you are likely to be familiar with it and it is easy to
4710 understand.  Used as an interactive command, @code{beginning-of-buffer}
4711 moves the cursor to the beginning of the buffer, leaving the mark at the
4712 previous position.  It is generally bound to @kbd{M-<}.
4714 In this section, we will discuss a shortened version of the function
4715 that shows how it is most frequently used.  This shortened function
4716 works as written, but it does not contain the code for a complex option.
4717 In another section, we will describe the entire function.
4718 (@xref{beginning-of-buffer, , Complete Definition of
4719 @code{beginning-of-buffer}}.)
4721 Before looking at the code, let's consider what the function
4722 definition has to contain: it must include an expression that makes
4723 the function interactive so it can be called by typing @kbd{M-x
4724 beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4725 must include code to leave a mark at the original position in the
4726 buffer; and it must include code to move the cursor to the beginning
4727 of the buffer.
4729 @need 1250
4730 Here is the complete text of the shortened version of the function:
4732 @smallexample
4733 @group
4734 (defun simplified-beginning-of-buffer ()
4735   "Move point to the beginning of the buffer;
4736 leave mark at previous position."
4737   (interactive)
4738   (push-mark)
4739   (goto-char (point-min)))
4740 @end group
4741 @end smallexample
4743 Like all function definitions, this definition has five parts following
4744 the special form @code{defun}:
4746 @enumerate
4747 @item
4748 The name: in this example, @code{simplified-beginning-of-buffer}.
4750 @item
4751 A list of the arguments: in this example, an empty list, @code{()},
4753 @item
4754 The documentation string.
4756 @item
4757 The interactive expression.
4759 @item
4760 The body.
4761 @end enumerate
4763 @noindent
4764 In this function definition, the argument list is empty; this means that
4765 this function does not require any arguments.  (When we look at the
4766 definition for the complete function, we will see that it may be passed
4767 an optional argument.)
4769 The interactive expression tells Emacs that the function is intended to
4770 be used interactively.  In this example, @code{interactive} does not have
4771 an argument because @code{simplified-beginning-of-buffer} does not
4772 require one.
4774 @need 800
4775 The body of the function consists of the two lines:
4777 @smallexample
4778 @group
4779 (push-mark)
4780 (goto-char (point-min))
4781 @end group
4782 @end smallexample
4784 The first of these lines is the expression, @code{(push-mark)}.  When
4785 this expression is evaluated by the Lisp interpreter, it sets a mark at
4786 the current position of the cursor, wherever that may be.  The position
4787 of this mark is saved in the mark ring.
4789 The next line is @code{(goto-char (point-min))}.  This expression
4790 jumps the cursor to the minimum point in the buffer, that is, to the
4791 beginning of the buffer (or to the beginning of the accessible portion
4792 of the buffer if it is narrowed.  @xref{Narrowing & Widening, ,
4793 Narrowing and Widening}.)
4795 The @code{push-mark} command sets a mark at the place where the cursor
4796 was located before it was moved to the beginning of the buffer by the
4797 @code{(goto-char (point-min))} expression.  Consequently, you can, if
4798 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4800 That is all there is to the function definition!
4802 @findex describe-function
4803 When you are reading code such as this and come upon an unfamiliar
4804 function, such as @code{goto-char}, you can find out what it does by
4805 using the @code{describe-function} command.  To use this command, type
4806 @kbd{C-h f} and then type in the name of the function and press
4807 @key{RET}.  The @code{describe-function} command will print the
4808 function's documentation string in a @file{*Help*} window.  For
4809 example, the documentation for @code{goto-char} is:
4811 @smallexample
4812 @group
4813 One arg, a number.  Set point to that number.
4814 Beginning of buffer is position (point-min),
4815 end is (point-max).
4816 @end group
4817 @end smallexample
4819 @noindent
4820 (The prompt for @code{describe-function} will offer you the symbol
4821 under or preceding the cursor, so you can save typing by positioning
4822 the cursor right over or after the function and then typing @kbd{C-h f
4823 @key{RET}}.)
4825 The @code{end-of-buffer} function definition is written in the same way as
4826 the @code{beginning-of-buffer} definition except that the body of the
4827 function contains the expression @code{(goto-char (point-max))} in place
4828 of @code{(goto-char (point-min))}.
4830 @node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4831 @comment  node-name,  next,  previous,  up
4832 @section The Definition of @code{mark-whole-buffer}
4833 @findex mark-whole-buffer
4835 The @code{mark-whole-buffer} function is no harder to understand than the
4836 @code{simplified-beginning-of-buffer} function.  In this case, however,
4837 we will look at the complete function, not a shortened version.
4839 The @code{mark-whole-buffer} function is not as commonly used as the
4840 @code{beginning-of-buffer} function, but is useful nonetheless: it
4841 marks a whole buffer as a region by putting point at the beginning and
4842 a mark at the end of the buffer.  It is generally bound to @kbd{C-x
4846 @menu
4847 * mark-whole-buffer overview::
4848 * Body of mark-whole-buffer::   Only three lines of code.
4849 @end menu
4852 @node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4853 @ifnottex
4854 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4855 @end ifnottex
4857 @need 1250
4858 In GNU Emacs 20, the code for the complete function looks like this:
4860 @smallexample
4861 @group
4862 (defun mark-whole-buffer ()
4863   "Put point at beginning and mark at end of buffer."
4864   (interactive)
4865   (push-mark (point))
4866   (push-mark (point-max))
4867   (goto-char (point-min)))
4868 @end group
4869 @end smallexample
4871 @need 1250
4872 Like all other functions, the @code{mark-whole-buffer} function fits
4873 into the template for a function definition.  The template looks like
4874 this:
4876 @smallexample
4877 @group
4878 (defun @var{name-of-function} (@var{argument-list})
4879   "@var{documentation}@dots{}"
4880   (@var{interactive-expression}@dots{})
4881   @var{body}@dots{})
4882 @end group
4883 @end smallexample
4885 Here is how the function works: the name of the function is
4886 @code{mark-whole-buffer}; it is followed by an empty argument list,
4887 @samp{()}, which means that the function does not require arguments.
4888 The documentation comes next.
4890 The next line is an @code{(interactive)} expression that tells Emacs
4891 that the function will be used interactively.  These details are similar
4892 to the @code{simplified-beginning-of-buffer} function described in the
4893 previous section.
4895 @node Body of mark-whole-buffer,  , mark-whole-buffer overview, mark-whole-buffer
4896 @comment  node-name,  next,  previous,  up
4897 @subsection Body of @code{mark-whole-buffer}
4899 The body of the @code{mark-whole-buffer} function consists of three
4900 lines of code:
4902 @smallexample
4903 @group
4904 (push-mark (point))
4905 (push-mark (point-max))
4906 (goto-char (point-min))
4907 @end group
4908 @end smallexample
4910 The first of these lines is the expression, @code{(push-mark (point))}.
4912 This line does exactly the same job as the first line of the body of
4913 the @code{simplified-beginning-of-buffer} function, which is written
4914 @code{(push-mark)}.  In both cases, the Lisp interpreter sets a mark
4915 at the current position of the cursor.
4917 I don't know why the expression in @code{mark-whole-buffer} is written
4918 @code{(push-mark (point))} and the expression in
4919 @code{beginning-of-buffer} is written @code{(push-mark)}.  Perhaps
4920 whoever wrote the code did not know that the arguments for
4921 @code{push-mark} are optional and that if @code{push-mark} is not
4922 passed an argument, the function automatically sets mark at the
4923 location of point by default.  Or perhaps the expression was written
4924 so as to parallel the structure of the next line.  In any case, the
4925 line causes Emacs to determine the position of point and set a mark
4926 there.
4928 The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4929 This expression sets a mark at the point in the buffer
4930 that has the highest number.  This will be the end of the buffer (or,
4931 if the buffer is narrowed, the end of the accessible portion of the
4932 buffer.  @xref{Narrowing & Widening, , Narrowing and Widening}, for
4933 more about narrowing.)  After this mark has been set, the previous
4934 mark, the one set at point, is no longer set, but Emacs remembers its
4935 position, just as all other recent marks are always remembered.  This
4936 means that you can, if you wish, go back to that position by typing
4937 @kbd{C-u C-@key{SPC}} twice.
4939 (In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4940 complicated than shown here.  The line reads
4942 @smallexample
4943 (push-mark (point-max) nil t)
4944 @end smallexample
4946 @noindent
4947 (The expression works nearly the same as before.  It sets a mark at
4948 the highest numbered place in the buffer that it can.  However, in
4949 this version, @code{push-mark} has two additional arguments.  The
4950 second argument to @code{push-mark} is @code{nil}.  This tells the
4951 function it @emph{should} display a message that says `Mark set' when
4952 it pushes the mark.  The third argument is @code{t}.  This tells
4953 @code{push-mark} to activate the mark when Transient Mark mode is
4954 turned on.  Transient Mark mode highlights the currently active
4955 region.  It is usually turned off.)
4957 Finally, the last line of the function is @code{(goto-char
4958 (point-min)))}.  This is written exactly the same way as it is written
4959 in @code{beginning-of-buffer}.  The expression moves the cursor to
4960 the minimum point in the buffer, that is, to the beginning of the buffer
4961 (or to the beginning of the accessible portion of the buffer).  As a
4962 result of this, point is placed at the beginning of the buffer and mark
4963 is set at the end of the buffer.  The whole buffer is, therefore, the
4964 region.
4966 @node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4967 @comment  node-name,  next,  previous,  up
4968 @section The Definition of @code{append-to-buffer}
4969 @findex append-to-buffer
4971 The @code{append-to-buffer} command is very nearly as simple as the
4972 @code{mark-whole-buffer} command.  What it does is copy the region (that
4973 is, the part of the buffer between point and mark) from the current
4974 buffer to a specified buffer.
4976 @menu
4977 * append-to-buffer overview::
4978 * append interactive::          A two part interactive expression.
4979 * append-to-buffer body::       Incorporates a @code{let} expression.
4980 * append save-excursion::       How the @code{save-excursion} works.
4981 @end menu
4983 @node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4984 @ifnottex
4985 @unnumberedsubsec An Overview of @code{append-to-buffer}
4986 @end ifnottex
4988 @findex insert-buffer-substring
4989 The @code{append-to-buffer} command uses the
4990 @code{insert-buffer-substring} function to copy the region.
4991 @code{insert-buffer-substring} is described by its name: it takes a
4992 string of characters from part of a buffer, a ``substring'', and
4993 inserts them into another buffer.  Most of @code{append-to-buffer} is
4994 concerned with setting up the conditions for
4995 @code{insert-buffer-substring} to work: the code must specify both the
4996 buffer to which the text will go and the region that will be copied.
4997 Here is the complete text of the function:
4999 @smallexample
5000 @group
5001 (defun append-to-buffer (buffer start end)
5002   "Append to specified buffer the text of the region.
5003 It is inserted into that buffer before its point.
5004 @end group
5006 @group
5007 When calling from a program, give three arguments:
5008 a buffer or the name of one, and two character numbers
5009 specifying the portion of the current buffer to be copied."
5010   (interactive "BAppend to buffer:@: \nr")
5011   (let ((oldbuf (current-buffer)))
5012     (save-excursion
5013       (set-buffer (get-buffer-create buffer))
5014       (insert-buffer-substring oldbuf start end))))
5015 @end group
5016 @end smallexample
5018 The function can be understood by looking at it as a series of
5019 filled-in templates.
5021 The outermost template is for the function definition.  In this
5022 function, it looks like this (with several slots filled in):
5024 @smallexample
5025 @group
5026 (defun append-to-buffer (buffer start end)
5027   "@var{documentation}@dots{}"
5028   (interactive "BAppend to buffer:@: \nr")
5029   @var{body}@dots{})
5030 @end group
5031 @end smallexample
5033 The first line of the function includes its name and three arguments.
5034 The arguments are the @code{buffer} to which the text will be copied, and
5035 the @code{start} and @code{end} of the region in the current buffer that
5036 will be copied.
5038 The next part of the function is the documentation, which is clear and
5039 complete.
5041 @node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
5042 @comment  node-name,  next,  previous,  up
5043 @subsection The @code{append-to-buffer} Interactive Expression
5045 Since the @code{append-to-buffer} function will be used interactively,
5046 the function must have an @code{interactive} expression.  (For a
5047 review of @code{interactive}, see @ref{Interactive, , Making a
5048 Function Interactive}.)  The expression reads as follows:
5050 @smallexample
5051 (interactive "BAppend to buffer:@: \nr")
5052 @end smallexample
5054 @noindent
5055 This expression has an argument inside of quotation marks and that
5056 argument has two parts, separated by @samp{\n}.
5058 The first part is @samp{BAppend to buffer:@: }.  Here, the @samp{B}
5059 tells Emacs to ask for the name of the buffer that will be passed to the
5060 function.  Emacs will ask for the name by prompting the user in the
5061 minibuffer, using the string following the @samp{B}, which is the string
5062 @samp{Append to buffer:@: }.  Emacs then binds the variable @code{buffer}
5063 in the function's argument list to the specified buffer.
5065 The newline, @samp{\n}, separates the first part of the argument from
5066 the second part.  It is followed by an @samp{r} that tells Emacs to bind
5067 the two arguments that follow the symbol @code{buffer} in the function's
5068 argument list (that is, @code{start} and @code{end}) to the values of
5069 point and mark.
5071 @node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5072 @comment  node-name,  next,  previous,  up
5073 @subsection The Body of @code{append-to-buffer}
5075 The body of the @code{append-to-buffer} function begins with @code{let}.
5077 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5078 @code{let} expression is to create and give initial values to one or
5079 more variables that will only be used within the body of the
5080 @code{let}.  This means that such a variable will not be confused with
5081 any variable of the same name outside the @code{let} expression.
5083 We can see how the @code{let} expression fits into the function as a
5084 whole by showing a template for @code{append-to-buffer} with the
5085 @code{let} expression in outline:
5087 @smallexample
5088 @group
5089 (defun append-to-buffer (buffer start end)
5090   "@var{documentation}@dots{}"
5091   (interactive "BAppend to buffer:@: \nr")
5092   (let ((@var{variable} @var{value}))
5093         @var{body}@dots{})
5094 @end group
5095 @end smallexample
5097 The @code{let} expression has three elements:
5099 @enumerate
5100 @item
5101 The symbol @code{let};
5103 @item
5104 A varlist containing, in this case, a single two-element list,
5105 @code{(@var{variable} @var{value})};
5107 @item
5108 The body of the @code{let} expression.
5109 @end enumerate
5111 @need 800
5112 In the @code{append-to-buffer} function, the varlist looks like this:
5114 @smallexample
5115 (oldbuf (current-buffer))
5116 @end smallexample
5118 @noindent
5119 In this part of the @code{let} expression, the one variable,
5120 @code{oldbuf}, is bound to the value returned by the
5121 @code{(current-buffer)} expression.  The variable, @code{oldbuf}, is
5122 used to keep track of the buffer in which you are working and from
5123 which you will copy.
5125 The element or elements of a varlist are surrounded by a set of
5126 parentheses so the Lisp interpreter can distinguish the varlist from
5127 the body of the @code{let}.  As a consequence, the two-element list
5128 within the varlist is surrounded by a circumscribing set of parentheses.
5129 The line looks like this:
5131 @smallexample
5132 @group
5133 (let ((oldbuf (current-buffer)))
5134   @dots{} )
5135 @end group
5136 @end smallexample
5138 @noindent
5139 The two parentheses before @code{oldbuf} might surprise you if you did
5140 not realize that the first parenthesis before @code{oldbuf} marks the
5141 boundary of the varlist and the second parenthesis marks the beginning
5142 of the two-element list, @code{(oldbuf (current-buffer))}.
5144 @node append save-excursion,  , append-to-buffer body, append-to-buffer
5145 @comment  node-name,  next,  previous,  up
5146 @subsection @code{save-excursion} in @code{append-to-buffer}
5148 The body of the @code{let} expression in @code{append-to-buffer}
5149 consists of a @code{save-excursion} expression.
5151 The @code{save-excursion} function saves the locations of point and
5152 mark, and restores them to those positions after the expressions in the
5153 body of the @code{save-excursion} complete execution.  In addition,
5154 @code{save-excursion} keeps track of the original buffer, and
5155 restores it.  This is how @code{save-excursion} is used in
5156 @code{append-to-buffer}.
5158 @need 1500
5159 @cindex Indentation for formatting
5160 @cindex Formatting convention
5161 Incidentally, it is worth noting here that a Lisp function is normally
5162 formatted so that everything that is enclosed in a multi-line spread is
5163 indented more to the right than the first symbol.  In this function
5164 definition, the @code{let} is indented more than the @code{defun}, and
5165 the @code{save-excursion} is indented more than the @code{let}, like
5166 this:
5168 @smallexample
5169 @group
5170 (defun @dots{}
5171   @dots{}
5172   @dots{}
5173   (let@dots{}
5174     (save-excursion
5175       @dots{}
5176 @end group
5177 @end smallexample
5179 @need 1500
5180 @noindent
5181 This formatting convention makes it easy to see that the two lines in
5182 the body of the @code{save-excursion} are enclosed by the parentheses
5183 associated with @code{save-excursion}, just as the
5184 @code{save-excursion} itself is enclosed by the parentheses associated
5185 with the @code{let}:
5187 @smallexample
5188 @group
5189 (let ((oldbuf (current-buffer)))
5190   (save-excursion
5191     (set-buffer (get-buffer-create buffer))
5192     (insert-buffer-substring oldbuf start end))))
5193 @end group
5194 @end smallexample
5196 @need 1200
5197 The use of the @code{save-excursion} function can be viewed as a process
5198 of filling in the slots of a template:
5200 @smallexample
5201 @group
5202 (save-excursion
5203   @var{first-expression-in-body}
5204   @var{second-expression-in-body}
5205    @dots{}
5206   @var{last-expression-in-body})
5207 @end group
5208 @end smallexample
5210 @need 1200
5211 @noindent
5212 In this function, the body of the @code{save-excursion} contains only
5213 two expressions.  The body looks like this:
5215 @smallexample
5216 @group
5217 (set-buffer (get-buffer-create buffer))
5218 (insert-buffer-substring oldbuf start end)
5219 @end group
5220 @end smallexample
5222 When the @code{append-to-buffer} function is evaluated, the two
5223 expressions in the body of the @code{save-excursion} are evaluated in
5224 sequence.  The value of the last expression is returned as the value of
5225 the @code{save-excursion} function; the other expression is evaluated
5226 only for its side effects.
5228 The first line in the body of the @code{save-excursion} uses the
5229 @code{set-buffer} function to change the current buffer to the one
5230 specified in the first argument to @code{append-to-buffer}.  (Changing
5231 the buffer is the side effect; as we have said before, in Lisp, a side
5232 effect is often the primary thing we want.)  The second line does the
5233 primary work of the function.
5235 The @code{set-buffer} function changes Emacs' attention to the buffer to
5236 which the text will be copied and from which @code{save-excursion} will
5237 return.
5239 @need 800
5240 The line looks like this:
5242 @smallexample
5243 (set-buffer (get-buffer-create buffer))
5244 @end smallexample
5246 The innermost expression of this list is @code{(get-buffer-create
5247 buffer)}.  This expression uses the @code{get-buffer-create} function,
5248 which either gets the named buffer, or if it does not exist, creates one
5249 with the given name.  This means you can use @code{append-to-buffer} to
5250 put text into a buffer that did not previously exist.
5252 @code{get-buffer-create} also keeps @code{set-buffer} from getting an
5253 unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5254 were to specify a buffer that does not exist, Emacs would baulk.
5255 Since @code{get-buffer-create} will create a buffer if none exists,
5256 @code{set-buffer} is always provided with a buffer.
5258 @need 1250
5259 The last line of @code{append-to-buffer} does the work of appending
5260 the text:
5262 @smallexample
5263 (insert-buffer-substring oldbuf start end)
5264 @end smallexample
5266 @noindent
5267 The @code{insert-buffer-substring} function copies a string @emph{from}
5268 the buffer specified as its first argument and inserts the string into
5269 the present buffer.  In this case, the argument to
5270 @code{insert-buffer-substring} is the value of the variable created and
5271 bound by the @code{let}, namely the value of @code{oldbuf}, which was
5272 the current buffer when you gave the @code{append-to-buffer} command.
5274 After @code{insert-buffer-substring} has done its work,
5275 @code{save-excursion} will restore the action to the original buffer and
5276 @code{append-to-buffer} will have done its job.
5278 @need 800
5279 Written in skeletal form, the workings of the body look like this:
5281 @smallexample
5282 @group
5283 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5284   (save-excursion                       ; @r{Keep track of buffer.}
5285     @var{change-buffer}
5286     @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5288   @var{change-back-to-original-buffer-when-finished}
5289 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5291 @end group
5292 @end smallexample
5294 In summary, @code{append-to-buffer} works as follows: it saves the value
5295 of the current buffer in the variable called @code{oldbuf}.  It gets the
5296 new buffer, creating one if need be, and switches Emacs to it.  Using
5297 the value of @code{oldbuf}, it inserts the region of text from the old
5298 buffer into the new buffer; and then using @code{save-excursion}, it
5299 brings you back to your original buffer.
5301 In looking at @code{append-to-buffer}, you have explored a fairly
5302 complex function.  It shows how to use @code{let} and
5303 @code{save-excursion}, and how to change to and come back from another
5304 buffer.  Many function definitions use @code{let},
5305 @code{save-excursion}, and @code{set-buffer} this way.
5307 @node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5308 @comment  node-name,  next,  previous,  up
5309 @section Review
5311 Here is a brief summary of the various functions discussed in this chapter.
5313 @table @code
5314 @item describe-function
5315 @itemx describe-variable
5316 Print the documentation for a function or variable.
5317 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5319 @item find-tag
5320 Find the file containing the source for a function or variable and
5321 switch buffers to it, positioning point at the beginning of the item.
5322 Conventionally bound to @kbd{M-.} (that's a period following the
5323 @key{META} key).
5325 @item save-excursion
5326 Save the location of point and mark and restore their values after the
5327 arguments to @code{save-excursion} have been evaluated.  Also, remember
5328 the current buffer and return to it.
5330 @item push-mark
5331 Set mark at a location and record the value of the previous mark on the
5332 mark ring.  The mark is a location in the buffer that will keep its
5333 relative position even if text is added to or removed from the buffer.
5335 @item goto-char
5336 Set point to the location specified by the value of the argument, which
5337 can be a number, a marker,  or an expression that returns the number of
5338 a position, such as @code{(point-min)}.
5340 @item insert-buffer-substring
5341 Copy a region of text from a buffer that is passed to the function as
5342 an argument and insert the region into the current buffer.
5344 @item mark-whole-buffer
5345 Mark the whole buffer as a region.  Normally bound to @kbd{C-x h}.
5347 @item set-buffer
5348 Switch the attention of Emacs to another buffer, but do not change the
5349 window being displayed.  Used when the program rather than a human is
5350 to work on a different buffer.
5352 @item get-buffer-create
5353 @itemx get-buffer
5354 Find a named buffer or create one if a buffer of that name does not
5355 exist.  The @code{get-buffer} function returns @code{nil} if the named
5356 buffer does not exist.
5357 @end table
5359 @need 1500
5360 @node Buffer Exercises,  , Buffer Related Review, Buffer Walk Through
5361 @section Exercises
5363 @itemize @bullet
5364 @item
5365 Write your own @code{simplified-end-of-buffer} function definition;
5366 then test it to see whether it works.
5368 @item
5369 Use @code{if} and @code{get-buffer} to write a function that prints a
5370 message telling you whether a buffer exists.
5372 @item
5373 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5374 function.
5375 @end itemize
5377 @node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5378 @comment  node-name,  next,  previous,  up
5379 @chapter A Few More Complex Functions
5381 In this chapter, we build on what we have learned in previous chapters
5382 by looking at more complex functions.  The @code{copy-to-buffer}
5383 function illustrates use of two @code{save-excursion} expressions in
5384 one definition, while the @code{insert-buffer} function illustrates
5385 use of an asterisk in an @code{interactive} expression, use of
5386 @code{or}, and the important distinction between a name and the object
5387 to which the name refers.
5389 @menu
5390 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
5391 * insert-buffer::               Read-only, and with @code{or}.
5392 * beginning-of-buffer::         Shows @code{goto-char},
5393                                 @code{point-min}, and @code{push-mark}.
5394 * Second Buffer Related Review::
5395 * optional Exercise::
5396 @end menu
5398 @node copy-to-buffer, insert-buffer, More Complex, More Complex
5399 @comment  node-name,  next,  previous,  up
5400 @section The Definition of @code{copy-to-buffer}
5401 @findex copy-to-buffer
5403 After understanding how @code{append-to-buffer} works, it is easy to
5404 understand @code{copy-to-buffer}.  This function copies text into a
5405 buffer, but instead of adding to the second buffer, it replaces the
5406 previous text in the second buffer.  The code for the
5407 @code{copy-to-buffer} function is almost the same as the code for
5408 @code{append-to-buffer}, except that @code{erase-buffer} and a second
5409 @code{save-excursion} are used.  (@xref{append-to-buffer, , The
5410 Definition of @code{append-to-buffer}}, for the description of
5411 @code{append-to-buffer}.)
5413 @need 800
5414 The body of @code{copy-to-buffer} looks like this
5416 @smallexample
5417 @group
5418 @dots{}
5419 (interactive "BCopy to buffer:@: \nr")
5420   (let ((oldbuf (current-buffer)))
5421     (save-excursion
5422       (set-buffer (get-buffer-create buffer))
5423       (erase-buffer)
5424       (save-excursion
5425         (insert-buffer-substring oldbuf start end)))))
5426 @end group
5427 @end smallexample
5429 This code is similar to the code in @code{append-to-buffer}: it is
5430 only after changing to the buffer to which the text will be copied
5431 that the definition for this function diverges from the definition for
5432 @code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5433 buffer's former contents.  (This is what is meant by `replacement'; to
5434 replace text, Emacs erases the previous text and then inserts new
5435 text.)  After erasing the previous contents of the buffer,
5436 @code{save-excursion} is used for a second time and the new text is
5437 inserted.
5439 Why is @code{save-excursion} used twice?  Consider again what the
5440 function does.
5442 @need 1250
5443 In outline, the body of @code{copy-to-buffer} looks like this:
5445 @smallexample
5446 @group
5447 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5448   (save-excursion         ; @r{First use of @code{save-excursion}.}
5449     @var{change-buffer}
5450       (erase-buffer)
5451       (save-excursion     ; @r{Second use of @code{save-excursion}.}
5452         @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5453 @end group
5454 @end smallexample
5456 The first use of @code{save-excursion} returns Emacs to the buffer from
5457 which the text is being copied.  That is clear, and is just like its use
5458 in @code{append-to-buffer}.  Why the second use?  The reason is that
5459 @code{insert-buffer-substring} always leaves point at the @emph{end} of
5460 the region being inserted.  The second @code{save-excursion} causes
5461 Emacs to leave point at the beginning of the text being inserted.  In
5462 most circumstances, users prefer to find point at the beginning of
5463 inserted text.  (Of course, the @code{copy-to-buffer} function returns
5464 the user to the original buffer when done---but if the user @emph{then}
5465 switches to the copied-to buffer, point will go to the beginning of the
5466 text.  Thus, this use of a second @code{save-excursion} is a little
5467 nicety.)
5469 @node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5470 @comment  node-name,  next,  previous,  up
5471 @section The Definition of @code{insert-buffer}
5472 @findex insert-buffer
5474 @code{insert-buffer} is yet another buffer-related function.  This
5475 command copies another buffer @emph{into} the current buffer.  It is the
5476 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5477 copy a region of text @emph{from} the current buffer to another buffer.
5479 In addition, this code illustrates the use of @code{interactive} with a
5480 buffer that might be @dfn{read-only} and the important distinction
5481 between the name of an object and the object actually referred to.
5483 @menu
5484 * insert-buffer code::
5485 * insert-buffer interactive::   When you can read, but not write.
5486 * insert-buffer body::          The body has an @code{or} and a @code{let}.
5487 * if & or::                     Using an @code{if} instead of an @code{or}.
5488 * Insert or::                   How the @code{or} expression works.
5489 * Insert let::                  Two @code{save-excursion} expressions.
5490 @end menu
5492 @node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5493 @ifnottex
5494 @unnumberedsubsec The Code for @code{insert-buffer}
5495 @end ifnottex
5497 @need 800
5498 Here is the code:
5500 @smallexample
5501 @group
5502 (defun insert-buffer (buffer)
5503   "Insert after point the contents of BUFFER.
5504 Puts mark after the inserted text.
5505 BUFFER may be a buffer or a buffer name."
5506   (interactive "*bInsert buffer:@: ")
5507 @end group
5508 @group
5509   (or (bufferp buffer)
5510       (setq buffer (get-buffer buffer)))
5511   (let (start end newmark)
5512     (save-excursion
5513       (save-excursion
5514         (set-buffer buffer)
5515         (setq start (point-min) end (point-max)))
5516 @end group
5517 @group
5518       (insert-buffer-substring buffer start end)
5519       (setq newmark (point)))
5520     (push-mark newmark)))
5521 @end group
5522 @end smallexample
5524 @need 1200
5525 As with other function definitions, you can use a template to see an
5526 outline of the function:
5528 @smallexample
5529 @group
5530 (defun insert-buffer (buffer)
5531   "@var{documentation}@dots{}"
5532   (interactive "*bInsert buffer:@: ")
5533   @var{body}@dots{})
5534 @end group
5535 @end smallexample
5537 @node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5538 @comment  node-name,  next,  previous,  up
5539 @subsection The Interactive Expression in @code{insert-buffer}
5540 @findex interactive, @r{example use of}
5542 In @code{insert-buffer}, the argument to the @code{interactive}
5543 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5544 buffer:@: }.
5546 @menu
5547 * Read-only buffer::            When a buffer cannot be modified.
5548 * b for interactive::           An existing buffer or else its name.
5549 @end menu
5551 @node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5552 @comment  node-name,  next,  previous,  up
5553 @unnumberedsubsubsec A Read-only Buffer
5554 @cindex Read-only buffer
5555 @cindex Asterisk for read-only buffer
5556 @findex * @r{for read-only buffer}
5558 The asterisk is for the situation when the current buffer is a
5559 read-only buffer---a buffer that cannot be modified.  If
5560 @code{insert-buffer} is called when the current buffer is read-only, a
5561 message to this effect is printed in the echo area and the terminal
5562 may beep or blink at you; you will not be permitted to insert anything
5563 into current buffer.  The asterisk does not need to be followed by a
5564 newline to separate it from the next argument.
5566 @node b for interactive,  , Read-only buffer, insert-buffer interactive
5567 @comment  node-name,  next,  previous,  up
5568 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5570 The next argument in the interactive expression starts with a lower
5571 case @samp{b}.  (This is different from the code for
5572 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5573 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5574 The lower-case @samp{b} tells the Lisp interpreter that the argument
5575 for @code{insert-buffer} should be an existing buffer or else its
5576 name.  (The upper-case @samp{B} option provides for the possibility
5577 that the buffer does not exist.)  Emacs will prompt you for the name
5578 of the buffer, offering you a default buffer, with name completion
5579 enabled.  If the buffer does not exist, you receive a message that
5580 says ``No match''; your terminal may beep at you as well.
5582 @node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5583 @comment  node-name,  next,  previous,  up
5584 @subsection The Body of the @code{insert-buffer} Function
5586 The body of the @code{insert-buffer} function has two major parts: an
5587 @code{or} expression and a @code{let} expression.  The purpose of the
5588 @code{or} expression is to ensure that the argument @code{buffer} is
5589 bound to a buffer and not just the name of a buffer.  The body of the
5590 @code{let} expression contains the code which copies the other buffer
5591 into the current buffer.
5593 @need 1250
5594 In outline, the two expressions fit into the @code{insert-buffer}
5595 function like this:
5597 @smallexample
5598 @group
5599 (defun insert-buffer (buffer)
5600   "@var{documentation}@dots{}"
5601   (interactive "*bInsert buffer:@: ")
5602   (or @dots{}
5603       @dots{}
5604 @end group
5605 @group
5606   (let (@var{varlist})
5607       @var{body-of-}@code{let}@dots{} )
5608 @end group
5609 @end smallexample
5611 To understand how the @code{or} expression ensures that the argument
5612 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5613 is first necessary to understand the @code{or} function.
5615 Before doing this, let me rewrite this part of the function using
5616 @code{if} so that you can see what is done in a manner that will be familiar.
5618 @node if & or, Insert or, insert-buffer body, insert-buffer
5619 @comment  node-name,  next,  previous,  up
5620 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5622 The job to be done is to make sure the value of @code{buffer} is a
5623 buffer itself and not the name of a buffer.  If the value is the name,
5624 then the buffer itself must be got.
5626 You can imagine yourself at a conference where an usher is wandering
5627 around holding a list with your name on it and looking for you: the
5628 usher is ``bound'' to your name, not to you; but when the usher finds
5629 you and takes your arm, the usher becomes ``bound'' to you.
5631 @need 800
5632 In Lisp, you might describe this situation like this:
5634 @smallexample
5635 @group
5636 (if (not (holding-on-to-guest))
5637     (find-and-take-arm-of-guest))
5638 @end group
5639 @end smallexample
5641 We want to do the same thing with a buffer---if we do not have the
5642 buffer itself, we want to get it.
5644 @need 1200
5645 Using a predicate called @code{bufferp} that tells us whether we have a
5646 buffer (rather than its name), we can write the code like this:
5648 @smallexample
5649 @group
5650 (if (not (bufferp buffer))              ; @r{if-part}
5651     (setq buffer (get-buffer buffer)))  ; @r{then-part}
5652 @end group
5653 @end smallexample
5655 @noindent
5656 Here, the true-or-false-test of the @code{if} expression is
5657 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5658 @w{@code{(setq buffer (get-buffer buffer))}}.
5660 In the test, the function @code{bufferp} returns true if its argument is
5661 a buffer---but false if its argument is the name of the buffer.  (The
5662 last character of the function name @code{bufferp} is the character
5663 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5664 indicates that the function is a predicate, which is a term that means
5665 that the function will determine whether some property is true or false.
5666 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5667 Argument}.)
5669 @need 1200
5670 The function @code{not} precedes the expression @code{(bufferp buffer)},
5671 so the true-or-false-test looks like this:
5673 @smallexample
5674 (not (bufferp buffer))
5675 @end smallexample
5677 @noindent
5678 @code{not} is a function that returns true if its argument is false
5679 and false if its argument is true.  So if @code{(bufferp buffer)}
5680 returns true, the @code{not} expression returns false and vice-versa:
5681 what is ``not true'' is false and what is ``not false'' is true.
5683 Using this test, the @code{if} expression works as follows: when the
5684 value of the variable @code{buffer} is actually a buffer rather then
5685 its name, the true-or-false-test returns false and the @code{if}
5686 expression does not evaluate the then-part.  This is fine, since we do
5687 not need to do anything to the variable @code{buffer} if it really is
5688 a buffer.
5690 On the other hand, when the value of @code{buffer} is not a buffer
5691 itself, but the name of a buffer, the true-or-false-test returns true
5692 and the then-part of the expression is evaluated.  In this case, the
5693 then-part is @code{(setq buffer (get-buffer buffer))}.  This
5694 expression uses the @code{get-buffer} function to return an actual
5695 buffer itself, given its name.  The @code{setq} then sets the variable
5696 @code{buffer} to the value of the buffer itself, replacing its previous
5697 value (which was the name of the buffer).
5699 @node Insert or, Insert let, if & or, insert-buffer
5700 @comment  node-name,  next,  previous,  up
5701 @subsection The @code{or} in the Body
5703 The purpose of the @code{or} expression in the @code{insert-buffer}
5704 function is to ensure that the argument @code{buffer} is bound to a
5705 buffer and not just to the name of a buffer.  The previous section shows
5706 how the job could have been done using an @code{if} expression.
5707 However, the @code{insert-buffer} function actually uses @code{or}.
5708 To understand this, it is necessary to understand how @code{or} works.
5710 @findex or
5711 An @code{or} function can have any number of arguments.  It evaluates
5712 each argument in turn and returns the value of the first of its
5713 arguments that is not @code{nil}.  Also, and this is a crucial feature
5714 of @code{or}, it does not evaluate any subsequent arguments after
5715 returning the first non-@code{nil} value.
5717 @need 800
5718 The @code{or} expression looks like this:
5720 @smallexample
5721 @group
5722 (or (bufferp buffer)
5723     (setq buffer (get-buffer buffer)))
5724 @end group
5725 @end smallexample
5727 @noindent
5728 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5729 This expression returns true (a non-@code{nil} value) if the buffer is
5730 actually a buffer, and not just the name of a buffer.  In the @code{or}
5731 expression, if this is the case, the @code{or} expression returns this
5732 true value and does not evaluate the next expression---and this is fine
5733 with us, since we do not want to do anything to the value of
5734 @code{buffer} if it really is a buffer.
5736 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5737 which it will be if the value of @code{buffer} is the name of a buffer,
5738 the Lisp interpreter evaluates the next element of the @code{or}
5739 expression.  This is the expression @code{(setq buffer (get-buffer
5740 buffer))}.  This expression returns a non-@code{nil} value, which
5741 is the value to which it sets the variable @code{buffer}---and this
5742 value is a buffer itself, not the name of a buffer.
5744 The result of all this is that the symbol @code{buffer} is always
5745 bound to a buffer itself rather than to the name of a buffer.  All
5746 this is necessary because the @code{set-buffer} function in a
5747 following line only works with a buffer itself, not with the name to a
5748 buffer.
5750 @need 1250
5751 Incidentally, using @code{or}, the situation with the usher would be
5752 written like this:
5754 @smallexample
5755 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5756 @end smallexample
5758 @node Insert let,  , Insert or, insert-buffer
5759 @comment  node-name,  next,  previous,  up
5760 @subsection The @code{let} Expression in @code{insert-buffer}
5762 After ensuring that the variable @code{buffer} refers to a buffer itself
5763 and not just to the name of a buffer, the @code{insert-buffer function}
5764 continues with a @code{let} expression.  This specifies three local
5765 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5766 to the initial value @code{nil}.  These variables are used inside the
5767 remainder of the @code{let} and temporarily hide any other occurrence of
5768 variables of the same name in Emacs until the end of the @code{let}.
5770 @need 1200
5771 The body of the @code{let} contains two @code{save-excursion}
5772 expressions.  First, we will look at the inner @code{save-excursion}
5773 expression in detail.  The expression looks like this:
5775 @smallexample
5776 @group
5777 (save-excursion
5778   (set-buffer buffer)
5779   (setq start (point-min) end (point-max)))
5780 @end group
5781 @end smallexample
5783 @noindent
5784 The expression @code{(set-buffer buffer)} changes Emacs' attention
5785 from the current buffer to the one from which the text will copied.
5786 In that buffer, the variables @code{start} and @code{end} are set to
5787 the beginning and end of the buffer, using the commands
5788 @code{point-min} and @code{point-max}.  Note that we have here an
5789 illustration of how @code{setq} is able to set two variables in the
5790 same expression.  The first argument of @code{setq} is set to the
5791 value of its second, and its third argument is set to the value of its
5792 fourth.
5794 After the body of the inner @code{save-excursion} is evaluated, the
5795 @code{save-excursion} restores the original buffer, but @code{start} and
5796 @code{end} remain set to the values of the beginning and end of the
5797 buffer from which the text will be copied.
5799 @need 1250
5800 The outer @code{save-excursion} expression looks like this:
5802 @smallexample
5803 @group
5804 (save-excursion
5805   (@var{inner-}@code{save-excursion}@var{-expression}
5806      (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5807   (insert-buffer-substring buffer start end)
5808   (setq newmark (point)))
5809 @end group
5810 @end smallexample
5812 @noindent
5813 The @code{insert-buffer-substring} function copies the text
5814 @emph{into} the current buffer @emph{from} the region indicated by
5815 @code{start} and @code{end} in @code{buffer}.  Since the whole of the
5816 second buffer lies between @code{start} and @code{end}, the whole of
5817 the second buffer is copied into the buffer you are editing.  Next,
5818 the value of point, which will be at the end of the inserted text, is
5819 recorded in the variable @code{newmark}.
5821 After the body of the outer @code{save-excursion} is evaluated, point
5822 and mark are relocated to their original places.
5824 However, it is convenient to locate a mark at the end of the newly
5825 inserted text and locate point at its beginning.  The @code{newmark}
5826 variable records the end of the inserted text.  In the last line of
5827 the @code{let} expression, the @code{(push-mark newmark)} expression
5828 function sets a mark to this location.  (The previous location of the
5829 mark is still accessible; it is recorded on the mark ring and you can
5830 go back to it with @kbd{C-u C-@key{SPC}}.)  Meanwhile, point is
5831 located at the beginning of the inserted text, which is where it was
5832 before you called the insert function.
5834 @need 1250
5835 The whole @code{let} expression looks like this:
5837 @smallexample
5838 @group
5839 (let (start end newmark)
5840   (save-excursion
5841     (save-excursion
5842       (set-buffer buffer)
5843       (setq start (point-min) end (point-max)))
5844     (insert-buffer-substring buffer start end)
5845     (setq newmark (point)))
5846   (push-mark newmark))
5847 @end group
5848 @end smallexample
5850 Like the @code{append-to-buffer} function, the @code{insert-buffer}
5851 function uses @code{let}, @code{save-excursion}, and
5852 @code{set-buffer}.  In addition, the function illustrates one way to
5853 use @code{or}.  All these functions are building blocks that we will
5854 find and use again and again.
5856 @node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5857 @comment  node-name,  next,  previous,  up
5858 @section Complete Definition of @code{beginning-of-buffer}
5859 @findex beginning-of-buffer
5861 The basic structure of the @code{beginning-of-buffer} function has
5862 already been discussed.  (@xref{simplified-beginning-of-buffer, , A
5863 Simplified @code{beginning-of-buffer} Definition}.)
5864 This section describes the complex part of the definition.
5866 As previously described, when invoked without an argument,
5867 @code{beginning-of-buffer} moves the cursor to the beginning of the
5868 buffer, leaving the mark at the previous position.  However, when the
5869 command is invoked with a number between one and ten, the function
5870 considers that number to be a fraction of the length of the buffer,
5871 measured in tenths, and Emacs moves the cursor that fraction of the way
5872 from the beginning of the buffer.  Thus, you can either call this
5873 function with the key command @kbd{M-<}, which will move the cursor to
5874 the beginning of the buffer, or with a key command such as @kbd{C-u 7
5875 M-<} which will move the cursor to a point 70% of the way through the
5876 buffer.  If a number bigger than ten is used for the argument, it moves
5877 to the end of the buffer.
5879 The @code{beginning-of-buffer} function can be called with or without an
5880 argument.  The use of the argument is optional.
5882 @menu
5883 * Optional Arguments::
5884 * beginning-of-buffer opt arg::  Example with optional argument.
5885 * beginning-of-buffer complete::
5886 @end menu
5888 @node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5889 @subsection Optional Arguments
5891 Unless told otherwise, Lisp expects that a function with an argument in
5892 its function definition will be called with a value for that argument.
5893 If that does not happen, you get an error and a message that says
5894 @samp{Wrong number of arguments}.
5896 @cindex Optional arguments
5897 @cindex Keyword
5898 @findex optional
5899 However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5900 be used to tell the Lisp interpreter that an argument is optional.
5901 The keyword is @code{&optional}.  (The @samp{&} in front of
5902 @samp{optional} is part of the keyword.)  In a function definition, if
5903 an argument follows the keyword @code{&optional}, a value does not
5904 need to be passed to that argument when the function is called.
5906 @need 1200
5907 The first line of the function definition of @code{beginning-of-buffer}
5908 therefore looks like this:
5910 @smallexample
5911 (defun beginning-of-buffer (&optional arg)
5912 @end smallexample
5914 @need 1250
5915 In outline, the whole function looks like this:
5917 @smallexample
5918 @group
5919 (defun beginning-of-buffer (&optional arg)
5920   "@var{documentation}@dots{}"
5921   (interactive "P")
5922   (push-mark)
5923   (goto-char
5924     (@var{if-there-is-an-argument}
5925         @var{figure-out-where-to-go}
5926       @var{else-go-to}
5927       (point-min))))
5928 @end group
5929 @end smallexample
5931 The function is similar to the @code{simplified-beginning-of-buffer}
5932 function except that the @code{interactive} expression has @code{"P"}
5933 as an argument and the @code{goto-char} function is followed by an
5934 if-then-else expression that figures out where to put the cursor if
5935 there is an argument.
5937 The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5938 a prefix argument, if there is one, to the function.  A prefix argument
5939 is made by typing the @key{META} key followed by a number, or by typing
5940 @kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5941 defaults to 4).
5943 The true-or-false-test of the @code{if} expression is simple: it is
5944 simply the argument @code{arg}.  If @code{arg} has a value that is not
5945 @code{nil}, which will be the case if @code{beginning-of-buffer} is
5946 called with an argument, then this true-or-false-test will return true
5947 and the then-part of the @code{if} expression will be evaluated.  On the
5948 other hand, if @code{beginning-of-buffer} is not called with an
5949 argument, the value of @code{arg} will be @code{nil} and the else-part
5950 of the @code{if} expression will be evaluated.  The else-part is simply
5951 @code{point-min}, and when this is the outcome, the whole
5952 @code{goto-char} expression is @code{(goto-char (point-min))}, which is
5953 how we saw the @code{beginning-of-buffer} function in its simplified
5954 form.
5956 @node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5957 @subsection @code{beginning-of-buffer} with an Argument
5959 When @code{beginning-of-buffer} is called with an argument, an
5960 expression is evaluated which calculates what value to pass to
5961 @code{goto-char}.  This expression is rather complicated at first sight.
5962 It includes an inner @code{if} expression and much arithmetic.  It looks
5963 like this:
5965 @smallexample
5966 @group
5967 (if (> (buffer-size) 10000)
5968     ;; @r{Avoid overflow for large buffer sizes!}
5969     (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5970   (/
5971    (+ 10
5972       (*
5973        (buffer-size) (prefix-numeric-value arg))) 10))
5974 @end group
5975 @end smallexample
5977 @menu
5978 * Disentangle beginning-of-buffer::
5979 * Large buffer case::
5980 * Small buffer case::
5981 @end menu
5983 @node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5984 @ifnottex
5985 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5986 @end ifnottex
5988 Like other complex-looking expressions, the conditional expression
5989 within @code{beginning-of-buffer} can be disentangled by looking at it
5990 as parts of a template, in this case, the template for an if-then-else
5991 expression.  In skeletal form, the expression looks like this:
5993 @smallexample
5994 @group
5995 (if (@var{buffer-is-large}
5996     @var{divide-buffer-size-by-10-and-multiply-by-arg}
5997   @var{else-use-alternate-calculation}
5998 @end group
5999 @end smallexample
6001 The true-or-false-test of this inner @code{if} expression checks the
6002 size of the buffer.  The reason for this is that the old Version 18
6003 Emacs used numbers that are no bigger than eight million or so
6004 and in the computation that followed, the programmer feared that Emacs
6005 might try to use over-large numbers if the buffer were large.  The
6006 term `overflow', mentioned in the comment, means numbers that are over
6007 large.  Version 21 Emacs uses larger numbers, but this code has not
6008 been touched, if only because people now look at buffers that are far,
6009 far larger than ever before.
6011 There are two cases:  if the buffer is large and if it is not.
6013 @node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
6014 @comment  node-name,  next,  previous,  up
6015 @unnumberedsubsubsec What happens in a large buffer
6017 In @code{beginning-of-buffer}, the inner @code{if} expression tests
6018 whether the size of the buffer is greater than 10,000 characters.  To do
6019 this, it uses the @code{>} function and the @code{buffer-size} function.
6021 @need 800
6022 The line looks like this:
6024 @smallexample
6025 (if (> (buffer-size) 10000)
6026 @end smallexample
6028 @need 1200
6029 @noindent
6030 When the buffer is large, the then-part of the @code{if} expression is
6031 evaluated.  It reads like this (after formatting for easy reading):
6033 @smallexample
6034 @group
6036   (prefix-numeric-value arg)
6037   (/ (buffer-size) 10))
6038 @end group
6039 @end smallexample
6041 @noindent
6042 This expression is a multiplication, with two arguments to the function
6043 @code{*}.
6045 The first argument is @code{(prefix-numeric-value arg)}.  When
6046 @code{"P"} is used as the argument for @code{interactive}, the value
6047 passed to the function as its argument is passed a ``raw prefix
6048 argument'', and not a number.  (It is a number in a list.)  To perform
6049 the arithmetic, a conversion is necessary, and
6050 @code{prefix-numeric-value} does the job.
6052 @findex / @r{(division)}
6053 @cindex Division
6054 The second argument is @code{(/ (buffer-size) 10)}.  This expression
6055 divides the numeric value of the buffer by ten.  This produces a number
6056 that tells how many characters make up one tenth of the buffer size.
6057 (In Lisp, @code{/} is used for division, just as @code{*} is
6058 used for multiplication.)
6060 @need 1200
6061 In the multiplication expression as a whole, this amount is multiplied
6062 by the value of the prefix argument---the multiplication looks like this:
6064 @smallexample
6065 @group
6066 (* @var{numeric-value-of-prefix-arg}
6067    @var{number-of-characters-in-one-tenth-of-the-buffer})
6068 @end group
6069 @end smallexample
6071 @noindent
6072 If, for example, the prefix argument is @samp{7}, the one-tenth value
6073 will be multiplied by 7 to give a position 70% of the way through the
6074 buffer.
6076 @need 1200
6077 The result of all this is that if the buffer is large, the
6078 @code{goto-char} expression reads like this:
6080 @smallexample
6081 @group
6082 (goto-char (* (prefix-numeric-value arg)
6083               (/ (buffer-size) 10)))
6084 @end group
6085 @end smallexample
6087 This puts the cursor where we want it.
6089 @node Small buffer case,  , Large buffer case, beginning-of-buffer opt arg
6090 @comment  node-name,  next,  previous,  up
6091 @unnumberedsubsubsec What happens in a small buffer
6093 If the buffer contains fewer than 10,000 characters, a slightly
6094 different computation is performed.  You might think this is not
6095 necessary, since the first computation could do the job.  However, in
6096 a small buffer, the first method may not put the cursor on exactly the
6097 desired line; the second method does a better job.
6099 @need 800
6100 The code looks like this:
6102 @c Keep this on one line.
6103 @smallexample
6104 (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6105 @end smallexample
6107 @need 1200
6108 @noindent
6109 This is code in which you figure out what happens by discovering how the
6110 functions are embedded in parentheses.  It is easier to read if you
6111 reformat it with each expression indented more deeply than its
6112 enclosing expression:
6114 @smallexample
6115 @group
6116   (/
6117    (+ 10
6118       (*
6119        (buffer-size)
6120        (prefix-numeric-value arg)))
6121    10))
6122 @end group
6123 @end smallexample
6125 @need 1200
6126 @noindent
6127 Looking at parentheses, we see that the innermost operation is
6128 @code{(prefix-numeric-value arg)}, which converts the raw argument to a
6129 number.  This number is multiplied by the buffer size in the following
6130 expression:
6132 @smallexample
6133 (* (buffer-size) (prefix-numeric-value arg)
6134 @end smallexample
6136 @noindent
6137 This multiplication creates a number that may be larger than the size of
6138 the buffer---seven times larger if the argument is 7, for example.  Ten
6139 is then added to this number and finally the large number is divided by
6140 ten to provide a value that is one character larger than the percentage
6141 position in the buffer.
6143 The number that results from all this is passed to @code{goto-char} and
6144 the cursor is moved to that point.
6146 @node beginning-of-buffer complete,  , beginning-of-buffer opt arg, beginning-of-buffer
6147 @comment  node-name,  next,  previous,  up
6148 @subsection The Complete @code{beginning-of-buffer}
6150 @need 800
6151 Here is the complete text of the @code{beginning-of-buffer} function:
6153 @smallexample
6154 @group
6155 (defun beginning-of-buffer (&optional arg)
6156   "Move point to the beginning of the buffer;
6157 leave mark at previous position.
6158 With arg N, put point N/10 of the way
6159 from the true beginning.
6160 Don't use this in Lisp programs!
6161 \(goto-char (point-min)) is faster
6162 and does not set the mark."
6163   (interactive "P")
6164   (push-mark)
6165 @end group
6166 @group
6167   (goto-char
6168    (if arg
6169        (if (> (buffer-size) 10000)
6170            ;; @r{Avoid overflow for large buffer sizes!}
6171            (* (prefix-numeric-value arg)
6172               (/ (buffer-size) 10))
6173 @end group
6174 @group
6175          (/ (+ 10 (* (buffer-size)
6176                      (prefix-numeric-value arg)))
6177             10))
6178      (point-min)))
6179   (if arg (forward-line 1)))
6180 @end group
6181 @end smallexample
6183 @noindent
6184 Except for two small points, the previous discussion shows how this
6185 function works.  The first point deals with a detail in the
6186 documentation string, and the second point concerns the last line of
6187 the function.
6189 @need 800
6190 In the documentation string, there is reference to an expression:
6192 @smallexample
6193 \(goto-char (point-min))
6194 @end smallexample
6196 @noindent
6197 A @samp{\} is used before the first parenthesis of this expression.
6198 This @samp{\} tells the Lisp interpreter that the expression should be
6199 printed as shown in the documentation rather than evaluated as a
6200 symbolic expression, which is what it looks like.
6202 @need 1200
6203 Finally, the last line of the @code{beginning-of-buffer} command says to
6204 move point to the beginning of the next line if the command is
6205 invoked with an argument:
6207 @smallexample
6208 (if arg (forward-line 1)))
6209 @end smallexample
6211 @noindent
6212 This puts the cursor at the beginning of the first line after the
6213 appropriate tenths position in the buffer.  This is a flourish that
6214 means that the cursor is always located @emph{at least} the requested
6215 tenths of the way through the buffer, which is a nicety that is,
6216 perhaps, not necessary, but which, if it did not occur, would be sure to
6217 draw complaints.
6219 @node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6220 @comment  node-name,  next,  previous,  up
6221 @section Review
6223 Here is a brief summary of some of the topics covered in this chapter.
6225 @table @code
6226 @item or
6227 Evaluate each argument in sequence, and return the value of the first
6228 argument that is not @code{nil}; if none return a value that is not
6229 @code{nil}, return @code{nil}.  In brief, return the first true value
6230 of the arguments; return a true value if one @emph{or} any of the
6231 other are true.
6233 @item and
6234 Evaluate each argument in sequence, and if any are @code{nil}, return
6235 @code{nil}; if none are @code{nil}, return the value of the last
6236 argument.  In brief, return a true value only if all the arguments are
6237 true; return a true value if one @emph{and} each of the others is
6238 true.
6240 @item &optional
6241 A keyword used to indicate that an argument to a function definition
6242 is optional; this means that the function can be evaluated without the
6243 argument, if desired.
6245 @item prefix-numeric-value
6246 Convert the `raw prefix argument' produced by @code{(interactive
6247 "P")} to a numeric value.
6249 @item forward-line
6250 Move point forward to the beginning of the next line, or if the argument
6251 is greater than one, forward that many lines.  If it can't move as far
6252 forward as it is supposed to, @code{forward-line} goes forward as far as
6253 it can and then returns a count of the number of additional lines it was
6254 supposed to move but couldn't.
6256 @item erase-buffer
6257 Delete the entire contents of the current buffer.
6259 @item bufferp
6260 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6261 @end table
6263 @node optional Exercise,  , Second Buffer Related Review, More Complex
6264 @section @code{optional} Argument Exercise
6266 Write an interactive function with an optional argument that tests
6267 whether its argument, a number, is greater or less than the value of
6268 @code{fill-column}, and tells you which, in a message.  However, if you
6269 do not pass an argument to the function, use 56 as a default value.
6271 @node Narrowing & Widening, car cdr & cons, More Complex, Top
6272 @comment  node-name,  next,  previous,  up
6273 @chapter Narrowing and Widening
6274 @cindex Focusing attention (narrowing)
6275 @cindex Narrowing
6276 @cindex Widening
6278 Narrowing is a feature of Emacs that makes it possible for you to focus
6279 on a specific part of a buffer, and work without accidentally changing
6280 other parts.  Narrowing is normally disabled since it can confuse
6281 novices.
6283 @menu
6284 * Narrowing advantages::        The advantages of narrowing
6285 * save-restriction::            The @code{save-restriction} special form.
6286 * what-line::                   The number of the line that point is on.
6287 * narrow Exercise::
6288 @end menu
6290 @node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6291 @ifnottex
6292 @unnumberedsec The Advantages of Narrowing
6293 @end ifnottex
6295 With narrowing, the rest of a buffer is made invisible, as if it weren't
6296 there.  This is an advantage if, for example, you want to replace a word
6297 in one part of a buffer but not in another: you narrow to the part you want
6298 and the replacement is carried out only in that section, not in the rest
6299 of the buffer.  Searches will only work within a narrowed region, not
6300 outside of one, so if you are fixing a part of a document, you can keep
6301 yourself from accidentally finding parts you do not need to fix by
6302 narrowing just to the region you want.
6303 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6305 However, narrowing does make the rest of the buffer invisible, which
6306 can scare people who inadvertently invoke narrowing and think they
6307 have deleted a part of their file.  Moreover, the @code{undo} command
6308 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6309 (nor should it), so people can become quite desperate if they do not
6310 know that they can return the rest of a buffer to visibility with the
6311 @code{widen} command.
6312 (The key binding for @code{widen} is @kbd{C-x n w}.)
6314 Narrowing is just as useful to the Lisp interpreter as to a human.
6315 Often, an Emacs Lisp function is designed to work on just part of a
6316 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6317 buffer that has been narrowed.  The @code{what-line} function, for
6318 example, removes the narrowing from a buffer, if it has any narrowing
6319 and when it has finished its job, restores the narrowing to what it was.
6320 On the other hand, the @code{count-lines} function, which is called by
6321 @code{what-line}, uses narrowing to restrict itself to just that portion
6322 of the buffer in which it is interested and then restores the previous
6323 situation.
6325 @node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6326 @comment  node-name,  next,  previous,  up
6327 @section The @code{save-restriction} Special Form
6328 @findex save-restriction
6330 In Emacs Lisp, you can use the @code{save-restriction} special form to
6331 keep track of whatever narrowing is in effect, if any.  When the Lisp
6332 interpreter meets with @code{save-restriction}, it executes the code
6333 in the body of the @code{save-restriction} expression, and then undoes
6334 any changes to narrowing that the code caused.  If, for example, the
6335 buffer is narrowed and the code that follows @code{save-restriction}
6336 gets rid of the narrowing, @code{save-restriction} returns the buffer
6337 to its narrowed region afterwards.  In the @code{what-line} command,
6338 any narrowing the buffer may have is undone by the @code{widen}
6339 command that immediately follows the @code{save-restriction} command.
6340 Any original narrowing is restored just before the completion of the
6341 function.
6343 @need 1250
6344 The template for a @code{save-restriction} expression is simple:
6346 @smallexample
6347 @group
6348 (save-restriction
6349   @var{body}@dots{} )
6350 @end group
6351 @end smallexample
6353 @noindent
6354 The body of the @code{save-restriction} is one or more expressions that
6355 will be evaluated in sequence by the Lisp interpreter.
6357 Finally, a point to note: when you use both @code{save-excursion} and
6358 @code{save-restriction}, one right after the other, you should use
6359 @code{save-excursion} outermost.  If you write them in reverse order,
6360 you may fail to record narrowing in the buffer to which Emacs switches
6361 after calling @code{save-excursion}.  Thus, when written together,
6362 @code{save-excursion} and @code{save-restriction} should be written
6363 like this:
6365 @smallexample
6366 @group
6367 (save-excursion
6368   (save-restriction
6369     @var{body}@dots{}))
6370 @end group
6371 @end smallexample
6373 In other circumstances, when not written together, the
6374 @code{save-excursion} and @code{save-restriction} special forms must
6375 be written in the order appropriate to the function.
6377 @need 1250
6378 For example,
6380 @smallexample
6381 @group
6382   (save-restriction
6383     (widen)
6384     (save-excursion
6385     @var{body}@dots{}))
6386 @end group
6387 @end smallexample
6389 @node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6390 @comment  node-name,  next,  previous,  up
6391 @section @code{what-line}
6392 @findex what-line
6393 @cindex Widening, example of
6395 The @code{what-line} command tells you the number of the line in which
6396 the cursor is located.  The function illustrates the use of the
6397 @code{save-restriction} and @code{save-excursion} commands.  Here is the
6398 text of the function in full:
6400 @smallexample
6401 @group
6402 (defun what-line ()
6403   "Print the current line number (in the buffer) of point."
6404   (interactive)
6405   (save-restriction
6406     (widen)
6407     (save-excursion
6408       (beginning-of-line)
6409       (message "Line %d"
6410                (1+ (count-lines 1 (point)))))))
6411 @end group
6412 @end smallexample
6414 The function has a documentation line and is interactive, as you would
6415 expect.  The next two lines use the functions @code{save-restriction} and
6416 @code{widen}.
6418 The @code{save-restriction} special form notes whatever narrowing is in
6419 effect, if any, in the current buffer and restores that narrowing after
6420 the code in the body of the @code{save-restriction} has been evaluated.
6422 The @code{save-restriction} special form is followed by @code{widen}.
6423 This function undoes any narrowing the current buffer may have had
6424 when @code{what-line} was called.  (The narrowing that was there is
6425 the narrowing that @code{save-restriction} remembers.)  This widening
6426 makes it possible for the line counting commands to count from the
6427 beginning of the buffer.  Otherwise, they would have been limited to
6428 counting within the accessible region.  Any original narrowing is
6429 restored just before the completion of the function by the
6430 @code{save-restriction} special form.
6432 The call to @code{widen} is followed by @code{save-excursion}, which
6433 saves the location of the cursor (i.e., of point) and of the mark, and
6434 restores them after the code in the body of the @code{save-excursion}
6435 uses the @code{beginning-of-line} function to move point.
6437 (Note that the @code{(widen)} expression comes between the
6438 @code{save-restriction} and @code{save-excursion} special forms.  When
6439 you write the two @code{save- @dots{}} expressions in sequence, write
6440 @code{save-excursion} outermost.)
6442 @need 1200
6443 The last two lines of the @code{what-line} function are functions to
6444 count the number of lines in the buffer and then print the number in the
6445 echo area.
6447 @smallexample
6448 @group
6449 (message "Line %d"
6450          (1+ (count-lines 1 (point)))))))
6451 @end group
6452 @end smallexample
6454 The @code{message} function prints a one-line message at the bottom of the
6455 Emacs screen.  The first argument is inside of quotation marks and is
6456 printed as a string of characters.  However, it may contain @samp{%d},
6457 @samp{%s}, or @samp{%c} to print arguments that follow the string.
6458 @samp{%d} prints the argument as a decimal, so the message will say
6459 something such as @samp{Line 243}.
6461 @need 1200
6462 The number that is printed in place of the @samp{%d} is computed by the
6463 last line of the function:
6465 @smallexample
6466 (1+ (count-lines 1 (point)))
6467 @end smallexample
6469 @noindent
6470 What this does is count the lines from the first position of the
6471 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6472 one to that number.  (The @code{1+} function adds one to its
6473 argument.)  We add one to it because line 2 has only one line before
6474 it, and @code{count-lines} counts only the lines @emph{before} the
6475 current line.
6477 After @code{count-lines} has done its job, and the message has been
6478 printed in the echo area, the @code{save-excursion} restores point and
6479 mark to their original positions; and @code{save-restriction} restores
6480 the original narrowing, if any.
6482 @node narrow Exercise,  , what-line, Narrowing & Widening
6483 @section Exercise with Narrowing
6485 Write a function that will display the first 60 characters of the
6486 current buffer, even if you have narrowed the buffer to its latter
6487 half so that the first line is inaccessible.  Restore point, mark,
6488 and narrowing.  For this exercise, you need to use
6489 @code{save-restriction}, @code{widen}, @code{goto-char},
6490 @code{point-min}, @code{buffer-substring}, @code{message}, and other
6491 functions, a whole potpourri.
6493 @node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6494 @comment  node-name,  next,  previous,  up
6495 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6496 @findex car, @r{introduced}
6497 @findex cdr, @r{introduced}
6499 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6500 functions.  The @code{cons} function is used to construct lists, and
6501 the @code{car} and @code{cdr} functions are used to take them apart.
6503 In the walk through of the @code{copy-region-as-kill} function, we
6504 will see @code{cons} as well as two variants on @code{cdr},
6505 namely, @code{setcdr} and @code{nthcdr}.  (@xref{copy-region-as-kill}.)
6507 @menu
6508 * Strange Names::               An historical aside: why the strange names?
6509 * car & cdr::                   Functions for extracting part of a list.
6510 * cons::                        Constructing a list.
6511 * nthcdr::                      Calling @code{cdr} repeatedly.
6512 * nth::
6513 * setcar::                      Changing the first element of a list.
6514 * setcdr::                      Changing the rest of a list.
6515 * cons Exercise::
6516 @end menu
6518 @node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6519 @ifnottex
6520 @unnumberedsec Strange Names
6521 @end ifnottex
6523 The name of the @code{cons} function is not unreasonable: it is an
6524 abbreviation of the word `construct'.  The origins of the names for
6525 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6526 is an acronym from the phrase `Contents of the Address part of the
6527 Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6528 the phrase `Contents of the Decrement part of the Register'.  These
6529 phrases refer to specific pieces of hardware on the very early
6530 computer on which the original Lisp was developed.  Besides being
6531 obsolete, the phrases have been completely irrelevant for more than 25
6532 years to anyone thinking about Lisp.  Nonetheless, although a few
6533 brave scholars have begun to use more reasonable names for these
6534 functions, the old terms are still in use.  In particular, since the
6535 terms are used in the Emacs Lisp source code, we will use them in this
6536 introduction.
6538 @node car & cdr, cons, Strange Names, car cdr & cons
6539 @comment  node-name,  next,  previous,  up
6540 @section @code{car} and @code{cdr}
6542 The @sc{car} of a list is, quite simply, the first item in the list.
6543 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6544 @code{rose}.
6546 @need 1200
6547 If you are reading this in Info in GNU Emacs, you can see this by
6548 evaluating the following:
6550 @smallexample
6551 (car '(rose violet daisy buttercup))
6552 @end smallexample
6554 @noindent
6555 After evaluating the expression, @code{rose} will appear in the echo
6556 area.
6558 Clearly, a more reasonable name for the @code{car} function would be
6559 @code{first} and this is often suggested.
6561 @code{car} does not remove the first item from the list; it only reports
6562 what it is.  After @code{car} has been applied to a list, the list is
6563 still the same as it was.  In the jargon, @code{car} is
6564 `non-destructive'.  This feature turns out to be important.
6566 The @sc{cdr} of a list is the rest of the list, that is, the
6567 @code{cdr} function returns the part of the list that follows the
6568 first item.  Thus, while the @sc{car} of the list @code{'(rose violet
6569 daisy buttercup)} is @code{rose}, the rest of the list, the value
6570 returned by the @code{cdr} function, is @code{(violet daisy
6571 buttercup)}.
6573 @need 1250
6574 You can see this by evaluating the following in the usual way:
6576 @smallexample
6577 (cdr '(rose violet daisy buttercup))
6578 @end smallexample
6580 @noindent
6581 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6582 the echo area.
6584 Like @code{car}, @code{cdr} does not remove any elements from the
6585 list---it just returns a report of what the second and subsequent
6586 elements are.
6588 Incidentally, in the example, the list of flowers is quoted.  If it were
6589 not, the Lisp interpreter would try to evaluate the list by calling
6590 @code{rose} as a function.  In this example, we do not want to do that.
6592 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6594 (There is a lesson here: when you name new functions, consider very
6595 carefully what you are doing, since you may be stuck with the names
6596 for far longer than you expect.  The reason this document perpetuates
6597 these names is that the Emacs Lisp source code uses them, and if I did
6598 not use them, you would have a hard time reading the code; but do,
6599 please, try to avoid using these terms yourself.  The people who come
6600 after you will be grateful to you.)
6602 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6603 such as the list @code{(pine fir oak maple)}, the element of the list
6604 returned by the function @code{car} is the symbol @code{pine} without
6605 any parentheses around it.  @code{pine} is the first element in the
6606 list.  However, the @sc{cdr} of the list is a list itself, @code{(fir
6607 oak maple)}, as you can see by evaluating the following expressions in
6608 the usual way:
6610 @smallexample
6611 @group
6612 (car '(pine fir oak maple))
6614 (cdr '(pine fir oak maple))
6615 @end group
6616 @end smallexample
6618 On the other hand, in a list of lists, the first element is itself a
6619 list.  @code{car} returns this first element as a list.  For example,
6620 the following list contains three sub-lists, a list of carnivores, a
6621 list of herbivores and a list of sea mammals:
6623 @smallexample
6624 @group
6625 (car '((lion tiger cheetah)
6626        (gazelle antelope zebra)
6627        (whale dolphin seal)))
6628 @end group
6629 @end smallexample
6631 @noindent
6632 In this example, the first element or @sc{car} of the list is the list of
6633 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6634 @code{((gazelle antelope zebra) (whale dolphin seal))}.
6636 @smallexample
6637 @group
6638 (cdr '((lion tiger cheetah)
6639        (gazelle antelope zebra)
6640        (whale dolphin seal)))
6641 @end group
6642 @end smallexample
6644 It is worth saying again that @code{car} and @code{cdr} are
6645 non-destructive---that is, they do not modify or change lists to which
6646 they are applied.  This is very important for how they are used.
6648 Also, in the first chapter, in the discussion about atoms, I said that
6649 in Lisp, ``certain kinds of atom, such as an array, can be separated
6650 into parts; but the mechanism for doing this is different from the
6651 mechanism for splitting a list.  As far as Lisp is concerned, the
6652 atoms of a list are unsplittable.''  (@xref{Lisp Atoms}.)  The
6653 @code{car} and @code{cdr} functions are used for splitting lists and
6654 are considered fundamental to Lisp.  Since they cannot split or gain
6655 access to the parts of an array, an array is considered an atom.
6656 Conversely, the other fundamental function, @code{cons}, can put
6657 together or construct a list, but not an array.  (Arrays are handled
6658 by array-specific functions.  @xref{Arrays, , Arrays, elisp, The GNU
6659 Emacs Lisp Reference Manual}.)
6661 @node cons, nthcdr, car & cdr, car cdr & cons
6662 @comment  node-name,  next,  previous,  up
6663 @section @code{cons}
6664 @findex cons, @r{introduced}
6666 The @code{cons} function constructs lists; it is the inverse of
6667 @code{car} and @code{cdr}.  For example, @code{cons} can be used to make
6668 a four element list from the three element list, @code{(fir oak maple)}:
6670 @smallexample
6671 (cons 'pine '(fir oak maple))
6672 @end smallexample
6674 @need 800
6675 @noindent
6676 After evaluating this list, you will see
6678 @smallexample
6679 (pine fir oak maple)
6680 @end smallexample
6682 @noindent
6683 appear in the echo area.  @code{cons} causes the creation of a new
6684 list in which the element is followed by the elements of the original
6685 list.
6687 We often say that `@code{cons} puts a new element at the beginning of
6688 a list; it attaches or pushes elements onto the list', but this
6689 phrasing can be misleading, since @code{cons} does not change an
6690 existing list, but creates a new one.
6692 Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
6694 @menu
6695 * Build a list::
6696 * length::                      How to find the length of a list.
6697 @end menu
6699 @node Build a list, length, cons, cons
6700 @ifnottex
6701 @unnumberedsubsec Build a list
6702 @end ifnottex
6704 @code{cons} must have a list to attach to.@footnote{Actually, you can
6705 @code{cons} an element to an atom to produce a dotted pair.  Dotted
6706 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6707 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.}  You
6708 cannot start from absolutely nothing.  If you are building a list, you
6709 need to provide at least an empty list at the beginning.  Here is a
6710 series of @code{cons} expressions that build up a list of flowers.  If
6711 you are reading this in Info in GNU Emacs, you can evaluate each of
6712 the expressions in the usual way; the value is printed in this text
6713 after @samp{@result{}}, which you may read as `evaluates to'.
6715 @smallexample
6716 @group
6717 (cons 'buttercup ())
6718      @result{} (buttercup)
6719 @end group
6721 @group
6722 (cons 'daisy '(buttercup))
6723      @result{} (daisy buttercup)
6724 @end group
6726 @group
6727 (cons 'violet '(daisy buttercup))
6728      @result{} (violet daisy buttercup)
6729 @end group
6731 @group
6732 (cons 'rose '(violet daisy buttercup))
6733      @result{} (rose violet daisy buttercup)
6734 @end group
6735 @end smallexample
6737 @noindent
6738 In the first example, the empty list is shown as @code{()} and a list
6739 made up of @code{buttercup} followed by the empty list is constructed.
6740 As you can see, the empty list is not shown in the list that was
6741 constructed.  All that you see is @code{(buttercup)}.  The empty list is
6742 not counted as an element of a list because there is nothing in an empty
6743 list.  Generally speaking, an empty list is invisible.
6745 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6746 two element list by putting @code{daisy} in front of @code{buttercup};
6747 and the third example constructs a three element list by putting
6748 @code{violet} in front of @code{daisy} and @code{buttercup}.
6750 @node length,  , Build a list, cons
6751 @comment  node-name,  next,  previous,  up
6752 @subsection Find the Length of a List: @code{length}
6753 @findex length
6755 You can find out how many elements there are in a list by using the Lisp
6756 function @code{length}, as in the following examples:
6758 @smallexample
6759 @group
6760 (length '(buttercup))
6761      @result{} 1
6762 @end group
6764 @group
6765 (length '(daisy buttercup))
6766      @result{} 2
6767 @end group
6769 @group
6770 (length (cons 'violet '(daisy buttercup)))
6771      @result{} 3
6772 @end group
6773 @end smallexample
6775 @noindent
6776 In the third example, the @code{cons} function is used to construct a
6777 three element list which is then passed to the @code{length} function as
6778 its argument.
6780 @need 1200
6781 We can also use @code{length} to count the number of elements in an
6782 empty list:
6784 @smallexample
6785 @group
6786 (length ())
6787      @result{} 0
6788 @end group
6789 @end smallexample
6791 @noindent
6792 As you would expect, the number of elements in an empty list is zero.
6794 An interesting experiment is to find out what happens if you try to find
6795 the length of no list at all; that is, if you try to call @code{length}
6796 without giving it an argument, not even an empty list:
6798 @smallexample
6799 (length )
6800 @end smallexample
6802 @need 800
6803 @noindent
6804 What you see, if you evaluate this, is the error message
6806 @smallexample
6807 Wrong number of arguments: #<subr length>, 0
6808 @end smallexample
6810 @noindent
6811 This means that the function receives the wrong number of
6812 arguments, zero, when it expects some other number of arguments.  In
6813 this case, one argument is expected, the argument being a list whose
6814 length the function is measuring.  (Note that @emph{one} list is
6815 @emph{one} argument, even if the list has many elements inside it.)
6817 The part of the error message that says @samp{#<subr length>} is the
6818 name of the function.  This is written with a special notation,
6819 @samp{#<subr}, that indicates that the function @code{length} is one
6820 of the primitive functions written in C rather than in Emacs Lisp.
6821 (@samp{subr} is an abbreviation for `subroutine'.)  @xref{What Is a
6822 Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6823 Manual}, for more about subroutines.
6825 @node nthcdr, nth, cons, car cdr & cons
6826 @comment  node-name,  next,  previous,  up
6827 @section @code{nthcdr}
6828 @findex nthcdr
6830 The @code{nthcdr} function is associated with the @code{cdr} function.
6831 What it does is take the @sc{cdr} of a list repeatedly.
6833 If you take the @sc{cdr} of the list @code{(pine fir
6834 oak maple)}, you will be returned the list @code{(fir oak maple)}.  If you
6835 repeat this on what was returned, you will be returned the list
6836 @code{(oak maple)}.  (Of course, repeated @sc{cdr}ing on the original
6837 list will just give you the original @sc{cdr} since the function does
6838 not change the list.  You need to evaluate the @sc{cdr} of the
6839 @sc{cdr} and so on.)  If you continue this, eventually you will be
6840 returned an empty list, which in this case, instead of being shown as
6841 @code{()} is shown as @code{nil}.
6843 @need 1200
6844 For review, here is a series of repeated @sc{cdr}s, the text following
6845 the @samp{@result{}} shows what is returned.
6847 @smallexample
6848 @group
6849 (cdr '(pine fir oak maple))
6850      @result{}(fir oak maple)
6851 @end group
6853 @group
6854 (cdr '(fir oak maple))
6855      @result{} (oak maple)
6856 @end group
6858 @group
6859 (cdr '(oak maple))
6860      @result{}(maple)
6861 @end group
6863 @group
6864 (cdr '(maple))
6865      @result{} nil
6866 @end group
6868 @group
6869 (cdr 'nil)
6870      @result{} nil
6871 @end group
6873 @group
6874 (cdr ())
6875      @result{} nil
6876 @end group
6877 @end smallexample
6879 @need 1200
6880 You can also do several @sc{cdr}s without printing the values in
6881 between, like this:
6883 @smallexample
6884 @group
6885 (cdr (cdr '(pine fir oak maple)))
6886      @result{} (oak maple)
6887 @end group
6888 @end smallexample
6890 @noindent
6891 In this example, the Lisp interpreter evaluates the innermost list first.
6892 The innermost list is quoted, so it just passes the list as it is to the
6893 innermost @code{cdr}.  This @code{cdr} passes a list made up of the
6894 second and subsequent elements of the list to the outermost @code{cdr},
6895 which produces a list composed of the third and subsequent elements of
6896 the original list.  In this example, the @code{cdr} function is repeated
6897 and returns a list that consists of the original list without its
6898 first two elements.
6900 The @code{nthcdr} function does the same as repeating the call to
6901 @code{cdr}.  In the following example, the argument 2 is passed to the
6902 function @code{nthcdr}, along with the list, and the value returned is
6903 the list without its first two items, which is exactly the same
6904 as repeating @code{cdr} twice on the list:
6906 @smallexample
6907 @group
6908 (nthcdr 2 '(pine fir oak maple))
6909      @result{} (oak maple)
6910 @end group
6911 @end smallexample
6913 @need 1200
6914 Using the original four element list, we can see what happens when
6915 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6916 and 5:
6918 @smallexample
6919 @group
6920 ;; @r{Leave the list as it was.}
6921 (nthcdr 0 '(pine fir oak maple))
6922      @result{} (pine fir oak maple)
6923 @end group
6925 @group
6926 ;; @r{Return a copy without the first element.}
6927 (nthcdr 1 '(pine fir oak maple))
6928      @result{} (fir oak maple)
6929 @end group
6931 @group
6932 ;; @r{Return a copy of the list without three elements.}
6933 (nthcdr 3 '(pine fir oak maple))
6934      @result{} (maple)
6935 @end group
6937 @group
6938 ;; @r{Return a copy lacking all four elements.}
6939 (nthcdr 4 '(pine fir oak maple))
6940      @result{} nil
6941 @end group
6943 @group
6944 ;; @r{Return a copy lacking all elements.}
6945 (nthcdr 5 '(pine fir oak maple))
6946      @result{} nil
6947 @end group
6948 @end smallexample
6950 @node nth, setcar, nthcdr, car cdr & cons
6951 @comment  node-name,  next,  previous,  up
6952 @section @code{nth}
6953 @findex nth
6955 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6956 The @code{nth} function takes the @sc{car} of the result returned by
6957 @code{nthcdr}.  It returns the Nth element of the list.
6959 @need 1500
6960 Thus, if it were not defined in C for speed, the definition of
6961 @code{nth} would be:
6963 @smallexample
6964 @group
6965 (defun nth (n list)
6966   "Returns the Nth element of LIST.
6967 N counts from zero.  If LIST is not that long, nil is returned."
6968   (car (nthcdr n list)))
6969 @end group
6970 @end smallexample
6972 @noindent
6973 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6974 but its definition was redone in C in the 1980s.)
6976 The @code{nth} function returns a single element of a list.
6977 This can be very convenient.
6979 Note that the elements are numbered from zero, not one.  That is to
6980 say, the first element of a list, its @sc{car} is the zeroth element.
6981 This is called `zero-based' counting and often bothers people who
6982 are accustomed to the first element in a list being number one, which
6983 is `one-based'.
6985 @need 1250
6986 For example:
6988 @smallexample
6989 @group
6990 (nth 0 '("one" "two" "three"))
6991     @result{} "one"
6993 (nth 1 '("one" "two" "three"))
6994     @result{} "two"
6995 @end group
6996 @end smallexample
6998 It is worth mentioning that @code{nth}, like @code{nthcdr} and
6999 @code{cdr}, does not change the original list---the function is
7000 non-destructive.  This is in sharp contrast to the @code{setcar} and
7001 @code{setcdr} functions.
7003 @node setcar, setcdr, nth, car cdr & cons
7004 @comment  node-name,  next,  previous,  up
7005 @section @code{setcar}
7006 @findex setcar
7008 As you might guess from their names, the @code{setcar} and @code{setcdr}
7009 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7010 They actually change the original list, unlike @code{car} and @code{cdr}
7011 which leave the original list as it was.  One way to find out how this
7012 works is to experiment.  We will start with the @code{setcar} function.
7014 @need 1200
7015 First, we can make a list and then set the value of a variable to the
7016 list, using the @code{setq} function.  Here is a list of animals:
7018 @smallexample
7019 (setq animals '(antelope giraffe lion tiger))
7020 @end smallexample
7022 @noindent
7023 If you are reading this in Info inside of GNU Emacs, you can evaluate
7024 this expression in the usual fashion, by positioning the cursor after
7025 the expression and typing @kbd{C-x C-e}.  (I'm doing this right here as
7026 I write this.  This is one of the advantages of having the interpreter
7027 built into the computing environment.)
7029 @need 1200
7030 When we evaluate the variable @code{animals}, we see that it is bound to
7031 the list @code{(antelope giraffe lion tiger)}:
7033 @smallexample
7034 @group
7035 animals
7036      @result{} (antelope giraffe lion tiger)
7037 @end group
7038 @end smallexample
7040 @noindent
7041 Put another way, the variable @code{animals} points to the list
7042 @code{(antelope giraffe lion tiger)}.
7044 Next, evaluate the function @code{setcar} while passing it two
7045 arguments, the variable @code{animals} and the quoted symbol
7046 @code{hippopotamus}; this is done by writing the three element list
7047 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7048 usual fashion:
7050 @smallexample
7051 (setcar animals 'hippopotamus)
7052 @end smallexample
7054 @need 1200
7055 @noindent
7056 After evaluating this expression, evaluate the variable @code{animals}
7057 again.  You will see that the list of animals has changed:
7059 @smallexample
7060 @group
7061 animals
7062      @result{} (hippopotamus giraffe lion tiger)
7063 @end group
7064 @end smallexample
7066 @noindent
7067 The first element on the list, @code{antelope} is replaced by
7068 @code{hippopotamus}.
7070 So we can see that @code{setcar} did not add a new element to the list
7071 as @code{cons} would have; it replaced @code{giraffe} with
7072 @code{hippopotamus}; it @emph{changed} the list.
7074 @node setcdr, cons Exercise, setcar, car cdr & cons
7075 @comment  node-name,  next,  previous,  up
7076 @section @code{setcdr}
7077 @findex setcdr
7079 The @code{setcdr} function is similar to the @code{setcar} function,
7080 except that the function replaces the second and subsequent elements of
7081 a list rather than the first element.
7083 @need 1200
7084 To see how this works, set the value of the variable to a list of
7085 domesticated animals by evaluating the following expression:
7087 @smallexample
7088 (setq domesticated-animals '(horse cow sheep goat))
7089 @end smallexample
7091 @need 1200
7092 @noindent
7093 If you now evaluate the list, you will be returned the list
7094 @code{(horse cow sheep goat)}:
7096 @smallexample
7097 @group
7098 domesticated-animals
7099      @result{} (horse cow sheep goat)
7100 @end group
7101 @end smallexample
7103 @need 1200
7104 Next, evaluate @code{setcdr} with two arguments, the name of the
7105 variable which has a list as its value, and the list to which the
7106 @sc{cdr} of the first list will be set;
7108 @smallexample
7109 (setcdr domesticated-animals '(cat dog))
7110 @end smallexample
7112 @noindent
7113 If you evaluate this expression, the list @code{(cat dog)} will appear
7114 in the echo area.  This is the value returned by the function.  The
7115 result we are interested in is the ``side effect'', which we can see by
7116 evaluating the variable @code{domesticated-animals}:
7118 @smallexample
7119 @group
7120 domesticated-animals
7121      @result{} (horse cat dog)
7122 @end group
7123 @end smallexample
7125 @noindent
7126 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7127 @code{(horse cat dog)}.  The @sc{cdr} of the list is changed from
7128 @code{(cow sheep goat)} to @code{(cat dog)}.
7130 @node cons Exercise,  , setcdr, car cdr & cons
7131 @section Exercise
7133 Construct a list of four birds by evaluating several expressions with
7134 @code{cons}.  Find out what happens when you @code{cons} a list onto
7135 itself.  Replace the first element of the list of four birds with a
7136 fish.  Replace the rest of that list with a list of other fish.
7138 @node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7139 @comment  node-name,  next,  previous,  up
7140 @chapter Cutting and Storing Text
7141 @cindex Cutting and storing text
7142 @cindex Storing and cutting text
7143 @cindex Killing text
7144 @cindex Clipping text
7145 @cindex Erasing text
7146 @cindex Deleting text
7148 Whenever you cut or clip text out of a buffer with a `kill' command in
7149 GNU Emacs, it is stored in a list and you can bring it back with a
7150 `yank' command.
7152 (The use of the word `kill' in Emacs for processes which specifically
7153 @emph{do not} destroy the values of the entities is an unfortunate
7154 historical accident.  A much more appropriate word would be `clip' since
7155 that is what the kill commands do; they clip text out of a buffer and
7156 put it into storage from which it can be brought back.  I have often
7157 been tempted to replace globally all occurrences of `kill' in the Emacs
7158 sources with `clip' and all occurrences of `killed' with `clipped'.)
7160 @menu
7161 * Storing Text::                Text is stored in a list.
7162 * zap-to-char::                 Cutting out text up to a character.
7163 * kill-region::                 Cutting text out of a region.
7164 * Digression into C::           Minor note on C programming language macros.
7165 * defvar::                      How to give a variable an initial value.
7166 * copy-region-as-kill::         A definition for copying text.
7167 * cons & search-fwd Review::
7168 * search Exercises::
7169 @end menu
7171 @node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7172 @ifnottex
7173 @unnumberedsec Storing Text in a List
7174 @end ifnottex
7176 When text is cut out of a buffer, it is stored on a list.  Successive
7177 pieces of text are stored on the list successively, so the list might
7178 look like this:
7180 @smallexample
7181 ("a piece of text" "previous piece")
7182 @end smallexample
7184 @need 1200
7185 @noindent
7186 The function @code{cons} can be used to to create a new list from a
7187 piece of text (an `atom', to use the jargon) and an existing list,
7188 like this:
7190 @smallexample
7191 @group
7192 (cons "another piece"
7193       '("a piece of text" "previous piece"))
7194 @end group
7195 @end smallexample
7197 @need 1200
7198 @noindent
7199 If you evaluate this expression, a list of three elements will appear in
7200 the echo area:
7202 @smallexample
7203 ("another piece" "a piece of text" "previous piece")
7204 @end smallexample
7206 With the @code{car} and @code{nthcdr} functions, you can retrieve
7207 whichever piece of text you want.  For example, in the following code,
7208 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7209 and the @code{car} returns the first element of that remainder---the
7210 second element of the original list:
7212 @smallexample
7213 @group
7214 (car (nthcdr 1 '("another piece"
7215                  "a piece of text"
7216                  "previous piece")))
7217      @result{} "a piece of text"
7218 @end group
7219 @end smallexample
7221 The actual functions in Emacs are more complex than this, of course.
7222 The code for cutting and retrieving text has to be written so that
7223 Emacs can figure out which element in the list you want---the first,
7224 second, third, or whatever.  In addition, when you get to the end of
7225 the list, Emacs should give you the first element of the list, rather
7226 than nothing at all.
7228 The list that holds the pieces of text is called the @dfn{kill ring}.
7229 This chapter leads up to a description of the kill ring and how it is
7230 used by first tracing how the @code{zap-to-char} function works.  This
7231 function uses (or `calls') a function that invokes a function that
7232 manipulates the kill ring.  Thus, before reaching the mountains, we
7233 climb the foothills.
7235 A subsequent chapter describes how text that is cut from the buffer is
7236 retrieved.  @xref{Yanking, , Yanking Text Back}.
7238 @node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7239 @comment  node-name,  next,  previous,  up
7240 @section @code{zap-to-char}
7241 @findex zap-to-char
7243 The @code{zap-to-char} function barely changed between GNU Emacs
7244 version 19 and GNU Emacs version 21.  However, @code{zap-to-char}
7245 calls another function, @code{kill-region}, which enjoyed a major rewrite
7246 on the way to version 21.
7248 The @code{kill-region} function in Emacs 19 is complex, but does not
7249 use code that is important at this time.  We will skip it.
7251 The @code{kill-region} function in Emacs 21 is easier to read than the
7252 same function in Emacs 19 and introduces a very important concept,
7253 that of error handling.  We will walk through the function.
7255 But first, let us look at the interactive @code{zap-to-char} function.
7257 @menu
7258 * Complete zap-to-char::        The complete implementation.
7259 * zap-to-char interactive::     A three part interactive expression.
7260 * zap-to-char body::            A short overview.
7261 * search-forward::              How to search for a string.
7262 * progn::                       The @code{progn} special form.
7263 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
7264 @end menu
7266 @node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7267 @ifnottex
7268 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7269 @end ifnottex
7271 The GNU Emacs version 19 and version 21 implementations of the
7272 @code{zap-to-char} function are nearly identical in form, and they
7273 work alike.  The function removes the text in the region between the
7274 location of the cursor (i.e., of point) up to and including the next
7275 occurrence of a specified character.  The text that @code{zap-to-char}
7276 removes is put in the kill ring; and it can be retrieved from the kill
7277 ring by typing @kbd{C-y} (@code{yank}).  If the command is given an
7278 argument, it removes text through that number of occurrences.  Thus,
7279 if the cursor were at the beginning of this sentence and the character
7280 were @samp{s}, @samp{Thus} would be removed.  If the argument were
7281 two, @samp{Thus, if the curs} would be removed, up to and including
7282 the @samp{s} in @samp{cursor}.
7284 If the specified character is not found, @code{zap-to-char} will say
7285 ``Search failed'', tell you the character you typed, and not remove
7286 any text.
7288 In order to determine how much text to remove, @code{zap-to-char} uses
7289 a search function.  Searches are used extensively in code that
7290 manipulates text, and we will focus attention on them as well as on the
7291 deletion command.
7293 @need 800
7294 Here is the complete text of the version 19 implementation of the function:
7296 @c v 19
7297 @smallexample
7298 @group
7299 (defun zap-to-char (arg char)  ; version 19 implementation
7300   "Kill up to and including ARG'th occurrence of CHAR.
7301 Goes backward if ARG is negative; error if CHAR not found."
7302   (interactive "*p\ncZap to char: ")
7303   (kill-region (point)
7304                (progn
7305                  (search-forward
7306                   (char-to-string char) nil nil arg)
7307                  (point))))
7308 @end group
7309 @end smallexample
7311 @node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7312 @comment  node-name,  next,  previous,  up
7313 @subsection The @code{interactive} Expression
7315 @need 800
7316 The interactive expression in the @code{zap-to-char} command looks like
7317 this:
7319 @smallexample
7320 (interactive "*p\ncZap to char: ")
7321 @end smallexample
7323 The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7324 three different things.  First, and most simply, the asterisk, @samp{*},
7325 causes an error to be signalled if the buffer is read-only.  This means that
7326 if you try @code{zap-to-char} in a read-only buffer you will not be able to
7327 remove text, and you will receive a message that says ``Buffer is
7328 read-only''; your terminal may beep at you as well.
7330 The version 21 implementation does not have the asterisk, @samp{*}.  The
7331 function works the same as in version 19: in both cases, it cannot
7332 remove text from a read-only buffer but the function does copy the
7333 text that would have been removed to the kill ring.  Also, in both
7334 cases, you see an error message.
7336 However, the version 19 implementation copies text from a read-only
7337 buffer only because of a mistake in the implementation of
7338 @code{interactive}.  According to the documentation for
7339 @code{interactive}, the asterisk, @samp{*}, should prevent the
7340 @code{zap-to-char} function from doing anything at all when the buffer
7341 is read only.  The function should not copy the text to the kill ring.
7342 It is a bug that it does.
7344 In version 21, @code{interactive} is implemented correctly.  So the
7345 asterisk, @samp{*}, had to be removed from the interactive
7346 specification.  If you insert an @samp{*} and evaluate the function
7347 definition, then the next time you run the @code{zap-to-char} function
7348 on a read-only buffer, you will not copy any text.
7350 That change aside, and a change to the documentation, the two versions
7351 of the  @code{zap-to-char} function are identical.
7353 Let us continue with the interactive specification.
7355 The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7356 This part is separated from the next part by a newline, @samp{\n}.
7357 The @samp{p} means that the first argument to the function will be
7358 passed the value of a `processed prefix'.  The prefix argument is
7359 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number.  If
7360 the function is called interactively without a prefix, 1 is passed to
7361 this argument.
7363 The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7364 }.  In this part, the lower case @samp{c} indicates that
7365 @code{interactive} expects a prompt and that the argument will be a
7366 character.  The prompt follows the @samp{c} and is the string @samp{Zap
7367 to char:@: } (with a space after the colon to make it look good).
7369 What all this does is prepare the arguments to @code{zap-to-char} so they
7370 are of the right type, and give the user a prompt.
7372 @node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7373 @comment  node-name,  next,  previous,  up
7374 @subsection The Body of @code{zap-to-char}
7376 The body of the @code{zap-to-char} function contains the code that
7377 kills (that is, removes) the text in the region from the current
7378 position of the cursor up to and including the specified character.
7379 The first part of the code looks like this:
7381 @smallexample
7382 (kill-region (point) @dots{}
7383 @end smallexample
7385 @noindent
7386 @code{(point)} is the current position of the cursor.
7388 The next part of the code is an expression using @code{progn}.  The body
7389 of the @code{progn} consists of calls to @code{search-forward} and
7390 @code{point}.
7392 It is easier to understand how @code{progn} works after learning about
7393 @code{search-forward}, so we will look at @code{search-forward} and
7394 then at @code{progn}.
7396 @node search-forward, progn, zap-to-char body, zap-to-char
7397 @comment  node-name,  next,  previous,  up
7398 @subsection The @code{search-forward} Function
7399 @findex search-forward
7401 The @code{search-forward} function is used to locate the
7402 zapped-for-character in @code{zap-to-char}.  If the search is
7403 successful, @code{search-forward} leaves point immediately after the
7404 last character in the target string.  (In @code{zap-to-char}, the
7405 target string is just one character long.)  If the search is
7406 backwards, @code{search-forward} leaves point just before the first
7407 character in the target.  Also, @code{search-forward} returns @code{t}
7408 for true.  (Moving point is therefore a `side effect'.)
7410 @need 1250
7411 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7413 @smallexample
7414 (search-forward (char-to-string char) nil nil arg)
7415 @end smallexample
7417 The @code{search-forward} function takes four arguments:
7419 @enumerate
7420 @item
7421 The first argument is the target, what is searched for.  This must be a
7422 string, such as @samp{"z"}.
7424 As it happens, the argument passed to @code{zap-to-char} is a single
7425 character.  Because of the way computers are built, the Lisp
7426 interpreter may treat a single character as being different from a
7427 string of characters.  Inside the computer, a single character has a
7428 different electronic format than a string of one character.  (A single
7429 character can often be recorded in the computer using exactly one
7430 byte; but a string may be longer, and the computer needs to be ready
7431 for this.)  Since the @code{search-forward} function searches for a
7432 string, the character that the @code{zap-to-char} function receives as
7433 its argument must be converted inside the computer from one format to
7434 the other; otherwise the @code{search-forward} function will fail.
7435 The @code{char-to-string} function is used to make this conversion.
7437 @item
7438 The second argument bounds the search; it is specified as a position in
7439 the buffer.  In this case, the search can go to the end of the buffer,
7440 so no bound is set and the second argument is @code{nil}.
7442 @item
7443 The third argument tells the function what it should do if the search
7444 fails---it can signal an error (and print a message) or it can return
7445 @code{nil}.  A @code{nil} as the third argument causes the function to
7446 signal an error when the search fails.
7448 @item
7449 The fourth argument to @code{search-forward} is the repeat count---how
7450 many occurrences of the string to look for.  This argument is optional
7451 and if the function is called without a repeat count, this argument is
7452 passed the value 1.  If this argument is negative, the search goes
7453 backwards.
7454 @end enumerate
7456 @need 800
7457 In template form, a @code{search-forward} expression looks like this:
7459 @smallexample
7460 @group
7461 (search-forward "@var{target-string}"
7462                 @var{limit-of-search}
7463                 @var{what-to-do-if-search-fails}
7464                 @var{repeat-count})
7465 @end group
7466 @end smallexample
7468 We will look at @code{progn} next.
7470 @node progn, Summing up zap-to-char, search-forward, zap-to-char
7471 @comment  node-name,  next,  previous,  up
7472 @subsection The @code{progn} Special Form
7473 @findex progn
7475 @code{progn} is a special form that causes each of its arguments to be
7476 evaluated in sequence and then returns the value of the last one.  The
7477 preceding expressions are evaluated only for the side effects they
7478 perform.  The values produced by them are discarded.
7480 @need 800
7481 The template for a @code{progn} expression is very simple:
7483 @smallexample
7484 @group
7485 (progn
7486   @var{body}@dots{})
7487 @end group
7488 @end smallexample
7490 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7491 put point in exactly the right position; and return the location of
7492 point so that @code{kill-region} will know how far to kill to.
7494 The first argument to the @code{progn} is @code{search-forward}.  When
7495 @code{search-forward} finds the string, the function leaves point
7496 immediately after the last character in the target string.  (In this
7497 case the target string is just one character long.)  If the search is
7498 backwards, @code{search-forward} leaves point just before the first
7499 character in the target.  The movement of point is a side effect.
7501 The second and last argument to @code{progn} is the expression
7502 @code{(point)}.  This expression returns the value of point, which in
7503 this case will be the location to which it has been moved by
7504 @code{search-forward}.  This value is returned by the @code{progn}
7505 expression and is passed to @code{kill-region} as @code{kill-region}'s
7506 second argument.
7508 @node Summing up zap-to-char,  , progn, zap-to-char
7509 @comment  node-name,  next,  previous,  up
7510 @subsection Summing up @code{zap-to-char}
7512 Now that we have seen how @code{search-forward} and @code{progn} work,
7513 we can see how the @code{zap-to-char} function works as a whole.
7515 The first argument to @code{kill-region} is the position of the cursor
7516 when the @code{zap-to-char} command is given---the value of point at
7517 that time.  Within the @code{progn}, the search function then moves
7518 point to just after the zapped-to-character and @code{point} returns the
7519 value of this location.  The @code{kill-region} function puts together
7520 these two values of point, the first one as the beginning of the region
7521 and the second one as the end of the region, and removes the region.
7523 The @code{progn} special form is necessary because the @code{kill-region}
7524 command takes two arguments; and it would fail if @code{search-forward}
7525 and @code{point} expressions were  written in sequence as two
7526 additional arguments.  The @code{progn} expression is a single argument
7527 to @code{kill-region} and returns the one value that @code{kill-region}
7528 needs for its second argument.
7530 @node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7531 @comment  node-name,  next,  previous,  up
7532 @section @code{kill-region}
7533 @findex kill-region
7535 The @code{zap-to-char} function uses the @code{kill-region} function.
7536 This function clips text from a region and copies that text to
7537 the kill ring, from which it may be retrieved.
7539 The Emacs 21 version of that function uses @code{condition-case} and
7540 @code{copy-region-as-kill}, both of which we will explain.
7541 @code{condition-case} is an important special form.
7543 In essence, the @code{kill-region} function calls
7544 @code{condition-case}, which takes three arguments.  In this function,
7545 the first argument does nothing.  The second argument contains the
7546 code that does the work when all goes well.  The third argument
7547 contains the code that is called in the event of an error.
7549 @menu
7550 * Complete kill-region::        The function definition.
7551 * condition-case::              Dealing with a problem.
7552 * delete-and-extract-region::   Doing the work.
7553 @end menu
7555 @node Complete kill-region, condition-case, kill-region, kill-region
7556 @ifnottex
7557 @unnumberedsubsec The Complete @code{kill-region} Definition
7558 @end ifnottex
7560 @need 1200
7561 We will go through the @code{condition-case} code in a moment.  First,
7562 let us look at the complete definition of @code{kill-region}, with
7563 comments added:
7565 @c v 21
7566 @smallexample
7567 @group
7568 (defun kill-region (beg end)
7569   "Kill between point and mark.
7570 The text is deleted but saved in the kill ring."
7571   (interactive "r")
7572 @end group
7574 @group
7575   ;; 1. `condition-case' takes three arguments.
7576   ;;    If the first argument is nil, as it is here,
7577   ;;    information about the error signal is not
7578   ;;    stored for use by another function.
7579   (condition-case nil
7580 @end group
7582 @group
7583       ;; 2. The second argument to `condition-case'
7584       ;;    tells the Lisp interpreter what to do when all goes well.
7585 @end group
7587 @group
7588       ;;    The `delete-and-extract-region' function usually does the
7589       ;;    work.  If the beginning and ending of the region are both
7590       ;;    the same, then the variable `string' will be empty, or nil
7591       (let ((string (delete-and-extract-region beg end)))
7592 @end group
7594 @group
7595         ;; `when' is an `if' clause that cannot take an `else-part'.
7596         ;; Emacs normally sets the value of `last-command' to the
7597         ;; previous command.
7598 @end group
7599 @group
7600         ;; `kill-append' concatenates the new string and the old.
7601         ;; `kill-new' inserts text into a new item in the kill ring.
7602         (when string
7603           (if (eq last-command 'kill-region)
7604               ;; if true, prepend string
7605               (kill-append string (< end beg))
7606             (kill-new string)))
7607         (setq this-command 'kill-region))
7608 @end group
7610 @group
7611     ;; 3. The third argument to `condition-case' tells the interpreter
7612     ;;    what to do with an error.
7613 @end group
7614 @group
7615     ;;    The third argument has a conditions part and a body part.
7616     ;;    If the conditions are met (in this case,
7617     ;;             if text or buffer is read-only)
7618     ;;    then the body is executed.
7619 @end group
7620 @group
7621     ((buffer-read-only text-read-only) ;; this is the if-part
7622      ;; then...
7623      (copy-region-as-kill beg end)
7624 @end group
7625 @group
7626      (if kill-read-only-ok            ;; usually this variable is nil
7627          (message "Read only text copied to kill ring")
7628        ;; or else, signal an error if the buffer is read-only;
7629        (barf-if-buffer-read-only)
7630        ;; and, in any case, signal that the text is read-only.
7631        (signal 'text-read-only (list (current-buffer)))))))
7632 @end group
7633 @end smallexample
7635 @node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7636 @comment  node-name,  next,  previous,  up
7637 @subsection @code{condition-case}
7638 @findex condition-case
7640 As we have seen earlier (@pxref{Making Errors, , Generate an Error
7641 Message}), when the Emacs Lisp interpreter has trouble evaluating an
7642 expression, it provides you with help; in the jargon, this is called
7643 ``signaling an error''.  Usually, the computer stops the program and
7644 shows you a message.
7646 However, some programs undertake complicated actions.  They should not
7647 simply stop on an error.  In the @code{kill-region} function, the most
7648 likely error is that you will try to kill text that is read-only and
7649 cannot be removed.  So the @code{kill-region} function contains code
7650 to handle this circumstance.  This code, which makes up the body of
7651 the @code{kill-region} function, is inside of a @code{condition-case}
7652 special form.
7654 @need 800
7655 The template for @code{condition-case} looks like this:
7657 @smallexample
7658 @group
7659 (condition-case
7660   @var{var}
7661   @var{bodyform}
7662   @var{error-handler}@dots{})
7663 @end group
7664 @end smallexample
7666 The second argument, @var{bodyform}, is straightforward.  The
7667 @code{condition-case} special form causes the Lisp interpreter to
7668 evaluate the code in @var{bodyform}.  If no error occurs, the special
7669 form returns the code's value and produces the side-effects, if any.
7671 In short, the @var{bodyform} part of a @code{condition-case}
7672 expression determines what should happen when everything works
7673 correctly.
7675 However, if an error occurs, among its other actions, the function
7676 generating the error signal will define one or more error condition
7677 names.
7679 An error handler is the third argument to @code{condition case}.
7680 An error handler has two parts, a @var{condition-name} and a
7681 @var{body}.  If the @var{condition-name} part of an error handler
7682 matches a condition name generated by an error, then the @var{body}
7683 part of the error handler is run.
7685 As you will expect, the @var{condition-name} part of an error handler
7686 may be either a single condition name or a list of condition names.
7688 Also, a complete @code{condition-case} expression may contain more
7689 than one error handler.  When an error occurs, the first applicable
7690 handler is run.
7692 Lastly, the first argument to the @code{condition-case} expression,
7693 the @var{var} argument, is sometimes bound to a variable that
7694 contains information about the error.  However, if that argument is
7695 nil, as is the case in @code{kill-region}, that information is
7696 discarded.
7698 @need 1200
7699 In brief, in the @code{kill-region} function, the code
7700 @code{condition-case} works like this:
7702 @smallexample
7703 @group
7704 @var{If no errors}, @var{run only this code}
7705     @var{but}, @var{if errors}, @var{run this other code}.
7706 @end group
7707 @end smallexample
7709 @node delete-and-extract-region,  , condition-case, kill-region
7710 @comment  node-name,  next,  previous,  up
7711 @subsection @code{delete-and-extract-region}
7712 @findex delete-and-extract-region
7714 A @code{condition-case} expression has two parts, a part that is
7715 evaluated in the expectation that all will go well, but which may
7716 generate an error; and a part that is evaluated when there is an
7717 error.
7719 First, let us look at the code in @code{kill-region} that is run in
7720 the expectation that all goes well.  This is the core of the function.
7721 The code looks like this:
7723 @smallexample
7724 @group
7725 (let ((string (delete-and-extract-region beg end)))
7726   (when string
7727     (if (eq last-command 'kill-region)
7728         (kill-append string (< end beg))
7729       (kill-new string)))
7730   (setq this-command 'kill-region))
7731 @end group
7732 @end smallexample
7734 It looks complicated because we have the new functions
7735 @code{delete-and-extract-region}, @code{kill-append}, and
7736 @code{kill-new} as well as the new variables,
7737 @code{last-command} and @code{this-command}.
7739 The @code{delete-and-extract-region} function is straightforward.  It
7740 is a built-in function that deletes the text in a region (a side
7741 effect) and also returns that text.  This is the function that
7742 actually removes the text.  (And if it cannot do that, it signals the
7743 error.)
7745 In this @code{let} expression, the text that
7746 @code{delete-and-extract-region} returns is placed in the local
7747 variable called @samp{string}.  This is the text that is removed from
7748 the buffer.  (To be more precise, the variable is set to point to the
7749 address of the extracted text; to say it is `placed in' the variable
7750 is simply a shorthand.)
7752 If the variable @samp{string} does point to text, that text is added
7753 to the kill ring.  The variable will have a @code{nil} value if no
7754 text was removed.
7756 The code uses @code{when} to determine whether the variable
7757 @samp{string} points to text.  A @code{when} statement is simply a
7758 programmers' convenience.  A @code{when} statement is an @code{if}
7759 statement without the possibility of an else clause.  In your mind, you
7760 can replace @code{when} with @code{if} and understand what goes on.
7761 That is what the Lisp interpreter does.
7763 @cindex Macro, lisp
7764 @cindex Lisp macro
7765 Technically speaking, @code{when} is a Lisp macro.  A Lisp @dfn{macro}
7766 enables you to define new control constructs and other language
7767 features.  It tells the interpreter how to compute another Lisp
7768 expression which will in turn compute the value.  In this case, the
7769 `other expression' is an @code{if} expression.  For more about Lisp
7770 macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7771 Manual}.  The C programming language also provides macros.  These are
7772 different, but also useful.  We will briefly look at C macros in
7773 @ref{Digression into C}.
7775 @need 1200
7776 If the string has content, then another conditional expression is
7777 executed.  This is an @code{if} with both a then-part and an else-part.
7779 @smallexample
7780 @group
7781 (if (eq last-command 'kill-region)
7782     (kill-append string (< end beg))
7783   (kill-new string)))
7784 @end group
7785 @end smallexample
7787 The then-part is evaluated if the previous command was another call to
7788 @code{kill-region}; if not, the else-part is evaluated.
7790 @code{last-command} is a variable that comes with Emacs that we have
7791 not seen before.  Normally, whenever a function is executed, Emacs
7792 sets the value of @code{last-command} to the previous command.
7794 @need 1200
7795 In this segment of the definition, the @code{if} expression checks
7796 whether the previous command was @code{kill-region}.  If it was,
7798 @smallexample
7799 (kill-append string (< end beg))
7800 @end smallexample
7802 @noindent
7803 concatenates a copy of the newly clipped text to the just previously
7804 clipped text in the kill ring.  (If the @w{@code{(< end beg))}}
7805 expression is true, @code{kill-append} prepends the string to the just
7806 previously clipped text.  For a detailed discussion, see
7807 @ref{kill-append function, , The @code{kill-append} function}.)
7809 If you then yank back the text, i.e., `paste' it, you get both
7810 pieces of text at once.  That way, if you delete two words in a row,
7811 and then yank them back, you get both words, in their proper order,
7812 with one yank.  (The @w{@code{(< end beg))}} expression makes sure the
7813 order is correct.)
7815 On the other hand, if the previous command is not @code{kill-region},
7816 then the @code{kill-new} function is called, which adds the text to
7817 the kill ring as the latest item, and sets the
7818 @code{kill-ring-yank-pointer} variable to point to it.
7820 @node Digression into C, defvar, kill-region, Cutting & Storing Text
7821 @comment  node-name,  next,  previous,  up
7822 @section Digression into C
7823 @findex delete-and-extract-region
7824 @cindex C, a digression into
7825 @cindex Digression into C
7827 The @code{zap-to-char} command uses the
7828 @code{delete-and-extract-region} function, which in turn uses two
7829 other functions, @code{copy-region-as-kill} and
7830 @code{del_range_1}.  The @code{copy-region-as-kill} function will be
7831 described in a following section; it puts a copy of the region in the
7832 kill ring so it can be yanked back.  (@xref{copy-region-as-kill, ,
7833 @code{copy-region-as-kill}}.)
7835 The @code{delete-and-extract-region} function removes the contents of
7836 a region and you cannot get them back.
7838 Unlike the other code discussed here, @code{delete-and-extract-region}
7839 is not written in Emacs Lisp; it is written in C and is one of the
7840 primitives of the GNU Emacs system.  Since it is very simple, I will
7841 digress briefly from Lisp and describe it here.
7843 @need 1500
7844 Like many of the other Emacs primitives,
7845 @code{delete-and-extract-region} is written as an instance of a C
7846 macro, a macro being a template for code.  The complete macro looks
7847 like this:
7849 @c /usr/local/src/emacs/src/editfns.c
7850 @smallexample
7851 @group
7852 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7853        Sdelete_and_extract_region, 2, 2, 0,
7854   "Delete the text between START and END and return it.")
7855   (start, end)
7856      Lisp_Object start, end;
7858   validate_region (&start, &end);
7859   return del_range_1 (XINT (start), XINT (end), 1, 1);
7861 @end group
7862 @end smallexample
7864 Without going into the details of the macro writing process, let me
7865 point out that this macro starts with the word @code{DEFUN}.  The word
7866 @code{DEFUN} was chosen since the code serves the same purpose as
7867 @code{defun} does in Lisp.  The word @code{DEFUN} is followed by seven
7868 parts inside of parentheses:
7870 @itemize @bullet
7871 @item
7872 The first part is the name given to the function in Lisp,
7873 @code{delete-and-extract-region}.
7875 @item
7876 The second part is the name of the function in C,
7877 @code{Fdelete_and_extract_region}.  By convention, it starts with
7878 @samp{F}.  Since C does not use hyphens in names, underscores are used
7879 instead.
7881 @item
7882 The third part is the name for the C constant structure that records
7883 information on this function for internal use.  It is the name of the
7884 function in C but begins with an @samp{S} instead of an @samp{F}.
7886 @item
7887 The fourth and fifth parts specify the minimum and maximum number of
7888 arguments the function can have.  This function demands exactly 2
7889 arguments.
7891 @item
7892 The sixth part is nearly like the argument that follows the
7893 @code{interactive} declaration in a function written in Lisp: a letter
7894 followed, perhaps, by a prompt.  The only difference from the Lisp is
7895 when the macro is called with no arguments.  Then you write a @code{0}
7896 (which is a `null string'), as in this macro.
7898 If you were to specify arguments, you would place them between
7899 quotation marks.  The C macro for @code{goto-char} includes
7900 @code{"NGoto char: "} in this position to indicate that the function
7901 expects a raw prefix, in this case, a numerical location in a buffer,
7902 and provides a prompt.
7904 @item
7905 The seventh part is a documentation string, just like the one for a
7906 function written in Emacs Lisp, except that every newline must be
7907 written explicitly as @samp{\n} followed by a backslash and carriage
7908 return.
7910 @need 1000
7911 Thus, the first two lines of documentation for  @code{goto-char} are
7912 written like this:
7914 @smallexample
7915 @group
7916   "Set point to POSITION, a number or marker.\n\
7917 Beginning of buffer is position (point-min), end is (point-max).
7918 @end group
7919 @end smallexample
7920 @end itemize
7922 @need 1200
7923 In a C macro, the formal parameters come next, with a statement of
7924 what kind of object they are, followed by what might be called the `body'
7925 of the macro.  For @code{delete-and-extract-region} the `body'
7926 consists of the following two lines:
7928 @smallexample
7929 @group
7930 validate_region (&start, &end);
7931 return del_range_1 (XINT (start), XINT (end), 1, 1);
7932 @end group
7933 @end smallexample
7935 The first function, @code{validate_region} checks whether the values
7936 passed as the beginning and end of the region are the proper type and
7937 are within range.  The second function, @code{del_range_1}, actually
7938 deletes the text.
7940 @code{del_range_1} is a complex function we will not look into.  It
7941 updates the buffer and does other things.
7943 However, it is worth looking at the two arguments passed to
7944 @code{del_range}.  These are @w{@code{XINT (start)}} and @w{@code{XINT
7945 (end)}}.
7947 As far as the C language is concerned, @code{start} and @code{end} are
7948 two integers that mark the beginning and end of the region to be
7949 deleted@footnote{More precisely, and requiring more expert knowledge
7950 to understand, the two integers are of type `Lisp_Object', which can
7951 also be a C union instead of an integer type.}.
7953 In early versions of Emacs, these two numbers were thirty-two bits
7954 long, but the code is slowly being generalized to handle other
7955 lengths.  Three of the available bits are used to specify the type of
7956 information and a fourth bit is used for handling the computer's
7957 memory; the remaining bits are used as `content'.
7959 @samp{XINT} is a C macro that extracts the relevant number from the
7960 longer collection of bits; the four other bits are discarded.
7962 @need 800
7963 The command in @code{delete-and-extract-region} looks like this:
7965 @smallexample
7966 del_range_1 (XINT (start), XINT (end), 1, 1);
7967 @end smallexample
7969 @noindent
7970 It deletes the region between the beginning position, @code{start},
7971 and the ending position, @code{end}.
7973 From the point of view of the person writing Lisp, Emacs is all very
7974 simple; but hidden underneath is a great deal of complexity to make it
7975 all work.
7977 @node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7978 @comment  node-name,  next,  previous,  up
7979 @section Initializing a Variable with @code{defvar}
7980 @findex defvar
7981 @cindex Initializing a variable
7982 @cindex Variable initialization
7984 Unlike the @code{delete-and-extract-region} function, the
7985 @code{copy-region-as-kill} function is written in Emacs Lisp.  Two
7986 functions within it, @code{kill-append} and @code{kill-new}, copy a
7987 region in a buffer and save it in a variable called the
7988 @code{kill-ring}.  This section describes how the @code{kill-ring}
7989 variable is created and initialized using the @code{defvar} special
7990 form.
7992 (Again we note that the term @code{kill-ring} is a misnomer.  The text
7993 that is clipped out of the buffer can be brought back; it is not a ring
7994 of corpses, but a ring of resurrectable text.)
7996 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7997 given an initial value by using the @code{defvar} special form.  The
7998 name comes from ``define variable''.
8000 The @code{defvar} special form is similar to @code{setq} in that it sets
8001 the value of a variable.  It is unlike @code{setq} in two ways: first,
8002 it only sets the value of the variable if the variable does not already
8003 have a value.  If the variable already has a value, @code{defvar} does
8004 not override the existing value.  Second, @code{defvar} has a
8005 documentation string.
8007 (Another special form, @code{defcustom}, is designed for variables
8008 that people customize.  It has more features than @code{defvar}.
8009 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
8011 @menu
8012 * See variable current value::
8013 * defvar and asterisk::         An old-time convention.
8014 @end menu
8016 @node See variable current value, defvar and asterisk, defvar, defvar
8017 @ifnottex
8018 @unnumberedsubsec Seeing the Current Value of a Variable
8019 @end ifnottex
8021 You can see the current value of a variable, any variable, by using
8022 the @code{describe-variable} function, which is usually invoked by
8023 typing @kbd{C-h v}.  If you type @kbd{C-h v} and then @code{kill-ring}
8024 (followed by @key{RET}) when prompted, you will see what is in your
8025 current kill ring---this may be quite a lot!  Conversely, if you have
8026 been doing nothing this Emacs session except read this document, you
8027 may have nothing in it.  Also, you will see the documentation for
8028 @code{kill-ring}:
8030 @smallexample
8031 @group
8032 Documentation:
8033 List of killed text sequences.
8034 Since the kill ring is supposed to interact nicely with cut-and-paste
8035 facilities offered by window systems, use of this variable should
8036 @end group
8037 @group
8038 interact nicely with `interprogram-cut-function' and
8039 `interprogram-paste-function'.  The functions `kill-new',
8040 `kill-append', and `current-kill' are supposed to implement this
8041 interaction; you may want to use them instead of manipulating the kill
8042 ring directly.
8043 @end group
8044 @end smallexample
8046 @need 800
8047 The kill ring is defined by a @code{defvar} in the following way:
8049 @smallexample
8050 @group
8051 (defvar kill-ring nil
8052   "List of killed text sequences.
8053 @dots{}")
8054 @end group
8055 @end smallexample
8057 @noindent
8058 In this variable definition, the variable is given an initial value of
8059 @code{nil}, which makes sense, since if you have saved nothing, you want
8060 nothing back if you give a @code{yank} command.  The documentation
8061 string is written just like the documentation string of a @code{defun}.
8062 As with the documentation string of the @code{defun}, the first line of
8063 the documentation should be a complete sentence, since some commands,
8064 like @code{apropos}, print only the first line of documentation.
8065 Succeeding lines should not be indented; otherwise they look odd when
8066 you use @kbd{C-h v} (@code{describe-variable}).
8068 @node defvar and asterisk,  , See variable current value, defvar
8069 @subsection @code{defvar} and an asterisk
8070 @findex defvar @r{for a user customizable variable}
8071 @findex defvar @r{with an asterisk}
8073 In the past, Emacs used the @code{defvar} special form both for
8074 internal variables that you would not expect a user to change and for
8075 variables that you do expect a user to change.  Although you can still
8076 use @code{defvar} for user customizable variables, please use
8077 @code{defcustom} instead, since that special form provides a path into
8078 the Customization commands.  (@xref{defcustom, , Setting Variables
8079 with @code{defcustom}}.)
8081 When you specified a variable using the @code{defvar} special form,
8082 you could distinguish a readily settable variable from others by
8083 typing an asterisk, @samp{*}, in the first column of its documentation
8084 string.  For example:
8086 @smallexample
8087 @group
8088 (defvar shell-command-default-error-buffer nil
8089   "*Buffer name for `shell-command' @dots{} error output.
8090 @dots{} ")
8091 @end group
8092 @end smallexample
8094 @noindent
8095 This means that you could (and still can) use the @code{edit-options}
8096 command to change the value of
8097 @code{shell-command-default-error-buffer} temporarily.
8099 @findex edit-options
8100 However, options set using @code{edit-options} are set only for the
8101 duration of your editing session.  The new values are not saved
8102 between sessions.  Each time Emacs starts, it reads the original
8103 value, unless you change the value within your @file{.emacs} file,
8104 either by setting it manually or by using @code{customize}.
8105 @xref{Emacs Initialization, , Your @file{.emacs} File}.
8107 For me, the major use of the @code{edit-options} command is to suggest
8108 variables that I might want to set in my @file{.emacs} file.  I urge
8109 you to look through the list.  (@xref{Edit Options, , Editing Variable
8110 Values, emacs, The GNU Emacs Manual}.)
8112 @node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8113 @comment  node-name,  next,  previous,  up
8114 @section @code{copy-region-as-kill}
8115 @findex copy-region-as-kill
8116 @findex nthcdr
8118 The @code{copy-region-as-kill} function copies a region of text from a
8119 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8120 in the @code{kill-ring}.
8122 If you call @code{copy-region-as-kill} immediately after a
8123 @code{kill-region} command, Emacs appends the newly copied text to the
8124 previously copied text.  This means that if you yank back the text, you
8125 get it all, from both this and the previous operation.  On the other
8126 hand, if some other command precedes the @code{copy-region-as-kill},
8127 the function copies the text into a separate entry in the kill ring.
8129 @menu
8130 * Complete copy-region-as-kill::  The complete function definition.
8131 * copy-region-as-kill body::    The body of @code{copy-region-as-kill}.
8132 @end menu
8134 @node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8135 @ifnottex
8136 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8137 @end ifnottex
8139 @need 1200
8140 Here is the complete text of the version 21 @code{copy-region-as-kill}
8141 function:
8143 @smallexample
8144 @group
8145 (defun copy-region-as-kill (beg end)
8146   "Save the region as if killed, but don't kill it.
8147 In Transient Mark mode, deactivate the mark.
8148 If `interprogram-cut-function' is non-nil, also save
8149 the text for a window system cut and paste."
8150   (interactive "r")
8151 @end group
8152 @group
8153   (if (eq last-command 'kill-region)
8154       (kill-append (buffer-substring beg end) (< end beg))
8155     (kill-new (buffer-substring beg end)))
8156 @end group
8157 @group
8158   (if transient-mark-mode
8159       (setq deactivate-mark t))
8160   nil)
8161 @end group
8162 @end smallexample
8164 @need 800
8165 As usual, this function can be divided into its component parts:
8167 @smallexample
8168 @group
8169 (defun copy-region-as-kill (@var{argument-list})
8170   "@var{documentation}@dots{}"
8171   (interactive "r")
8172   @var{body}@dots{})
8173 @end group
8174 @end smallexample
8176 The arguments are @code{beg} and @code{end} and the function is
8177 interactive with @code{"r"}, so the two arguments must refer to the
8178 beginning and end of the region.  If you have been reading though this
8179 document from the beginning, understanding these parts of a function is
8180 almost becoming routine.
8182 The documentation is somewhat confusing unless you remember that the
8183 word `kill' has a meaning different from its usual meaning.  The
8184 `Transient Mark' and @code{interprogram-cut-function} comments explain
8185 certain side-effects.
8187 After you once set a mark, a buffer always contains a region.  If you
8188 wish, you can use Transient Mark mode to highlight the region
8189 temporarily.  (No one wants to highlight the region all the time, so
8190 Transient Mark mode highlights it only at appropriate times.  Many
8191 people turn off Transient Mark mode, so the region is never
8192 highlighted.)
8194 Also, a windowing system allows you to copy, cut, and paste among
8195 different programs.  In the X windowing system, for example, the
8196 @code{interprogram-cut-function} function is @code{x-select-text},
8197 which works with the windowing system's equivalent of the Emacs kill
8198 ring.
8200 The body of the @code{copy-region-as-kill} function starts with an
8201 @code{if} clause.  What this clause does is distinguish between two
8202 different situations: whether or not this command is executed
8203 immediately after a previous @code{kill-region} command.  In the first
8204 case, the new region is appended to the previously copied text.
8205 Otherwise, it is inserted into the beginning of the kill ring as a
8206 separate piece of text from the previous piece.
8208 The last two lines of the function prevent the region from lighting up
8209 if Transient Mark mode is turned on.
8211 The body of @code{copy-region-as-kill} merits discussion in detail.
8213 @node copy-region-as-kill body,  , Complete copy-region-as-kill, copy-region-as-kill
8214 @comment  node-name,  next,  previous,  up
8215 @subsection The Body of @code{copy-region-as-kill}
8217 The @code{copy-region-as-kill} function works in much the same way as
8218 the @code{kill-region} function (@pxref{kill-region,
8219 ,@code{kill-region}}).  Both are written so that two or more kills in
8220 a row combine their text into a single entry.  If you yank back the
8221 text from the kill ring, you get it all in one piece.  Moreover, kills
8222 that kill forward from the current position of the cursor are added to
8223 the end of the previously copied text and commands that copy text
8224 backwards add it to the beginning of the previously copied text.  This
8225 way, the words in the text stay in the proper order.
8227 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8228 use of the @code{last-command} variable that keeps track of the
8229 previous Emacs command.
8231 @menu
8232 * last-command & this-command::
8233 * kill-append function::
8234 * kill-new function::
8235 @end menu
8237 @node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8238 @ifnottex
8239 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8240 @end ifnottex
8242 Normally, whenever a function is executed, Emacs sets the value of
8243 @code{this-command} to the function being executed (which in this case
8244 would be @code{copy-region-as-kill}).  At the same time, Emacs sets
8245 the value of @code{last-command} to the previous value of
8246 @code{this-command}.
8248 In the first part of the body of the @code{copy-region-as-kill}
8249 function, an @code{if} expression determines whether the value of
8250 @code{last-command} is @code{kill-region}.  If so, the then-part of
8251 the @code{if} expression is evaluated; it uses the @code{kill-append}
8252 function to concatenate the text copied at this call to the function
8253 with the text already in the first element (the @sc{car}) of the kill
8254 ring.  On the other hand, if the value of @code{last-command} is not
8255 @code{kill-region}, then the @code{copy-region-as-kill} function
8256 attaches a new element to the kill ring using the @code{kill-new}
8257 function.
8259 @need 1250
8260 The @code{if} expression reads as follows; it uses @code{eq}, which is
8261 a function we have not yet seen:
8263 @smallexample
8264 @group
8265   (if (eq last-command 'kill-region)
8266       ;; @r{then-part}
8267       (kill-append (buffer-substring beg end) (< end beg))
8268     ;; @r{else-part}
8269     (kill-new (buffer-substring beg end)))
8270 @end group
8271 @end smallexample
8273 @findex eq @r{(example of use)}
8274 @noindent
8275 The @code{eq} function tests whether its first argument is the same Lisp
8276 object as its second argument.  The @code{eq} function is similar to the
8277 @code{equal} function in that it is used to test for equality, but
8278 differs in that it determines whether two representations are actually
8279 the same object inside the computer, but with different names.
8280 @code{equal} determines whether the structure and contents of two
8281 expressions are the same.
8283 If the previous command was @code{kill-region}, then the Emacs Lisp
8284 interpreter calls the @code{kill-append} function
8286 @node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8287 @unnumberedsubsubsec The @code{kill-append} function
8288 @findex kill-append
8290 @need 800
8291 The @code{kill-append} function looks like this:
8293 @smallexample
8294 @group
8295 (defun kill-append (string before-p)
8296   "Append STRING to the end of the latest kill in the kill ring.
8297 If BEFORE-P is non-nil, prepend STRING to the kill.
8298 If `interprogram-cut-function' is set, pass the resulting kill to
8299 it."
8300   (kill-new (if before-p
8301                 (concat string (car kill-ring))
8302               (concat (car kill-ring) string))
8303             t))
8304 @end group
8305 @end smallexample
8307 @noindent
8308 The @code{kill-append} function is fairly straightforward.  It uses
8309 the @code{kill-new} function, which we will discuss in more detail in
8310 a moment.
8312 First, let us look at the conditional that is one of the two arguments
8313 to @code{kill-new}.  It uses @code{concat} to concatenate the new text
8314 to the @sc{car} of the kill ring.  Whether it prepends or appends the
8315 text depends on the results of an @code{if} expression:
8317 @smallexample
8318 @group
8319 (if before-p                            ; @r{if-part}
8320     (concat string (car kill-ring))     ; @r{then-part}
8321   (concat (car kill-ring) string))      ; @r{else-part}
8322 @end group
8323 @end smallexample
8325 @noindent
8326 If the region being killed is before the region that was killed in the
8327 last command, then it should be prepended before the material that was
8328 saved in the previous kill; and conversely, if the killed text follows
8329 what was just killed, it should be appended after the previous text.
8330 The @code{if} expression depends on the predicate @code{before-p} to
8331 decide whether the newly saved text should be put before or after the
8332 previously saved text.
8334 The symbol @code{before-p} is the name of one of the arguments to
8335 @code{kill-append}.  When the @code{kill-append} function is
8336 evaluated, it is bound to the value returned by evaluating the actual
8337 argument.  In this case, this is the expression @code{(< end beg)}.
8338 This expression does not directly determine whether the killed text in
8339 this command is located before or after the kill text of the last
8340 command; what is does is determine whether the value of the variable
8341 @code{end} is less than the value of the variable @code{beg}.  If it
8342 is, it means that the user is most likely heading towards the
8343 beginning of the buffer.  Also, the result of evaluating the predicate
8344 expression, @code{(< end beg)}, will be true and the text will be
8345 prepended before the previous text.  On the other hand, if the value of
8346 the variable @code{end} is greater than the value of the variable
8347 @code{beg}, the text will be appended after the previous text.
8349 @need 800
8350 When the newly saved text will be prepended, then the string with the new
8351 text will be concatenated before the old text:
8353 @smallexample
8354 (concat string (car kill-ring))
8355 @end smallexample
8357 @need 1200
8358 @noindent
8359 But if the text will be appended, it will be concatenated
8360 after the old text:
8362 @smallexample
8363 (concat (car kill-ring) string))
8364 @end smallexample
8366 To understand how this works, we first need to review the
8367 @code{concat} function.  The @code{concat} function links together or
8368 unites two strings of text.  The result is a string.  For example:
8370 @smallexample
8371 @group
8372 (concat "abc" "def")
8373      @result{} "abcdef"
8374 @end group
8376 @group
8377 (concat "new "
8378         (car '("first element" "second element")))
8379      @result{} "new first element"
8381 (concat (car
8382         '("first element" "second element")) " modified")
8383      @result{} "first element modified"
8384 @end group
8385 @end smallexample
8387 We can now make sense of @code{kill-append}: it modifies the contents
8388 of the kill ring.  The kill ring is a list, each element of which is
8389 saved text.  The @code{kill-append} function uses the @code{kill-new}
8390 function which in turn uses the @code{setcar} function.
8392 @node kill-new function,  , kill-append function, copy-region-as-kill body
8393 @unnumberedsubsubsec The @code{kill-new} function
8394 @findex kill-new
8396 @need 1200
8397 The @code{kill-new} function looks like this:
8399 @smallexample
8400 @group
8401 (defun kill-new (string &optional replace)
8402   "Make STRING the latest kill in the kill ring.
8403 Set the kill-ring-yank pointer to point to it.
8404 If `interprogram-cut-function' is non-nil, apply it to STRING.
8405 Optional second argument REPLACE non-nil means that STRING will replace
8406 the front of the kill ring, rather than being added to the list."
8407 @end group
8408 @group
8409   (and (fboundp 'menu-bar-update-yank-menu)
8410        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8411 @end group
8412 @group
8413   (if (and replace kill-ring)
8414       (setcar kill-ring string)
8415     (setq kill-ring (cons string kill-ring))
8416     (if (> (length kill-ring) kill-ring-max)
8417         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8418 @end group
8419 @group
8420   (setq kill-ring-yank-pointer kill-ring)
8421   (if interprogram-cut-function
8422       (funcall interprogram-cut-function string (not replace))))
8423 @end group
8424 @end smallexample
8426 As usual, we can look at this function in parts.
8428 @need 1200
8429 The first line of the documentation makes sense:
8431 @smallexample
8432 Make STRING the latest kill in the kill ring.
8433 @end smallexample
8435 @noindent
8436 Let's skip over the rest of the documentation for the moment.
8438 Also, let's skip over the first two lines of code, those involving
8439 @code{menu-bar-update-yank-menu}.  We will explain them below.
8441 @need 1200
8442 The critical lines are these:
8444 @smallexample
8445 @group
8446   (if (and replace kill-ring)
8447       ;; @r{then}
8448       (setcar kill-ring string)
8449 @end group
8450 @group
8451     ;; @r{else}
8452     (setq kill-ring (cons string kill-ring))
8453     (if (> (length kill-ring) kill-ring-max)
8454         ;; @r{avoid overly long kill ring}
8455         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8456 @end group
8457 @group
8458   (setq kill-ring-yank-pointer kill-ring)
8459   (if interprogram-cut-function
8460       (funcall interprogram-cut-function string (not replace))))
8461 @end group
8462 @end smallexample
8464 The conditional test is @w{@code{(and replace kill-ring)}}.
8465 This will be true when two conditions are met:  the kill ring has
8466 something in it, and the @code{replace} variable is true.
8468 @need 1250
8469 The @code{kill-append} function sets @code{replace} to be true; then,
8470 when the kill ring has at least one item in it, the @code{setcar}
8471 expression is executed:
8473 @smallexample
8474 (setcar kill-ring string)
8475 @end smallexample
8477 The @code{setcar} function actually changes the first element of the
8478 @code{kill-ring} list to the value of @code{string}.  It replaces the
8479 first element.
8481 On the other hand, if the kill ring is empty, or replace is false, the
8482 else-part of the condition is executed:
8484 @smallexample
8485 @group
8486 (setq kill-ring (cons string kill-ring))
8487 (if (> (length kill-ring) kill-ring-max)
8488     (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8489 @end group
8490 @end smallexample
8492 @noindent
8493 This expression first constructs a new version of the kill ring by
8494 prepending @code{string} to the existing kill ring as a new element.
8495 Then it executes a second @code{if} clause.  This second @code{if}
8496 clause keeps the kill ring from growing too long.
8498 Let's look at these two expressions in order.
8500 The @code{setq} line of the else-part sets the new value of the kill
8501 ring to what results from adding the string being killed to the old kill
8502 ring.
8504 @need 800
8505 We can see how this works with an example:
8507 @smallexample
8508 (setq example-list '("here is a clause" "another clause"))
8509 @end smallexample
8511 @need 1200
8512 @noindent
8513 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8514 @code{example-list} and see what it returns:
8516 @smallexample
8517 @group
8518 example-list
8519      @result{} ("here is a clause" "another clause")
8520 @end group
8521 @end smallexample
8523 @need 1200
8524 @noindent
8525 Now, we can add a new element on to this list by evaluating the
8526 following expression:
8527 @findex cons, @r{example}
8529 @smallexample
8530 (setq example-list (cons "a third clause" example-list))
8531 @end smallexample
8533 @need 800
8534 @noindent
8535 When we evaluate @code{example-list}, we find its value is:
8537 @smallexample
8538 @group
8539 example-list
8540      @result{} ("a third clause" "here is a clause" "another clause")
8541 @end group
8542 @end smallexample
8544 @noindent
8545 Thus, the third clause was added to the list by @code{cons}.
8547 @need 1200
8548 This is exactly similar to what the @code{setq} and @code{cons} do in
8549 the function.  Here is the line again:
8551 @smallexample
8552 (setq kill-ring (cons string kill-ring))
8553 @end smallexample
8555 @need 1200
8556 Now for the second part of the @code{if} clause.  This expression
8557 keeps the kill ring from growing too long.  It looks like this:
8559 @smallexample
8560 @group
8561 (if (> (length kill-ring) kill-ring-max)
8562     (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8563 @end group
8564 @end smallexample
8566 The code checks whether the length of the kill ring is greater than
8567 the maximum permitted length.  This is the value of
8568 @code{kill-ring-max} (which is 60, by default).  If the length of the
8569 kill ring is too long, then this code sets the last element of the
8570 kill ring to @code{nil}.  It does this by using two functions,
8571 @code{nthcdr} and @code{setcdr}.
8573 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8574 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8575 @sc{car} of a list.  In this case, however, @code{setcdr} will not be
8576 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8577 function is used to cause it to set the @sc{cdr} of the next to last
8578 element of the kill ring---this means that since the @sc{cdr} of the
8579 next to last element is the last element of the kill ring, it will set
8580 the last element of the kill ring.
8582 @findex nthcdr, @r{example}
8583 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8584 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8585 @dots{}  It does this @var{N} times and returns the results.
8587 @findex setcdr, @r{example}
8588 Thus, if we had a four element list that was supposed to be three
8589 elements long, we could set the @sc{cdr} of the next to last element
8590 to @code{nil}, and thereby shorten the list.
8592 You can see this by evaluating the following three expressions in turn.
8593 First set the value of @code{trees} to @code{(maple oak pine birch)},
8594 then set the @sc{cdr} of its second @sc{cdr} to @code{nil} and then
8595 find the value of @code{trees}:
8597 @smallexample
8598 @group
8599 (setq trees '(maple oak pine birch))
8600      @result{} (maple oak pine birch)
8601 @end group
8603 @group
8604 (setcdr (nthcdr 2 trees) nil)
8605      @result{} nil
8607 trees
8608      @result{} (maple oak pine)
8609 @end group
8610 @end smallexample
8612 @noindent
8613 (The value returned by the @code{setcdr} expression is @code{nil} since
8614 that is what the @sc{cdr} is set to.)
8616 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8617 @sc{cdr} a number of times that is one less than the maximum permitted
8618 size of the kill ring and sets the @sc{cdr} of that element (which
8619 will be the rest of the elements in the kill ring) to @code{nil}.
8620 This prevents the kill ring from growing too long.
8622 @need 800
8623 The next to last expression in the @code{kill-new} function is
8625 @smallexample
8626 (setq kill-ring-yank-pointer kill-ring)
8627 @end smallexample
8629 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8630 the @code{kill-ring}.
8632 Even though the @code{kill-ring-yank-pointer} is called a
8633 @samp{pointer}, it is a variable just like the kill ring.  However, the
8634 name has been chosen to help humans understand how the variable is used.
8635 The variable is used in functions such as @code{yank} and
8636 @code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8638 @need 1200
8639 Now, to return to the first two lines in the body of the function:
8641 @smallexample
8642 @group
8643   (and (fboundp 'menu-bar-update-yank-menu)
8644        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8645 @end group
8646 @end smallexample
8648 @noindent
8649 This is an expression whose first element is the function @code{and}.
8651 @findex and, @r{introduced}
8652 The @code{and} special form evaluates each of its arguments until one of
8653 the arguments returns a value of @code{nil}, in which case the
8654 @code{and} expression returns @code{nil}; however, if none of the
8655 arguments returns a value of @code{nil}, the value resulting from
8656 evaluating the last argument is returned.  (Since such a value is not
8657 @code{nil}, it is considered true in Emacs Lisp.)  In other words, an
8658 @code{and} expression returns a true value only if all its arguments
8659 are true.
8660 @findex and
8662 In this case, the expression tests first to see whether
8663 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8664 calls it.  The @code{fboundp} function returns true if the symbol it
8665 is testing has a function definition that `is not void'.  If the
8666 symbol's function definition were void, we would receive an error
8667 message, as we did when we created errors intentionally (@pxref{Making
8668 Errors, , Generate an Error Message}).
8670 @need 1200
8671 Essentially, the @code{and} is an @code{if} expression that reads like
8672 this:
8674 @smallexample
8675 @group
8676 if @var{the-menu-bar-function-exists}
8677   then @var{execute-it}
8678 @end group
8679 @end smallexample
8681 @code{menu-bar-update-yank-menu} is one of the functions that make it
8682 possible to use the `Select and Paste' menu in the Edit item of a menu
8683 bar; using a mouse, you can look at the various pieces of text you
8684 have saved and select one piece to paste.
8686 Finally, the last expression in the @code{kill-new} function adds the
8687 newly copied string to whatever facility exists for copying and
8688 pasting among different programs running in a windowing system.  In
8689 the X Windowing system, for example, the @code{x-select-text} function
8690 takes the string and stores it in memory operated by X.  You can paste
8691 the string in another program, such as an Xterm.
8693 @need 1200
8694 The expression looks like this:
8696 @smallexample
8697 @group
8698   (if interprogram-cut-function
8699       (funcall interprogram-cut-function string (not replace))))
8700 @end group
8701 @end smallexample
8703 If an @code{interprogram-cut-function} exists, then Emacs executes
8704 @code{funcall}, which in turn calls its first argument as a function
8705 and passes the remaining arguments to it.  (Incidentally, as far as I
8706 can see, this @code{if} expression could be replaced by an @code{and}
8707 expression similar to the one in the first part of the function.)
8709 We are not going to discuss windowing systems and other programs
8710 further, but merely note that this is a mechanism that enables GNU
8711 Emacs to work easily and well with other programs.
8713 This code for placing text in the kill ring, either concatenated with
8714 an existing element or as a new element, leads us to the code for
8715 bringing back text that has been cut out of the buffer---the yank
8716 commands.  However, before discussing the yank commands, it is better
8717 to learn how lists are implemented in a computer.  This will make
8718 clear such mysteries as the use of the term `pointer'.
8720 @node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8721 @comment  node-name,  next,  previous,  up
8722 @section Review
8724 Here is a brief summary of some recently introduced functions.
8726 @table @code
8727 @item car
8728 @itemx cdr
8729 @code{car} returns the first element of a list; @code{cdr} returns the
8730 second and subsequent elements of a list.
8732 @need 1250
8733 For example:
8735 @smallexample
8736 @group
8737 (car '(1 2 3 4 5 6 7))
8738      @result{} 1
8739 (cdr '(1 2 3 4 5 6 7))
8740      @result{} (2 3 4 5 6 7)
8741 @end group
8742 @end smallexample
8744 @item cons
8745 @code{cons} constructs a list by prepending its first argument to its
8746 second argument.
8748 @need 1250
8749 For example:
8751 @smallexample
8752 @group
8753 (cons 1 '(2 3 4))
8754      @result{} (1 2 3 4)
8755 @end group
8756 @end smallexample
8758 @item nthcdr
8759 Return the result of taking @sc{cdr} `n' times on a list.
8760 @iftex
8762 @tex
8763 $n^{th}$
8764 @end tex
8765 @code{cdr}.
8766 @end iftex
8767 The `rest of the rest', as it were.
8769 @need 1250
8770 For example:
8772 @smallexample
8773 @group
8774 (nthcdr 3 '(1 2 3 4 5 6 7))
8775      @result{} (4 5 6 7)
8776 @end group
8777 @end smallexample
8779 @item setcar
8780 @itemx setcdr
8781 @code{setcar} changes the first element of a list; @code{setcdr}
8782 changes the second and subsequent elements of a list.
8784 @need 1250
8785 For example:
8787 @smallexample
8788 @group
8789 (setq triple '(1 2 3))
8791 (setcar triple '37)
8793 triple
8794      @result{} (37 2 3)
8796 (setcdr triple '("foo" "bar"))
8798 triple
8799      @result{} (37 "foo" "bar")
8800 @end group
8801 @end smallexample
8803 @item progn
8804 Evaluate each argument in sequence and then return the value of the
8805 last.
8807 @need 1250
8808 For example:
8810 @smallexample
8811 @group
8812 (progn 1 2 3 4)
8813      @result{} 4
8814 @end group
8815 @end smallexample
8817 @item save-restriction
8818 Record whatever narrowing is in effect in the current buffer, if any,
8819 and restore that narrowing after evaluating the arguments.
8821 @item search-forward
8822 Search for a string, and if the string is found, move point.
8824 @need 1250
8825 @noindent
8826 Takes four arguments:
8828 @enumerate
8829 @item
8830 The string to search for.
8832 @item
8833 Optionally, the limit of the search.
8835 @item
8836 Optionally, what to do if the search fails, return @code{nil} or an
8837 error message.
8839 @item
8840 Optionally, how many times to repeat the search; if negative, the
8841 search goes backwards.
8842 @end enumerate
8844 @item kill-region
8845 @itemx delete-region
8846 @itemx copy-region-as-kill
8848 @code{kill-region} cuts the text between point and mark from the
8849 buffer and stores that text in the kill ring, so you can get it back
8850 by yanking.
8852 @code{delete-and-extract-region} removes the text between point and
8853 mark from the buffer and throws it away.  You cannot get it back.
8855 @code{copy-region-as-kill} copies the text between point and mark into
8856 the kill ring, from which you can get it by yanking.  The function
8857 does not cut or remove the text from the buffer.
8858 @end table
8860 @need 1500
8861 @node search Exercises,  , cons & search-fwd Review, Cutting & Storing Text
8862 @section Searching Exercises
8864 @itemize @bullet
8865 @item
8866 Write an interactive function that searches for a string.  If the
8867 search finds the string, leave point after it and display a message
8868 that says ``Found!''.  (Do not use @code{search-forward} for the name
8869 of this function; if you do, you will overwrite the existing version of
8870 @code{search-forward} that comes with Emacs.  Use a name such as
8871 @code{test-search} instead.)
8873 @item
8874 Write a function that prints the third element of the kill ring in the
8875 echo area, if any; if the kill ring does not contain a third element,
8876 print an appropriate message.
8877 @end itemize
8879 @node List Implementation, Yanking, Cutting & Storing Text, Top
8880 @comment  node-name,  next,  previous,  up
8881 @chapter How Lists are Implemented
8882 @cindex Lists in a computer
8884 In Lisp, atoms are recorded in a straightforward fashion; if the
8885 implementation is not straightforward in practice, it is, nonetheless,
8886 straightforward in theory.  The atom @samp{rose}, for example, is
8887 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8888 @samp{e}.  A list, on the other hand, is kept differently.  The mechanism
8889 is equally simple, but it takes a moment to get used to the idea.  A
8890 list is kept using a series of pairs of pointers.  In the series, the
8891 first pointer in each pair points to an atom or to another list, and the
8892 second pointer in each pair points to the next pair, or to the symbol
8893 @code{nil}, which marks the end of the list.
8895 A pointer itself is quite simply the electronic address of what is
8896 pointed to.  Hence, a list is kept as a series of electronic addresses.
8898 @menu
8899 * Lists diagrammed::
8900 * Symbols as Chest::            Exploring a powerful metaphor.
8901 * List Exercise::
8902 @end menu
8904 @node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8905 @ifnottex
8906 @unnumberedsec Lists diagrammed
8907 @end ifnottex
8909 For example, the list @code{(rose violet buttercup)} has three elements,
8910 @samp{rose}, @samp{violet}, and @samp{buttercup}.  In the computer, the
8911 electronic address of @samp{rose} is recorded in a segment of computer
8912 memory along with the address that gives the electronic address of where
8913 the atom @samp{violet} is located; and that address (the one that tells
8914 where @samp{violet} is located) is kept along with an address that tells
8915 where the address for the atom @samp{buttercup} is located.
8917 @need 1200
8918 This sounds more complicated than it is and is easier seen in a diagram:
8920 @c clear print-postscript-figures
8921 @c !!! cons-cell-diagram #1
8922 @ifnottex
8923 @smallexample
8924 @group
8925     ___ ___      ___ ___      ___ ___
8926    |___|___|--> |___|___|--> |___|___|--> nil
8927      |            |            |
8928      |            |            |
8929       --> rose     --> violet   --> buttercup
8930 @end group
8931 @end smallexample
8932 @end ifnottex
8933 @ifset print-postscript-figures
8934 @sp 1
8935 @tex
8936 @image{cons-1}
8937 %%%% old method of including an image
8938 % \input /usr/local/lib/tex/inputs/psfig.tex
8939 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8940 % \catcode`\@=0 %
8941 @end tex
8942 @sp 1
8943 @end ifset
8944 @ifclear print-postscript-figures
8945 @iftex
8946 @smallexample
8947 @group
8948     ___ ___      ___ ___      ___ ___
8949    |___|___|--> |___|___|--> |___|___|--> nil
8950      |            |            |
8951      |            |            |
8952       --> rose     --> violet   --> buttercup
8953 @end group
8954 @end smallexample
8955 @end iftex
8956 @end ifclear
8958 @noindent
8959 In the diagram, each box represents a word of computer memory that
8960 holds a Lisp object, usually in the form of a memory address.  The boxes,
8961 i.e.@: the addresses, are in pairs.  Each arrow points to what the address
8962 is the address of, either an atom or another pair of addresses.  The
8963 first box is the electronic address of @samp{rose} and the arrow points
8964 to @samp{rose}; the second box is the address of the next pair of boxes,
8965 the first part of which is the address of @samp{violet} and the second
8966 part of which is the address of the next pair.  The very last box
8967 points to the symbol @code{nil}, which marks the end of the list.
8969 @need 1200
8970 When a variable is set to a list with a function such as @code{setq},
8971 it stores the address of the first box in the variable.  Thus,
8972 evaluation of the expression
8974 @smallexample
8975 (setq bouquet '(rose violet buttercup))
8976 @end smallexample
8978 @need 1250
8979 @noindent
8980 creates a situation like this:
8982 @c cons-cell-diagram #2
8983 @ifnottex
8984 @smallexample
8985 @group
8986 bouquet
8987      |
8988      |     ___ ___      ___ ___      ___ ___
8989       --> |___|___|--> |___|___|--> |___|___|--> nil
8990             |            |            |
8991             |            |            |
8992              --> rose     --> violet   --> buttercup
8993 @end group
8994 @end smallexample
8995 @end ifnottex
8996 @ifset print-postscript-figures
8997 @sp 1
8998 @tex
8999 @image{cons-2}
9000 %%%% old method of including an image
9001 % \input /usr/local/lib/tex/inputs/psfig.tex
9002 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9003 % \catcode`\@=0 %
9004 @end tex
9005 @sp 1
9006 @end ifset
9007 @ifclear print-postscript-figures
9008 @iftex
9009 @smallexample
9010 @group
9011 bouquet
9012      |
9013      |     ___ ___      ___ ___      ___ ___
9014       --> |___|___|--> |___|___|--> |___|___|--> nil
9015             |            |            |
9016             |            |            |
9017              --> rose     --> violet   --> buttercup
9018 @end group
9019 @end smallexample
9020 @end iftex
9021 @end ifclear
9023 @noindent
9024 In this example, the symbol @code{bouquet} holds the address of the first
9025 pair of boxes.
9027 @need 1200
9028 This same list can be illustrated in a different sort of box notation
9029 like this:
9031 @c cons-cell-diagram #2a
9032 @ifnottex
9033 @smallexample
9034 @group
9035 bouquet
9037  |    --------------       ---------------       ----------------
9038  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9039   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9040      |       |      |     |        |      |     | cup     |      |
9041       --------------       ---------------       ----------------
9042 @end group
9043 @end smallexample
9044 @end ifnottex
9045 @ifset print-postscript-figures
9046 @sp 1
9047 @tex
9048 @image{cons-2a}
9049 %%%% old method of including an image
9050 % \input /usr/local/lib/tex/inputs/psfig.tex
9051 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9052 % \catcode`\@=0 %
9053 @end tex
9054 @sp 1
9055 @end ifset
9056 @ifclear print-postscript-figures
9057 @iftex
9058 @smallexample
9059 @group
9060 bouquet
9062  |    --------------       ---------------       ----------------
9063  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9064   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9065      |       |      |     |        |      |     | cup     |      |
9066       --------------       ---------------       ----------------
9067 @end group
9068 @end smallexample
9069 @end iftex
9070 @end ifclear
9072 (Symbols consist of more than pairs of addresses, but the structure of
9073 a symbol is made up of addresses.  Indeed, the symbol @code{bouquet}
9074 consists of a group of address-boxes, one of which is the address of
9075 the printed word @samp{bouquet}, a second of which is the address of a
9076 function definition attached to the symbol, if any, a third of which
9077 is the address of the first pair of address-boxes for the list
9078 @code{(rose violet buttercup)}, and so on.  Here we are showing that
9079 the symbol's third address-box points to the first pair of
9080 address-boxes for the list.)
9082 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9083 changed; the symbol simply has an address further down the list.  (In
9084 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.)  Thus,
9085 evaluation of the following expression
9087 @smallexample
9088 (setq flowers (cdr bouquet))
9089 @end smallexample
9091 @need 800
9092 @noindent
9093 produces this:
9095 @c cons-cell-diagram #3
9096 @ifnottex
9097 @sp 1
9098 @smallexample
9099 @group
9100 bouquet        flowers
9101   |              |
9102   |     ___ ___  |     ___ ___      ___ ___
9103    --> |   |   |  --> |   |   |    |   |   |
9104        |___|___|----> |___|___|--> |___|___|--> nil
9105          |              |            |
9106          |              |            |
9107           --> rose       --> violet   --> buttercup
9108 @end group
9109 @end smallexample
9110 @sp 1
9111 @end ifnottex
9112 @ifset print-postscript-figures
9113 @sp 1
9114 @tex
9115 @image{cons-3}
9116 %%%% old method of including an image
9117 % \input /usr/local/lib/tex/inputs/psfig.tex
9118 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9119 % \catcode`\@=0 %
9120 @end tex
9121 @sp 1
9122 @end ifset
9123 @ifclear print-postscript-figures
9124 @iftex
9125 @sp 1
9126 @smallexample
9127 @group
9128 bouquet        flowers
9129   |              |
9130   |     ___ ___  |     ___ ___      ___ ___
9131    --> |   |   |  --> |   |   |    |   |   |
9132        |___|___|----> |___|___|--> |___|___|--> nil
9133          |              |            |
9134          |              |            |
9135           --> rose       --> violet   --> buttercup
9136 @end group
9137 @end smallexample
9138 @sp 1
9139 @end iftex
9140 @end ifclear
9142 @noindent
9143 The value of @code{flowers} is @code{(violet buttercup)}, which is
9144 to say, the symbol @code{flowers} holds the address of the pair of
9145 address-boxes, the first of which holds the address of @code{violet},
9146 and the second of which holds the address of @code{buttercup}.
9148 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9149 pair}.  @xref{List Type, , List Type , elisp, The GNU Emacs Lisp
9150 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9151 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9152 information about cons cells and dotted pairs.
9154 @need 1200
9155 The function @code{cons} adds a new pair of addresses to the front of
9156 a series of addresses like that shown above.  For example, evaluating
9157 the expression
9159 @smallexample
9160 (setq bouquet (cons 'lily bouquet))
9161 @end smallexample
9163 @need 1500
9164 @noindent
9165 produces:
9167 @c cons-cell-diagram #4
9168 @ifnottex
9169 @sp 1
9170 @smallexample
9171 @group
9172 bouquet                       flowers
9173   |                             |
9174   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9175    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9176        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9177          |              |              |             |
9178          |              |              |             |
9179           --> lily      --> rose       --> violet    --> buttercup
9180 @end group
9181 @end smallexample
9182 @sp 1
9183 @end ifnottex
9184 @ifset print-postscript-figures
9185 @sp 1
9186 @tex
9187 @image{cons-4}
9188 %%%% old method of including an image
9189 % \input /usr/local/lib/tex/inputs/psfig.tex
9190 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9191 % \catcode`\@=0 %
9192 @end tex
9193 @sp 1
9194 @end ifset
9195 @ifclear print-postscript-figures
9196 @iftex
9197 @sp 1
9198 @smallexample
9199 @group
9200 bouquet                       flowers
9201   |                             |
9202   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9203    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9204        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9205          |              |              |             |
9206          |              |              |             |
9207           --> lily      --> rose       --> violet    --> buttercup
9208 @end group
9209 @end smallexample
9210 @sp 1
9211 @end iftex
9212 @end ifclear
9214 @need 1200
9215 @noindent
9216 However, this does not change the value of the symbol
9217 @code{flowers}, as you can see by evaluating the following,
9219 @smallexample
9220 (eq (cdr (cdr bouquet)) flowers)
9221 @end smallexample
9223 @noindent
9224 which returns @code{t} for true.
9226 Until it is reset, @code{flowers} still has the value
9227 @code{(violet buttercup)}; that is, it has the address of the cons
9228 cell whose first address is of @code{violet}.  Also, this does not
9229 alter any of the pre-existing cons cells; they are all still there.
9231 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9232 of the next cons cell in the series; to get the @sc{car} of a list,
9233 you get the address of the first element of the list; to @code{cons} a
9234 new element on a list, you add a new cons cell to the front of the list.
9235 That is all there is to it!  The underlying structure of Lisp is
9236 brilliantly simple!
9238 And what does the last address in a series of cons cells refer to?  It
9239 is the address of the empty list, of @code{nil}.
9241 In summary, when a Lisp variable is set to a value, it is provided with
9242 the address of the list to which the variable refers.
9244 @node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9245 @section Symbols as a Chest of Drawers
9246 @cindex Symbols as a Chest of Drawers
9247 @cindex Chest of Drawers, metaphor for a symbol
9248 @cindex Drawers, Chest of, metaphor for a symbol
9250 In an earlier section, I suggested that you might imagine a symbol as
9251 being a chest of drawers.  The function definition is put in one
9252 drawer, the value in another, and so on.  What is put in the drawer
9253 holding the value can be changed without affecting the contents of the
9254 drawer holding the function definition, and vice-versa.
9256 Actually, what is put in each drawer is the address of the value or
9257 function definition.  It is as if you found an old chest in the attic,
9258 and in one of its drawers you found a map giving you directions to
9259 where the buried treasure lies.
9261 (In addition to its name, symbol definition, and variable value, a
9262 symbol has a `drawer' for a @dfn{property list} which can be used to
9263 record other information.  Property lists are not discussed here; see
9264 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9265 Reference Manual}.)
9267 @need 1500
9268 Here is a fanciful representation:
9270 @c chest-of-drawers diagram
9271 @ifnottex
9272 @sp 1
9273 @smallexample
9274 @group
9275             Chest of Drawers            Contents of Drawers
9277             __   o0O0o   __
9278           /                 \
9279          ---------------------
9280         |    directions to    |            [map to]
9281         |     symbol name     |             bouquet
9282         |                     |
9283         +---------------------+
9284         |    directions to    |
9285         |  symbol definition  |             [none]
9286         |                     |
9287         +---------------------+
9288         |    directions to    |            [map to]
9289         |    variable value   |             (rose violet buttercup)
9290         |                     |
9291         +---------------------+
9292         |    directions to    |
9293         |    property list    |             [not described here]
9294         |                     |
9295         +---------------------+
9296         |/                   \|
9297 @end group
9298 @end smallexample
9299 @sp 1
9300 @end ifnottex
9301 @ifset print-postscript-figures
9302 @sp 1
9303 @tex
9304 @image{drawers}
9305 %%%% old method of including an image
9306 % \input /usr/local/lib/tex/inputs/psfig.tex
9307 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9308 % \catcode`\@=0 %
9309 @end tex
9310 @sp 1
9311 @end ifset
9312 @ifclear print-postscript-figures
9313 @iftex
9314 @sp 1
9315 @smallexample
9316 @group
9317             Chest of Drawers            Contents of Drawers
9319             __   o0O0o   __
9320           /                 \
9321          ---------------------
9322         |    directions to    |            [map to]
9323         |     symbol name     |             bouquet
9324         |                     |
9325         +---------------------+
9326         |    directions to    |
9327         |  symbol definition  |             [none]
9328         |                     |
9329         +---------------------+
9330         |    directions to    |            [map to]
9331         |    variable value   |             (rose violet buttercup)
9332         |                     |
9333         +---------------------+
9334         |    directions to    |
9335         |    property list    |             [not described here]
9336         |                     |
9337         +---------------------+
9338         |/                   \|
9339 @end group
9340 @end smallexample
9341 @sp 1
9342 @end iftex
9343 @end ifclear
9345 @node List Exercise,  , Symbols as Chest, List Implementation
9346 @section Exercise
9348 Set @code{flowers} to @code{violet} and @code{buttercup}.  Cons two
9349 more flowers on to this list and set this new list to
9350 @code{more-flowers}.  Set the @sc{car} of @code{flowers} to a fish.
9351 What does the @code{more-flowers} list now contain?
9353 @node Yanking, Loops & Recursion, List Implementation, Top
9354 @comment  node-name,  next,  previous,  up
9355 @chapter Yanking Text Back
9356 @findex yank
9357 @findex rotate-yank-pointer
9358 @cindex Text retrieval
9359 @cindex Retrieving text
9360 @cindex Pasting text
9362 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9363 you can bring it back with a `yank' command.  The text that is cut out of
9364 the buffer is put in the kill ring and the yank commands insert the
9365 appropriate contents of the kill ring back into a buffer (not necessarily
9366 the original buffer).
9368 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9369 the kill ring into the current buffer.  If the @kbd{C-y} command is
9370 followed immediately by @kbd{M-y}, the first element is replaced by
9371 the second element.  Successive @kbd{M-y} commands replace the second
9372 element with the third, fourth, or fifth element, and so on.  When the
9373 last element in the kill ring is reached, it is replaced by the first
9374 element and the cycle is repeated.  (Thus the kill ring is called a
9375 `ring' rather than just a `list'.  However, the actual data structure
9376 that holds the text is a list.
9377 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9378 list is handled as a ring.)
9380 @menu
9381 * Kill Ring Overview::          The kill ring is a list.
9382 * kill-ring-yank-pointer::      The @code{kill-ring-yank-pointer} variable.
9383 * yank nthcdr Exercises::
9384 @end menu
9386 @node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9387 @comment  node-name,  next,  previous,  up
9388 @section Kill Ring Overview
9389 @cindex Kill ring overview
9391 The kill ring is a list of textual strings.  This is what it looks like:
9393 @smallexample
9394 ("some text" "a different piece of text" "yet more text")
9395 @end smallexample
9397 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9398 string of characters saying @samp{some text} would be inserted in this
9399 buffer where my cursor is located.
9401 The @code{yank} command is also used for duplicating text by copying it.
9402 The copied text is not cut from the buffer, but a copy of it is put on the
9403 kill ring and is inserted by yanking it back.
9405 Three functions are used for bringing text back from the kill ring:
9406 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9407 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9408 which is used by the two other functions.
9410 These functions refer to the kill ring through a variable called the
9411 @code{kill-ring-yank-pointer}.  Indeed, the insertion code for both the
9412 @code{yank} and @code{yank-pop} functions is:
9414 @smallexample
9415 (insert (car kill-ring-yank-pointer))
9416 @end smallexample
9418 To begin to understand how @code{yank} and @code{yank-pop} work, it is
9419 first necessary to look at the @code{kill-ring-yank-pointer} variable
9420 and the @code{rotate-yank-pointer} function.
9422 @node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9423 @comment  node-name,  next,  previous,  up
9424 @section The @code{kill-ring-yank-pointer} Variable
9426 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9427 a variable.  It points to something by being bound to the value of what
9428 it points to, like any other Lisp variable.
9430 @need 1000
9431 Thus, if the value of the kill ring is:
9433 @smallexample
9434 ("some text" "a different piece of text" "yet more text")
9435 @end smallexample
9437 @need 1250
9438 @noindent
9439 and the @code{kill-ring-yank-pointer} points to the second clause, the
9440 value of @code{kill-ring-yank-pointer} is:
9442 @smallexample
9443 ("a different piece of text" "yet more text")
9444 @end smallexample
9446 As explained in the previous chapter (@pxref{List Implementation}), the
9447 computer does not keep two different copies of the text being pointed to
9448 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}.  The
9449 words ``a different piece of text'' and ``yet more text'' are not
9450 duplicated.  Instead, the two Lisp variables point to the same pieces of
9451 text.  Here is a diagram:
9453 @c cons-cell-diagram #5
9454 @ifnottex
9455 @smallexample
9456 @group
9457 kill-ring     kill-ring-yank-pointer
9458     |               |
9459     |      ___ ___  |     ___ ___      ___ ___
9460      ---> |   |   |  --> |   |   |    |   |   |
9461           |___|___|----> |___|___|--> |___|___|--> nil
9462             |              |            |
9463             |              |            |
9464             |              |             --> "yet more text"
9465             |              |
9466             |               --> "a different piece of text
9467             |
9468              --> "some text"
9469 @end group
9470 @end smallexample
9471 @sp 1
9472 @end ifnottex
9473 @ifset print-postscript-figures
9474 @sp 1
9475 @tex
9476 @image{cons-5}
9477 %%%% old method of including an image
9478 % \input /usr/local/lib/tex/inputs/psfig.tex
9479 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9480 % \catcode`\@=0 %
9481 @end tex
9482 @sp 1
9483 @end ifset
9484 @ifclear print-postscript-figures
9485 @iftex
9486 @smallexample
9487 @group
9488 kill-ring     kill-ring-yank-pointer
9489     |               |
9490     |      ___ ___  |     ___ ___      ___ ___
9491      ---> |   |   |  --> |   |   |    |   |   |
9492           |___|___|----> |___|___|--> |___|___|--> nil
9493             |              |            |
9494             |              |            |
9495             |              |             --> "yet more text"
9496             |              |
9497             |               --> "a different piece of text
9498             |
9499              --> "some text"
9500 @end group
9501 @end smallexample
9502 @sp 1
9503 @end iftex
9504 @end ifclear
9506 Both the variable @code{kill-ring} and the variable
9507 @code{kill-ring-yank-pointer} are pointers.  But the kill ring itself is
9508 usually described as if it were actually what it is composed of.  The
9509 @code{kill-ring} is spoken of as if it were the list rather than that it
9510 points to the list.  Conversely, the @code{kill-ring-yank-pointer} is
9511 spoken of as pointing to a list.
9513 These two ways of talking about the same thing sound confusing at first but
9514 make sense on reflection.  The kill ring is generally thought of as the
9515 complete structure of data that holds the information of what has recently
9516 been cut out of the Emacs buffers.  The @code{kill-ring-yank-pointer}
9517 on the other hand, serves to indicate---that is, to `point to'---that part
9518 of the kill ring of which the first element (the @sc{car}) will be
9519 inserted.
9521 The @code{rotate-yank-pointer} function changes the element in the
9522 kill ring to which the @code{kill-ring-yank-pointer} points; when the
9523 pointer is set to point to the next element beyond the end of the kill
9524 ring, it automatically sets it to point to the first element of the
9525 kill ring.  This is how the list is transformed into a ring.  The
9526 @code{rotate-yank-pointer} function itself is not difficult, but
9527 contains many details.  It and the much simpler @code{yank} and
9528 @code{yank-pop} functions are described in an appendix.
9529 @xref{Kill Ring, , Handling the Kill Ring}.
9531 @need 1500
9532 @node yank nthcdr Exercises,  , kill-ring-yank-pointer, Yanking
9533 @section Exercises with @code{yank} and @code{nthcdr}
9535 @itemize @bullet
9536 @item
9537 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9538 your kill ring.  Add several items to your kill ring; look at its
9539 value again.  Using @kbd{M-y} (@code{yank-pop)}, move all the way
9540 around the kill ring.  How many items were in your kill ring?  Find
9541 the value of @code{kill-ring-max}.  Was your kill ring full, or could
9542 you have kept more blocks of text within it?
9544 @item
9545 Using @code{nthcdr} and @code{car}, construct a series of expressions
9546 to return the first, second, third, and fourth elements of a list.
9547 @end itemize
9549 @node Loops & Recursion, Regexp Search, Yanking, Top
9550 @comment  node-name,  next,  previous,  up
9551 @chapter Loops and Recursion
9552 @cindex Loops and recursion
9553 @cindex Recursion and loops
9554 @cindex Repetition (loops)
9556 Emacs Lisp has two primary ways to cause an expression, or a series of
9557 expressions, to be evaluated repeatedly: one uses a @code{while}
9558 loop, and the other uses @dfn{recursion}.
9560 Repetition can be very valuable.  For example, to move forward four
9561 sentences, you need only write a program that will move forward one
9562 sentence and then repeat the process four times.  Since a computer does
9563 not get bored or tired, such repetitive action does not have the
9564 deleterious effects that excessive or the wrong kinds of repetition can
9565 have on humans.
9567 People mostly write Emacs Lisp functions using @code{while} loops and
9568 their kin; but you can use recursion, which provides a very powerful
9569 way to think about and then to solve problems@footnote{You can write
9570 recursive functions to be frugal or wasteful of mental or computer
9571 resources; as it happens, methods that people find easy---that are
9572 frugal of `mental resources'---sometimes use considerable computer
9573 resources.  Emacs was designed to run on machines that we now consider
9574 limited and its default settings are conservative.  You may want to
9575 increase the values of @code{max-specpdl-size} and
9576 @code{max-lisp-eval-depth}.  In my @file{.emacs} file, I set them to
9577 15 and 30 times their default value.}.
9579 @menu
9580 * while::                       Causing a stretch of code to repeat.
9581 * dolist dotimes::
9582 * Recursion::                   Causing a function to call itself.
9583 * Looping exercise::
9584 @end menu
9586 @node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9587 @comment  node-name,  next,  previous,  up
9588 @section @code{while}
9589 @cindex Loops
9590 @findex while
9592 The @code{while} special form tests whether the value returned by
9593 evaluating its first argument is true or false.  This is similar to what
9594 the Lisp interpreter does with an @code{if}; what the interpreter does
9595 next, however, is different.
9597 In a @code{while} expression, if the value returned by evaluating the
9598 first argument is false, the Lisp interpreter skips the rest of the
9599 expression (the @dfn{body} of the expression) and does not evaluate it.
9600 However, if the value is true, the Lisp interpreter evaluates the body
9601 of the expression and then again tests whether the first argument to
9602 @code{while} is true or false.  If the value returned by evaluating the
9603 first argument is again true, the Lisp interpreter again evaluates the
9604 body of the expression.
9606 @need 1200
9607 The template for a @code{while} expression looks like this:
9609 @smallexample
9610 @group
9611 (while @var{true-or-false-test}
9612   @var{body}@dots{})
9613 @end group
9614 @end smallexample
9616 @menu
9617 * Looping with while::          Repeat so long as test returns true.
9618 * Loop Example::                A @code{while} loop that uses a list.
9619 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
9620 * Incrementing Loop::           A loop with an incrementing counter.
9621 * Decrementing Loop::           A loop with a decrementing counter.
9622 @end menu
9624 @node Looping with while, Loop Example, while, while
9625 @ifnottex
9626 @unnumberedsubsec Looping with @code{while}
9627 @end ifnottex
9629 So long as the true-or-false-test of the @code{while} expression
9630 returns a true value when it is evaluated, the body is repeatedly
9631 evaluated.  This process is called a loop since the Lisp interpreter
9632 repeats the same thing again and again, like an airplane doing a loop.
9633 When the result of evaluating the true-or-false-test is false, the
9634 Lisp interpreter does not evaluate the rest of the @code{while}
9635 expression and `exits the loop'.
9637 Clearly, if the value returned by evaluating the first argument to
9638 @code{while} is always true, the body following will be evaluated
9639 again and again @dots{} and again @dots{} forever.  Conversely, if the
9640 value returned is never true, the expressions in the body will never
9641 be evaluated.  The craft of writing a @code{while} loop consists of
9642 choosing a mechanism such that the true-or-false-test returns true
9643 just the number of times that you want the subsequent expressions to
9644 be evaluated, and then have the test return false.
9646 The value returned by evaluating a @code{while} is the value of the
9647 true-or-false-test.  An interesting consequence of this is that a
9648 @code{while} loop that evaluates without error will return @code{nil}
9649 or false regardless of whether it has looped 1 or 100 times or none at
9650 all.  A @code{while} expression that evaluates successfully never
9651 returns a true value!  What this means is that @code{while} is always
9652 evaluated for its side effects, which is to say, the consequences of
9653 evaluating the expressions within the body of the @code{while} loop.
9654 This makes sense.  It is not the mere act of looping that is desired,
9655 but the consequences of what happens when the expressions in the loop
9656 are repeatedly evaluated.
9658 @node Loop Example, print-elements-of-list, Looping with while, while
9659 @comment  node-name,  next,  previous,  up
9660 @subsection A @code{while} Loop and a List
9662 A common way to control a @code{while} loop is to test whether a list
9663 has any elements.  If it does, the loop is repeated; but if it does not,
9664 the repetition is ended.  Since this is an important technique, we will
9665 create a short example to illustrate it.
9667 A simple way to test whether a list has elements is to evaluate the
9668 list: if it has no elements, it is an empty list and will return the
9669 empty list, @code{()}, which is a synonym for @code{nil} or false.  On
9670 the other hand, a list with elements will return those elements when it
9671 is evaluated.  Since Emacs Lisp considers as true any value that is not
9672 @code{nil}, a list that returns elements will test true in a
9673 @code{while} loop.
9675 @need 1200
9676 For example, you can set the variable @code{empty-list} to @code{nil} by
9677 evaluating the following @code{setq} expression:
9679 @smallexample
9680 (setq empty-list ())
9681 @end smallexample
9683 @noindent
9684 After evaluating the @code{setq} expression, you can evaluate the
9685 variable @code{empty-list} in the usual way, by placing the cursor after
9686 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9687 echo area:
9689 @smallexample
9690 empty-list
9691 @end smallexample
9693 On the other hand, if you set a variable to be a list with elements, the
9694 list will appear when you evaluate the variable, as you can see by
9695 evaluating the following two expressions:
9697 @smallexample
9698 @group
9699 (setq animals '(gazelle giraffe lion tiger))
9701 animals
9702 @end group
9703 @end smallexample
9705 Thus, to create a @code{while} loop that tests whether there are any
9706 items in the list @code{animals}, the first part of the loop will be
9707 written like this:
9709 @smallexample
9710 @group
9711 (while animals
9712        @dots{}
9713 @end group
9714 @end smallexample
9716 @noindent
9717 When the @code{while} tests its first argument, the variable
9718 @code{animals} is evaluated.  It returns a list.  So long as the list
9719 has elements, the @code{while} considers the results of the test to be
9720 true; but when the list is empty, it considers the results of the test
9721 to be false.
9723 To prevent the @code{while} loop from running forever, some mechanism
9724 needs to be provided to empty the list eventually.  An oft-used
9725 technique is to have one of the subsequent forms in the @code{while}
9726 expression set the value of the list to be the @sc{cdr} of the list.
9727 Each time the @code{cdr} function is evaluated, the list will be made
9728 shorter, until eventually only the empty list will be left.  At this
9729 point, the test of the @code{while} loop will return false, and the
9730 arguments to the @code{while} will no longer be evaluated.
9732 For example, the list of animals bound to the variable @code{animals}
9733 can be set to be the @sc{cdr} of the original list with the
9734 following expression:
9736 @smallexample
9737 (setq animals (cdr animals))
9738 @end smallexample
9740 @noindent
9741 If you have evaluated the previous expressions and then evaluate this
9742 expression, you will see @code{(giraffe lion tiger)} appear in the echo
9743 area.  If you evaluate the expression again, @code{(lion tiger)} will
9744 appear in the echo area.  If you evaluate it again and yet again,
9745 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
9747 A template for a @code{while} loop that uses the @code{cdr} function
9748 repeatedly to cause the true-or-false-test eventually to test false
9749 looks like this:
9751 @smallexample
9752 @group
9753 (while @var{test-whether-list-is-empty}
9754   @var{body}@dots{}
9755   @var{set-list-to-cdr-of-list})
9756 @end group
9757 @end smallexample
9759 This test and use of @code{cdr} can be put together in a function that
9760 goes through a list and prints each element of the list on a line of its
9761 own.
9763 @node print-elements-of-list, Incrementing Loop, Loop Example, while
9764 @subsection An Example: @code{print-elements-of-list}
9765 @findex print-elements-of-list
9767 The @code{print-elements-of-list} function illustrates a @code{while}
9768 loop with a list.
9770 @cindex @file{*scratch*} buffer
9771 The function requires several lines for its output.  If you are
9772 reading this in Emacs 21 or a later version, you can evaluate the
9773 following expression inside of Info, as usual.
9775 If you are using an earlier version of Emacs, you need to copy the
9776 necessary expressions to your @file{*scratch*} buffer and evaluate
9777 them there.  This is because the echo area had only one line in the
9778 earlier versions.
9780 You can copy the expressions by marking the beginning of the region
9781 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9782 the end of the region and then copying the region using @kbd{M-w}
9783 (@code{copy-region-as-kill}).  In the @file{*scratch*} buffer, you can
9784 yank the expressions back by typing @kbd{C-y} (@code{yank}).
9786 After you have copied the expressions to the @file{*scratch*} buffer,
9787 evaluate each expression in turn.  Be sure to evaluate the last
9788 expression, @code{(print-elements-of-list animals)}, by typing
9789 @kbd{C-u C-x C-e}, that is, by giving an argument to
9790 @code{eval-last-sexp}.  This will cause the result of the evaluation
9791 to be printed in the @file{*scratch*} buffer instead of being printed
9792 in the echo area.  (Otherwise you will see something like this in your
9793 echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
9794 each @samp{^J} stands for a `newline'.)
9796 @need 1500
9797 If you are using Emacs 21 or later, you can evaluate these expressions
9798 directly in the Info buffer, and the echo area will grow to show the
9799 results.
9801 @smallexample
9802 @group
9803 (setq animals '(gazelle giraffe lion tiger))
9805 (defun print-elements-of-list (list)
9806   "Print each element of LIST on a line of its own."
9807   (while list
9808     (print (car list))
9809     (setq list (cdr list))))
9811 (print-elements-of-list animals)
9812 @end group
9813 @end smallexample
9815 @need 1200
9816 @noindent
9817 When you evaluate the three expressions in sequence, you will see
9818 this:
9820 @smallexample
9821 @group
9822 gazelle
9824 giraffe
9826 lion
9828 tiger
9830 @end group
9831 @end smallexample
9833 Each element of the list is printed on a line of its own (that is what
9834 the function @code{print} does) and then the value returned by the
9835 function is printed.  Since the last expression in the function is the
9836 @code{while} loop, and since @code{while} loops always return
9837 @code{nil}, a @code{nil} is printed after the last element of the list.
9839 @node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9840 @comment  node-name,  next,  previous,  up
9841 @subsection A Loop with an Incrementing Counter
9843 A loop is not useful unless it stops when it ought.  Besides
9844 controlling a loop with a list, a common way of stopping a loop is to
9845 write the first argument as a test that returns false when the correct
9846 number of repetitions are complete.  This means that the loop must
9847 have a counter---an expression that counts how many times the loop
9848 repeats itself.
9850 The test can be an expression such as @code{(< count desired-number)}
9851 which returns @code{t} for true if the value of @code{count} is less
9852 than the @code{desired-number} of repetitions and @code{nil} for false if
9853 the value of @code{count} is equal to or is greater than the
9854 @code{desired-number}.  The expression that increments the count can be
9855 a simple @code{setq} such as @code{(setq count (1+ count))}, where
9856 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
9857 argument.  (The expression @w{@code{(1+ count)}} has the same result as
9858 @w{@code{(+ count 1)}}, but is easier for a human to read.)
9860 @need 1250
9861 The template for a @code{while} loop controlled by an incrementing
9862 counter looks like this:
9864 @smallexample
9865 @group
9866 @var{set-count-to-initial-value}
9867 (while (< count desired-number)         ; @r{true-or-false-test}
9868   @var{body}@dots{}
9869   (setq count (1+ count)))              ; @r{incrementer}
9870 @end group
9871 @end smallexample
9873 @noindent
9874 Note that you need to set the initial value of @code{count}; usually it
9875 is set to 1.
9877 @menu
9878 * Incrementing Example::        Counting pebbles in a triangle.
9879 * Inc Example parts::           The parts of the function definition.
9880 * Inc Example altogether::      Putting the function definition together.
9881 @end menu
9883 @node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9884 @unnumberedsubsubsec  Example with incrementing counter
9886 Suppose you are playing on the beach and decide to make a triangle of
9887 pebbles, putting one pebble in the first row, two in the second row,
9888 three in the third row and so on, like this:
9890 @sp 1
9891 @c pebble diagram
9892 @ifnottex
9893 @smallexample
9894 @group
9895                *
9896               * *
9897              * * *
9898             * * * *
9899 @end group
9900 @end smallexample
9901 @end ifnottex
9902 @iftex
9903 @smallexample
9904 @group
9905                @bullet{}
9906               @bullet{} @bullet{}
9907              @bullet{} @bullet{} @bullet{}
9908             @bullet{} @bullet{} @bullet{} @bullet{}
9909 @end group
9910 @end smallexample
9911 @end iftex
9912 @sp 1
9914 @noindent
9915 (About 2500 years ago, Pythagoras and others developed the beginnings of
9916 number theory by considering questions such as this.)
9918 Suppose you want to know how many pebbles you will need to make a
9919 triangle with 7 rows?
9921 Clearly, what you need to do is add up the numbers from 1 to 7.  There
9922 are two ways to do this; start with the smallest number, one, and add up
9923 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9924 number and add the list going down: 7, 6, 5, 4 and so on.  Because both
9925 mechanisms illustrate common ways of writing @code{while} loops, we will
9926 create two examples, one counting up and the other counting down.  In
9927 this first example, we will start with 1 and add 2, 3, 4 and so on.
9929 If you are just adding up a short list of numbers, the easiest way to do
9930 it is to add up all the numbers at once.  However, if you do not know
9931 ahead of time how many numbers your list will have, or if you want to be
9932 prepared for a very long list, then you need to design your addition so
9933 that what you do is repeat a simple process many times instead of doing
9934 a more complex process once.
9936 For example, instead of adding up all the pebbles all at once, what you
9937 can do is add the number of pebbles in the first row, 1, to the number
9938 in the second row, 2, and then add the total of those two rows to the
9939 third row, 3.  Then you can add the number in the fourth row, 4, to the
9940 total of the first three rows; and so on.
9942 The critical characteristic of the process is that each repetitive
9943 action is simple.  In this case, at each step we add only two numbers,
9944 the number of pebbles in the row and the total already found.  This
9945 process of adding two numbers is repeated again and again until the last
9946 row has been added to the total of all the preceding rows.  In a more
9947 complex loop the repetitive action might not be so simple, but it will
9948 be simpler than doing everything all at once.
9950 @node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9951 @unnumberedsubsubsec The parts of the function definition
9953 The preceding analysis gives us the bones of our function definition:
9954 first, we will need a variable that we can call @code{total} that will
9955 be the total number of pebbles.  This will be the value returned by
9956 the function.
9958 Second, we know that the function will require an argument: this
9959 argument will be the total number of rows in the triangle.  It can be
9960 called @code{number-of-rows}.
9962 Finally, we need a variable to use as a counter.  We could call this
9963 variable @code{counter}, but a better name is @code{row-number}.
9964 That is because what the counter does is count rows, and a program
9965 should be written to be as understandable as possible.
9967 When the Lisp interpreter first starts evaluating the expressions in the
9968 function, the value of @code{total} should be set to zero, since we have
9969 not added anything to it.  Then the function should add the number of
9970 pebbles in the first row to the total, and then add the number of
9971 pebbles in the second to the total, and then add the number of
9972 pebbles in the third row to the total, and so on, until there are no
9973 more rows left to add.
9975 Both @code{total} and @code{row-number} are used only inside the
9976 function, so they can be declared as local variables with @code{let}
9977 and given initial values.  Clearly, the initial value for @code{total}
9978 should be 0.  The initial value of @code{row-number} should be 1,
9979 since we start with the first row.  This means that the @code{let}
9980 statement will look like this:
9982 @smallexample
9983 @group
9984   (let ((total 0)
9985         (row-number 1))
9986     @var{body}@dots{})
9987 @end group
9988 @end smallexample
9990 After the internal variables are declared and bound to their initial
9991 values, we can begin the @code{while} loop.  The expression that serves
9992 as the test should return a value of @code{t} for true so long as the
9993 @code{row-number} is less than or equal to the @code{number-of-rows}.
9994 (If the expression tests true only so long as the row number is less
9995 than the number of rows in the triangle, the last row will never be
9996 added to the total; hence the row number has to be either less than or
9997 equal to the number of rows.)
9999 @need 1500
10000 @findex <= @r{(less than or equal)}
10001 Lisp provides the @code{<=} function that returns true if the value of
10002 its first argument is less than or equal to the value of its second
10003 argument and false otherwise.  So the expression that the @code{while}
10004 will evaluate as its test should look like this:
10006 @smallexample
10007 (<= row-number number-of-rows)
10008 @end smallexample
10010 The total number of pebbles can be found by repeatedly adding the number
10011 of pebbles in a row to the total already found.  Since the number of
10012 pebbles in the row is equal to the row number, the total can be found by
10013 adding the row number to the total.  (Clearly, in a more complex
10014 situation, the number of pebbles in the row might be related to the row
10015 number in a more complicated way; if this were the case, the row number
10016 would be replaced by the appropriate expression.)
10018 @smallexample
10019 (setq total (+ total row-number))
10020 @end smallexample
10022 @noindent
10023 What this does is set the new value of @code{total} to be equal to the
10024 sum of adding the number of pebbles in the row to the previous total.
10026 After setting the value of @code{total}, the conditions need to be
10027 established for the next repetition of the loop, if there is one.  This
10028 is done by incrementing the value of the @code{row-number} variable,
10029 which serves as a counter.  After the @code{row-number} variable has
10030 been incremented, the true-or-false-test at the beginning of the
10031 @code{while} loop tests whether its value is still less than or equal to
10032 the value of the @code{number-of-rows} and if it is, adds the new value
10033 of the @code{row-number} variable to the @code{total} of the previous
10034 repetition of the loop.
10036 @need 1200
10037 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10038 @code{row-number} variable can be incremented with this expression:
10040 @smallexample
10041 (setq row-number (1+ row-number))
10042 @end smallexample
10044 @node Inc Example altogether,  , Inc Example parts, Incrementing Loop
10045 @unnumberedsubsubsec Putting the function definition together
10047 We have created the parts for the function definition; now we need to
10048 put them together.
10050 @need 800
10051 First, the contents of the @code{while} expression:
10053 @smallexample
10054 @group
10055 (while (<= row-number number-of-rows)   ; @r{true-or-false-test}
10056   (setq total (+ total row-number))
10057   (setq row-number (1+ row-number)))    ; @r{incrementer}
10058 @end group
10059 @end smallexample
10061 Along with the @code{let} expression varlist, this very nearly
10062 completes the body of the function definition.  However, it requires
10063 one final element, the need for which is somewhat subtle.
10065 The final touch is to place the variable @code{total} on a line by
10066 itself after the @code{while} expression.  Otherwise, the value returned
10067 by the whole function is the value of the last expression that is
10068 evaluated in the body of the @code{let}, and this is the value
10069 returned by the @code{while}, which is always @code{nil}.
10071 This may not be evident at first sight.  It almost looks as if the
10072 incrementing expression is the last expression of the whole function.
10073 But that expression is part of the body of the @code{while}; it is the
10074 last element of the list that starts with the symbol @code{while}.
10075 Moreover, the whole of the @code{while} loop is a list within the body
10076 of the @code{let}.
10078 @need 1250
10079 In outline, the function will look like this:
10081 @smallexample
10082 @group
10083 (defun @var{name-of-function} (@var{argument-list})
10084   "@var{documentation}@dots{}"
10085   (let (@var{varlist})
10086     (while (@var{true-or-false-test})
10087       @var{body-of-while}@dots{} )
10088     @dots{} )                     ; @r{Need final expression here.}
10089 @end group
10090 @end smallexample
10092 The result of evaluating the @code{let} is what is going to be returned
10093 by the @code{defun} since the @code{let} is not embedded within any
10094 containing list, except for the @code{defun} as a whole.  However, if
10095 the @code{while} is the last element of the @code{let} expression, the
10096 function will always return @code{nil}.  This is not what we want!
10097 Instead, what we want is the value of the variable @code{total}.  This
10098 is returned by simply placing the symbol as the last element of the list
10099 starting with @code{let}.  It gets evaluated after the preceding
10100 elements of the list are evaluated, which means it gets evaluated after
10101 it has been assigned the correct value for the total.
10103 It may be easier to see this by printing the list starting with
10104 @code{let} all on one line.  This format makes it evident that the
10105 @var{varlist} and @code{while} expressions are the second and third
10106 elements of the list starting with @code{let}, and the @code{total} is
10107 the last element:
10109 @smallexample
10110 @group
10111 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10112 @end group
10113 @end smallexample
10115 @need 1200
10116 Putting everything together, the @code{triangle} function definition
10117 looks like this:
10119 @smallexample
10120 @group
10121 (defun triangle (number-of-rows)    ; @r{Version with}
10122                                     ; @r{  incrementing counter.}
10123   "Add up the number of pebbles in a triangle.
10124 The first row has one pebble, the second row two pebbles,
10125 the third row three pebbles, and so on.
10126 The argument is NUMBER-OF-ROWS."
10127 @end group
10128 @group
10129   (let ((total 0)
10130         (row-number 1))
10131     (while (<= row-number number-of-rows)
10132       (setq total (+ total row-number))
10133       (setq row-number (1+ row-number)))
10134     total))
10135 @end group
10136 @end smallexample
10138 @need 1200
10139 After you have installed @code{triangle} by evaluating the function, you
10140 can try it out.  Here are two examples:
10142 @smallexample
10143 @group
10144 (triangle 4)
10146 (triangle 7)
10147 @end group
10148 @end smallexample
10150 @noindent
10151 The sum of the first four numbers is 10 and the sum of the first seven
10152 numbers is 28.
10154 @node Decrementing Loop,  , Incrementing Loop, while
10155 @comment  node-name,  next,  previous,  up
10156 @subsection Loop with a Decrementing Counter
10158 Another common way to write a @code{while} loop is to write the test
10159 so that it determines whether a counter is greater than zero.  So long
10160 as the counter is greater than zero, the loop is repeated.  But when
10161 the counter is equal to or less than zero, the loop is stopped.  For
10162 this to work, the counter has to start out greater than zero and then
10163 be made smaller and smaller by a form that is evaluated
10164 repeatedly.
10166 The test will be an expression such as @code{(> counter 0)} which
10167 returns @code{t} for true if the value of @code{counter} is greater
10168 than zero, and @code{nil} for false if the value of @code{counter} is
10169 equal to or less than zero.  The expression that makes the number
10170 smaller and smaller can be a simple @code{setq} such as @code{(setq
10171 counter (1- counter))}, where @code{1-} is a built-in function in
10172 Emacs Lisp that subtracts 1 from its argument.
10174 @need 1250
10175 The template for a decrementing @code{while} loop looks like this:
10177 @smallexample
10178 @group
10179 (while (> counter 0)                    ; @r{true-or-false-test}
10180   @var{body}@dots{}
10181   (setq counter (1- counter)))          ; @r{decrementer}
10182 @end group
10183 @end smallexample
10185 @menu
10186 * Decrementing Example::        More pebbles on the beach.
10187 * Dec Example parts::           The parts of the function definition.
10188 * Dec Example altogether::      Putting the function definition together.
10189 @end menu
10191 @node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10192 @unnumberedsubsubsec Example with decrementing counter
10194 To illustrate a loop with a decrementing counter, we will rewrite the
10195 @code{triangle} function so the counter decreases to zero.
10197 This is the reverse of the earlier version of the function.  In this
10198 case, to find out how many pebbles are needed to make a triangle with
10199 3 rows, add the number of pebbles in the third row, 3, to the number
10200 in the preceding row, 2, and then add the total of those two rows to
10201 the row that precedes them, which is 1.
10203 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10204 the number of pebbles in the seventh row, 7, to the number in the
10205 preceding row, which is 6, and then add the total of those two rows to
10206 the row that precedes them, which is 5, and so on.  As in the previous
10207 example, each addition only involves adding two numbers, the total of
10208 the rows already added up and the number of pebbles in the row that is
10209 being added to the total.  This process of adding two numbers is
10210 repeated again and again until there are no more pebbles to add.
10212 We know how many pebbles to start with: the number of pebbles in the
10213 last row is equal to the number of rows.  If the triangle has seven
10214 rows, the number of pebbles in the last row is 7.  Likewise, we know how
10215 many pebbles are in the preceding row: it is one less than the number in
10216 the row.
10218 @node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10219 @unnumberedsubsubsec The parts of the function definition
10221 We start with three variables: the total number of rows in the
10222 triangle; the number of pebbles in a row; and the total number of
10223 pebbles, which is what we want to calculate.  These variables can be
10224 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10225 @code{total}, respectively.
10227 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10228 inside the function and are declared with @code{let}.  The initial
10229 value of @code{total} should, of course, be zero.  However, the
10230 initial value of @code{number-of-pebbles-in-row} should be equal to
10231 the number of rows in the triangle, since the addition will start with
10232 the longest row.
10234 @need 1250
10235 This means that the beginning of the @code{let} expression will look
10236 like this:
10238 @smallexample
10239 @group
10240 (let ((total 0)
10241       (number-of-pebbles-in-row number-of-rows))
10242   @var{body}@dots{})
10243 @end group
10244 @end smallexample
10246 The total number of pebbles can be found by repeatedly adding the number
10247 of pebbles in a row to the total already found, that is, by repeatedly
10248 evaluating the following expression:
10250 @smallexample
10251 (setq total (+ total number-of-pebbles-in-row))
10252 @end smallexample
10254 @noindent
10255 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10256 the @code{number-of-pebbles-in-row} should be decremented by one, since
10257 the next time the loop repeats, the preceding row will be
10258 added to the total.
10260 The number of pebbles in a preceding row is one less than the number of
10261 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10262 used to compute the number of pebbles in the preceding row.  This can be
10263 done with the following expression:
10265 @smallexample
10266 @group
10267 (setq number-of-pebbles-in-row
10268       (1- number-of-pebbles-in-row))
10269 @end group
10270 @end smallexample
10272 Finally, we know that the @code{while} loop should stop making repeated
10273 additions when there are no pebbles in a row.  So the test for
10274 the @code{while} loop is simply:
10276 @smallexample
10277 (while (> number-of-pebbles-in-row 0)
10278 @end smallexample
10280 @node Dec Example altogether,  , Dec Example parts, Decrementing Loop
10281 @unnumberedsubsubsec Putting the function definition together
10283 We can put these expressions together to create a function definition
10284 that works.  However, on examination, we find that one of the local
10285 variables is unneeded!
10287 @need 1250
10288 The function definition looks like this:
10290 @smallexample
10291 @group
10292 ;;; @r{First subtractive version.}
10293 (defun triangle (number-of-rows)
10294   "Add up the number of pebbles in a triangle."
10295   (let ((total 0)
10296         (number-of-pebbles-in-row number-of-rows))
10297     (while (> number-of-pebbles-in-row 0)
10298       (setq total (+ total number-of-pebbles-in-row))
10299       (setq number-of-pebbles-in-row
10300             (1- number-of-pebbles-in-row)))
10301     total))
10302 @end group
10303 @end smallexample
10305 As written, this function works.
10307 However, we do not need @code{number-of-pebbles-in-row}.
10309 @cindex Argument as local variable
10310 When the @code{triangle} function is evaluated, the symbol
10311 @code{number-of-rows} will be bound to a number, giving it an initial
10312 value.  That number can be changed in the body of the function as if
10313 it were a local variable, without any fear that such a change will
10314 effect the value of the variable outside of the function.  This is a
10315 very useful characteristic of Lisp; it means that the variable
10316 @code{number-of-rows} can be used anywhere in the function where
10317 @code{number-of-pebbles-in-row} is used.
10319 @need 800
10320 Here is a second version of the function written a bit more cleanly:
10322 @smallexample
10323 @group
10324 (defun triangle (number)                ; @r{Second version.}
10325   "Return sum of numbers 1 through NUMBER inclusive."
10326   (let ((total 0))
10327     (while (> number 0)
10328       (setq total (+ total number))
10329       (setq number (1- number)))
10330     total))
10331 @end group
10332 @end smallexample
10334 In brief, a properly written @code{while} loop will consist of three parts:
10336 @enumerate
10337 @item
10338 A test that will return false after the loop has repeated itself the
10339 correct number of times.
10341 @item
10342 An expression the evaluation of which will return the value desired
10343 after being repeatedly evaluated.
10345 @item
10346 An expression to change the value passed to the true-or-false-test so
10347 that the test returns false after the loop has repeated itself the right
10348 number of times.
10349 @end enumerate
10351 @node dolist dotimes, Recursion, while, Loops & Recursion
10352 @comment  node-name,  next,  previous,  up
10353 @section Save your time: @code{dolist} and @code{dotimes}
10355 In addition to @code{while}, both @code{dolist} and @code{dotimes}
10356 provide for looping.  Sometimes these are quicker to write than the
10357 equivalent @code{while} loop.  Both are Lisp macros.  (@xref{Macros, ,
10358 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10360 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10361 list':  @code{dolist} automatically shortens the list each time it
10362 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10363 each shorter version of the list to the first of its arguments.
10365 @code{dotimes} loops a specific number of times: you specify the number.
10367 @menu
10368 * dolist::
10369 * dotimes::
10370 @end menu
10372 @node dolist, dotimes, dolist dotimes, dolist dotimes
10373 @unnumberedsubsubsec The @code{dolist} Macro
10374 @findex dolist
10376 Suppose, for example, you want to reverse a list, so that
10377 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10379 @need 1250
10380 In practice, you would use the @code{reverse} function, like this:
10382 @smallexample
10383 @group
10384 (setq animals '(gazelle giraffe lion tiger))
10386 (reverse animals)
10387 @end group
10388 @end smallexample
10390 @need 800
10391 @noindent
10392 Here is how you could reverse the list using a @code{while} loop:
10394 @smallexample
10395 @group
10396 (setq animals '(gazelle giraffe lion tiger))
10398 (defun reverse-list-with-while (list)
10399   "Using while, reverse the order of LIST."
10400   (let (value)  ; make sure list starts empty
10401     (while list
10402       (setq value (cons (car list) value))
10403       (setq list (cdr list)))
10404     value))
10406 (reverse-list-with-while animals)
10407 @end group
10408 @end smallexample
10410 @need 800
10411 @noindent
10412 And here is how you could use the @code{dolist} macro:
10414 @smallexample
10415 @group
10416 (setq animals '(gazelle giraffe lion tiger))
10418 (defun reverse-list-with-dolist (list)
10419   "Using dolist, reverse the order of LIST."
10420   (let (value)  ; make sure list starts empty
10421     (dolist (element list value)
10422       (setq value (cons element value)))))
10424 (reverse-list-with-dolist animals)
10425 @end group
10426 @end smallexample
10428 @need 1250
10429 @noindent
10430 In Info, you can place your cursor after the closing parenthesis of
10431 each expression and type @kbd{C-x C-e}; in each case, you should see
10433 @smallexample
10434 (tiger lion giraffe gazelle)
10435 @end smallexample
10437 @noindent
10438 in the echo area.
10440 For this example, the existing @code{reverse} function is obviously best.
10441 The @code{while} loop is just like our first example (@pxref{Loop
10442 Example, , A @code{while} Loop and a List}).  The @code{while} first
10443 checks whether the list has elements; if so, it constructs a new list
10444 by adding the first element of the list to the existing list (which in
10445 the first iteration of the loop is @code{nil}).  Since the second
10446 element is prepended in front of the first element, and the third
10447 element is prepended in front of the second element, the list is reversed.
10449 In the expression using a @code{while} loop,
10450 the @w{@code{(setq list (cdr list))}}
10451 expression shortens the list, so the @code{while} loop eventually
10452 stops.  In addition, it provides the @code{cons} expression with a new
10453 first element by creating a new and shorter list at each repetition of
10454 the loop.
10456 The @code{dolist} expression does very much the same as the
10457 @code{while} expression, except that the @code{dolist} macro does some
10458 of the work you have to do when writing a @code{while} expression.
10460 Like a @code{while} loop, a @code{dolist} loops.  What is different is
10461 that it automatically shortens the list each time it loops --- it
10462 `@sc{cdr}s down the list' on its own --- and it automatically binds
10463 the @sc{car} of each shorter version of the list to the first of its
10464 arguments.
10466 In the example, the @sc{car} of each shorter version of the list is
10467 referred to using the symbol @samp{element}, the list itself is called
10468 @samp{list}, and the value returned is called @samp{value}.  The
10469 remainder of the @code{dolist} expression is the body.
10471 The @code{dolist} expression binds the @sc{car} of each shorter
10472 version of the list to @code{element} and then evaluates the body of
10473 the expression; and repeats the loop.  The result is returned in
10474 @code{value}.
10476 @node dotimes,  , dolist, dolist dotimes
10477 @unnumberedsubsubsec The @code{dotimes} Macro
10478 @findex dotimes
10480 The @code{dotimes} macro is similar to @code{dolist}, except that it
10481 loops a specific number of times.
10483 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10484 and so forth each time around the loop, and the value of the third
10485 argument is returned.  You need to provide the value of the second
10486 argument, which is how many times the macro loops.
10488 @need 1250
10489 For example, the following binds the numbers from 0 up to, but not
10490 including, the number 3 to the first argument, @var{number}, and then
10491 constructs a list of the three numbers.  (The first number is 0, the
10492 second number is 1, and the third number is 2; this makes a total of
10493 three numbers in all, starting with zero as the first number.)
10495 @smallexample
10496 @group
10497 (let (value)      ; otherwise a value is a void variable
10498   (dotimes (number 3 value)
10499     (setq value (cons number value))))
10501 @result{} (2 1 0)
10502 @end group
10503 @end smallexample
10505 @noindent
10506 @code{dotimes} returns @code{value}, so the way to use
10507 @code{dotimes} is to operate on some expression @var{number} number of
10508 times and then return the result, either as a list or an atom.
10510 @need 1250
10511 Here is an example of a @code{defun} that uses @code{dotimes} to add
10512 up the number of pebbles in a triangle.
10514 @smallexample
10515 @group
10516 (defun triangle-using-dotimes (number-of-rows)
10517   "Using dotimes, add up the number of pebbles in a triangle."
10518 (let ((total 0))  ; otherwise a total is a void variable
10519   (dotimes (number number-of-rows total)
10520     (setq total (+ total (1+ number))))))
10522 (triangle-using-dotimes 4)
10523 @end group
10524 @end smallexample
10526 @node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10527 @comment  node-name,  next,  previous,  up
10528 @section Recursion
10529 @cindex Recursion
10531 A recursive function contains code that tells the Lisp interpreter to
10532 call a program that runs exactly like itself, but with slightly
10533 different arguments.  The code runs exactly the same because it has
10534 the same name.  However, even though the program has the same name, it
10535 is not the same entity.  It is different.  In the jargon, it is a
10536 different `instance'.
10538 Eventually, if the program is written correctly, the `slightly
10539 different arguments' will become sufficiently different from the first
10540 arguments that the final instance will stop.
10542 @menu
10543 * Building Robots::             Same model, different serial number ...
10544 * Recursive Definition Parts::  Walk until you stop ...
10545 * Recursion with list::         Using a list as the test whether to recurse.
10546 * Recursive triangle function::
10547 * Recursion with cond::
10548 * Recursive Patterns::          Often used templates.
10549 * No Deferment::                Don't store up work ...
10550 * No deferment solution::
10551 @end menu
10553 @node Building Robots, Recursive Definition Parts, Recursion, Recursion
10554 @comment  node-name,  next,  previous,  up
10555 @subsection Building Robots: Extending the Metaphor
10556 @cindex Building robots
10557 @cindex Robots, building
10559 It is sometimes helpful to think of a running program as a robot that
10560 does a job.  In doing its job, a recursive function calls on a second
10561 robot to help it.  The second robot is identical to the first in every
10562 way, except that the second robot helps the first and has been
10563 passed different arguments than the first.
10565 In a recursive function, the second robot may call a third; and the
10566 third may call a fourth, and so on.  Each of these is a different
10567 entity; but all are clones.
10569 Since each robot has slightly different instructions---the arguments
10570 will differ from one robot to the next---the last robot should know
10571 when to stop.
10573 Let's expand on the metaphor in which a computer program is a robot.
10575 A function definition provides the blueprints for a robot.  When you
10576 install a function definition, that is, when you evaluate a
10577 @code{defun} special form, you install the necessary equipment to
10578 build robots.  It is as if you were in a factory, setting up an
10579 assembly line.  Robots with the same name are built according to the
10580 same blueprints.  So they have, as it were, the same `model number',
10581 but a different `serial number'.
10583 We often say that a recursive function `calls itself'.  What we mean
10584 is that the instructions in a recursive function cause the Lisp
10585 interpreter to run a different function that has the same name and
10586 does the same job as the first, but with different arguments.
10588 It is important that the arguments differ from one instance to the
10589 next; otherwise, the process will never stop.
10591 @node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10592 @comment  node-name,  next,  previous,  up
10593 @subsection The Parts of a Recursive Definition
10594 @cindex Parts of a Recursive Definition
10595 @cindex Recursive Definition Parts
10597 A recursive function typically contains a conditional expression which
10598 has three parts:
10600 @enumerate
10601 @item
10602 A true-or-false-test that determines whether the function is called
10603 again, here called the @dfn{do-again-test}.
10605 @item
10606 The name of the function.  When this name is called, a new instance of
10607 the function---a new robot, as it were---is created and told what to do.
10609 @item
10610 An expression that returns a different value each time the function is
10611 called, here called the @dfn{next-step-expression}.  Consequently, the
10612 argument (or arguments) passed to the new instance of the function
10613 will be different from that passed to the previous instance.  This
10614 causes the conditional expression, the @dfn{do-again-test}, to test
10615 false after the correct number of repetitions.
10616 @end enumerate
10618 Recursive functions can be much simpler than any other kind of
10619 function.  Indeed, when people first start to use them, they often look
10620 so mysteriously simple as to be incomprehensible.  Like riding a
10621 bicycle, reading a recursive function definition takes a certain knack
10622 which is hard at first but then seems simple.
10624 @need 1200
10625 There are several different common recursive patterns.  A very simple
10626 pattern looks like this:
10628 @smallexample
10629 @group
10630 (defun @var{name-of-recursive-function} (@var{argument-list})
10631   "@var{documentation}@dots{}"
10632   (if @var{do-again-test}
10633     @var{body}@dots{}
10634     (@var{name-of-recursive-function}
10635          @var{next-step-expression})))
10636 @end group
10637 @end smallexample
10639 Each time a recursive function is evaluated, a new instance of it is
10640 created and told what to do.  The arguments tell the instance what to do.
10642 An argument is bound to the value of the next-step-expression.  Each
10643 instance runs with a different value of the next-step-expression.
10645 The value in the next-step-expression is used in the do-again-test.
10647 The value returned by the next-step-expression is passed to the new
10648 instance of the function, which evaluates it (or some
10649 transmogrification of it) to determine whether to continue or stop.
10650 The next-step-expression is designed so that the do-again-test returns
10651 false when the function should no longer be repeated.
10653 The do-again-test is sometimes called the @dfn{stop condition},
10654 since it stops the repetitions when it tests false.
10656 @node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10657 @comment  node-name,  next,  previous,  up
10658 @subsection Recursion with a List
10660 The example of a @code{while} loop that printed the elements of a list
10661 of numbers can be written recursively.  Here is the code, including
10662 an expression to set the value of the variable @code{animals} to a list.
10664 If you are using Emacs 20 or before, this example must be copied to
10665 the @file{*scratch*} buffer and each expression must be evaluated
10666 there.  Use @kbd{C-u C-x C-e} to evaluate the
10667 @code{(print-elements-recursively animals)} expression so that the
10668 results are printed in the buffer; otherwise the Lisp interpreter will
10669 try to squeeze the results into the one line of the echo area.
10671 Also, place your cursor immediately after the last closing parenthesis
10672 of the @code{print-elements-recursively} function, before the comment.
10673 Otherwise, the Lisp interpreter will try to evaluate the comment.
10675 If you are using Emacs 21 or later, you can evaluate this expression
10676 directly in Info.
10678 @findex print-elements-recursively
10679 @smallexample
10680 @group
10681 (setq animals '(gazelle giraffe lion tiger))
10683 (defun print-elements-recursively (list)
10684   "Print each element of LIST on a line of its own.
10685 Uses recursion."
10686   (if list                              ; @r{do-again-test}
10687       (progn
10688         (print (car list))              ; @r{body}
10689         (print-elements-recursively     ; @r{recursive call}
10690          (cdr list)))))                 ; @r{next-step-expression}
10692 (print-elements-recursively animals)
10693 @end group
10694 @end smallexample
10696 The @code{print-elements-recursively} function first tests whether
10697 there is any content in the list; if there is, the function prints the
10698 first element of the list, the @sc{car} of the list.  Then the
10699 function `invokes itself', but gives itself as its argument, not the
10700 whole list, but the second and subsequent elements of the list, the
10701 @sc{cdr} of the list.
10703 Put another way, if the list is not empty, the function invokes
10704 another instance of code that is similar to the initial code, but is a
10705 different thread of execution, with different arguments than the first
10706 instance.
10708 Put in yet another way, if the list is not empty, the first robot
10709 assemblies a second robot and tells it what to do; the second robot is
10710 a different individual from the first, but is the same model.
10712 When the second evaluation occurs, the @code{if} expression is
10713 evaluated and if true, prints the first element of the list it
10714 receives as its argument (which is the second element of the original
10715 list).  Then the function `calls itself' with the @sc{cdr} of the list
10716 it is invoked with, which (the second time around) is the @sc{cdr} of
10717 the @sc{cdr} of the original list.
10719 Note that although we say that the function `calls itself', what we
10720 mean is that the Lisp interpreter assembles and instructs a new
10721 instance of the program.  The new instance is a clone of the first,
10722 but is a separate individual.
10724 Each time the function `invokes itself', it invokes itself on a
10725 shorter version of the original list.  It creates a new instance that
10726 works on a shorter list.
10728 Eventually, the function invokes itself on an empty list.  It creates
10729 a new instance whose argument is @code{nil}.  The conditional expression
10730 tests the value of @code{list}.  Since the value of @code{list} is
10731 @code{nil}, the @code{if} expression tests false so the then-part is
10732 not evaluated.  The function as a whole then returns @code{nil}.
10734 @need 1200
10735 When you evaluate @code{(print-elements-recursively animals)} in the
10736 @file{*scratch*} buffer, you see this result:
10738 @smallexample
10739 @group
10740 gazelle
10742 giraffe
10744 lion
10746 tiger
10748 @end group
10749 @end smallexample
10751 @node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10752 @comment  node-name,  next,  previous,  up
10753 @subsection Recursion in Place of a Counter
10754 @findex triangle-recursively
10756 @need 1200
10757 The @code{triangle} function described in a previous section can also
10758 be written recursively.  It looks like this:
10760 @smallexample
10761 @group
10762 (defun triangle-recursively (number)
10763   "Return the sum of the numbers 1 through NUMBER inclusive.
10764 Uses recursion."
10765   (if (= number 1)                    ; @r{do-again-test}
10766       1                               ; @r{then-part}
10767     (+ number                         ; @r{else-part}
10768        (triangle-recursively          ; @r{recursive call}
10769         (1- number)))))               ; @r{next-step-expression}
10771 (triangle-recursively 7)
10772 @end group
10773 @end smallexample
10775 @noindent
10776 You can install this function by evaluating it and then try it by
10777 evaluating @code{(triangle-recursively 7)}.  (Remember to put your
10778 cursor immediately after the last parenthesis of the function
10779 definition, before the comment.)  The function evaluates to 28.
10781 To understand how this function works, let's consider what happens in the
10782 various cases when the function is passed 1, 2, 3, or 4 as the value of
10783 its argument.
10785 @menu
10786 * Recursive Example arg of 1 or 2::
10787 * Recursive Example arg of 3 or 4::
10788 @end menu
10790 @node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10791 @ifnottex
10792 @unnumberedsubsubsec An argument of 1 or 2
10793 @end ifnottex
10795 First, what happens if the value of the argument is 1?
10797 The function has an @code{if} expression after the documentation
10798 string.  It tests whether the value of @code{number} is equal to 1; if
10799 so, Emacs evaluates the then-part of the @code{if} expression, which
10800 returns the number 1 as the value of the function.  (A triangle with
10801 one row has one pebble in it.)
10803 Suppose, however, that the value of the argument is 2.  In this case,
10804 Emacs evaluates the else-part of the @code{if} expression.
10806 @need 1200
10807 The else-part consists of an addition, the recursive call to
10808 @code{triangle-recursively} and a decrementing action; and it looks like
10809 this:
10811 @smallexample
10812 (+ number (triangle-recursively (1- number)))
10813 @end smallexample
10815 When Emacs evaluates this expression, the innermost expression is
10816 evaluated first; then the other parts in sequence.  Here are the steps
10817 in detail:
10819 @table @i
10820 @item Step 1 @w{  } Evaluate the innermost expression.
10822 The innermost expression is @code{(1- number)} so Emacs decrements the
10823 value of @code{number} from 2 to 1.
10825 @item Step 2 @w{  } Evaluate the @code{triangle-recursively} function.
10827 The Lisp interpreter creates an individual instance of
10828 @code{triangle-recursively}.  It does not matter that this function is
10829 contained within itself.  Emacs passes the result Step 1 as the
10830 argument used by this instance of the @code{triangle-recursively}
10831 function
10833 In this case, Emacs evaluates @code{triangle-recursively} with an
10834 argument of 1.  This means that this evaluation of
10835 @code{triangle-recursively} returns 1.
10837 @item Step 3 @w{  } Evaluate the value of @code{number}.
10839 The variable @code{number} is the second element of the list that
10840 starts with @code{+}; its value is 2.
10842 @item Step 4 @w{  } Evaluate the @code{+} expression.
10844 The @code{+} expression receives two arguments, the first
10845 from the evaluation of @code{number} (Step 3) and the second from the
10846 evaluation of @code{triangle-recursively} (Step 2).
10848 The result of the addition is the sum of 2 plus 1, and the number 3 is
10849 returned, which is correct.  A triangle with two rows has three
10850 pebbles in it.
10851 @end table
10853 @node Recursive Example arg of 3 or 4,  , Recursive Example arg of 1 or 2, Recursive triangle function
10854 @unnumberedsubsubsec An argument of 3 or 4
10856 Suppose that @code{triangle-recursively} is called with an argument of
10859 @table @i
10860 @item Step 1 @w{  } Evaluate the do-again-test.
10862 The @code{if} expression is evaluated first.  This is the do-again
10863 test and returns false, so the else-part of the @code{if} expression
10864 is evaluated.  (Note that in this example, the do-again-test causes
10865 the function to call itself when it tests false, not when it tests
10866 true.)
10868 @item Step 2 @w{  } Evaluate the innermost expression of the else-part.
10870 The innermost expression of the else-part is evaluated, which decrements
10871 3 to 2.  This is the next-step-expression.
10873 @item Step 3 @w{  } Evaluate the @code{triangle-recursively} function.
10875 The number 2 is passed to the @code{triangle-recursively} function.
10877 We know what happens when Emacs evaluates @code{triangle-recursively} with
10878 an argument of 2.  After going through the sequence of actions described
10879 earlier, it returns a value of 3.  So that is what will happen here.
10881 @item Step 4 @w{  } Evaluate the addition.
10883 3 will be passed as an argument to the addition and will be added to the
10884 number with which the function was called, which is 3.
10885 @end table
10887 @noindent
10888 The value returned by the function as a whole will be 6.
10890 Now that we know what will happen when @code{triangle-recursively} is
10891 called with an argument of 3, it is evident what will happen if it is
10892 called with an argument of 4:
10894 @quotation
10895 @need 800
10896 In the recursive call, the evaluation of
10898 @smallexample
10899 (triangle-recursively (1- 4))
10900 @end smallexample
10902 @need 800
10903 @noindent
10904 will return the value of evaluating
10906 @smallexample
10907 (triangle-recursively 3)
10908 @end smallexample
10910 @noindent
10911 which is 6 and this value will be added to 4 by the addition in the
10912 third line.
10913 @end quotation
10915 @noindent
10916 The value returned by the function as a whole will be 10.
10918 Each time @code{triangle-recursively} is evaluated, it evaluates a
10919 version of itself---a different instance of itself---with a smaller
10920 argument, until the argument is small enough so that it does not
10921 evaluate itself.
10923 Note that this particular design for a recursive function
10924 requires that operations be deferred.
10926 Before @code{(triangle-recursively 7)} can calculate its answer, it
10927 must call @code{(triangle-recursively 6)}; and before
10928 @code{(triangle-recursively 6)} can calculate its answer, it must call
10929 @code{(triangle-recursively 5)}; and so on.  That is to say, the
10930 calculation that @code{(triangle-recursively 7)} makes must be
10931 deferred until @code{(triangle-recursively 6)} makes its calculation;
10932 and @code{(triangle-recursively 6)} must defer until
10933 @code{(triangle-recursively 5)} completes; and so on.
10935 If each of these instances of @code{triangle-recursively} are thought
10936 of as different robots, the first robot must wait for the second to
10937 complete its job, which must wait until the third completes, and so
10940 There is a way around this kind of waiting, which we will discuss in
10941 @ref{No Deferment, , Recursion without Deferments}.
10943 @node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10944 @comment  node-name,  next,  previous,  up
10945 @subsection Recursion Example Using @code{cond}
10946 @findex cond
10948 The version of @code{triangle-recursively} described earlier is written
10949 with the @code{if} special form.  It can also be written using another
10950 special form called @code{cond}.  The name of the special form
10951 @code{cond} is an abbreviation of the word @samp{conditional}.
10953 Although the @code{cond} special form is not used as often in the
10954 Emacs Lisp sources as @code{if}, it is used often enough to justify
10955 explaining it.
10957 @need 800
10958 The template for a @code{cond} expression looks like this:
10960 @smallexample
10961 @group
10962 (cond
10963  @var{body}@dots{})
10964 @end group
10965 @end smallexample
10967 @noindent
10968 where the @var{body} is a series of lists.
10970 @need 800
10971 Written out more fully, the template looks like this:
10973 @smallexample
10974 @group
10975 (cond
10976  (@var{first-true-or-false-test} @var{first-consequent})
10977  (@var{second-true-or-false-test} @var{second-consequent})
10978  (@var{third-true-or-false-test} @var{third-consequent})
10979   @dots{})
10980 @end group
10981 @end smallexample
10983 When the Lisp interpreter evaluates the @code{cond} expression, it
10984 evaluates the first element (the @sc{car} or true-or-false-test) of
10985 the first expression in a series of expressions within the body of the
10986 @code{cond}.
10988 If the true-or-false-test returns @code{nil} the rest of that
10989 expression, the consequent, is skipped and  the true-or-false-test of the
10990 next expression is evaluated.  When an expression is found whose
10991 true-or-false-test returns a value that is not @code{nil}, the
10992 consequent of that expression is evaluated.  The consequent can be one
10993 or more expressions.  If the consequent consists of more than one
10994 expression, the expressions are evaluated in sequence and the value of
10995 the last one is returned.  If the expression does not have a consequent,
10996 the value of the true-or-false-test is returned.
10998 If none of the true-or-false-tests test true, the @code{cond} expression
10999 returns @code{nil}.
11001 @need 1250
11002 Written using @code{cond}, the @code{triangle} function looks like this:
11004 @smallexample
11005 @group
11006 (defun triangle-using-cond (number)
11007   (cond ((<= number 0) 0)
11008         ((= number 1) 1)
11009         ((> number 1)
11010          (+ number (triangle-using-cond (1- number))))))
11011 @end group
11012 @end smallexample
11014 @noindent
11015 In this example, the @code{cond} returns 0 if the number is less than or
11016 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11017 number (triangle-using-cond (1- number)))} if the number is greater than
11020 @node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11021 @comment  node-name,  next,  previous,  up
11022 @subsection Recursive Patterns
11023 @cindex Recursive Patterns
11025 Here are three common recursive patterns.  Each involves a list.
11026 Recursion does not need to involve lists, but Lisp is designed for lists
11027 and this provides a sense of its primal capabilities.
11029 @menu
11030 * Every::
11031 * Accumulate::
11032 * Keep::
11033 @end menu
11035 @node Every, Accumulate, Recursive Patterns, Recursive Patterns
11036 @comment  node-name,  next,  previous,  up
11037 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11038 @cindex Every, type of recursive pattern
11039 @cindex Recursive pattern: every
11041 In the @code{every} recursive pattern, an action is performed on every
11042 element of a list.
11044 @need 1500
11045 The basic pattern is:
11047 @itemize @bullet
11048 @item
11049 If a list be empty, return @code{nil}.
11050 @item
11051 Else, act on the beginning of the list (the @sc{car} of the list)
11052     @itemize @minus
11053     @item
11054     through a recursive call by the function on the rest (the
11055     @sc{cdr}) of the list,
11056     @item
11057     and, optionally, combine the acted-on element, using @code{cons},
11058     with the results of acting on the rest.
11059     @end itemize
11060 @end itemize
11062 @need 1500
11063 Here is example:
11065 @smallexample
11066 @group
11067 (defun square-each (numbers-list)
11068   "Square each of a NUMBERS LIST, recursively."
11069   (if (not numbers-list)                ; do-again-test
11070       nil
11071     (cons
11072      (* (car numbers-list) (car numbers-list))
11073      (square-each (cdr numbers-list))))) ; next-step-expression
11074 @end group
11076 @group
11077 (square-each '(1 2 3))
11078     @result{} (1 4 9)
11079 @end group
11080 @end smallexample
11082 @need 1200
11083 @noindent
11084 If @code{numbers-list} is empty, do nothing.  But if it has content,
11085 construct a list combining the square of the first number in the list
11086 with the result of the recursive call.
11088 (The example follows the pattern exactly: @code{nil} is returned if
11089 the numbers' list is empty.  In practice, you would write the
11090 conditional so it carries out the action when the numbers' list is not
11091 empty.)
11093 The @code{print-elements-recursively} function (@pxref{Recursion with
11094 list, , Recursion with a List}) is another example of an @code{every}
11095 pattern, except in this case, rather than bring the results together
11096 using @code{cons}, we print each element of output.
11098 @need 1250
11099 The @code{print-elements-recursively} function looks like this:
11101 @smallexample
11102 @group
11103 (setq animals '(gazelle giraffe lion tiger))
11104 @end group
11106 @group
11107 (defun print-elements-recursively (list)
11108   "Print each element of LIST on a line of its own.
11109 Uses recursion."
11110   (if list                              ; @r{do-again-test}
11111       (progn
11112         (print (car list))              ; @r{body}
11113         (print-elements-recursively     ; @r{recursive call}
11114          (cdr list)))))                 ; @r{next-step-expression}
11116 (print-elements-recursively animals)
11117 @end group
11118 @end smallexample
11120 @need 1500
11121 The pattern for @code{print-elements-recursively} is:
11123 @itemize @bullet
11124 @item
11125 If the list be empty, do nothing.
11126 @item
11127 But if the list has at least one element,
11128     @itemize @minus
11129     @item
11130     act on the beginning of the list (the @sc{car} of the list),
11131     @item
11132     and make a recursive call on the rest (the @sc{cdr}) of the list.
11133     @end itemize
11134 @end itemize
11136 @node Accumulate, Keep, Every, Recursive Patterns
11137 @comment  node-name,  next,  previous,  up
11138 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11139 @cindex Accumulate, type of recursive pattern
11140 @cindex Recursive pattern: accumulate
11142 Another recursive pattern is called the @code{accumulate} pattern.  In
11143 the @code{accumulate} recursive pattern, an action is performed on
11144 every element of a list and the result of that action is accumulated
11145 with the results of performing the action on the other elements.
11147 This is very like the `every' pattern using @code{cons}, except that
11148 @code{cons} is not used, but some other combiner.
11150 @need 1500
11151 The pattern is:
11153 @itemize @bullet
11154 @item
11155 If a list be empty, return zero or some other constant.
11156 @item
11157 Else, act on the beginning of the list (the @sc{car} of the list),
11158     @itemize @minus
11159     @item
11160     and combine that acted-on element, using @code{+} or
11161     some other combining function, with
11162     @item
11163     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11164     @end itemize
11165 @end itemize
11167 @need 1500
11168 Here is an example:
11170 @smallexample
11171 @group
11172 (defun add-elements (numbers-list)
11173   "Add the elements of NUMBERS-LIST together."
11174   (if (not numbers-list)
11175       0
11176     (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11177 @end group
11179 @group
11180 (add-elements '(1 2 3 4))
11181     @result{} 10
11182 @end group
11183 @end smallexample
11185 @xref{Files List, , Making a List of Files}, for an example of the
11186 accumulate pattern.
11188 @node Keep,  , Accumulate, Recursive Patterns
11189 @comment  node-name,  next,  previous,  up
11190 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11191 @cindex Keep, type of recursive pattern
11192 @cindex Recursive pattern: keep
11194 A third recursive pattern is called the @code{keep} pattern.
11195 In the @code{keep} recursive pattern, each element of a list is tested;
11196 the element is acted on and the results are kept only if the element
11197 meets a criterion.
11199 Again, this is very like the `every' pattern, except the element is
11200 skipped unless it meets a criterion.
11202 @need 1500
11203 The pattern has three parts:
11205 @itemize @bullet
11206 @item
11207 If a list be empty, return @code{nil}.
11208 @item
11209 Else, if the beginning of the list (the @sc{car} of the list) passes
11210         a test
11211     @itemize @minus
11212     @item
11213     act on that element and combine it, using @code{cons} with
11214     @item
11215     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11216     @end itemize
11217 @item
11218 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11219 the test
11220     @itemize @minus
11221     @item
11222     skip on that element,
11223     @item
11224     and, recursively call the function on the rest (the @sc{cdr}) of the list.
11225     @end itemize
11226 @end itemize
11228 @need 1500
11229 Here is an example that uses @code{cond}:
11231 @smallexample
11232 @group
11233 (defun keep-three-letter-words (word-list)
11234   "Keep three letter words in WORD-LIST."
11235   (cond
11236    ;; First do-again-test: stop-condition
11237    ((not word-list) nil)
11239    ;; Second do-again-test: when to act
11240    ((eq 3 (length (symbol-name (car word-list))))
11241     ;; combine acted-on element with recursive call on shorter list
11242     (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11244    ;; Third do-again-test: when to skip element;
11245    ;;   recursively call shorter list with next-step expression
11246    (t  (keep-three-letter-words (cdr word-list)))))
11247 @end group
11249 @group
11250 (keep-three-letter-words '(one two three four five six))
11251     @result{} (one two six)
11252 @end group
11253 @end smallexample
11255 It goes without saying that you need not use @code{nil} as the test for
11256 when to stop; and you can, of course, combine these patterns.
11258 @node No Deferment, No deferment solution, Recursive Patterns, Recursion
11259 @subsection Recursion without Deferments
11260 @cindex Deferment in recursion
11261 @cindex Recursion without Deferments
11263 Let's consider again what happens with the @code{triangle-recursively}
11264 function.  We will find that the intermediate calculations are
11265 deferred until all can be done.
11267 @need 800
11268 Here is the function definition:
11270 @smallexample
11271 @group
11272 (defun triangle-recursively (number)
11273   "Return the sum of the numbers 1 through NUMBER inclusive.
11274 Uses recursion."
11275   (if (= number 1)                    ; @r{do-again-test}
11276       1                               ; @r{then-part}
11277     (+ number                         ; @r{else-part}
11278        (triangle-recursively          ; @r{recursive call}
11279         (1- number)))))               ; @r{next-step-expression}
11280 @end group
11281 @end smallexample
11283 What happens when we call this function with a argument of 7?
11285 The first instance of the @code{triangle-recursively} function adds
11286 the number 7 to the value returned by a second instance of
11287 @code{triangle-recursively}, an instance that has been passed an
11288 argument of 6.  That is to say, the first calculation is:
11290 @smallexample
11291 (+ 7 (triangle-recursively 6))
11292 @end smallexample
11294 @noindent
11295 The first instance of @code{triangle-recursively}---you may want to
11296 think of it as a little robot---cannot complete its job.  It must hand
11297 off the calculation for @code{(triangle-recursively 6)} to a second
11298 instance of the program, to a second robot.  This second individual is
11299 completely different from the first one; it is, in the jargon, a
11300 `different instantiation'.  Or, put another way, it is a different
11301 robot.  It is the same model as the first; it calculates triangle
11302 numbers recursively; but it has a different serial number.
11304 And what does @code{(triangle-recursively 6)} return?  It returns the
11305 number 6 added to the value returned by evaluating
11306 @code{triangle-recursively} with an argument of 5.  Using the robot
11307 metaphor, it asks yet another robot to help it.
11309 @need 800
11310 Now the total is:
11312 @smallexample
11313 (+ 7 6 (triangle-recursively 5))
11314 @end smallexample
11316 @need 800
11317 And what happens next?
11319 @smallexample
11320 (+ 7 6 5 (triangle-recursively 4))
11321 @end smallexample
11323 Each time @code{triangle-recursively} is called, except for the last
11324 time, it creates another instance of the program---another robot---and
11325 asks it to make a calculation.
11327 @need 800
11328 Eventually, the full addition is set up and performed:
11330 @smallexample
11331 (+ 7 6 5 4 3 2 1)
11332 @end smallexample
11334 This design for the function defers the calculation of the first step
11335 until the second can be done, and defers that until the third can be
11336 done, and so on.  Each deferment means the computer must remember what
11337 is being waited on.  This is not a problem when there are only a few
11338 steps, as in this example.  But it can be a problem when there are
11339 more steps.
11341 @node No deferment solution,  , No Deferment, Recursion
11342 @subsection No Deferment Solution
11343 @cindex No deferment solution
11344 @cindex Defermentless solution
11345 @cindex Solution without deferment
11347 The solution to the problem of deferred operations is to write in a
11348 manner that does not defer operations@footnote{The phrase @dfn{tail
11349 recursive} is used to describe such a process, one that uses
11350 `constant space'.}.  This requires
11351 writing to a different pattern, often one that involves writing two
11352 function definitions, an `initialization' function and a `helper'
11353 function.
11355 The `initialization' function sets up the job; the `helper' function
11356 does the work.
11358 @need 1200
11359 Here are the two function definitions for adding up numbers.  They are
11360 so simple, I find them hard to understand.
11362 @smallexample
11363 @group
11364 (defun triangle-initialization (number)
11365   "Return the sum of the numbers 1 through NUMBER inclusive.
11366 This is the `initialization' component of a two function
11367 duo that uses recursion."
11368   (triangle-recursive-helper 0 0 number))
11369 @end group
11370 @end smallexample
11372 @smallexample
11373 @group
11374 (defun triangle-recursive-helper (sum counter number)
11375   "Return SUM, using COUNTER, through NUMBER inclusive.
11376 This is the `helper' component of a two function duo
11377 that uses recursion."
11378   (if (> counter number)
11379       sum
11380     (triangle-recursive-helper (+ sum counter)  ; @r{sum}
11381                                (1+ counter)     ; @r{counter}
11382                                number)))        ; @r{number}
11383 @end group
11384 @end smallexample
11386 @need 1250
11387 Install both function definitions by evaluating them, then call
11388 @code{triangle-initialization} with 2 rows:
11390 @smallexample
11391 @group
11392 (triangle-initialization 2)
11393     @result{} 3
11394 @end group
11395 @end smallexample
11397 The `initialization' function calls the first instance of the `helper'
11398 function with three arguments: zero, zero, and a number which is the
11399 number of rows in the triangle.
11401 The first two arguments passed to the `helper' function are
11402 initialization values.  These values are changed when
11403 @code{triangle-recursive-helper} invokes new instances.@footnote{The
11404 jargon is mildly confusing:  @code{triangle-recursive-helper} uses a
11405 process that is iterative in a procedure that is recursive.  The
11406 process is called iterative because the computer need only record the
11407 three values, @code{sum}, @code{counter}, and @code{number}; the
11408 procedure is recursive because the function `calls itself'.  On the
11409 other hand, both the process and the procedure used by
11410 @code{triangle-recursively} are called recursive.  The word
11411 `recursive' has different meanings in the two contexts.}
11413 Let's see what happens when we have a triangle that has one row.  (This
11414 triangle will have one pebble in it!)
11416 @need 1200
11417 @code{triangle-initialization} will call its helper with
11418 the arguments @w{@code{0 0 1}}.  That function will run the conditional
11419 test whether @code{(> counter number)}:
11421 @smallexample
11422 (> 0 1)
11423 @end smallexample
11425 @need 1200
11426 @noindent
11427 and find that the result is false, so it will invoke
11428 the then-part of the @code{if} clause:
11430 @smallexample
11431 @group
11432     (triangle-recursive-helper
11433      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11434      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11435      number)          ; @r{number stays the same}
11436 @end group
11437 @end smallexample
11439 @need 800
11440 @noindent
11441 which will first compute:
11443 @smallexample
11444 @group
11445 (triangle-recursive-helper (+ 0 0)  ; @r{sum}
11446                            (1+ 0)   ; @r{counter}
11447                            1)       ; @r{number}
11448 @exdent which is:
11450 (triangle-recursive-helper 0 1 1)
11451 @end group
11452 @end smallexample
11454 Again, @code{(> counter number)} will be false, so again, the Lisp
11455 interpreter will evaluate @code{triangle-recursive-helper}, creating a
11456 new instance with new arguments.
11458 @need 800
11459 This new instance will be;
11461 @smallexample
11462 @group
11463     (triangle-recursive-helper
11464      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11465      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11466      number)          ; @r{number stays the same}
11468 @exdent which is:
11470 (triangle-recursive-helper 1 2 1)
11471 @end group
11472 @end smallexample
11474 In this case, the @code{(> counter number)} test will be true!  So the
11475 instance will return the value of the sum, which will be 1, as
11476 expected.
11478 Now, let's pass @code{triangle-initialization} an argument
11479 of 2, to find out how many pebbles there are in a triangle with two rows.
11481 That function calls @code{(triangle-recursive-helper 0 0 2)}.
11483 @need 800
11484 In stages, the instances called will be:
11486 @smallexample
11487 @group
11488                           @r{sum counter number}
11489 (triangle-recursive-helper 0    1       2)
11491 (triangle-recursive-helper 1    2       2)
11493 (triangle-recursive-helper 3    3       2)
11494 @end group
11495 @end smallexample
11497 When the last instance is called, the @code{(> counter number)} test
11498 will be true, so the instance will return the value of @code{sum},
11499 which will be 3.
11501 This kind of pattern helps when you are writing functions that can use
11502 many resources in a computer.
11504 @need 1500
11505 @node Looping exercise,  , Recursion, Loops & Recursion
11506 @section Looping Exercise
11508 @itemize @bullet
11509 @item
11510 Write a function similar to @code{triangle} in which each row has a
11511 value which is the square of the row number.  Use a @code{while} loop.
11513 @item
11514 Write a function similar to @code{triangle} that multiplies instead of
11515 adds the values.
11517 @item
11518 Rewrite these two functions recursively.  Rewrite these functions
11519 using @code{cond}.
11521 @c comma in printed title causes problem in Info cross reference
11522 @item
11523 Write a function for Texinfo mode that creates an index entry at the
11524 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
11525 (In a Texinfo file, @samp{@@dfn} marks a definition.  For more
11526 information, see
11527 @ifinfo
11528 @ref{Indicating, , Indicating Definitions, texinfo}.)
11529 @end ifinfo
11530 @ifhtml
11531 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}.)
11532 @end ifhtml
11533 @iftex
11534 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
11535 Documentation Format}.)
11536 @end iftex
11537 @end itemize
11539 @node Regexp Search, Counting Words, Loops & Recursion, Top
11540 @comment  node-name,  next,  previous,  up
11541 @chapter Regular Expression Searches
11542 @cindex Searches, illustrating
11543 @cindex Regular expression searches
11544 @cindex Patterns, searching for
11545 @cindex Motion by sentence and paragraph
11546 @cindex Sentences, movement by
11547 @cindex Paragraphs, movement by
11549 Regular expression searches are used extensively in GNU Emacs.  The
11550 two functions, @code{forward-sentence} and @code{forward-paragraph},
11551 illustrate these searches well.  They use regular expressions to find
11552 where to move point.  The phrase `regular expression' is often written
11553 as `regexp'.
11555 Regular expression searches are described in @ref{Regexp Search, ,
11556 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11557 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11558 Manual}.  In writing this chapter, I am presuming that you have at
11559 least a mild acquaintance with them.  The major point to remember is
11560 that regular expressions permit you to search for patterns as well as
11561 for literal strings of characters.  For example, the code in
11562 @code{forward-sentence} searches for the pattern of possible
11563 characters that could mark the end of a sentence, and moves point to
11564 that spot.
11566 Before looking at the code for the @code{forward-sentence} function, it
11567 is worth considering what the pattern that marks the end of a sentence
11568 must be.  The pattern is discussed in the next section; following that
11569 is a description of the regular expression search function,
11570 @code{re-search-forward}.  The @code{forward-sentence} function
11571 is described in the section following.  Finally, the
11572 @code{forward-paragraph} function is described in the last section of
11573 this chapter.  @code{forward-paragraph} is a complex function that
11574 introduces several new features.
11576 @menu
11577 * sentence-end::                The regular expression for @code{sentence-end}.
11578 * re-search-forward::           Very similar to @code{search-forward}.
11579 * forward-sentence::            A straightforward example of regexp search.
11580 * forward-paragraph::           A somewhat complex example.
11581 * etags::                       How to create your own @file{TAGS} table.
11582 * Regexp Review::
11583 * re-search Exercises::
11584 @end menu
11586 @node sentence-end, re-search-forward, Regexp Search, Regexp Search
11587 @comment  node-name,  next,  previous,  up
11588 @section The Regular Expression for @code{sentence-end}
11589 @findex sentence-end
11591 The symbol @code{sentence-end} is bound to the pattern that marks the
11592 end of a sentence.  What should this regular expression be?
11594 Clearly, a sentence may be ended by a period, a question mark, or an
11595 exclamation mark.  Indeed, only clauses that end with one of those three
11596 characters should be considered the end of a sentence.  This means that
11597 the pattern should include the character set:
11599 @smallexample
11600 [.?!]
11601 @end smallexample
11603 However, we do not want @code{forward-sentence} merely to jump to a
11604 period, a question mark, or an exclamation mark, because such a character
11605 might be used in the middle of a sentence.  A period, for example, is
11606 used after abbreviations.  So other information is needed.
11608 According to convention, you type two spaces after every sentence, but
11609 only one space after a period, a question mark, or an exclamation mark in
11610 the body of a sentence.  So a period, a question mark, or an exclamation
11611 mark followed by two spaces is a good indicator of an end of sentence.
11612 However, in a file, the two spaces may instead be a tab or the end of a
11613 line.  This means that the regular expression should include these three
11614 items as alternatives.
11616 @need 800
11617 This group of alternatives will look like this:
11619 @smallexample
11620 @group
11621 \\($\\| \\|  \\)
11622        ^   ^^
11623       TAB  SPC
11624 @end group
11625 @end smallexample
11627 @noindent
11628 Here, @samp{$} indicates the end of the line, and I have pointed out
11629 where the tab and two spaces are inserted in the expression.  Both are
11630 inserted by putting the actual characters into the expression.
11632 Two backslashes, @samp{\\}, are required before the parentheses and
11633 vertical bars: the first backslash quotes the following backslash in
11634 Emacs; and the second indicates that the following character, the
11635 parenthesis or the vertical bar, is special.
11637 @need 1000
11638 Also, a sentence may be followed by one or more carriage returns, like
11639 this:
11641 @smallexample
11642 @group
11645 @end group
11646 @end smallexample
11648 @noindent
11649 Like tabs and spaces, a carriage return is inserted into a regular
11650 expression by inserting it literally.  The asterisk indicates that the
11651 @key{RET} is repeated zero or more times.
11653 But a sentence end does not consist only of a period, a question mark or
11654 an exclamation mark followed by appropriate space: a closing quotation
11655 mark or a closing brace of some kind may precede the space.  Indeed more
11656 than one such mark or brace may precede the space.  These require a
11657 expression that looks like this:
11659 @smallexample
11660 []\"')@}]*
11661 @end smallexample
11663 In this expression, the first @samp{]} is the first character in the
11664 expression; the second character is @samp{"}, which is preceded by a
11665 @samp{\} to tell Emacs the @samp{"} is @emph{not} special.  The last
11666 three characters are @samp{'}, @samp{)}, and @samp{@}}.
11668 All this suggests what the regular expression pattern for matching the
11669 end of a sentence should be; and, indeed, if we evaluate
11670 @code{sentence-end} we find that it returns the following value:
11672 @smallexample
11673 @group
11674 sentence-end
11675      @result{} "[.?!][]\"')@}]*\\($\\|     \\|  \\)[
11677 @end group
11678 @end smallexample
11680 @ignore
11682 @noindent
11683 (Note that here the @key{TAB}, two spaces, and  @key{RET} are shown
11684 literally in the pattern.)
11686 This regular expression can be decyphered as follows:
11688 @table @code
11689 @item [.?!]
11690 The first part of the pattern is the three characters, a period, a question
11691 mark and an exclamation mark, within square brackets.  The pattern must
11692 begin with one or other of these characters.
11694 @item []\"')@}]*
11695 The second part of the pattern is the group of closing braces and
11696 quotation marks, which can appear zero or more times.  These may follow
11697 the period, question mark or exclamation mark.  In a regular expression,
11698 the backslash, @samp{\}, followed by the double quotation mark,
11699 @samp{"}, indicates the class of string-quote characters.  Usually, the
11700 double quotation mark is the only character in this class.  The
11701 asterisk, @samp{*}, indicates that the items in the previous group (the
11702 group surrounded by square brackets, @samp{[]}) may be repeated zero or
11703 more times.
11705 @item \\($\\|   \\|  \\)
11706 The third part of the pattern is one or other of: either the end of a
11707 line, or two blank spaces, or a tab.  The double back-slashes are used
11708 to prevent Emacs from reading the parentheses and vertical bars as part
11709 of the search pattern; the parentheses are used to mark the group and
11710 the vertical bars are used to indicated that the patterns to either side
11711 of them are alternatives.  The dollar sign is used to indicate the end
11712 of a line and both the two spaces and the tab are each inserted as is to
11713 indicate what they are.
11715 @item [@key{RET}]*
11716 Finally, the last part of the pattern indicates that the end of the line
11717 or the whitespace following the period, question mark or exclamation
11718 mark may, but need not, be followed by one or more carriage returns.  In
11719 the pattern, the carriage return is inserted as an actual carriage
11720 return between square brackets but here it is shown as @key{RET}.
11721 @end table
11723 @end ignore
11725 @node re-search-forward, forward-sentence, sentence-end, Regexp Search
11726 @comment  node-name,  next,  previous,  up
11727 @section The @code{re-search-forward} Function
11728 @findex re-search-forward
11730 The @code{re-search-forward} function is very like the
11731 @code{search-forward} function.  (@xref{search-forward, , The
11732 @code{search-forward} Function}.)
11734 @code{re-search-forward} searches for a regular expression.  If the
11735 search is successful, it leaves point immediately after the last
11736 character in the target.  If the search is backwards, it leaves point
11737 just before the first character in the target.  You may tell
11738 @code{re-search-forward} to return @code{t} for true.  (Moving point
11739 is therefore a `side effect'.)
11741 Like @code{search-forward}, the @code{re-search-forward} function takes
11742 four arguments:
11744 @enumerate
11745 @item
11746 The first argument is the regular expression that the function searches
11747 for.  The regular expression will be a string between quotations marks.
11749 @item
11750 The optional second argument limits how far the function will search; it is a
11751 bound, which is specified as a position in the buffer.
11753 @item
11754 The optional third argument specifies how the function responds to
11755 failure: @code{nil} as the third argument causes the function to
11756 signal an error (and print a message) when the search fails; any other
11757 value causes it to return @code{nil} if the search fails and @code{t}
11758 if the search succeeds.
11760 @item
11761 The optional fourth argument is the repeat count.  A negative repeat
11762 count causes @code{re-search-forward} to search backwards.
11763 @end enumerate
11765 @need 800
11766 The template for @code{re-search-forward} looks like this:
11768 @smallexample
11769 @group
11770 (re-search-forward "@var{regular-expression}"
11771                 @var{limit-of-search}
11772                 @var{what-to-do-if-search-fails}
11773                 @var{repeat-count})
11774 @end group
11775 @end smallexample
11777 The second, third, and fourth arguments are optional.  However, if you
11778 want to pass a value to either or both of the last two arguments, you
11779 must also pass a value to all the preceding arguments.  Otherwise, the
11780 Lisp interpreter will mistake which argument you are passing the value
11783 @need 1200
11784 In the @code{forward-sentence} function, the regular expression will be
11785 the value of the variable @code{sentence-end}, namely:
11787 @smallexample
11788 @group
11789 "[.?!][]\"')@}]*\\($\\|  \\|  \\)[
11791 @end group
11792 @end smallexample
11794 @noindent
11795 The limit of the search will be the end of the paragraph (since a
11796 sentence cannot go beyond a paragraph).  If the search fails, the
11797 function will return @code{nil}; and the repeat count will be provided
11798 by the argument to the @code{forward-sentence} function.
11800 @node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11801 @comment  node-name,  next,  previous,  up
11802 @section @code{forward-sentence}
11803 @findex forward-sentence
11805 The command to move the cursor forward a sentence is a straightforward
11806 illustration of how to use regular expression searches in Emacs Lisp.
11807 Indeed, the function looks longer and more complicated than it is; this
11808 is because the function is designed to go backwards as well as forwards;
11809 and, optionally, over more than one sentence.  The function is usually
11810 bound to the key command @kbd{M-e}.
11812 @menu
11813 * Complete forward-sentence::
11814 * fwd-sentence while loops::    Two @code{while} loops.
11815 * fwd-sentence re-search::      A regular expression search.
11816 @end menu
11818 @node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11819 @ifnottex
11820 @unnumberedsubsec Complete @code{forward-sentence} function definition
11821 @end ifnottex
11823 @need 1250
11824 Here is the code for @code{forward-sentence}:
11826 @smallexample
11827 @group
11828 (defun forward-sentence (&optional arg)
11829   "Move forward to next sentence-end.  With argument, repeat.
11830 With negative argument, move backward repeatedly to sentence-beginning.
11831 Sentence ends are identified by the value of sentence-end
11832 treated as a regular expression.  Also, every paragraph boundary
11833 terminates sentences as well."
11834 @end group
11835 @group
11836   (interactive "p")
11837   (or arg (setq arg 1))
11838   (while (< arg 0)
11839     (let ((par-beg
11840            (save-excursion (start-of-paragraph-text) (point))))
11841       (if (re-search-backward
11842            (concat sentence-end "[^ \t\n]") par-beg t)
11843           (goto-char (1- (match-end 0)))
11844         (goto-char par-beg)))
11845     (setq arg (1+ arg)))
11846   (while (> arg 0)
11847     (let ((par-end
11848            (save-excursion (end-of-paragraph-text) (point))))
11849       (if (re-search-forward sentence-end par-end t)
11850           (skip-chars-backward " \t\n")
11851         (goto-char par-end)))
11852     (setq arg (1- arg))))
11853 @end group
11854 @end smallexample
11856 The function looks long at first sight and it is best to look at its
11857 skeleton first, and then its muscle.  The way to see the skeleton is to
11858 look at the expressions that start in the left-most columns:
11860 @smallexample
11861 @group
11862 (defun forward-sentence (&optional arg)
11863   "@var{documentation}@dots{}"
11864   (interactive "p")
11865   (or arg (setq arg 1))
11866   (while (< arg 0)
11867     @var{body-of-while-loop}
11868   (while (> arg 0)
11869     @var{body-of-while-loop}
11870 @end group
11871 @end smallexample
11873 This looks much simpler!  The function definition consists of
11874 documentation, an @code{interactive} expression, an @code{or}
11875 expression, and @code{while} loops.
11877 Let's look at each of these parts in turn.
11879 We note that the documentation is thorough and understandable.
11881 The function has an @code{interactive "p"} declaration.  This means
11882 that the processed prefix argument, if any, is passed to the
11883 function as its argument.  (This will be a number.)  If the function
11884 is not passed an argument (it is optional) then the argument
11885 @code{arg} will be bound to 1.  When @code{forward-sentence} is called
11886 non-interactively without an argument, @code{arg} is bound to
11887 @code{nil}.
11889 The @code{or} expression handles the prefix argument.  What it does is
11890 either leave the value of @code{arg} as it is, but only if @code{arg}
11891 is bound to a value; or it sets the value of @code{arg} to 1, in the
11892 case when @code{arg} is bound to @code{nil}.
11894 @node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11895 @unnumberedsubsec The @code{while} loops
11897 Two @code{while} loops follow the @code{or} expression.  The first
11898 @code{while} has a true-or-false-test that tests true if the prefix
11899 argument for @code{forward-sentence} is a negative number.  This is for
11900 going backwards.  The body of this loop is similar to the body of the
11901 second @code{while} clause, but it is not exactly the same.  We will
11902 skip this @code{while} loop and concentrate on the second @code{while}
11903 loop.
11905 @need 1500
11906 The second @code{while} loop is for moving point forward.  Its skeleton
11907 looks like this:
11909 @smallexample
11910 @group
11911 (while (> arg 0)            ; @r{true-or-false-test}
11912   (let @var{varlist}
11913     (if (@var{true-or-false-test})
11914         @var{then-part}
11915       @var{else-part}
11916   (setq arg (1- arg))))     ; @code{while} @r{loop decrementer}
11917 @end group
11918 @end smallexample
11920 The @code{while} loop is of the decrementing kind.
11921 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.)  It
11922 has a true-or-false-test that tests true so long as the counter (in
11923 this case, the variable @code{arg}) is greater than zero; and it has a
11924 decrementer that subtracts 1 from the value of the counter every time
11925 the loop repeats.
11927 If no prefix argument is given to @code{forward-sentence}, which is
11928 the most common way the command is used, this @code{while} loop will
11929 run once, since the value of @code{arg} will be 1.
11931 The body of the @code{while} loop consists of a @code{let} expression,
11932 which creates and binds a local variable, and has, as its body, an
11933 @code{if} expression.
11935 @need 1250
11936 The body of the @code{while} loop looks like this:
11938 @smallexample
11939 @group
11940 (let ((par-end
11941        (save-excursion (end-of-paragraph-text) (point))))
11942   (if (re-search-forward sentence-end par-end t)
11943       (skip-chars-backward " \t\n")
11944     (goto-char par-end)))
11945 @end group
11946 @end smallexample
11948 The @code{let} expression creates and binds the local variable
11949 @code{par-end}.  As we shall see, this local variable is designed to
11950 provide a bound or limit to the regular expression search.  If the
11951 search fails to find a proper sentence ending in the paragraph, it will
11952 stop on reaching the end of the paragraph.
11954 But first, let us examine how @code{par-end} is bound to the value of
11955 the end of the paragraph.  What happens is that the @code{let} sets the
11956 value of @code{par-end} to the value returned when the Lisp interpreter
11957 evaluates the expression
11959 @smallexample
11960 @group
11961 (save-excursion (end-of-paragraph-text) (point))
11962 @end group
11963 @end smallexample
11965 @noindent
11966 In this expression, @code{(end-of-paragraph-text)} moves point to the
11967 end of the paragraph, @code{(point)} returns the value of point, and then
11968 @code{save-excursion} restores point to its original position.  Thus,
11969 the @code{let} binds @code{par-end} to the value returned by the
11970 @code{save-excursion} expression, which is the position of the end of
11971 the paragraph.  (The @code{(end-of-paragraph-text)} function uses
11972 @code{forward-paragraph}, which we will discuss shortly.)
11974 @need 1200
11975 Emacs next evaluates the body of the @code{let}, which is an @code{if}
11976 expression that looks like this:
11978 @smallexample
11979 @group
11980 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
11981     (skip-chars-backward " \t\n")              ; @r{then-part}
11982   (goto-char par-end)))                        ; @r{else-part}
11983 @end group
11984 @end smallexample
11986 The @code{if} tests whether its first argument is true and if so,
11987 evaluates its then-part; otherwise, the Emacs Lisp interpreter
11988 evaluates the else-part.  The true-or-false-test of the @code{if}
11989 expression is the regular expression search.
11991 It may seem odd to have what looks like the `real work' of
11992 the @code{forward-sentence} function buried here, but this is a common
11993 way this kind of operation is carried out in Lisp.
11995 @node fwd-sentence re-search,  , fwd-sentence while loops, forward-sentence
11996 @unnumberedsubsec The regular expression search
11998 The @code{re-search-forward} function searches for the end of the
11999 sentence, that is, for the pattern defined by the @code{sentence-end}
12000 regular expression.  If the pattern is found---if the end of the sentence is
12001 found---then the @code{re-search-forward} function does two things:
12003 @enumerate
12004 @item
12005 The @code{re-search-forward} function carries out a side effect, which
12006 is to move point to the end of the occurrence found.
12008 @item
12009 The @code{re-search-forward} function returns a value of true.  This is
12010 the value received by the @code{if}, and means that the search was
12011 successful.
12012 @end enumerate
12014 @noindent
12015 The side effect, the movement of point, is completed before the
12016 @code{if} function is handed the value returned by the successful
12017 conclusion of the search.
12019 When the @code{if} function receives the value of true from a successful
12020 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12021 which is the expression @code{(skip-chars-backward " \t\n")}.  This
12022 expression moves backwards over any blank spaces, tabs or carriage
12023 returns until a printed character is found and then leaves point after
12024 the character.  Since point has already been moved to the end of the
12025 pattern that marks the end of the sentence, this action leaves point
12026 right after the closing printed character of the sentence, which is
12027 usually a period.
12029 On the other hand, if the @code{re-search-forward} function fails to
12030 find a pattern marking the end of the sentence, the function returns
12031 false.  The false then causes the @code{if} to evaluate its third
12032 argument, which is @code{(goto-char par-end)}:  it moves point to the
12033 end of the paragraph.
12035 Regular expression searches are exceptionally useful and the pattern
12036 illustrated by @code{re-search-forward}, in which the search is the
12037 test of an @code{if} expression, is handy.  You will see or write code
12038 incorporating this pattern often.
12040 @node forward-paragraph, etags, forward-sentence, Regexp Search
12041 @comment  node-name,  next,  previous,  up
12042 @section @code{forward-paragraph}: a Goldmine of Functions
12043 @findex forward-paragraph
12045 The @code{forward-paragraph} function moves point forward to the end
12046 of the paragraph.  It is usually bound to @kbd{M-@}} and makes use of a
12047 number of functions that are important in themselves, including
12048 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12050 The function definition for @code{forward-paragraph} is considerably
12051 longer than the function definition for @code{forward-sentence}
12052 because it works with a paragraph, each line of which may begin with a
12053 fill prefix.
12055 A fill prefix consists of a string of characters that are repeated at
12056 the beginning of each line.  For example, in Lisp code, it is a
12057 convention to start each line of a paragraph-long comment with
12058 @samp{;;; }.  In Text mode, four blank spaces make up another common
12059 fill prefix, creating an indented paragraph.  (@xref{Fill Prefix, , ,
12060 emacs, The GNU Emacs Manual}, for more information about fill
12061 prefixes.)
12063 The existence of a fill prefix means that in addition to being able to
12064 find the end of a paragraph whose lines begin on the left-most
12065 column, the @code{forward-paragraph} function must be able to find the
12066 end of a paragraph when all or many of the lines in the buffer begin
12067 with the fill prefix.
12069 Moreover, it is sometimes practical to ignore a fill prefix that
12070 exists, especially when blank lines separate paragraphs.
12071 This is an added complication.
12073 @menu
12074 * forward-paragraph in brief::  Key parts of the function definition.
12075 * fwd-para let::                The @code{let*} expression.
12076 * fwd-para while::              The forward motion @code{while} loop.
12077 * fwd-para between paragraphs::  Movement between paragraphs.
12078 * fwd-para within paragraph::   Movement within paragraphs.
12079 * fwd-para no fill prefix::     When there is no fill prefix.
12080 * fwd-para with fill prefix::   When there is a fill prefix.
12081 * fwd-para summary::            Summary of @code{forward-paragraph} code.
12082 @end menu
12084 @node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12085 @ifnottex
12086 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
12087 @end ifnottex
12089 Rather than print all of the @code{forward-paragraph} function, we
12090 will only print parts of it.  Read without preparation, the function
12091 can be daunting!
12093 @need 800
12094 In outline, the function looks like this:
12096 @smallexample
12097 @group
12098 (defun forward-paragraph (&optional arg)
12099   "@var{documentation}@dots{}"
12100   (interactive "p")
12101   (or arg (setq arg 1))
12102   (let*
12103       @var{varlist}
12104     (while (< arg 0)        ; @r{backward-moving-code}
12105       @dots{}
12106       (setq arg (1+ arg)))
12107     (while (> arg 0)        ; @r{forward-moving-code}
12108       @dots{}
12109       (setq arg (1- arg)))))
12110 @end group
12111 @end smallexample
12113 The first parts of the function are routine: the function's argument
12114 list consists of one optional argument.  Documentation follows.
12116 The lower case @samp{p} in the @code{interactive} declaration means
12117 that the processed prefix argument, if any, is passed to the function.
12118 This will be a number, and is the repeat count of how many paragraphs
12119 point will move.  The @code{or} expression in the next line handles
12120 the common case when no argument is passed to the function, which occurs
12121 if the function is called from other code rather than interactively.
12122 This case was described earlier.  (@xref{forward-sentence, The
12123 @code{forward-sentence} function}.)  Now we reach the end of the
12124 familiar part of this function.
12126 @node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12127 @unnumberedsubsec The @code{let*} expression
12129 The next line of the @code{forward-paragraph} function begins a
12130 @code{let*} expression.  This is a different kind of expression than
12131 we have seen so far.  The symbol is @code{let*} not @code{let}.
12133 The @code{let*} special form is like @code{let} except that Emacs sets
12134 each variable in sequence, one after another, and variables in the
12135 latter part of the varlist can make use of the values to which Emacs
12136 set variables in the earlier part of the varlist.
12138 In the @code{let*} expression in this function, Emacs binds two
12139 variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12140 The value to which @code{paragraph-separate} is bound depends on the
12141 value of @code{fill-prefix-regexp}.
12143 @need 1200
12144 Let's look at each in turn.  The symbol @code{fill-prefix-regexp} is
12145 set to the value returned by evaluating the following list:
12147 @smallexample
12148 @group
12149 (and fill-prefix
12150      (not (equal fill-prefix ""))
12151      (not paragraph-ignore-fill-prefix)
12152      (regexp-quote fill-prefix))
12153 @end group
12154 @end smallexample
12156 @noindent
12157 This is an expression whose first element is the @code{and} special form.
12159 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12160 function}), the @code{and} special form evaluates each of its
12161 arguments until one of the arguments returns a value of @code{nil}, in
12162 which case the @code{and} expression returns @code{nil}; however, if
12163 none of the arguments returns a value of @code{nil}, the value
12164 resulting from evaluating the last argument is returned.  (Since such
12165 a value is not @code{nil}, it is considered true in Lisp.)  In other
12166 words, an @code{and} expression returns a true value only if all its
12167 arguments are true.
12168 @findex and
12170 In this case, the variable @code{fill-prefix-regexp} is bound to a
12171 non-@code{nil} value only if the following four expressions produce a
12172 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12173 @code{fill-prefix-regexp} is bound to @code{nil}.
12175 @table @code
12176 @item fill-prefix
12177 When this variable is evaluated, the value of the fill prefix, if any,
12178 is returned.  If there is no fill prefix, this variable returns
12179 @code{nil}.
12181 @item (not (equal fill-prefix "")
12182 This expression checks whether an existing fill prefix is an empty
12183 string, that is, a string with no characters in it.  An empty string is
12184 not a useful fill prefix.
12186 @item (not paragraph-ignore-fill-prefix)
12187 This expression returns @code{nil} if the variable
12188 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12189 true value such as @code{t}.
12191 @item (regexp-quote fill-prefix)
12192 This is the last argument to the @code{and} special form.  If all the
12193 arguments to the @code{and} are true, the value resulting from
12194 evaluating this expression will be returned by the @code{and} expression
12195 and bound to the variable @code{fill-prefix-regexp},
12196 @end table
12198 @findex regexp-quote
12199 @noindent
12200 The result of evaluating this @code{and} expression successfully is that
12201 @code{fill-prefix-regexp} will be bound to the value of
12202 @code{fill-prefix} as modified by the @code{regexp-quote} function.
12203 What @code{regexp-quote} does is read a string and return a regular
12204 expression that will exactly match the string and match nothing else.
12205 This means that @code{fill-prefix-regexp} will be set to a value that
12206 will exactly match the fill prefix if the fill prefix exists.
12207 Otherwise, the variable will be set to @code{nil}.
12209 The second local variable in the @code{let*} expression is
12210 @code{paragraph-separate}.  It is bound to the value returned by
12211 evaluating the expression:
12213 @smallexample
12214 @group
12215 (if fill-prefix-regexp
12216     (concat paragraph-separate
12217             "\\|^" fill-prefix-regexp "[ \t]*$")
12218   paragraph-separate)))
12219 @end group
12220 @end smallexample
12222 This expression shows why @code{let*} rather than @code{let} was used.
12223 The true-or-false-test for the @code{if} depends on whether the variable
12224 @code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12226 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12227 the else-part of the @code{if} expression and binds
12228 @code{paragraph-separate} to its local value.
12229 (@code{paragraph-separate} is a regular expression that matches what
12230 separates paragraphs.)
12232 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12233 the then-part of the @code{if} expression and binds
12234 @code{paragraph-separate} to a regular expression that includes the
12235 @code{fill-prefix-regexp} as part of the pattern.
12237 Specifically, @code{paragraph-separate} is set to the original value
12238 of the paragraph separate regular expression concatenated with an
12239 alternative expression that consists of the @code{fill-prefix-regexp}
12240 followed by a blank line.  The @samp{^} indicates that the
12241 @code{fill-prefix-regexp} must begin a line, and the optional
12242 whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12243 The @samp{\\|} defines this portion of the regexp as an alternative to
12244 @code{paragraph-separate}.
12246 Now we get into the body of the @code{let*}.  The first part of the body
12247 of the @code{let*} deals with the case when the function is given a
12248 negative argument and is therefore moving backwards.  We will skip this
12249 section.
12251 @node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12252 @unnumberedsubsec The forward motion @code{while} loop
12254 The second part of the body of the @code{let*} deals with forward
12255 motion.  It is a @code{while} loop that repeats itself so long as the
12256 value of @code{arg} is greater than zero.  In the most common use of
12257 the function, the value of the argument is 1, so the body of the
12258 @code{while} loop is evaluated exactly once, and the cursor moves
12259 forward one paragraph.
12261 This part handles three situations: when point is between paragraphs,
12262 when point is within a paragraph and there is a fill prefix, and
12263 when point is within a paragraph and there is no fill prefix.
12265 @need 800
12266 The @code{while} loop looks like this:
12268 @smallexample
12269 @group
12270 (while (> arg 0)
12271   (beginning-of-line)
12273   ;; @r{between paragraphs}
12274   (while (prog1 (and (not (eobp))
12275                      (looking-at paragraph-separate))
12276            (forward-line 1)))
12277 @end group
12279 @group
12280   ;; @r{within paragraphs, with a fill prefix}
12281   (if fill-prefix-regexp
12282       ;; @r{There is a fill prefix; it overrides paragraph-start.}
12283       (while (and (not (eobp))
12284                   (not (looking-at paragraph-separate))
12285                   (looking-at fill-prefix-regexp))
12286         (forward-line 1))
12287 @end group
12289 @group
12290     ;; @r{within paragraphs, no fill prefix}
12291     (if (re-search-forward paragraph-start nil t)
12292         (goto-char (match-beginning 0))
12293       (goto-char (point-max))))
12295   (setq arg (1- arg)))
12296 @end group
12297 @end smallexample
12299 We can see immediately that this is a decrementing counter @code{while}
12300 loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12302 @need 800
12303 The body of the loop consists of three expressions:
12305 @smallexample
12306 @group
12307 ;; @r{between paragraphs}
12308 (beginning-of-line)
12309 (while
12310     @var{body-of-while})
12311 @end group
12313 @group
12314 ;; @r{within paragraphs, with fill prefix}
12315 (if @var{true-or-false-test}
12316     @var{then-part}
12317 @end group
12319 @group
12320 ;; @r{within paragraphs, no fill prefix}
12321   @var{else-part}
12322 @end group
12323 @end smallexample
12325 @noindent
12326 When the Emacs Lisp interpreter evaluates the body of the
12327 @code{while} loop, the first thing it does is evaluate the
12328 @code{(beginning-of-line)} expression and move point to the beginning
12329 of the line.  Then there is an inner @code{while} loop.  This
12330 @code{while} loop is designed to move the cursor out of the blank
12331 space between paragraphs, if it should happen to be there.  Finally,
12332 there is an @code{if} expression that actually moves point to the end
12333 of the paragraph.
12335 @node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12336 @unnumberedsubsec Between paragraphs
12338 First, let us look at the inner @code{while} loop.  This loop handles
12339 the case when point is between paragraphs; it uses three functions
12340 that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12341 @findex prog1
12342 @findex eobp
12343 @findex looking-at
12345 @itemize @bullet
12346 @item
12347 @code{prog1} is similar to the @code{progn} special form,
12348 except that @code{prog1} evaluates its arguments in sequence and then
12349 returns the value of its first argument as the value of the whole
12350 expression.  (@code{progn} returns the value of its last argument as the
12351 value of the expression.) The second and subsequent arguments to
12352 @code{prog1} are evaluated only for their side effects.
12354 @item
12355 @code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12356 function that returns true if point is at the end of the buffer.
12358 @item
12359 @code{looking-at} is a function that returns true if the text following
12360 point matches the regular expression passed @code{looking-at} as its
12361 argument.
12362 @end itemize
12364 @need 800
12365 The @code{while} loop we are studying looks like this:
12367 @smallexample
12368 @group
12369 (while (prog1 (and (not (eobp))
12370                    (looking-at paragraph-separate))
12371               (forward-line 1)))
12372 @end group
12373 @end smallexample
12375 @need 1200
12376 @noindent
12377 This is a @code{while} loop with no body!  The true-or-false-test of the
12378 loop is the expression:
12380 @smallexample
12381 @group
12382 (prog1 (and (not (eobp))
12383             (looking-at paragraph-separate))
12384        (forward-line 1))
12385 @end group
12386 @end smallexample
12388 @noindent
12389 The first argument to the @code{prog1} is the @code{and} expression.  It
12390 has within in it a test of whether point is at the end of the buffer and
12391 also a test of whether the pattern following point matches the regular
12392 expression for separating paragraphs.
12394 If the cursor is not at the end of the buffer and if the characters
12395 following the cursor mark the separation between two paragraphs, then
12396 the @code{and} expression is true.  After evaluating the @code{and}
12397 expression, the Lisp interpreter evaluates the second argument to
12398 @code{prog1}, which is @code{forward-line}.  This moves point forward
12399 one line.  The value returned by the @code{prog1} however, is the
12400 value of its first argument, so the @code{while} loop continues so
12401 long as point is not at the end of the buffer and is between
12402 paragraphs.  When, finally, point is moved to a paragraph, the
12403 @code{and} expression tests false.  Note however, that the
12404 @code{forward-line} command is carried out anyhow.  This means that
12405 when point is moved from between paragraphs to a paragraph, it is left
12406 at the beginning of the second line of the paragraph.
12408 @node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12409 @unnumberedsubsec Within paragraphs
12411 The next expression in the outer @code{while} loop is an @code{if}
12412 expression.  The Lisp interpreter evaluates the then-part of the
12413 @code{if} when the @code{fill-prefix-regexp} variable has a value other
12414 than @code{nil}, and it evaluates the else-part when the value of
12415 @code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12416 fill prefix.
12418 @node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12419 @unnumberedsubsec No fill prefix
12421 It is simplest to look at the code for the case when there is no fill
12422 prefix first.  This code consists of yet another inner @code{if}
12423 expression, and reads as follows:
12425 @smallexample
12426 @group
12427 (if (re-search-forward paragraph-start nil t)
12428     (goto-char (match-beginning 0))
12429   (goto-char (point-max)))
12430 @end group
12431 @end smallexample
12433 @noindent
12434 This expression actually does the work that most people think of as
12435 the primary purpose of the @code{forward-paragraph} command: it causes
12436 a regular expression search to occur that searches forward to the
12437 start of the next paragraph and if it is found, moves point there; but
12438 if the start of another paragraph if not found, it moves point to the
12439 end of the accessible region of the buffer.
12441 The only unfamiliar part of this is the use of @code{match-beginning}.
12442 This is another function that is new to us.  The
12443 @code{match-beginning} function returns a number specifying the
12444 location of the start of the text that was matched by the last regular
12445 expression search.
12447 The @code{match-beginning} function is used here because of a
12448 characteristic of a forward search: a successful forward search,
12449 regardless of whether it is a plain search or a regular expression
12450 search, will move point to the end of the text that is found.  In this
12451 case, a successful search will move point to the end of the pattern for
12452 @code{paragraph-start}, which will be the beginning of the next
12453 paragraph rather than the end of the current one.
12455 However, we want to put point at the end of the current paragraph, not at
12456 the beginning of the next one.  The two positions may be different,
12457 because there may be several blank lines between paragraphs.
12459 @findex match-beginning
12460 When given an argument of 0, @code{match-beginning} returns the position
12461 that is the start of the text that the most recent regular
12462 expression search matched.  In this case, the most recent regular
12463 expression search is the one looking for @code{paragraph-start}, so
12464 @code{match-beginning} returns the beginning position of the pattern,
12465 rather than the end of the pattern.  The beginning position is the end
12466 of the paragraph.
12468 (Incidentally, when passed a positive number as an argument, the
12469 @code{match-beginning} function will place point at that parenthesized
12470 expression in the last regular expression.  It is a useful function.)
12472 @node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12473 @unnumberedsubsec With a fill prefix
12475 The inner @code{if} expression just discussed is the else-part of an enclosing
12476 @code{if} expression which tests whether there is a fill prefix.  If
12477 there is a fill prefix, the then-part of this @code{if} is evaluated.
12478 It looks like this:
12480 @smallexample
12481 @group
12482 (while (and (not (eobp))
12483             (not (looking-at paragraph-separate))
12484             (looking-at fill-prefix-regexp))
12485   (forward-line 1))
12486 @end group
12487 @end smallexample
12489 @noindent
12490 What this expression does is move point forward line by line so long
12491 as three conditions are true:
12493 @enumerate
12494 @item
12495 Point is not at the end of the buffer.
12497 @item
12498 The text following point does not separate paragraphs.
12500 @item
12501 The pattern following point is the fill prefix regular expression.
12502 @end enumerate
12504 The last condition may be puzzling, until you remember that point was
12505 moved to the beginning of the line early in the @code{forward-paragraph}
12506 function.  This means that if the text has a fill prefix, the
12507 @code{looking-at} function will see it.
12509 @node fwd-para summary,  , fwd-para with fill prefix, forward-paragraph
12510 @unnumberedsubsec Summary
12512 In summary, when moving forward, the @code{forward-paragraph} function
12513 does the following:
12515 @itemize @bullet
12516 @item
12517 Move point to the beginning of the line.
12519 @item
12520 Skip over lines between paragraphs.
12522 @item
12523 Check whether there is a fill prefix, and if there is:
12525 @itemize ---
12527 @item
12528 Go forward line by line so long as the line is not a paragraph
12529 separating line.
12530 @end itemize
12532 @item
12533 But if there is no fill prefix,
12535 @itemize ---
12537 @item
12538 Search for the next paragraph start pattern.
12540 @item
12541 Go to the beginning of the paragraph start pattern, which will be the
12542 end of the previous paragraph.
12544 @item
12545 Or else go to the end of the accessible portion of the buffer.
12546 @end itemize
12547 @end itemize
12549 @need 1200
12550 For review, here is the code we have just been discussing, formatted
12551 for clarity:
12553 @smallexample
12554 @group
12555 (interactive "p")
12556 (or arg (setq arg 1))
12557 (let* (
12558        (fill-prefix-regexp
12559         (and fill-prefix (not (equal fill-prefix ""))
12560              (not paragraph-ignore-fill-prefix)
12561              (regexp-quote fill-prefix)))
12562 @end group
12564 @group
12565        (paragraph-separate
12566         (if fill-prefix-regexp
12567             (concat paragraph-separate
12568                     "\\|^"
12569                     fill-prefix-regexp
12570                     "[ \t]*$")
12571           paragraph-separate)))
12573   @var{omitted-backward-moving-code} @dots{}
12574 @end group
12576 @group
12577   (while (> arg 0)                ; @r{forward-moving-code}
12578     (beginning-of-line)
12580     (while (prog1 (and (not (eobp))
12581                        (looking-at paragraph-separate))
12582              (forward-line 1)))
12583 @end group
12585 @group
12586     (if fill-prefix-regexp
12587         (while (and (not (eobp))  ; @r{then-part}
12588                     (not (looking-at paragraph-separate))
12589                     (looking-at fill-prefix-regexp))
12590           (forward-line 1))
12591 @end group
12592 @group
12593                                   ; @r{else-part: the inner-if}
12594       (if (re-search-forward paragraph-start nil t)
12595           (goto-char (match-beginning 0))
12596         (goto-char (point-max))))
12598     (setq arg (1- arg)))))        ; @r{decrementer}
12599 @end group
12600 @end smallexample
12602 The full definition for the @code{forward-paragraph} function not only
12603 includes this code for going forwards, but also code for going backwards.
12605 If you are reading this inside of GNU Emacs and you want to see the
12606 whole function, you can type @kbd{C-h f} (@code{describe-function})
12607 and the name of the function.  This gives you the function
12608 documentation and the name of the library containing the function's
12609 source.  Place point over the name of the library and press the RET
12610 key; you will be taken directly to the source.  (Be sure to install
12611 your sources!  Without them, you are like a person who tries to drive
12612 a car with his eyes shut!)
12614 @c !!! again, 21.0.100 tags table location in this paragraph
12615 Or -- a good habit to get into -- you can type @kbd{M-.}
12616 (@code{find-tag}) and the name of the function when prompted for it.
12617 This will take you directly to the source.  If the @code{find-tag}
12618 function first asks you for the name of a @file{TAGS} table, give it
12619 the name of the @file{TAGS} file such as
12620 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS}.  (The exact path to your
12621 @file{TAGS} file depends on how your copy of Emacs was installed.)
12623 You can also create your own @file{TAGS} file for directories that
12624 lack one.
12625 @ifnottex
12626 @xref{etags, , Create Your Own @file{TAGS} File}.
12627 @end ifnottex
12629 @node etags, Regexp Review, forward-paragraph, Regexp Search
12630 @section Create Your Own @file{TAGS} File
12631 @findex etags
12632 @cindex @file{TAGS} file, create own
12634 The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12635 source for a function, variable, node, or other source.  The function
12636 depends on tags tables to tell it where to go.
12638 You often need to build and install tags tables yourself.  They are
12639 not built automatically.  A tags table is called a @file{TAGS} file;
12640 the name is in upper case letters.
12642 You can create a @file{TAGS} file by calling the @code{etags} program
12643 that comes as a part of the Emacs distribution.  Usually, @code{etags}
12644 is compiled and installed when Emacs is built.  (@code{etags} is not
12645 an Emacs Lisp function or a part of Emacs; it is a C program.)
12647 @need 1250
12648 To create a @file{TAGS} file, first switch to the directory in which
12649 you want to create the file.  In Emacs you can do this with the
12650 @kbd{M-x cd} command, or by visiting a file in the directory, or by
12651 listing the directory with @kbd{C-x d} (@code{dired}).  Then run the
12652 compile command, with @w{@code{etags *.el}} as the command to execute
12654 @smallexample
12655 M-x compile RET etags *.el RET
12656 @end smallexample
12658 @noindent
12659 to create a @file{TAGS} file.
12661 For example, if you have a large number of files in your
12662 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12663 of which I load 12---you can create a @file{TAGS} file for the Emacs
12664 Lisp files in that directory.
12666 @need 1250
12667 The @code{etags} program takes all the
12668 usual shell `wildcards'.  For example, if you have two directories for
12669 which you want a single @file{TAGS file}, type
12670 @w{@code{etags *.el ../elisp/*.el}},
12671 where @file{../elisp/} is the second directory:
12673 @smallexample
12674 M-x compile RET etags *.el ../elisp/*.el RET
12675 @end smallexample
12677 @need 1250
12678 Type
12680 @smallexample
12681 M-x compile RET etags --help RET
12682 @end smallexample
12684 @noindent
12685 to see a list of the options accepted by @code{etags} as well as a
12686 list of supported languages.
12688 The @code{etags} program handles more than 20 languages, including
12689 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12690 Pascal, Perl, Python, Texinfo, makefiles, and most assemblers.  The
12691 program has no switches for specifying the language; it recognizes the
12692 language in an input file according to its file name and contents.
12694 @file{etags} is very helpful when you are writing code yourself and
12695 want to refer back to functions you have already written.  Just run
12696 @code{etags} again at intervals as you write new functions, so they
12697 become part of the @file{TAGS} file.
12699 If you think an appropriate @file{TAGS} file already exists for what
12700 you want, but do not know where it is, you can use the @code{locate}
12701 program to attempt to find it.
12703 Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12704 full path names of all your @file{TAGS} files.  On my system, this
12705 command lists 34 @file{TAGS} files.  On the other hand, a `plain
12706 vanilla' system I recently installed did not contain any @file{TAGS}
12707 files.
12709 If the tags table you want has been created, you can use the @code{M-x
12710 visit-tags-table} command to specify it.  Otherwise, you will need to
12711 create the tag table yourself and then use @code{M-x
12712 visit-tags-table}.
12714 @subsubheading Building Tags in the Emacs sources
12715 @cindex Building Tags in the Emacs sources
12716 @cindex Tags in the Emacs sources
12717 @findex make tags
12719 The GNU Emacs sources come with a @file{Makefile} that contains a
12720 sophisticated @code{etags} command that creates, collects, and merges
12721 tags tables from all over the Emacs sources and puts the information
12722 into one @file{TAGS} file in the @file{src/} directory below the top
12723 level of your Emacs source directory.
12725 @need 1250
12726 To build this @file{TAGS} file, go to the top level of your Emacs
12727 source directory and run the compile command @code{make tags}:
12729 @smallexample
12730 M-x compile RET make tags RET
12731 @end smallexample
12733 @noindent
12734 (The @code{make tags} command works well with the GNU Emacs sources,
12735 as well as with some other source packages.)
12737 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12738 Manual}.
12740 @node Regexp Review, re-search Exercises, etags, Regexp Search
12741 @comment  node-name,  next,  previous,  up
12742 @section Review
12744 Here is a brief summary of some recently introduced functions.
12746 @table @code
12747 @item while
12748 Repeatedly evaluate the body of the expression so long as the first
12749 element of the body tests true.  Then return @code{nil}.  (The
12750 expression is evaluated only for its side effects.)
12752 @need 1250
12753 For example:
12755 @smallexample
12756 @group
12757 (let ((foo 2))
12758   (while (> foo 0)
12759     (insert (format "foo is %d.\n" foo))
12760     (setq foo (1- foo))))
12762      @result{}      foo is 2.
12763              foo is 1.
12764              nil
12765 @end group
12766 @end smallexample
12767 @noindent
12768 (The @code{insert} function inserts its arguments at point; the
12769 @code{format} function returns a string formatted from its arguments
12770 the way @code{message} formats its arguments; @code{\n} produces a new
12771 line.)
12773 @item re-search-forward
12774 Search for a pattern, and if the pattern is found, move point to rest
12775 just after it.
12777 @noindent
12778 Takes four arguments, like @code{search-forward}:
12780 @enumerate
12781 @item
12782 A regular expression that specifies the pattern to search for.
12784 @item
12785 Optionally, the limit of the search.
12787 @item
12788 Optionally, what to do if the search fails, return @code{nil} or an
12789 error message.
12791 @item
12792 Optionally, how many times to repeat the search; if negative, the
12793 search goes backwards.
12794 @end enumerate
12796 @item let*
12797 Bind some variables locally to particular values,
12798 and then evaluate the remaining arguments, returning the value of the
12799 last one.  While binding the local variables, use the local values of
12800 variables bound earlier, if any.
12802 @need 1250
12803 For example:
12805 @smallexample
12806 @group
12807 (let* ((foo 7)
12808       (bar (* 3 foo)))
12809   (message "`bar' is %d." bar))
12810      @result{} `bar' is 21.
12811 @end group
12812 @end smallexample
12814 @item match-beginning
12815 Return the position of the start of the text found by the last regular
12816 expression search.
12818 @item looking-at
12819 Return @code{t} for true if the text after point matches the argument,
12820 which should be a regular expression.
12822 @item eobp
12823 Return @code{t} for true if point is at the end of the accessible part
12824 of a buffer.  The end of the accessible part is the end of the buffer
12825 if the buffer is not narrowed; it is the end of the narrowed part if
12826 the buffer is narrowed.
12828 @item prog1
12829 Evaluate each argument in sequence and then return the value of the
12830 @emph{first}.
12832 @need 1250
12833 For example:
12835 @smallexample
12836 @group
12837 (prog1 1 2 3 4)
12838      @result{} 1
12839 @end group
12840 @end smallexample
12841 @end table
12843 @need 1500
12844 @node re-search Exercises,  , Regexp Review, Regexp Search
12845 @section Exercises with @code{re-search-forward}
12847 @itemize @bullet
12848 @item
12849 Write a function to search for a regular expression that matches two
12850 or more blank lines in sequence.
12852 @item
12853 Write a function to search for duplicated words, such as `the the'.
12854 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12855 Manual}, for information on how to write a regexp (a regular
12856 expression) to match a string that is composed of two identical
12857 halves.  You can devise several regexps; some are better than others.
12858 The function I use is described in an appendix, along with several
12859 regexps.  @xref{the-the, , @code{the-the} Duplicated Words Function}.
12860 @end itemize
12862 @node Counting Words, Words in a defun, Regexp Search, Top
12863 @chapter Counting: Repetition and Regexps
12864 @cindex Repetition for word counting
12865 @cindex Regular expressions for word counting
12867 Repetition and regular expression searches are powerful tools that you
12868 often use when you write code in Emacs Lisp.  This chapter illustrates
12869 the use of regular expression searches through the construction of
12870 word count commands using @code{while} loops and recursion.
12872 @menu
12873 * Why Count Words::
12874 * count-words-region::          Use a regexp, but find a problem.
12875 * recursive-count-words::       Start with case of no words in region.
12876 * Counting Exercise::
12877 @end menu
12879 @node Why Count Words, count-words-region, Counting Words, Counting Words
12880 @ifnottex
12881 @unnumberedsec Counting words
12882 @end ifnottex
12884 The standard Emacs distribution contains a function for counting the
12885 number of lines within a region.  However, there is no corresponding
12886 function for counting words.
12888 Certain types of writing ask you to count words.  Thus, if you write
12889 an essay, you may be limited to 800 words; if you write a novel, you
12890 may discipline yourself to write 1000 words a day.  It seems odd to me
12891 that Emacs lacks a word count command.  Perhaps people use Emacs
12892 mostly for code or types of documentation that do not require word
12893 counts; or perhaps they restrict themselves to the operating system
12894 word count command, @code{wc}.  Alternatively, people may follow
12895 the publishers' convention and compute a word count by dividing the
12896 number of characters in a document by five.  In any event, here are
12897 commands to count words.
12899 @node count-words-region, recursive-count-words, Why Count Words, Counting Words
12900 @comment  node-name,  next,  previous,  up
12901 @section The @code{count-words-region} Function
12902 @findex count-words-region
12904 A word count command could count words in a line, paragraph, region,
12905 or buffer.  What should the command cover?  You could design the
12906 command to count the number of words in a complete buffer.  However,
12907 the Emacs tradition encourages flexibility---you may want to count
12908 words in just a section, rather than all of a buffer.  So it makes
12909 more sense to design the command to count the number of words in a
12910 region.  Once you have a @code{count-words-region} command, you can,
12911 if you wish, count words in a whole buffer by marking it with @kbd{C-x
12912 h} (@code{mark-whole-buffer}).
12914 Clearly, counting words is a repetitive act: starting from the
12915 beginning of the region, you count the first word, then the second
12916 word, then the third word, and so on, until you reach the end of the
12917 region.  This means that word counting is ideally suited to recursion
12918 or to a @code{while} loop.
12920 @menu
12921 * Design count-words-region::   The definition using a @code{while} loop.
12922 * Whitespace Bug::              The Whitespace Bug in @code{count-words-region}.
12923 @end menu
12925 @node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12926 @ifnottex
12927 @unnumberedsubsec Designing @code{count-words-region}
12928 @end ifnottex
12930 First, we will implement the word count command with a @code{while}
12931 loop, then with recursion.  The command will, of course, be
12932 interactive.
12934 @need 800
12935 The template for an interactive function definition is, as always:
12937 @smallexample
12938 @group
12939 (defun @var{name-of-function} (@var{argument-list})
12940   "@var{documentation}@dots{}"
12941   (@var{interactive-expression}@dots{})
12942   @var{body}@dots{})
12943 @end group
12944 @end smallexample
12946 What we need to do is fill in the slots.
12948 The name of the function should be self-explanatory and similar to the
12949 existing @code{count-lines-region} name.  This makes the name easier
12950 to remember.  @code{count-words-region} is a good choice.
12952 The function counts words within a region.  This means that the
12953 argument list must contain symbols that are bound to the two
12954 positions, the beginning and end of the region.  These two positions
12955 can be called @samp{beginning} and @samp{end} respectively.  The first
12956 line of the documentation should be a single sentence, since that is
12957 all that is printed as documentation by a command such as
12958 @code{apropos}.  The interactive expression will be of the form
12959 @samp{(interactive "r")}, since that will cause Emacs to pass the
12960 beginning and end of the region to the function's argument list.  All
12961 this is routine.
12963 The body of the function needs to be written to do three tasks:
12964 first, to set up conditions under which the @code{while} loop can
12965 count words, second, to run the @code{while} loop, and third, to send
12966 a message to the user.
12968 When a user calls @code{count-words-region}, point may be at the
12969 beginning or the end of the region.  However, the counting process
12970 must start at the beginning of the region.  This means we will want
12971 to put point there if it is not already there.  Executing
12972 @code{(goto-char beginning)} ensures this.  Of course, we will want to
12973 return point to its expected position when the function finishes its
12974 work.  For this reason, the body must be enclosed in a
12975 @code{save-excursion} expression.
12977 The central part of the body of the function consists of a
12978 @code{while} loop in which one expression jumps point forward word by
12979 word, and another expression counts those jumps.  The true-or-false-test
12980 of the @code{while} loop should test true so long as point should jump
12981 forward, and false when point is at the end of the region.
12983 We could use @code{(forward-word 1)} as the expression for moving point
12984 forward word by word, but it is easier to see what Emacs identifies as a
12985 `word' if we use a regular expression search.
12987 A regular expression search that finds the pattern for which it is
12988 searching leaves point after the last character matched.  This means
12989 that a succession of successful word searches will move point forward
12990 word by word.
12992 As a practical matter, we want the regular expression search to jump
12993 over whitespace and punctuation between words as well as over the
12994 words themselves.  A regexp that refuses to jump over interword
12995 whitespace would never jump more than one word!  This means that
12996 the regexp should include the whitespace and punctuation that follows
12997 a word, if any, as well as the word itself.  (A word may end a buffer
12998 and not have any following whitespace or punctuation, so that part of
12999 the regexp must be optional.)
13001 Thus, what we want for the regexp is a pattern defining one or more
13002 word constituent characters followed, optionally, by one or more
13003 characters that are not word constituents.  The regular expression for
13004 this is:
13006 @smallexample
13007 \w+\W*
13008 @end smallexample
13010 @noindent
13011 The buffer's syntax table determines which characters are and are not
13012 word constituents.  (@xref{Syntax, , What Constitutes a Word or
13013 Symbol?}, for more about syntax.  Also, see @ref{Syntax, Syntax, The
13014 Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
13015 Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13017 @need 800
13018 The search expression looks like this:
13020 @smallexample
13021 (re-search-forward "\\w+\\W*")
13022 @end smallexample
13024 @noindent
13025 (Note that paired backslashes precede the @samp{w} and @samp{W}.  A
13026 single backslash has special meaning to the Emacs Lisp interpreter.  It
13027 indicates that the following character is interpreted differently than
13028 usual.  For example, the two characters, @samp{\n}, stand for
13029 @samp{newline}, rather than for a backslash followed by @samp{n}.  Two
13030 backslashes in a row stand for an ordinary, `unspecial' backslash.)
13032 We need a counter to count how many words there are; this variable
13033 must first be set to 0 and then incremented each time Emacs goes
13034 around the @code{while} loop.  The incrementing expression is simply:
13036 @smallexample
13037 (setq count (1+ count))
13038 @end smallexample
13040 Finally, we want to tell the user how many words there are in the
13041 region.  The @code{message} function is intended for presenting this
13042 kind of information to the user.  The message has to be phrased so
13043 that it reads properly regardless of how many words there are in the
13044 region: we don't want to say that ``there are 1 words in the region''.
13045 The conflict between singular and plural is ungrammatical.  We can
13046 solve this problem by using a conditional expression that evaluates
13047 different messages depending on the number of words in the region.
13048 There are three possibilities: no words in the region, one word in the
13049 region, and more than one word.  This means that the @code{cond}
13050 special form is appropriate.
13052 @need 1500
13053 All this leads to the following function definition:
13055 @smallexample
13056 @group
13057 ;;; @r{First version; has bugs!}
13058 (defun count-words-region (beginning end)
13059   "Print number of words in the region.
13060 Words are defined as at least one word-constituent
13061 character followed by at least one character that
13062 is not a word-constituent.  The buffer's syntax
13063 table determines which characters these are."
13064   (interactive "r")
13065   (message "Counting words in region ... ")
13066 @end group
13068 @group
13069 ;;; @r{1. Set up appropriate conditions.}
13070   (save-excursion
13071     (goto-char beginning)
13072     (let ((count 0))
13073 @end group
13075 @group
13076 ;;; @r{2. Run the} while @r{loop.}
13077       (while (< (point) end)
13078         (re-search-forward "\\w+\\W*")
13079         (setq count (1+ count)))
13080 @end group
13082 @group
13083 ;;; @r{3. Send a message to the user.}
13084       (cond ((zerop count)
13085              (message
13086               "The region does NOT have any words."))
13087             ((= 1 count)
13088              (message
13089               "The region has 1 word."))
13090             (t
13091              (message
13092               "The region has %d words." count))))))
13093 @end group
13094 @end smallexample
13096 @noindent
13097 As written, the function works, but not in all circumstances.
13099 @node Whitespace Bug,  , Design count-words-region, count-words-region
13100 @comment  node-name,  next,  previous,  up
13101 @subsection The Whitespace Bug in @code{count-words-region}
13103 The @code{count-words-region} command described in the preceding
13104 section has two bugs, or rather, one bug with two manifestations.
13105 First, if you mark a region containing only whitespace in the middle
13106 of some text, the @code{count-words-region} command tells you that the
13107 region contains one word!  Second, if you mark a region containing
13108 only whitespace at the end of the buffer or the accessible portion of
13109 a narrowed buffer, the command displays an error message that looks
13110 like this:
13112 @smallexample
13113 Search failed: "\\w+\\W*"
13114 @end smallexample
13116 If you are reading this in Info in GNU Emacs, you can test for these
13117 bugs yourself.
13119 First, evaluate the function in the usual manner to install it.
13120 @ifinfo
13121 Here is a copy of the definition.  Place your cursor after the closing
13122 parenthesis and type @kbd{C-x C-e} to install it.
13124 @smallexample
13125 @group
13126 ;; @r{First version; has bugs!}
13127 (defun count-words-region (beginning end)
13128   "Print number of words in the region.
13129 Words are defined as at least one word-constituent character followed
13130 by at least one character that is not a word-constituent.  The buffer's
13131 syntax table determines which characters these are."
13132 @end group
13133 @group
13134   (interactive "r")
13135   (message "Counting words in region ... ")
13136 @end group
13138 @group
13139 ;;; @r{1. Set up appropriate conditions.}
13140   (save-excursion
13141     (goto-char beginning)
13142     (let ((count 0))
13143 @end group
13145 @group
13146 ;;; @r{2. Run the} while @r{loop.}
13147       (while (< (point) end)
13148         (re-search-forward "\\w+\\W*")
13149         (setq count (1+ count)))
13150 @end group
13152 @group
13153 ;;; @r{3. Send a message to the user.}
13154       (cond ((zerop count)
13155              (message "The region does NOT have any words."))
13156             ((= 1 count) (message "The region has 1 word."))
13157             (t (message "The region has %d words." count))))))
13158 @end group
13159 @end smallexample
13160 @end ifinfo
13162 @need 1000
13163 If you wish, you can also install this keybinding by evaluating it:
13165 @smallexample
13166 (global-set-key "\C-c=" 'count-words-region)
13167 @end smallexample
13169 To conduct the first test, set mark and point to the beginning and end
13170 of the following line and then type @kbd{C-c =} (or @kbd{M-x
13171 count-words-region} if you have not bound @kbd{C-c =}):
13173 @smallexample
13174     one   two  three
13175 @end smallexample
13177 @noindent
13178 Emacs will tell you, correctly, that the region has three words.
13180 Repeat the test, but place mark at the beginning of the line and place
13181 point just @emph{before} the word @samp{one}.  Again type the command
13182 @kbd{C-c =} (or @kbd{M-x count-words-region}).  Emacs should tell you
13183 that the region has no words, since it is composed only of the
13184 whitespace at the beginning of the line.  But instead Emacs tells you
13185 that the region has one word!
13187 For the third test, copy the sample line to the end of the
13188 @file{*scratch*} buffer and then type several spaces at the end of the
13189 line.  Place mark right after the word @samp{three} and point at the
13190 end of line.  (The end of the line will be the end of the buffer.)
13191 Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13192 Again, Emacs should tell you that the region has no words, since it is
13193 composed only of the whitespace at the end of the line.  Instead,
13194 Emacs displays an error message saying @samp{Search failed}.
13196 The two bugs stem from the same problem.
13198 Consider the first manifestation of the bug, in which the command
13199 tells you that the whitespace at the beginning of the line contains
13200 one word.  What happens is this: The @code{M-x count-words-region}
13201 command moves point to the beginning of the region.  The @code{while}
13202 tests whether the value of point is smaller than the value of
13203 @code{end}, which it is.  Consequently, the regular expression search
13204 looks for and finds the first word.  It leaves point after the word.
13205 @code{count} is set to one.  The @code{while} loop repeats; but this
13206 time the value of point is larger than the value of @code{end}, the
13207 loop is exited; and the function displays a message saying the number
13208 of words in the region is one.  In brief, the regular expression
13209 search looks for and finds the word even though it is outside
13210 the marked region.
13212 In the second manifestation of the bug, the region is whitespace at
13213 the end of the buffer.  Emacs says @samp{Search failed}.  What happens
13214 is that the true-or-false-test in the @code{while} loop tests true, so
13215 the search expression is executed.  But since there are no more words
13216 in the buffer, the search fails.
13218 In both manifestations of the bug, the search extends or attempts to
13219 extend outside of the region.
13221 The solution is to limit the search to the region---this is a fairly
13222 simple action, but as you may have come to expect, it is not quite as
13223 simple as you might think.
13225 As we have seen, the @code{re-search-forward} function takes a search
13226 pattern as its first argument.  But in addition to this first,
13227 mandatory argument, it accepts three optional arguments.  The optional
13228 second argument bounds the search.  The optional third argument, if
13229 @code{t}, causes the function to return @code{nil} rather than signal
13230 an error if the search fails.  The optional fourth argument is a
13231 repeat count.  (In Emacs, you can see a function's documentation by
13232 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13234 In the @code{count-words-region} definition, the value of the end of
13235 the region is held by the variable @code{end} which is passed as an
13236 argument to the function.  Thus, we can add @code{end} as an argument
13237 to the regular expression search expression:
13239 @smallexample
13240 (re-search-forward "\\w+\\W*" end)
13241 @end smallexample
13243 However, if you make only this change to the @code{count-words-region}
13244 definition and then test the new version of the definition on a
13245 stretch of whitespace, you will receive an error message saying
13246 @samp{Search failed}.
13248 What happens is this: the search is limited to the region, and fails
13249 as you expect because there are no word-constituent characters in the
13250 region.  Since it fails, we receive an error message.  But we do not
13251 want to receive an error message in this case; we want to receive the
13252 message that "The region does NOT have any words."
13254 The solution to this problem is to provide @code{re-search-forward}
13255 with a third argument of @code{t}, which causes the function to return
13256 @code{nil} rather than signal an error if the search fails.
13258 However, if you make this change and try it, you will see the message
13259 ``Counting words in region ... '' and @dots{} you will keep on seeing
13260 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13262 Here is what happens: the search is limited to the region, as before,
13263 and it fails because there are no word-constituent characters in the
13264 region, as expected.  Consequently, the @code{re-search-forward}
13265 expression returns @code{nil}.  It does nothing else.  In particular,
13266 it does not move point, which it does as a side effect if it finds the
13267 search target.  After the @code{re-search-forward} expression returns
13268 @code{nil}, the next expression in the @code{while} loop is evaluated.
13269 This expression increments the count.  Then the loop repeats.  The
13270 true-or-false-test tests true because the value of point is still less
13271 than the value of end, since the @code{re-search-forward} expression
13272 did not move point. @dots{} and the cycle repeats @dots{}
13274 The @code{count-words-region} definition requires yet another
13275 modification, to cause the true-or-false-test of the @code{while} loop
13276 to test false if the search fails.  Put another way, there are two
13277 conditions that must be satisfied in the true-or-false-test before the
13278 word count variable is incremented: point must still be within the
13279 region and the search expression must have found a word to count.
13281 Since both the first condition and the second condition must be true
13282 together, the two expressions, the region test and the search
13283 expression, can be joined with an @code{and} special form and embedded in
13284 the @code{while} loop as the true-or-false-test, like this:
13286 @smallexample
13287 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13288 @end smallexample
13290 @c colon in printed section title causes problem in Info cross reference
13291 @c also trouble with an overfull hbox
13292 @iftex
13293 @noindent
13294 (For information about @code{and}, see
13295 @ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13296 Functions}.)
13297 @end iftex
13298 @ifinfo
13299 @noindent
13300 (@xref{forward-paragraph}, for information about @code{and}.)
13301 @end ifinfo
13303 The @code{re-search-forward} expression returns @code{t} if the search
13304 succeeds and as a side effect moves point.  Consequently, as words are
13305 found, point is moved through the region.  When the search
13306 expression fails to find another word, or when point reaches the end
13307 of the region, the true-or-false-test tests false, the @code{while}
13308 loop exists, and the @code{count-words-region} function displays one
13309 or other of its messages.
13311 After incorporating these final changes, the @code{count-words-region}
13312 works without bugs (or at least, without bugs that I have found!).
13313 Here is what it looks like:
13315 @smallexample
13316 @group
13317 ;;; @r{Final version:} @code{while}
13318 (defun count-words-region (beginning end)
13319   "Print number of words in the region."
13320   (interactive "r")
13321   (message "Counting words in region ... ")
13322 @end group
13324 @group
13325 ;;; @r{1. Set up appropriate conditions.}
13326   (save-excursion
13327     (let ((count 0))
13328       (goto-char beginning)
13329 @end group
13331 @group
13332 ;;; @r{2. Run the} while @r{loop.}
13333       (while (and (< (point) end)
13334                   (re-search-forward "\\w+\\W*" end t))
13335         (setq count (1+ count)))
13336 @end group
13338 @group
13339 ;;; @r{3. Send a message to the user.}
13340       (cond ((zerop count)
13341              (message
13342               "The region does NOT have any words."))
13343             ((= 1 count)
13344              (message
13345               "The region has 1 word."))
13346             (t
13347              (message
13348               "The region has %d words." count))))))
13349 @end group
13350 @end smallexample
13352 @node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13353 @comment  node-name,  next,  previous,  up
13354 @section Count Words Recursively
13355 @cindex Count words recursively
13356 @cindex Recursively counting words
13357 @cindex Words, counted recursively
13359 You can write the function for counting words recursively as well as
13360 with a @code{while} loop.  Let's see how this is done.
13362 First, we need to recognize that the @code{count-words-region}
13363 function has three jobs: it sets up the appropriate conditions for
13364 counting to occur; it counts the words in the region; and it sends a
13365 message to the user telling how many words there are.
13367 If we write a single recursive function to do everything, we will
13368 receive a message for every recursive call.  If the region contains 13
13369 words, we will receive thirteen messages, one right after the other.
13370 We don't want this!  Instead, we must write two functions to do the
13371 job, one of which (the recursive function) will be used inside of the
13372 other.  One function will set up the conditions and display the
13373 message; the other will return the word count.
13375 Let us start with the function that causes the message to be displayed.
13376 We can continue to call this @code{count-words-region}.
13378 This is the function that the user will call.  It will be interactive.
13379 Indeed, it will be similar to our previous versions of this
13380 function, except that it will call @code{recursive-count-words} to
13381 determine how many words are in the region.
13383 @need 1250
13384 We can readily construct a template for this function, based on our
13385 previous versions:
13387 @smallexample
13388 @group
13389 ;; @r{Recursive version; uses regular expression search}
13390 (defun count-words-region (beginning end)
13391   "@var{documentation}@dots{}"
13392   (@var{interactive-expression}@dots{})
13393 @end group
13394 @group
13396 ;;; @r{1. Set up appropriate conditions.}
13397   (@var{explanatory message})
13398   (@var{set-up functions}@dots{}
13399 @end group
13400 @group
13402 ;;; @r{2. Count the words.}
13403     @var{recursive call}
13404 @end group
13405 @group
13407 ;;; @r{3. Send a message to the user.}
13408     @var{message providing word count}))
13409 @end group
13410 @end smallexample
13412 The definition looks straightforward, except that somehow the count
13413 returned by the recursive call must be passed to the message
13414 displaying the word count.  A little thought suggests that this can be
13415 done by making use of a @code{let} expression: we can bind a variable
13416 in the varlist of a @code{let} expression to the number of words in
13417 the region, as returned by the recursive call; and then the
13418 @code{cond} expression, using binding, can display the value to the
13419 user.
13421 Often, one thinks of the binding within a @code{let} expression as
13422 somehow secondary to the `primary' work of a function.  But in this
13423 case, what you might consider the `primary' job of the function,
13424 counting words, is done within the @code{let} expression.
13426 @need 1250
13427 Using @code{let}, the function definition looks like this:
13429 @smallexample
13430 @group
13431 (defun count-words-region (beginning end)
13432   "Print number of words in the region."
13433   (interactive "r")
13434 @end group
13436 @group
13437 ;;; @r{1. Set up appropriate conditions.}
13438   (message "Counting words in region ... ")
13439   (save-excursion
13440     (goto-char beginning)
13441 @end group
13443 @group
13444 ;;; @r{2. Count the words.}
13445     (let ((count (recursive-count-words end)))
13446 @end group
13448 @group
13449 ;;; @r{3. Send a message to the user.}
13450       (cond ((zerop count)
13451              (message
13452               "The region does NOT have any words."))
13453             ((= 1 count)
13454              (message
13455               "The region has 1 word."))
13456             (t
13457              (message
13458               "The region has %d words." count))))))
13459 @end group
13460 @end smallexample
13462 Next, we need to write the recursive counting function.
13464 A recursive function has at least three parts: the `do-again-test', the
13465 `next-step-expression', and the recursive call.
13467 The do-again-test determines whether the function will or will not be
13468 called again.  Since we are counting words in a region and can use a
13469 function that moves point forward for every word, the do-again-test
13470 can check whether point is still within the region.  The do-again-test
13471 should find the value of point and determine whether point is before,
13472 at, or after the value of the end of the region.  We can use the
13473 @code{point} function to locate point.  Clearly, we must pass the
13474 value of the end of the region to the recursive counting function as an
13475 argument.
13477 In addition, the do-again-test should also test whether the search finds a
13478 word.  If it does not, the function should not call itself again.
13480 The next-step-expression changes a value so that when the recursive
13481 function is supposed to stop calling itself, it stops.  More
13482 precisely, the next-step-expression changes a value so that at the
13483 right time, the do-again-test stops the recursive function from
13484 calling itself again.  In this case, the next-step-expression can be
13485 the expression that moves point forward, word by word.
13487 The third part of a recursive function is the recursive call.
13489 Somewhere, also, we also need a part that does the `work' of the
13490 function, a part that does the counting.  A vital part!
13492 @need 1250
13493 But already, we have an outline of the recursive counting function:
13495 @smallexample
13496 @group
13497 (defun recursive-count-words (region-end)
13498   "@var{documentation}@dots{}"
13499    @var{do-again-test}
13500    @var{next-step-expression}
13501    @var{recursive call})
13502 @end group
13503 @end smallexample
13505 Now we need to fill in the slots.  Let's start with the simplest cases
13506 first:  if point is at or beyond the end of the region, there cannot
13507 be any words in the region, so the function should return zero.
13508 Likewise, if the search fails, there are no words to count, so the
13509 function should return zero.
13511 On the other hand, if point is within the region and the search
13512 succeeds, the function should call itself again.
13514 @need 800
13515 Thus, the do-again-test should look like this:
13517 @smallexample
13518 @group
13519 (and (< (point) region-end)
13520      (re-search-forward "\\w+\\W*" region-end t))
13521 @end group
13522 @end smallexample
13524 Note that the search expression is part of the do-again-test---the
13525 function returns @code{t} if its search succeeds and @code{nil} if it
13526 fails.  (@xref{Whitespace Bug, , The Whitespace Bug in
13527 @code{count-words-region}}, for an explanation of how
13528 @code{re-search-forward} works.)
13530 The do-again-test is the true-or-false test of an @code{if} clause.
13531 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13532 clause should call the function again; but if it fails, the else-part
13533 should return zero since either point is outside the region or the
13534 search failed because there were no words to find.
13536 But before considering the recursive call, we need to consider the
13537 next-step-expression.  What is it?  Interestingly, it is the search
13538 part of the do-again-test.
13540 In addition to returning @code{t} or @code{nil} for the
13541 do-again-test, @code{re-search-forward} moves point forward as a side
13542 effect of a successful search.  This is the action that changes the
13543 value of point so that the recursive function stops calling itself
13544 when point completes its movement through the region.  Consequently,
13545 the @code{re-search-forward} expression is the next-step-expression.
13547 @need 1200
13548 In outline, then, the body of the @code{recursive-count-words}
13549 function looks like this:
13551 @smallexample
13552 @group
13553 (if @var{do-again-test-and-next-step-combined}
13554     ;; @r{then}
13555     @var{recursive-call-returning-count}
13556   ;; @r{else}
13557   @var{return-zero})
13558 @end group
13559 @end smallexample
13561 How to incorporate the mechanism that counts?
13563 If you are not used to writing recursive functions, a question like
13564 this can be troublesome.  But it can and should be approached
13565 systematically.
13567 We know that the counting mechanism should be associated in some way
13568 with the recursive call.  Indeed, since the next-step-expression moves
13569 point forward by one word, and since a recursive call is made for
13570 each word, the counting mechanism must be an expression that adds one
13571 to the value returned by a call to @code{recursive-count-words}.
13573 Consider several cases:
13575 @itemize @bullet
13576 @item
13577 If there are two words in the region, the function should return
13578 a value resulting from adding one to the value returned when it counts
13579 the first word, plus the number returned when it counts the remaining
13580 words in the region, which in this case is one.
13582 @item
13583 If there is one word in the region, the function should return
13584 a value resulting from adding one to the value returned when it counts
13585 that word, plus the number returned when it counts the remaining
13586 words in the region, which in this case is zero.
13588 @item
13589 If there are no words in the region, the function should return zero.
13590 @end itemize
13592 From the sketch we can see that the else-part of the @code{if} returns
13593 zero for the case of no words.  This means that the then-part of the
13594 @code{if} must return a value resulting from adding one to the value
13595 returned from a count of the remaining words.
13597 @need 1200
13598 The expression will look like this, where @code{1+} is a function that
13599 adds one to its argument.
13601 @smallexample
13602 (1+ (recursive-count-words region-end))
13603 @end smallexample
13605 @need 1200
13606 The whole @code{recursive-count-words} function will then look like
13607 this:
13609 @smallexample
13610 @group
13611 (defun recursive-count-words (region-end)
13612   "@var{documentation}@dots{}"
13614 ;;; @r{1. do-again-test}
13615   (if (and (< (point) region-end)
13616            (re-search-forward "\\w+\\W*" region-end t))
13617 @end group
13619 @group
13620 ;;; @r{2. then-part: the recursive call}
13621       (1+ (recursive-count-words region-end))
13623 ;;; @r{3. else-part}
13624     0))
13625 @end group
13626 @end smallexample
13628 @need 1250
13629 Let's examine how this works:
13631 If there are no words in the region, the else part of the @code{if}
13632 expression is evaluated and consequently the function returns zero.
13634 If there is one word in the region, the value of point is less than
13635 the value of @code{region-end} and the search succeeds.  In this case,
13636 the true-or-false-test of the @code{if} expression tests true, and the
13637 then-part of the @code{if} expression is evaluated.  The counting
13638 expression is evaluated.  This expression returns a value (which will
13639 be the value returned by the whole function) that is the sum of one
13640 added to the value returned by a recursive call.
13642 Meanwhile, the next-step-expression has caused point to jump over the
13643 first (and in this case only) word in the region.  This means that
13644 when @code{(recursive-count-words region-end)} is evaluated a second
13645 time, as a result of the recursive call, the value of point will be
13646 equal to or greater than the value of region end.  So this time,
13647 @code{recursive-count-words} will return zero.  The zero will be added
13648 to one, and the original evaluation of @code{recursive-count-words}
13649 will return one plus zero, which is one, which is the correct amount.
13651 Clearly, if there are two words in the region, the first call to
13652 @code{recursive-count-words} returns one added to the value returned
13653 by calling @code{recursive-count-words} on a region containing the
13654 remaining word---that is, it adds one to one, producing two, which is
13655 the correct amount.
13657 Similarly, if there are three words in the region, the first call to
13658 @code{recursive-count-words} returns one added to the value returned
13659 by calling @code{recursive-count-words} on a region containing the
13660 remaining two words---and so on and so on.
13662 @need 1250
13663 @noindent
13664 With full documentation the two functions look like this:
13666 @need 1250
13667 @noindent
13668 The recursive function:
13670 @findex recursive-count-words
13671 @smallexample
13672 @group
13673 (defun recursive-count-words (region-end)
13674   "Number of words between point and REGION-END."
13675 @end group
13677 @group
13678 ;;; @r{1. do-again-test}
13679   (if (and (< (point) region-end)
13680            (re-search-forward "\\w+\\W*" region-end t))
13681 @end group
13683 @group
13684 ;;; @r{2. then-part: the recursive call}
13685       (1+ (recursive-count-words region-end))
13687 ;;; @r{3. else-part}
13688     0))
13689 @end group
13690 @end smallexample
13692 @need 800
13693 @noindent
13694 The wrapper:
13696 @smallexample
13697 @group
13698 ;;; @r{Recursive version}
13699 (defun count-words-region (beginning end)
13700   "Print number of words in the region.
13701 @end group
13703 @group
13704 Words are defined as at least one word-constituent
13705 character followed by at least one character that is
13706 not a word-constituent.  The buffer's syntax table
13707 determines which characters these are."
13708 @end group
13709 @group
13710   (interactive "r")
13711   (message "Counting words in region ... ")
13712   (save-excursion
13713     (goto-char beginning)
13714     (let ((count (recursive-count-words end)))
13715 @end group
13716 @group
13717       (cond ((zerop count)
13718              (message
13719               "The region does NOT have any words."))
13720 @end group
13721 @group
13722             ((= 1 count)
13723              (message "The region has 1 word."))
13724             (t
13725              (message
13726               "The region has %d words." count))))))
13727 @end group
13728 @end smallexample
13730 @node Counting Exercise,  , recursive-count-words, Counting Words
13731 @section Exercise: Counting Punctuation
13733 Using a @code{while} loop, write a function to count the number of
13734 punctuation marks in a region---period, comma, semicolon, colon,
13735 exclamation mark, and question mark.  Do the same using recursion.
13737 @node Words in a defun, Readying a Graph, Counting Words, Top
13738 @chapter Counting Words in a @code{defun}
13739 @cindex Counting words in a @code{defun}
13740 @cindex Word counting in a @code{defun}
13742 Our next project is to count the number of words in a function
13743 definition.  Clearly, this can be done using some variant of
13744 @code{count-word-region}.  @xref{Counting Words, , Counting Words:
13745 Repetition and Regexps}.  If we are just going to count the words in
13746 one definition, it is easy enough to mark the definition with the
13747 @kbd{C-M-h} (@code{mark-defun}) command, and then call
13748 @code{count-word-region}.
13750 However, I am more ambitious: I want to count the words and symbols in
13751 every definition in the Emacs sources and then print a graph that
13752 shows how many functions there are of each length: how many contain 40
13753 to 49 words or symbols, how many contain 50 to 59 words or symbols,
13754 and so on.  I have often been curious how long a typical function is,
13755 and this will tell.
13757 @menu
13758 * Divide and Conquer::
13759 * Words and Symbols::           What to count?
13760 * Syntax::                      What constitutes a word or symbol?
13761 * count-words-in-defun::        Very like @code{count-words}.
13762 * Several defuns::              Counting several defuns in a file.
13763 * Find a File::                 Do you want to look at a file?
13764 * lengths-list-file::           A list of the lengths of many definitions.
13765 * Several files::               Counting in definitions in different files.
13766 * Several files recursively::   Recursively counting in different files.
13767 * Prepare the data::            Prepare the data for display in a graph.
13768 @end menu
13770 @node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13771 @ifnottex
13772 @unnumberedsec Divide and Conquer
13773 @end ifnottex
13775 Described in one phrase, the histogram project is daunting; but
13776 divided into numerous small steps, each of which we can take one at a
13777 time, the project becomes less fearsome.  Let us consider what the
13778 steps must be:
13780 @itemize @bullet
13781 @item
13782 First, write a function to count the words in one definition.  This
13783 includes the problem of handling symbols as well as words.
13785 @item
13786 Second, write a function to list the numbers of words in each function
13787 in a file.  This function can use the @code{count-words-in-defun}
13788 function.
13790 @item
13791 Third, write a function to list the numbers of words in each function
13792 in each of several files.  This entails automatically finding the
13793 various files, switching to them, and counting the words in the
13794 definitions within them.
13796 @item
13797 Fourth, write a function to convert the list of numbers that we
13798 created in step three to a form that will be suitable for printing as
13799 a graph.
13801 @item
13802 Fifth, write a function to print the results as a graph.
13803 @end itemize
13805 This is quite a project!  But if we take each step slowly, it will not
13806 be difficult.
13808 @node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13809 @section What to Count?
13810 @cindex Words and symbols in defun
13812 When we first start thinking about how to count the words in a
13813 function definition, the first question is (or ought to be) what are
13814 we going to count?  When we speak of `words' with respect to a Lisp
13815 function definition, we are actually speaking, in large part, of
13816 `symbols'.  For example, the following @code{multiply-by-seven}
13817 function contains the five symbols @code{defun},
13818 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}.  In
13819 addition, in the documentation string, it contains the four words
13820 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}.  The
13821 symbol @samp{number} is repeated, so the definition contains a total
13822 of ten words and symbols.
13824 @smallexample
13825 @group
13826 (defun multiply-by-seven (number)
13827   "Multiply NUMBER by seven."
13828   (* 7 number))
13829 @end group
13830 @end smallexample
13832 @noindent
13833 However, if we mark the @code{multiply-by-seven} definition with
13834 @kbd{C-M-h} (@code{mark-defun}), and then call
13835 @code{count-words-region} on it, we will find that
13836 @code{count-words-region} claims the definition has eleven words, not
13837 ten!  Something is wrong!
13839 The problem is twofold: @code{count-words-region} does not count the
13840 @samp{*} as a word, and it counts the single symbol,
13841 @code{multiply-by-seven}, as containing three words.  The hyphens are
13842 treated as if they were interword spaces rather than intraword
13843 connectors: @samp{multiply-by-seven} is counted as if it were written
13844 @samp{multiply by seven}.
13846 The cause of this confusion is the regular expression search within
13847 the @code{count-words-region} definition that moves point forward word
13848 by word.  In the canonical version of @code{count-words-region}, the
13849 regexp is:
13851 @smallexample
13852 "\\w+\\W*"
13853 @end smallexample
13855 @noindent
13856 This regular expression is a pattern defining one or more word
13857 constituent characters possibly followed by one or more characters
13858 that are not word constituents.  What is meant by `word constituent
13859 characters' brings us to the issue of syntax, which is worth a section
13860 of its own.
13862 @node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13863 @section What Constitutes a Word or Symbol?
13864 @cindex Syntax categories and tables
13866 Emacs treats different characters as belonging to different
13867 @dfn{syntax categories}.  For example, the regular expression,
13868 @samp{\\w+}, is a pattern specifying one or more @emph{word
13869 constituent} characters.  Word constituent characters are members of
13870 one syntax category.  Other syntax categories include the class of
13871 punctuation characters, such as the period and the comma, and the
13872 class of whitespace characters, such as the blank space and the tab
13873 character.  (For more information, see @ref{Syntax, Syntax, The Syntax
13874 Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13875 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13877 Syntax tables specify which characters belong to which categories.
13878 Usually, a hyphen is not specified as a `word constituent character'.
13879 Instead, it is specified as being in the `class of characters that are
13880 part of symbol names but not words.'  This means that the
13881 @code{count-words-region} function treats it in the same way it treats
13882 an interword white space, which is why @code{count-words-region}
13883 counts @samp{multiply-by-seven} as three words.
13885 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13886 one symbol: modify the syntax table or modify the regular expression.
13888 We could redefine a hyphen as a word constituent character by
13889 modifying the syntax table that Emacs keeps for each mode.  This
13890 action would serve our purpose, except that a hyphen is merely the
13891 most common character within symbols that is not typically a word
13892 constituent character; there are others, too.
13894 Alternatively, we can redefine the regular expression used in the
13895 @code{count-words} definition so as to include symbols.  This
13896 procedure has the merit of clarity, but the task is a little tricky.
13898 @need 1200
13899 The first part is simple enough: the pattern must match ``at least one
13900 character that is a word or symbol constituent''.  Thus:
13902 @smallexample
13903 "\\(\\w\\|\\s_\\)+"
13904 @end smallexample
13906 @noindent
13907 The @samp{\\(} is the first part of the grouping construct that
13908 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13909 by the @samp{\\|}.  The @samp{\\w} matches any word-constituent
13910 character and the @samp{\\s_} matches any character that is part of a
13911 symbol name but not a word-constituent character.  The @samp{+}
13912 following the group indicates that the word or symbol constituent
13913 characters must be matched at least once.
13915 However, the second part of the regexp is more difficult to design.
13916 What we want is to follow the first part with ``optionally one or more
13917 characters that are not constituents of a word or symbol''.  At first,
13918 I thought I could define this with the following:
13920 @smallexample
13921 "\\(\\W\\|\\S_\\)*"
13922 @end smallexample
13924 @noindent
13925 The upper case @samp{W} and @samp{S} match characters that are
13926 @emph{not} word or symbol constituents.  Unfortunately, this
13927 expression matches any character that is either not a word constituent
13928 or not a symbol constituent.  This matches any character!
13930 I then noticed that every word or symbol in my test region was
13931 followed by white space (blank space, tab, or newline).  So I tried
13932 placing a pattern to match one or more blank spaces after the pattern
13933 for one or more word or symbol constituents.  This failed, too.  Words
13934 and symbols are often separated by whitespace, but in actual code
13935 parentheses may follow symbols and punctuation may follow words.  So
13936 finally, I designed a pattern in which the word or symbol constituents
13937 are followed optionally by characters that are not white space and
13938 then followed optionally by white space.
13940 @need 800
13941 Here is the full regular expression:
13943 @smallexample
13944 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13945 @end smallexample
13947 @node count-words-in-defun, Several defuns, Syntax, Words in a defun
13948 @section The @code{count-words-in-defun} Function
13949 @cindex Counting words in a @code{defun}
13951 We have seen that there are several ways to write a
13952 @code{count-word-region} function.  To write a
13953 @code{count-words-in-defun}, we need merely adapt one of these
13954 versions.
13956 The version that uses a @code{while} loop is easy to understand, so I
13957 am going to adapt that.  Because @code{count-words-in-defun} will be
13958 part of a more complex program, it need not be interactive and it need
13959 not display a message but just return the count.  These considerations
13960 simplify the definition a little.
13962 On the other hand, @code{count-words-in-defun} will be used within a
13963 buffer that contains function definitions.  Consequently, it is
13964 reasonable to ask that the function determine whether it is called
13965 when point is within a function definition, and if it is, to return
13966 the count for that definition.  This adds complexity to the
13967 definition, but saves us from needing to pass arguments to the
13968 function.
13970 @need 1250
13971 These considerations lead us to prepare the following template:
13973 @smallexample
13974 @group
13975 (defun count-words-in-defun ()
13976   "@var{documentation}@dots{}"
13977   (@var{set up}@dots{}
13978      (@var{while loop}@dots{})
13979    @var{return count})
13980 @end group
13981 @end smallexample
13983 @noindent
13984 As usual, our job is to fill in the slots.
13986 First, the set up.
13988 We are presuming that this function will be called within a buffer
13989 containing function definitions.  Point will either be within a
13990 function definition or not.  For @code{count-words-in-defun} to work,
13991 point must move to the beginning of the definition, a counter must
13992 start at zero, and the counting loop must stop when point reaches the
13993 end of the definition.
13995 The @code{beginning-of-defun} function searches backwards for an
13996 opening delimiter such as a @samp{(} at the beginning of a line, and
13997 moves point to that position, or else to the limit of the search.  In
13998 practice, this means that @code{beginning-of-defun} moves point to the
13999 beginning of an enclosing or preceding function definition, or else to
14000 the beginning of the buffer.  We can use @code{beginning-of-defun} to
14001 place point where we wish to start.
14003 The @code{while} loop requires a counter to keep track of the words or
14004 symbols being counted.  A @code{let} expression can be used to create
14005 a local variable for this purpose, and bind it to an initial value of zero.
14007 The @code{end-of-defun} function works like @code{beginning-of-defun}
14008 except that it moves point to the end of the definition.
14009 @code{end-of-defun} can be used as part of an expression that
14010 determines the position of the end of the definition.
14012 The set up for @code{count-words-in-defun} takes shape rapidly: first
14013 we move point to the beginning of the definition, then we create a
14014 local variable to hold the count, and finally, we record the position
14015 of the end of the definition so the @code{while} loop will know when to stop
14016 looping.
14018 @need 1250
14019 The code looks like this:
14021 @smallexample
14022 @group
14023 (beginning-of-defun)
14024 (let ((count 0)
14025       (end (save-excursion (end-of-defun) (point))))
14026 @end group
14027 @end smallexample
14029 @noindent
14030 The code is simple.  The only slight complication is likely to concern
14031 @code{end}: it is bound to the position of the end of the definition
14032 by a @code{save-excursion} expression that returns the value of point
14033 after @code{end-of-defun} temporarily moves it to the end of the
14034 definition.
14036 The second part of the @code{count-words-in-defun}, after the set up,
14037 is the @code{while} loop.
14039 The loop must contain an expression that jumps point forward word by
14040 word and symbol by symbol, and another expression that counts the
14041 jumps.  The true-or-false-test for the @code{while} loop should test
14042 true so long as point should jump forward, and false when point is at
14043 the end of the definition.  We have already redefined the regular
14044 expression for this (@pxref{Syntax}), so the loop is straightforward:
14046 @smallexample
14047 @group
14048 (while (and (< (point) end)
14049             (re-search-forward
14050              "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14051   (setq count (1+ count)))
14052 @end group
14053 @end smallexample
14055 The third part of the function definition returns the count of words
14056 and symbols.  This part is the last expression within the body of the
14057 @code{let} expression, and can be, very simply, the local variable
14058 @code{count}, which when evaluated returns the count.
14060 @need 1250
14061 Put together, the @code{count-words-in-defun} definition looks like this:
14063 @findex count-words-in-defun
14064 @smallexample
14065 @group
14066 (defun count-words-in-defun ()
14067   "Return the number of words and symbols in a defun."
14068   (beginning-of-defun)
14069   (let ((count 0)
14070         (end (save-excursion (end-of-defun) (point))))
14071 @end group
14072 @group
14073     (while
14074         (and (< (point) end)
14075              (re-search-forward
14076               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14077               end t))
14078       (setq count (1+ count)))
14079     count))
14080 @end group
14081 @end smallexample
14083 How to test this?  The function is not interactive, but it is easy to
14084 put a wrapper around the function to make it interactive; we can use
14085 almost the same code as for the recursive version of
14086 @code{count-words-region}:
14088 @smallexample
14089 @group
14090 ;;; @r{Interactive version.}
14091 (defun count-words-defun ()
14092   "Number of words and symbols in a function definition."
14093   (interactive)
14094   (message
14095    "Counting words and symbols in function definition ... ")
14096 @end group
14097 @group
14098   (let ((count (count-words-in-defun)))
14099     (cond
14100      ((zerop count)
14101       (message
14102        "The definition does NOT have any words or symbols."))
14103 @end group
14104 @group
14105      ((= 1 count)
14106       (message
14107        "The definition has 1 word or symbol."))
14108      (t
14109       (message
14110        "The definition has %d words or symbols." count)))))
14111 @end group
14112 @end smallexample
14114 @need 800
14115 @noindent
14116 Let's re-use @kbd{C-c =} as a convenient keybinding:
14118 @smallexample
14119 (global-set-key "\C-c=" 'count-words-defun)
14120 @end smallexample
14122 Now we can try out @code{count-words-defun}: install both
14123 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14124 keybinding, and then place the cursor within the following definition:
14126 @smallexample
14127 @group
14128 (defun multiply-by-seven (number)
14129   "Multiply NUMBER by seven."
14130   (* 7 number))
14131      @result{} 10
14132 @end group
14133 @end smallexample
14135 @noindent
14136 Success!  The definition has 10 words and symbols.
14138 The next problem is to count the numbers of words and symbols in
14139 several definitions within a single file.
14141 @node Several defuns, Find a File, count-words-in-defun, Words in a defun
14142 @section Count Several @code{defuns} Within a File
14144 A file such as @file{simple.el} may have 80 or more function
14145 definitions within it.  Our long term goal is to collect statistics on
14146 many files, but as a first step, our immediate goal is to collect
14147 statistics on one file.
14149 The information will be a series of numbers, each number being the
14150 length of a function definition.  We can store the numbers in a list.
14152 We know that we will want to incorporate the information regarding one
14153 file with information about many other files; this means that the
14154 function for counting definition lengths within one file need only
14155 return the list of lengths.  It need not and should not display any
14156 messages.
14158 The word count commands contain one expression to jump point forward
14159 word by word and another expression to count the jumps.  The function
14160 to return the lengths of definitions can be designed to work the same
14161 way, with one expression to jump point forward definition by
14162 definition and another expression to construct the lengths' list.
14164 This statement of the problem makes it elementary to write the
14165 function definition.  Clearly, we will start the count at the
14166 beginning of the file, so the first command will be @code{(goto-char
14167 (point-min))}.  Next, we start the @code{while} loop; and the
14168 true-or-false test of the loop can be a regular expression search for
14169 the next function definition---so long as the search succeeds, point
14170 is moved forward and then the body of the loop is evaluated.  The body
14171 needs an expression that constructs the lengths' list.  @code{cons},
14172 the list construction command, can be used to create the list.  That
14173 is almost all there is to it.
14175 @need 800
14176 Here is what this fragment of code looks like:
14178 @smallexample
14179 @group
14180 (goto-char (point-min))
14181 (while (re-search-forward "^(defun" nil t)
14182   (setq lengths-list
14183         (cons (count-words-in-defun) lengths-list)))
14184 @end group
14185 @end smallexample
14187 What we have left out is the mechanism for finding the file that
14188 contains the function definitions.
14190 In previous examples, we either used this, the Info file, or we
14191 switched back and forth to some other buffer, such as the
14192 @file{*scratch*} buffer.
14194 Finding a file is a new process that we have not yet discussed.
14196 @node Find a File, lengths-list-file, Several defuns, Words in a defun
14197 @comment  node-name,  next,  previous,  up
14198 @section Find a File
14199 @cindex Find a File
14201 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14202 command.  This command is almost, but not quite right for the lengths
14203 problem.
14205 @need 1200
14206 Let's look at the source for @code{find-file} (you can use the
14207 @code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14208 find the source of a function):
14210 @smallexample
14211 @group
14212 (defun find-file (filename)
14213   "Edit file FILENAME.
14214 Switch to a buffer visiting file FILENAME,
14215 creating one if none already exists."
14216   (interactive "FFind file: ")
14217   (switch-to-buffer (find-file-noselect filename)))
14218 @end group
14219 @end smallexample
14221 The definition possesses short but complete documentation and an
14222 interactive specification that prompts you for a file name when you
14223 use the command interactively.  The body of the definition contains
14224 two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14226 According to its documentation as shown by @kbd{C-h f} (the
14227 @code{describe-function} command), the @code{find-file-noselect}
14228 function reads the named file into a buffer and returns the buffer.
14229 However, the buffer is not selected.  Emacs does not switch its
14230 attention (or yours if you are using @code{find-file-noselect}) to the
14231 named buffer.  That is what @code{switch-to-buffer} does: it switches
14232 the buffer to which Emacs attention is directed; and it switches the
14233 buffer displayed in the window to the new buffer.  We have discussed
14234 buffer switching elsewhere.  (@xref{Switching Buffers}.)
14236 In this histogram project, we do not need to display each file on the
14237 screen as the program determines the length of each definition within
14238 it.  Instead of employing @code{switch-to-buffer}, we can work with
14239 @code{set-buffer}, which redirects the attention of the computer
14240 program to a different buffer but does not redisplay it on the screen.
14241 So instead of calling on @code{find-file} to do the job, we must write
14242 our own expression.
14244 The task is easy: use  @code{find-file-noselect} and @code{set-buffer}.
14246 @node lengths-list-file, Several files, Find a File, Words in a defun
14247 @section @code{lengths-list-file} in Detail
14249 The core of the @code{lengths-list-file} function is a @code{while}
14250 loop containing a function to move point forward `defun by defun' and
14251 a function to count the number of words and symbols in each defun.
14252 This core must be surrounded by functions that do various other tasks,
14253 including finding the file, and ensuring that point starts out at the
14254 beginning of the file.  The function definition looks like this:
14255 @findex lengths-list-file
14257 @smallexample
14258 @group
14259 (defun lengths-list-file (filename)
14260   "Return list of definitions' lengths within FILE.
14261 The returned list is a list of numbers.
14262 Each number is the number of words or
14263 symbols in one function definition."
14264 @end group
14265 @group
14266   (message "Working on `%s' ... " filename)
14267   (save-excursion
14268     (let ((buffer (find-file-noselect filename))
14269           (lengths-list))
14270       (set-buffer buffer)
14271       (setq buffer-read-only t)
14272       (widen)
14273       (goto-char (point-min))
14274       (while (re-search-forward "^(defun" nil t)
14275         (setq lengths-list
14276               (cons (count-words-in-defun) lengths-list)))
14277       (kill-buffer buffer)
14278       lengths-list)))
14279 @end group
14280 @end smallexample
14282 @noindent
14283 The function is passed one argument, the name of the file on which it
14284 will work.  It has four lines of documentation, but no interactive
14285 specification.  Since people worry that a computer is broken if they
14286 don't see anything going on, the first line of the body is a
14287 message.
14289 The next line contains a @code{save-excursion} that returns Emacs'
14290 attention to the current buffer when the function completes.  This is
14291 useful in case you embed this function in another function that
14292 presumes point is restored to the original buffer.
14294 In the varlist of the @code{let} expression, Emacs finds the file and
14295 binds the local variable @code{buffer} to the buffer containing the
14296 file.  At the same time, Emacs creates @code{lengths-list} as a local
14297 variable.
14299 Next, Emacs switches its attention to the buffer.
14301 In the following line, Emacs makes the buffer read-only.  Ideally,
14302 this line is not necessary.  None of the functions for counting words
14303 and symbols in a function definition should change the buffer.
14304 Besides, the buffer is not going to be saved, even if it were changed.
14305 This line is entirely the consequence of great, perhaps excessive,
14306 caution.  The reason for the caution is that this function and those
14307 it calls work on the sources for Emacs and it is very inconvenient if
14308 they are inadvertently modified.  It goes without saying that I did
14309 not realize a need for this line until an experiment went awry and
14310 started to modify my Emacs source files @dots{}
14312 Next comes a call to widen the buffer if it is narrowed.  This
14313 function is usually not needed---Emacs creates a fresh buffer if none
14314 already exists; but if a buffer visiting the file already exists Emacs
14315 returns that one.  In this case, the buffer may be narrowed and must
14316 be widened.  If we wanted to be fully `user-friendly', we would
14317 arrange to save the restriction and the location of point, but we
14318 won't.
14320 The @code{(goto-char (point-min))} expression moves point to the
14321 beginning of the buffer.
14323 Then comes a @code{while} loop in which the `work' of the function is
14324 carried out.  In the loop, Emacs determines the length of each
14325 definition and constructs a lengths' list containing the information.
14327 Emacs kills the buffer after working through it.  This is to save
14328 space inside of Emacs.  My version of Emacs 19 contained over 300
14329 source files of interest; Emacs 21 contains over 800 source files.
14330 Another function will apply @code{lengths-list-file} to each of the
14331 files.
14333 Finally, the last expression within the @code{let} expression is the
14334 @code{lengths-list} variable; its value is returned as the value of
14335 the whole function.
14337 You can try this function by installing it in the usual fashion.  Then
14338 place your cursor after the following expression and type @kbd{C-x
14339 C-e} (@code{eval-last-sexp}).
14341 @c !!! 21.0.100 lisp sources location here
14342 @smallexample
14343 (lengths-list-file
14344  "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14345 @end smallexample
14347 @c was: (lengths-list-file "../lisp/debug.el")
14348 @c !!!  as of 21, Info file is in
14349 @c /usr/share/info/emacs-lisp-intro.info.gz
14350 @c but debug.el is in  /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14352 @noindent
14353 (You may need to change the pathname of the file; the one here worked
14354 with GNU Emacs version 21.0.100.  To change the expression, copy it to
14355 the @file{*scratch*} buffer and edit it.
14357 @need 1200
14358 @noindent
14359 (Also, to see the full length of the list, rather than a truncated
14360 version, you may have to evaluate the following:
14362 @smallexample
14363 (custom-set-variables '(eval-expression-print-length nil))
14364 @end smallexample
14366 @noindent
14367 (@xref{defcustom, , Setting Variables with @code{defcustom}}.
14368 Then evaluate the @code{lengths-list-file} expression.)
14370 @need 1200
14371 The lengths' list for @file{debug.el} takes less than a second to
14372 produce and looks like this:
14374 @smallexample
14375 (77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14376 @end smallexample
14378 @need 1500
14379 (Using my old machine, the version 19 lengths' list for @file{debug.el}
14380 took seven seconds to produce and looked like this:
14382 @smallexample
14383 (75 41 80 62 20 45 44 68 45 12 34 235)
14384 @end smallexample
14386 (The newer version of  @file{debug.el} contains more defuns than the
14387 earlier one; and my new machine is much faster than the old one.)
14389 Note that the length of the last definition in the file is first in
14390 the list.
14392 @node Several files, Several files recursively, lengths-list-file, Words in a defun
14393 @section Count Words in @code{defuns} in Different Files
14395 In the previous section, we created a function that returns a list of
14396 the lengths of each definition in a file.  Now, we want to define a
14397 function to return a master list of the lengths of the definitions in
14398 a list of files.
14400 Working on each of a list of files is a repetitious act, so we can use
14401 either a @code{while} loop or recursion.
14403 @menu
14404 * lengths-list-many-files::     Return a list of the lengths of defuns.
14405 * append::                      Attach one list to another.
14406 @end menu
14408 @node lengths-list-many-files, append, Several files, Several files
14409 @ifnottex
14410 @unnumberedsubsec Determine the lengths of @code{defuns}
14411 @end ifnottex
14413 The design using a @code{while} loop is routine.  The argument passed
14414 the function is a list of files.  As we saw earlier (@pxref{Loop
14415 Example}), you can write a @code{while} loop so that the body of the
14416 loop is evaluated if such a list contains elements, but to exit the
14417 loop if the list is empty.  For this design to work, the body of the
14418 loop must contain an expression that shortens the list each time the
14419 body is evaluated, so that eventually the list is empty.  The usual
14420 technique is to set the value of the list to the value of the @sc{cdr}
14421 of the list each time the body is evaluated.
14423 @need 800
14424 The template looks like this:
14426 @smallexample
14427 @group
14428 (while @var{test-whether-list-is-empty}
14429   @var{body}@dots{}
14430   @var{set-list-to-cdr-of-list})
14431 @end group
14432 @end smallexample
14434 Also, we remember that a @code{while} loop returns @code{nil} (the
14435 result of evaluating the true-or-false-test), not the result of any
14436 evaluation within its body.  (The evaluations within the body of the
14437 loop are done for their side effects.)  However, the expression that
14438 sets the lengths' list is part of the body---and that is the value
14439 that we want returned by the function as a whole.  To do this, we
14440 enclose the @code{while} loop within a @code{let} expression, and
14441 arrange that the last element of the @code{let} expression contains
14442 the value of the lengths' list.  (@xref{Incrementing Example, , Loop
14443 Example with an Incrementing Counter}.)
14445 @findex lengths-list-many-files
14446 @need 1250
14447 These considerations lead us directly to the function itself:
14449 @smallexample
14450 @group
14451 ;;; @r{Use @code{while} loop.}
14452 (defun lengths-list-many-files (list-of-files)
14453   "Return list of lengths of defuns in LIST-OF-FILES."
14454 @end group
14455 @group
14456   (let (lengths-list)
14458 ;;; @r{true-or-false-test}
14459     (while list-of-files
14460       (setq lengths-list
14461             (append
14462              lengths-list
14464 ;;; @r{Generate a lengths' list.}
14465              (lengths-list-file
14466               (expand-file-name (car list-of-files)))))
14467 @end group
14469 @group
14470 ;;; @r{Make files' list shorter.}
14471       (setq list-of-files (cdr list-of-files)))
14473 ;;; @r{Return final value of lengths' list.}
14474     lengths-list))
14475 @end group
14476 @end smallexample
14478 @code{expand-file-name} is a built-in function that converts a file
14479 name to the absolute, long, path name form of the directory in which
14480 the function is called.
14482 @c !!! 21.0.100 lisp sources location here
14483 @need 1500
14484 Thus, if @code{expand-file-name} is called on @code{debug.el} when
14485 Emacs is visiting the
14486 @file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14488 @smallexample
14489 debug.el
14490 @end smallexample
14492 @need 800
14493 @noindent
14494 becomes
14496 @c !!! 21.0.100 lisp sources location here
14497 @smallexample
14498 /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14499 @end smallexample
14501 The only other new element of this function definition is the as yet
14502 unstudied function @code{append}, which merits a short section for
14503 itself.
14505 @node append,  , lengths-list-many-files, Several files
14506 @subsection The @code{append} Function
14508 @need 800
14509 The @code{append} function attaches one list to another.  Thus,
14511 @smallexample
14512 (append '(1 2 3 4) '(5 6 7 8))
14513 @end smallexample
14515 @need 800
14516 @noindent
14517 produces the list
14519 @smallexample
14520 (1 2 3 4 5 6 7 8)
14521 @end smallexample
14523 This is exactly how we want to attach two lengths' lists produced by
14524 @code{lengths-list-file} to each other.  The results contrast with
14525 @code{cons},
14527 @smallexample
14528 (cons '(1 2 3 4) '(5 6 7 8))
14529 @end smallexample
14531 @need 1250
14532 @noindent
14533 which constructs a new list in which the first argument to @code{cons}
14534 becomes the first element of the new list:
14536 @smallexample
14537 ((1 2 3 4) 5 6 7 8)
14538 @end smallexample
14540 @node Several files recursively, Prepare the data, Several files, Words in a defun
14541 @section Recursively Count Words in Different Files
14543 Besides a @code{while} loop, you can work on each of a list of files
14544 with recursion.  A recursive version of @code{lengths-list-many-files}
14545 is short and simple.
14547 The recursive function has the usual parts: the `do-again-test', the
14548 `next-step-expression', and the recursive call.  The `do-again-test'
14549 determines whether the function should call itself again, which it
14550 will do if the @code{list-of-files} contains any remaining elements;
14551 the `next-step-expression' resets the @code{list-of-files} to the
14552 @sc{cdr} of itself, so eventually the list will be empty; and the
14553 recursive call calls itself on the shorter list.  The complete
14554 function is shorter than this description!
14555 @findex recursive-lengths-list-many-files
14557 @smallexample
14558 @group
14559 (defun recursive-lengths-list-many-files (list-of-files)
14560   "Return list of lengths of each defun in LIST-OF-FILES."
14561   (if list-of-files                     ; @r{do-again-test}
14562       (append
14563        (lengths-list-file
14564         (expand-file-name (car list-of-files)))
14565        (recursive-lengths-list-many-files
14566         (cdr list-of-files)))))
14567 @end group
14568 @end smallexample
14570 @noindent
14571 In a sentence, the function returns the lengths' list for the first of
14572 the @code{list-of-files} appended to the result of calling itself on
14573 the rest of the @code{list-of-files}.
14575 Here is a test of @code{recursive-lengths-list-many-files}, along with
14576 the results of running @code{lengths-list-file} on each of the files
14577 individually.
14579 Install @code{recursive-lengths-list-many-files} and
14580 @code{lengths-list-file}, if necessary, and then evaluate the
14581 following expressions.  You may need to change the files' pathnames;
14582 those here work when this Info file and the Emacs sources are located
14583 in their customary places.  To change the expressions, copy them to
14584 the @file{*scratch*} buffer, edit them, and then evaluate them.
14586 The results are shown after the @samp{@result{}}.  (These results are
14587 for files from Emacs Version 21.0.100; files from other versions of
14588 Emacs may produce different results.)
14590 @c !!! 21.0.100 lisp sources location here
14591 @smallexample
14592 @group
14593 (cd "/usr/local/share/emacs/21.0.100/")
14595 (lengths-list-file "./lisp/macros.el")
14596      @result{} (273 263 456 90)
14597 @end group
14599 @group
14600 (lengths-list-file "./lisp/mail/mailalias.el")
14601      @result{} (38 32 26 77 174 180 321 198 324)
14602 @end group
14604 @group
14605 (lengths-list-file "./lisp/makesum.el")
14606      @result{} (85 181)
14607 @end group
14609 @group
14610 (recursive-lengths-list-many-files
14611  '("./lisp/macros.el"
14612    "./lisp/mail/mailalias.el"
14613    "./lisp/makesum.el"))
14614        @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14615 @end group
14616 @end smallexample
14618 The @code{recursive-lengths-list-many-files} function produces the
14619 output we want.
14621 The next step is to prepare the data in the list for display in a graph.
14623 @node Prepare the data,  , Several files recursively, Words in a defun
14624 @section Prepare the Data for Display in a Graph
14626 The @code{recursive-lengths-list-many-files} function returns a list
14627 of numbers.  Each number records the length of a function definition.
14628 What we need to do now is transform this data into a list of numbers
14629 suitable for generating a graph.  The new list will tell how many
14630 functions definitions contain less than 10 words and
14631 symbols, how many contain between 10 and 19 words and symbols, how
14632 many contain between 20 and 29 words and symbols, and so on.
14634 In brief, we need to go through the lengths' list produced by the
14635 @code{recursive-lengths-list-many-files} function and count the number
14636 of defuns within each range of lengths, and produce a list of those
14637 numbers.
14639 Based on what we have done before, we can readily foresee that it
14640 should not be too hard to write a function that `@sc{cdr}s' down the
14641 lengths' list, looks at each element, determines which length range it
14642 is in, and increments a counter for that range.
14644 However, before beginning to write such a function, we should consider
14645 the advantages of sorting the lengths' list first, so the numbers are
14646 ordered from smallest to largest.  First, sorting will make it easier
14647 to count the numbers in each range, since two adjacent numbers will
14648 either be in the same length range or in adjacent ranges.  Second, by
14649 inspecting a sorted list, we can discover the highest and lowest
14650 number, and thereby determine the largest and smallest length range
14651 that we will need.
14653 @menu
14654 * Sorting::                     Sorting lists.
14655 * Files List::                  Making a list of files.
14656 * Counting function definitions::
14657 @end menu
14659 @node Sorting, Files List, Prepare the data, Prepare the data
14660 @subsection Sorting Lists
14661 @findex sort
14663 Emacs contains a function to sort lists, called (as you might guess)
14664 @code{sort}.  The @code{sort} function takes two arguments, the list
14665 to be sorted, and a predicate that determines whether the first of
14666 two list elements is ``less'' than the second.
14668 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14669 Type Object as an Argument}), a predicate is a function that
14670 determines whether some property is true or false.  The @code{sort}
14671 function will reorder a list according to whatever property the
14672 predicate uses; this means that @code{sort} can be used to sort
14673 non-numeric lists by non-numeric criteria---it can, for example,
14674 alphabetize a list.
14676 @need 1250
14677 The @code{<} function is used when sorting a numeric list.  For example,
14679 @smallexample
14680 (sort '(4 8 21 17 33 7 21 7) '<)
14681 @end smallexample
14683 @need 800
14684 @noindent
14685 produces this:
14687 @smallexample
14688 (4 7 7 8 17 21 21 33)
14689 @end smallexample
14691 @noindent
14692 (Note that in this example, both the arguments are quoted so that the
14693 symbols are not evaluated before being passed to @code{sort} as
14694 arguments.)
14696 Sorting the list returned by the
14697 @code{recursive-lengths-list-many-files} function is straightforward;
14698 it uses the @code{<} function:
14700 @smallexample
14701 @group
14702 (sort
14703  (recursive-lengths-list-many-files
14704   '("../lisp/macros.el"
14705     "../lisp/mailalias.el"
14706     "../lisp/makesum.el"))
14707  '<
14708 @end group
14709 @end smallexample
14711 @need 800
14712 @noindent
14713 which produces:
14715 @smallexample
14716 (85 86 116 122 154 176 179 265)
14717 @end smallexample
14719 @noindent
14720 (Note that in this example, the first argument to @code{sort} is not
14721 quoted, since the expression must be evaluated so as to produce the
14722 list that is passed to @code{sort}.)
14724 @node Files List, Counting function definitions, Sorting, Prepare the data
14725 @subsection Making a List of Files
14727 The @code{recursive-lengths-list-many-files} function requires a list
14728 of files as its argument.  For our test examples, we constructed such
14729 a list by hand; but the Emacs Lisp source directory is too large for
14730 us to do for that.  Instead, we will write a function to do the job
14731 for us.  In this function, we will use both a @code{while} loop and a
14732 recursive call.
14734 @findex directory-files
14735 We did not have to write a function like this for older versions of
14736 GNU Emacs, since they placed all the @samp{.el} files in one
14737 directory.  Instead, we were able to use the @code{directory-files}
14738 function, which lists the names of files that match a specified
14739 pattern within a single directory.
14741 However, recent versions of Emacs place Emacs Lisp files in
14742 sub-directories of the top level @file{lisp} directory.  This
14743 re-arrangement eases navigation.  For example, all the mail related
14744 files are in a @file{lisp} sub-directory called @file{mail}.  But at
14745 the same time, this arrangement forces us to create a file listing
14746 function that descends into the sub-directories.
14748 @findex files-in-below-directory
14749 We can create this function, called @code{files-in-below-directory},
14750 using familiar functions such as @code{car}, @code{nthcdr}, and
14751 @code{substring} in conjunction with an existing function called
14752 @code{directory-files-and-attributes}.  This latter function not only
14753 lists all the filenames in a directory, including the names
14754 of sub-directories, but also their attributes.
14756 To restate our goal: to create a function that will enable us
14757 to feed filenames to @code{recursive-lengths-list-many-files}
14758 as a list that looks like this (but with more elements):
14760 @smallexample
14761 @group
14762 ("../lisp/macros.el"
14763  "../lisp/mail/rmail.el"
14764  "../lisp/makesum.el")
14765 @end group
14766 @end smallexample
14768 The @code{directory-files-and-attributes} function returns a list of
14769 lists.  Each of the lists within the main list consists of 13
14770 elements.  The first element is a string that contains the name of the
14771 file -- which, in GNU/Linux, may be a `directory file', that is to
14772 say, a file with the special attributes of a directory.  The second
14773 element of the list is @code{t} for a directory, a string
14774 for symbolic link (the string is the name linked to), or @code{nil}.
14776 For example, the first @samp{.el} file in the @file{lisp/} directory
14777 is @file{abbrev.el}.  Its name is
14778 @file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14779 directory or a symbolic link.
14781 @need 1000
14782 This is how @code{directory-files-and-attributes} lists that file and
14783 its attributes:
14785 @smallexample
14786 @group
14787 ("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14790 1000
14792 @end group
14793 @group
14794 (15019 32380)
14795 (14883 48041)
14796 (15214 49336)
14797 11583
14798 "-rw-rw-r--"
14799 @end group
14800 @group
14802 341385
14803 776)
14804 @end group
14805 @end smallexample
14807 @need 1200
14808 On the other hand, @file{mail/} is a directory within the @file{lisp/}
14809 directory.  The beginning of its listing looks like this:
14811 @smallexample
14812 @group
14813 ("/usr/local/share/emacs/21.0.100/lisp/mail"
14815 @dots{}
14817 @end group
14818 @end smallexample
14820 (Look at the documentation of @code{file-attributes} to learn about
14821 the different attributes.  Bear in mind that the
14822 @code{file-attributes} function does not list the filename, so its
14823 first element is @code{directory-files-and-attributes}'s second
14824 element.)
14826 We will want our new function, @code{files-in-below-directory}, to
14827 list the @samp{.el} files in the directory it is told to check, and in
14828 any directories below that directory.
14830 This gives us a hint on how to construct
14831 @code{files-in-below-directory}:  within a directory, the function
14832 should add @samp{.el} filenames to a list; and if, within a directory,
14833 the function comes upon a sub-directory, it should go into that
14834 sub-directory and repeat its actions.
14836 However, we should note that every directory contains a name that
14837 refers to itself, called @file{.}, (``dot'') and a name that refers to
14838 its parent directory, called @file{..} (``double dot'').  (In
14839 @file{/}, the root directory, @file{..} refers to itself, since
14840 @file{/} has no parent.)  Clearly, we do not want our
14841 @code{files-in-below-directory} function to enter those directories,
14842 since they always lead us, directly or indirectly, to the current
14843 directory.
14845 Consequently, our @code{files-in-below-directory} function must do
14846 several tasks:
14848 @itemize @bullet
14849 @item
14850 Check to see whether it is looking at a filename that ends in
14851 @samp{.el}; and if so, add its name to a list.
14853 @item
14854 Check to see whether it is looking at a filename that is the name of a
14855 directory; and if so,
14857 @itemize @minus
14858 @item
14859 Check to see whether it is looking at @file{.}  or @file{..}; and if
14860 so skip it.
14862 @item
14863 Or else, go into that directory and repeat the process.
14864 @end itemize
14865 @end itemize
14867 Let's write a function definition to do these tasks.  We will use a
14868 @code{while} loop to move from one filename to another within a
14869 directory, checking what needs to be done; and we will use a recursive
14870 call to repeat the actions on each sub-directory.  The recursive
14871 pattern is `accumulate'
14872 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14873 using @code{append} as the combiner.
14875 @ignore
14876 (directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14877 (shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14878 @end ignore
14880 @c  /usr/local/share/emacs/21.0.100/lisp/
14882 @need 800
14883 Here is the function:
14885 @smallexample
14886 @group
14887 (defun files-in-below-directory (directory)
14888   "List the .el files in DIRECTORY and in its sub-directories."
14889   ;; Although the function will be used non-interactively,
14890   ;; it will be easier to test if we make it interactive.
14891   ;; The directory will have a name such as
14892   ;;  "/usr/local/share/emacs/21.0.100/lisp/"
14893   (interactive "DDirectory name: ")
14894 @end group
14895 @group
14896   (let (el-files-list
14897         (current-directory-list
14898          (directory-files-and-attributes directory t)))
14899     ;; while we are in the current directory
14900     (while current-directory-list
14901 @end group
14902 @group
14903       (cond
14904        ;; check to see whether filename ends in `.el'
14905        ;; and if so, append its name to a list.
14906        ((equal ".el" (substring (car (car current-directory-list)) -3))
14907         (setq el-files-list
14908               (cons (car (car current-directory-list)) el-files-list)))
14909 @end group
14910 @group
14911        ;; check whether filename is that of a directory
14912        ((eq t (car (cdr (car current-directory-list))))
14913         ;; decide whether to skip or recurse
14914         (if
14915             (equal (or "." "..")
14916                    (substring (car (car current-directory-list)) -1))
14917             ;; then do nothing if filename is that of
14918             ;;   current directory or parent
14919             ()
14920 @end group
14921 @group
14922           ;; else descend into the directory and repeat the process
14923           (setq el-files-list
14924                 (append
14925                  (files-in-below-directory
14926                   (car (car current-directory-list)))
14927                  el-files-list)))))
14928       ;; move to the next filename in the list; this also
14929       ;; shortens the list so the while loop eventually comes to an end
14930       (setq current-directory-list (cdr current-directory-list)))
14931     ;; return the filenames
14932     el-files-list))
14933 @end group
14934 @end smallexample
14936 @c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14938 The @code{files-in-below-directory} @code{directory-files} function
14939 takes one argument, the name of a directory.
14941 @need 1250
14942 Thus, on my system,
14944 @c !!! 21.0.100 lisp sources location here
14945 @smallexample
14946 @group
14947 (length
14948  (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14949 @end group
14950 @end smallexample
14952 @noindent
14953 tells me that my version 21.0.100 Lisp sources directory contains 754
14954 @samp{.el} files.
14956 @code{files-in-below-directory} returns a list in reverse alphabetical
14957 order.  An expression to sort the list in alphabetical order looks
14958 like this:
14960 @smallexample
14961 @group
14962 (sort
14963  (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14964  'string-lessp)
14965 @end group
14966 @end smallexample
14968 @ignore
14969 (defun test ()
14970   "Test how long it takes to find lengths of all elisp defuns."
14971   (insert "\n" (current-time-string) "\n")
14972   (sit-for 0)
14973   (sort
14974    (recursive-lengths-list-many-files
14975     '("../lisp/macros.el"
14976       "../lisp/mailalias.el"
14977       "../lisp/makesum.el"))
14978    '<)
14979   (insert (format "%s" (current-time-string))))
14981 @end ignore
14983 @node Counting function definitions,  , Files List, Prepare the data
14984 @subsection Counting function definitions
14986 Our immediate goal is to generate a list that tells us how many
14987 function definitions contain fewer than 10 words and symbols, how many
14988 contain between 10 and 19 words and symbols, how many contain between
14989 20 and 29 words and symbols, and so on.
14991 With a sorted list of numbers, this is easy: count how many elements
14992 of the list are smaller than 10, then, after moving past the numbers
14993 just counted, count how many are smaller than 20, then, after moving
14994 past the numbers just counted, count how many are smaller than 30, and
14995 so on.  Each of the numbers, 10, 20, 30, 40, and the like, is one
14996 larger than the top of that range.  We can call the list of such
14997 numbers the @code{top-of-ranges} list.
14999 @need 1200
15000 If we wished, we could generate this list automatically, but it is
15001 simpler to write a list manually.  Here it is:
15002 @vindex top-of-ranges
15004 @smallexample
15005 @group
15006 (defvar top-of-ranges
15007  '(10  20  30  40  50
15008    60  70  80  90 100
15009   110 120 130 140 150
15010   160 170 180 190 200
15011   210 220 230 240 250
15012   260 270 280 290 300)
15013  "List specifying ranges for `defuns-per-range'.")
15014 @end group
15015 @end smallexample
15017 To change the ranges, we edit this list.
15019 Next, we need to write the function that creates the list of the
15020 number of definitions within each range.  Clearly, this function must
15021 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15022 as arguments.
15024 The @code{defuns-per-range} function must do two things again and
15025 again: it must count the number of definitions within a range
15026 specified by the current top-of-range value; and it must shift to the
15027 next higher value in the @code{top-of-ranges} list after counting the
15028 number of definitions in the current range.  Since each of these
15029 actions is repetitive, we can use @code{while} loops for the job.
15030 One loop counts the number of definitions in the range defined by the
15031 current top-of-range value, and the other loop selects each of the
15032 top-of-range values in turn.
15034 Several entries of the @code{sorted-lengths} list are counted for each
15035 range; this means that the loop for the @code{sorted-lengths} list
15036 will be inside the loop for the @code{top-of-ranges} list, like a
15037 small gear inside a big gear.
15039 The inner loop counts the number of definitions within the range.  It
15040 is a simple counting loop of the type we have seen before.
15041 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15042 The true-or-false test of the loop tests whether the value from the
15043 @code{sorted-lengths} list is smaller than the current value of the
15044 top of the range.  If it is, the function increments the counter and
15045 tests the next value from the @code{sorted-lengths} list.
15047 @need 1250
15048 The inner loop looks like this:
15050 @smallexample
15051 @group
15052 (while @var{length-element-smaller-than-top-of-range}
15053   (setq number-within-range (1+ number-within-range))
15054   (setq sorted-lengths (cdr sorted-lengths)))
15055 @end group
15056 @end smallexample
15058 The outer loop must start with the lowest value of the
15059 @code{top-of-ranges} list, and then be set to each of the succeeding
15060 higher values in turn.  This can be done with a loop like this:
15062 @smallexample
15063 @group
15064 (while top-of-ranges
15065   @var{body-of-loop}@dots{}
15066   (setq top-of-ranges (cdr top-of-ranges)))
15067 @end group
15068 @end smallexample
15070 @need 1200
15071 Put together, the two loops look like this:
15073 @smallexample
15074 @group
15075 (while top-of-ranges
15077   ;; @r{Count the number of elements within the current range.}
15078   (while @var{length-element-smaller-than-top-of-range}
15079     (setq number-within-range (1+ number-within-range))
15080     (setq sorted-lengths (cdr sorted-lengths)))
15082   ;; @r{Move to next range.}
15083   (setq top-of-ranges (cdr top-of-ranges)))
15084 @end group
15085 @end smallexample
15087 In addition, in each circuit of the outer loop, Emacs should record
15088 the number of definitions within that range (the value of
15089 @code{number-within-range}) in a list.  We can use @code{cons} for
15090 this purpose.  (@xref{cons, , @code{cons}}.)
15092 The @code{cons} function works fine, except that the list it
15093 constructs will contain the number of definitions for the highest
15094 range at its beginning and the number of definitions for the lowest
15095 range at its end.  This is because @code{cons} attaches new elements
15096 of the list to the beginning of the list, and since the two loops are
15097 working their way through the lengths' list from the lower end first,
15098 the @code{defuns-per-range-list} will end up largest number first.
15099 But we will want to print our graph with smallest values first and the
15100 larger later.  The solution is to reverse the order of the
15101 @code{defuns-per-range-list}.  We can do this using the
15102 @code{nreverse} function, which reverses the order of a list.
15103 @findex nreverse
15105 @need 800
15106 For example,
15108 @smallexample
15109 (nreverse '(1 2 3 4))
15110 @end smallexample
15112 @need 800
15113 @noindent
15114 produces:
15116 @smallexample
15117 (4 3 2 1)
15118 @end smallexample
15120 Note that the @code{nreverse} function is ``destructive''---that is,
15121 it changes the list to which it is applied; this contrasts with the
15122 @code{car} and @code{cdr} functions, which are non-destructive.  In
15123 this case, we do not want the original @code{defuns-per-range-list},
15124 so it does not matter that it is destroyed.  (The @code{reverse}
15125 function provides a reversed copy of a list, leaving the original list
15126 as is.)
15127 @findex reverse
15129 @need 1250
15130 Put all together, the @code{defuns-per-range} looks like this:
15132 @smallexample
15133 @group
15134 (defun defuns-per-range (sorted-lengths top-of-ranges)
15135   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15136   (let ((top-of-range (car top-of-ranges))
15137         (number-within-range 0)
15138         defuns-per-range-list)
15139 @end group
15141 @group
15142     ;; @r{Outer loop.}
15143     (while top-of-ranges
15144 @end group
15146 @group
15147       ;; @r{Inner loop.}
15148       (while (and
15149               ;; @r{Need number for numeric test.}
15150               (car sorted-lengths)
15151               (< (car sorted-lengths) top-of-range))
15152 @end group
15154 @group
15155         ;; @r{Count number of definitions within current range.}
15156         (setq number-within-range (1+ number-within-range))
15157         (setq sorted-lengths (cdr sorted-lengths)))
15159       ;; @r{Exit inner loop but remain within outer loop.}
15160 @end group
15162 @group
15163       (setq defuns-per-range-list
15164             (cons number-within-range defuns-per-range-list))
15165       (setq number-within-range 0)      ; @r{Reset count to zero.}
15166 @end group
15168 @group
15169       ;; @r{Move to next range.}
15170       (setq top-of-ranges (cdr top-of-ranges))
15171       ;; @r{Specify next top of range value.}
15172       (setq top-of-range (car top-of-ranges)))
15173 @end group
15175 @group
15176     ;; @r{Exit outer loop and count the number of defuns larger than}
15177     ;; @r{  the largest top-of-range value.}
15178     (setq defuns-per-range-list
15179           (cons
15180            (length sorted-lengths)
15181            defuns-per-range-list))
15182 @end group
15184 @group
15185     ;; @r{Return a list of the number of definitions within each range,}
15186     ;; @r{  smallest to largest.}
15187     (nreverse defuns-per-range-list)))
15188 @end group
15189 @end smallexample
15191 @need 1200
15192 @noindent
15193 The function is straightforward except for one subtle feature.  The
15194 true-or-false test of the inner loop looks like this:
15196 @smallexample
15197 @group
15198 (and (car sorted-lengths)
15199      (< (car sorted-lengths) top-of-range))
15200 @end group
15201 @end smallexample
15203 @need 800
15204 @noindent
15205 instead of like this:
15207 @smallexample
15208 (< (car sorted-lengths) top-of-range)
15209 @end smallexample
15211 The purpose of the test is to determine whether the first item in the
15212 @code{sorted-lengths} list is less than the value of the top of the
15213 range.
15215 The simple version of the test works fine unless the
15216 @code{sorted-lengths} list has a @code{nil} value.  In that case, the
15217 @code{(car sorted-lengths)} expression function returns
15218 @code{nil}.  The @code{<} function cannot compare a number to
15219 @code{nil}, which is an empty list, so Emacs signals an error and
15220 stops the function from attempting to continue to execute.
15222 The @code{sorted-lengths} list always becomes @code{nil} when the
15223 counter reaches the end of the list.  This means that any attempt to
15224 use the @code{defuns-per-range} function with the simple version of
15225 the test will fail.
15227 We solve the problem by using the @code{(car sorted-lengths)}
15228 expression in conjunction with the @code{and} expression.  The
15229 @code{(car sorted-lengths)} expression returns a non-@code{nil}
15230 value so long as the list has at least one number within it, but
15231 returns @code{nil} if the list is empty.  The @code{and} expression
15232 first evaluates the @code{(car sorted-lengths)} expression, and
15233 if it is @code{nil}, returns false @emph{without} evaluating the
15234 @code{<} expression.  But if the @code{(car sorted-lengths)}
15235 expression returns a non-@code{nil} value, the @code{and} expression
15236 evaluates the @code{<} expression, and returns that value as the value
15237 of the @code{and} expression.
15239 @c colon in printed section title causes problem in Info cross reference
15240 This way, we avoid an error.
15241 @iftex
15242 @xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15243 Functions}, for more information about @code{and}.
15244 @end iftex
15245 @ifinfo
15246 @xref{forward-paragraph}, for more information about @code{and}.
15247 @end ifinfo
15249 Here is a short test of the @code{defuns-per-range} function.  First,
15250 evaluate the expression that binds (a shortened)
15251 @code{top-of-ranges} list to the list of values, then evaluate the
15252 expression for binding the @code{sorted-lengths} list, and then
15253 evaluate the @code{defuns-per-range} function.
15255 @smallexample
15256 @group
15257 ;; @r{(Shorter list than we will use later.)}
15258 (setq top-of-ranges
15259  '(110 120 130 140 150
15260    160 170 180 190 200))
15262 (setq sorted-lengths
15263       '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15265 (defuns-per-range sorted-lengths top-of-ranges)
15266 @end group
15267 @end smallexample
15269 @need 800
15270 @noindent
15271 The list returned looks like this:
15273 @smallexample
15274 (2 2 2 0 0 1 0 2 0 0 4)
15275 @end smallexample
15277 @noindent
15278 Indeed, there are two elements of the @code{sorted-lengths} list
15279 smaller than 110, two elements between 110 and 119, two elements
15280 between 120 and 129, and so on.  There are four elements with a value
15281 of 200 or larger.
15283 @c The next step is to turn this numbers' list into a graph.
15285 @node Readying a Graph, Emacs Initialization, Words in a defun, Top
15286 @chapter Readying a Graph
15287 @cindex Readying a graph
15288 @cindex Graph prototype
15289 @cindex Prototype graph
15290 @cindex Body of graph
15292 Our goal is to construct a graph showing the numbers of function
15293 definitions of various lengths in the Emacs lisp sources.
15295 As a practical matter, if you were creating a graph, you would
15296 probably use a program such as @code{gnuplot} to do the job.
15297 (@code{gnuplot} is nicely integrated into GNU Emacs.)  In this case,
15298 however, we create one from scratch, and in the process we will
15299 re-acquaint ourselves with some of what we learned before and learn
15300 more.
15302 In this chapter, we will first write a simple graph printing function.
15303 This first definition will be a @dfn{prototype}, a rapidly written
15304 function that enables us to reconnoiter this unknown graph-making
15305 territory.  We will discover dragons, or find that they are myth.
15306 After scouting the terrain, we will feel more confident and enhance
15307 the function to label the axes automatically.
15309 @menu
15310 * Columns of a graph::
15311 * graph-body-print::            How to print the body of a graph.
15312 * recursive-graph-body-print::
15313 * Printed Axes::
15314 * Line Graph Exercise::
15315 @end menu
15317 @node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15318 @ifnottex
15319 @unnumberedsec Printing the Columns of a Graph
15320 @end ifnottex
15322 Since Emacs is designed to be flexible and work with all kinds of
15323 terminals, including character-only terminals, the graph will need to
15324 be made from one of the `typewriter' symbols.  An asterisk will do; as
15325 we enhance the graph-printing function, we can make the choice of
15326 symbol a user option.
15328 We can call this function @code{graph-body-print}; it will take a
15329 @code{numbers-list} as its only argument.  At this stage, we will not
15330 label the graph, but only print its body.
15332 The @code{graph-body-print} function inserts a vertical column of
15333 asterisks for each element in the @code{numbers-list}.  The height of
15334 each line is determined by the value of that element of the
15335 @code{numbers-list}.
15337 Inserting columns is a repetitive act; that means that this function can
15338 be written either with a @code{while} loop or recursively.
15340 Our first challenge is to discover how to print a column of asterisks.
15341 Usually, in Emacs, we print characters onto a screen horizontally,
15342 line by line, by typing.  We have two routes we can follow: write our
15343 own column-insertion function or discover whether one exists in Emacs.
15345 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15346 command.  This command is like the @kbd{C-h a} (command-apropos)
15347 command, except that the latter finds only those functions that are
15348 commands.  The @kbd{M-x apropos} command lists all symbols that match
15349 a regular expression, including functions that are not interactive.
15350 @findex apropos
15352 What we want to look for is some command that prints or inserts
15353 columns.  Very likely, the name of the function will contain either
15354 the word `print' or the word `insert' or the word `column'.
15355 Therefore, we can simply type @kbd{M-x apropos RET
15356 print\|insert\|column RET} and look at the result.  On my system, this
15357 command takes quite some time, and then produces a list of 79
15358 functions and variables.  Scanning down the list, the only function
15359 that looks as if it might do the job is @code{insert-rectangle}.
15361 @need 1200
15362 Indeed, this is the function we want; its documentation says:
15364 @smallexample
15365 @group
15366 insert-rectangle:
15367 Insert text of RECTANGLE with upper left corner at point.
15368 RECTANGLE's first line is inserted at point,
15369 its second line is inserted at a point vertically under point, etc.
15370 RECTANGLE should be a list of strings.
15371 @end group
15372 @end smallexample
15374 We can run a quick test, to make sure it does what we expect of it.
15376 Here is the result of placing the cursor after the
15377 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15378 (@code{eval-last-sexp}).  The function inserts the strings
15379 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15380 point.  Also the function returns @code{nil}.
15382 @smallexample
15383 @group
15384 (insert-rectangle '("first" "second" "third"))first
15385                                               second
15386                                               third
15388 @end group
15389 @end smallexample
15391 @noindent
15392 Of course, we won't be inserting the text of the
15393 @code{insert-rectangle} expression itself into the buffer in which we
15394 are making the graph, but will call the function from our program.  We
15395 shall, however, have to make sure that point is in the buffer at the
15396 place where the @code{insert-rectangle} function will insert its
15397 column of strings.
15399 If you are reading this in Info, you can see how this works by
15400 switching to another buffer, such as the @file{*scratch*} buffer,
15401 placing point somewhere in the buffer, typing @kbd{M-:},
15402 typing the @code{insert-rectangle} expression into the minibuffer at
15403 the prompt, and then typing @key{RET}.  This causes Emacs to evaluate
15404 the expression in the minibuffer, but to use as the value of point the
15405 position of point in the @file{*scratch*} buffer.  (@kbd{M-:}
15406 is the keybinding for @code{eval-expression}.)
15408 We find when we do this that point ends up at the end of the last
15409 inserted line---that is to say, this function moves point as a
15410 side-effect.  If we were to repeat the command, with point at this
15411 position, the next insertion would be below and to the right of the
15412 previous insertion.  We don't want this!  If we are going to make a
15413 bar graph, the columns need to be beside each other.
15415 So we discover that each cycle of the column-inserting @code{while}
15416 loop must reposition point to the place we want it, and that place
15417 will be at the top, not the bottom, of the column.  Moreover, we
15418 remember that when we print a graph, we do not expect all the columns
15419 to be the same height.  This means that the top of each column may be
15420 at a different height from the previous one.  We cannot simply
15421 reposition point to the same line each time, but moved over to the
15422 right---or perhaps we can@dots{}
15424 We are planning to make the columns of the bar graph out of asterisks.
15425 The number of asterisks in the column is the number specified by the
15426 current element of the @code{numbers-list}.  We need to construct a
15427 list of asterisks of the right length for each call to
15428 @code{insert-rectangle}.  If this list consists solely of the requisite
15429 number of asterisks, then we will have position point the right number
15430 of lines above the base for the graph to print correctly.  This could
15431 be difficult.
15433 Alternatively, if we can figure out some way to pass
15434 @code{insert-rectangle} a list of the same length each time, then we
15435 can place point on the same line each time, but move it over one
15436 column to the right for each new column.  If we do this, however, some
15437 of the entries in the list passed to @code{insert-rectangle} must be
15438 blanks rather than asterisks.  For example, if the maximum height of
15439 the graph is 5, but the height of the column is 3, then
15440 @code{insert-rectangle} requires an argument that looks like this:
15442 @smallexample
15443 (" " " " "*" "*" "*")
15444 @end smallexample
15446 This last proposal is not so difficult, so long as we can determine
15447 the column height.  There are two ways for us to specify the column
15448 height: we can arbitrarily state what it will be, which would work
15449 fine for graphs of that height; or we can search through the list of
15450 numbers and use the maximum height of the list as the maximum height
15451 of the graph.  If the latter operation were difficult, then the former
15452 procedure would be easiest, but there is a function built into Emacs
15453 that determines the maximum of its arguments.  We can use that
15454 function.  The function is called @code{max} and it returns the
15455 largest of all its arguments, which must be numbers.  Thus, for
15456 example,
15458 @smallexample
15459 (max  3 4 6 5 7 3)
15460 @end smallexample
15462 @noindent
15463 returns 7.  (A corresponding function called @code{min} returns the
15464 smallest of all its arguments.)
15465 @findex max
15466 @findex min
15468 However, we cannot simply call @code{max} on the @code{numbers-list};
15469 the @code{max} function expects numbers as its argument, not a list of
15470 numbers.  Thus, the following expression,
15472 @smallexample
15473 (max  '(3 4 6 5 7 3))
15474 @end smallexample
15476 @need 800
15477 @noindent
15478 produces the following error message;
15480 @smallexample
15481 Wrong type of argument:  number-or-marker-p, (3 4 6 5 7 3)
15482 @end smallexample
15484 @findex apply
15485 We need a function that passes a list of arguments to a function.
15486 This function is @code{apply}.  This function `applies' its first
15487 argument (a function) to its remaining arguments, the last of which
15488 may be a list.
15490 @need 1250
15491 For example,
15493 @smallexample
15494 (apply 'max 3 4 7 3 '(4 8 5))
15495 @end smallexample
15497 @noindent
15498 returns 8.
15500 (Incidentally, I don't know how you would learn of this function
15501 without a book such as this.  It is possible to discover other
15502 functions, like @code{search-forward} or @code{insert-rectangle}, by
15503 guessing at a part of their names and then using @code{apropos}.  Even
15504 though its base in metaphor is clear---`apply' its first argument to
15505 the rest---I doubt a novice would come up with that particular word
15506 when using @code{apropos} or other aid.  Of course, I could be wrong;
15507 after all, the function was first named by someone who had to invent
15508 it.)
15510 The second and subsequent arguments to @code{apply} are optional, so
15511 we can use @code{apply} to call a function and pass the elements of a
15512 list to it, like this, which also returns 8:
15514 @smallexample
15515 (apply 'max '(4 8 5))
15516 @end smallexample
15518 This latter way is how we will use @code{apply}.  The
15519 @code{recursive-lengths-list-many-files} function returns a numbers'
15520 list to which we can apply @code{max} (we could also apply @code{max} to
15521 the sorted numbers' list; it does not matter whether the list is
15522 sorted or not.)
15524 @need 800
15525 Hence, the operation for finding the maximum height of the graph is this:
15527 @smallexample
15528 (setq max-graph-height (apply 'max numbers-list))
15529 @end smallexample
15531 Now we can return to the question of how to create a list of strings
15532 for a column of the graph.  Told the maximum height of the graph
15533 and the number of asterisks that should appear in the column, the
15534 function should return a list of strings for the
15535 @code{insert-rectangle} command to insert.
15537 Each column is made up of asterisks or blanks.  Since the function is
15538 passed the value of the height of the column and the number of
15539 asterisks in the column, the number of blanks can be found by
15540 subtracting the number of asterisks from the height of the column.
15541 Given the number of blanks and the number of asterisks, two
15542 @code{while} loops can be used to construct the list:
15544 @smallexample
15545 @group
15546 ;;; @r{First version.}
15547 (defun column-of-graph (max-graph-height actual-height)
15548   "Return list of strings that is one column of a graph."
15549   (let ((insert-list nil)
15550         (number-of-top-blanks
15551          (- max-graph-height actual-height)))
15552 @end group
15554 @group
15555     ;; @r{Fill in asterisks.}
15556     (while (> actual-height 0)
15557       (setq insert-list (cons "*" insert-list))
15558       (setq actual-height (1- actual-height)))
15559 @end group
15561 @group
15562     ;; @r{Fill in blanks.}
15563     (while (> number-of-top-blanks 0)
15564       (setq insert-list (cons " " insert-list))
15565       (setq number-of-top-blanks
15566             (1- number-of-top-blanks)))
15567 @end group
15569 @group
15570     ;; @r{Return whole list.}
15571     insert-list))
15572 @end group
15573 @end smallexample
15575 If you install this function and then evaluate the following
15576 expression you will see that it returns the list as desired:
15578 @smallexample
15579 (column-of-graph 5 3)
15580 @end smallexample
15582 @need 800
15583 @noindent
15584 returns
15586 @smallexample
15587 (" " " " "*" "*" "*")
15588 @end smallexample
15590 As written, @code{column-of-graph} contains a major flaw: the symbols
15591 used for the blank and for the marked entries in the column are
15592 `hard-coded' as a space and asterisk.  This is fine for a prototype,
15593 but you, or another user, may wish to use other symbols.  For example,
15594 in testing the graph function, you many want to use a period in place
15595 of the space, to make sure the point is being repositioned properly
15596 each time the @code{insert-rectangle} function is called; or you might
15597 want to substitute a @samp{+} sign or other symbol for the asterisk.
15598 You might even want to make a graph-column that is more than one
15599 display column wide.  The program should be more flexible.  The way to
15600 do that is to replace the blank and the asterisk with two variables
15601 that we can call @code{graph-blank} and @code{graph-symbol} and define
15602 those variables separately.
15604 Also, the documentation is not well written.  These considerations
15605 lead us to the second version of the function:
15607 @smallexample
15608 @group
15609 (defvar graph-symbol "*"
15610   "String used as symbol in graph, usually an asterisk.")
15611 @end group
15613 @group
15614 (defvar graph-blank " "
15615   "String used as blank in graph, usually a blank space.
15616 graph-blank must be the same number of columns wide
15617 as graph-symbol.")
15618 @end group
15619 @end smallexample
15621 @noindent
15622 (For an explanation of @code{defvar}, see
15623 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
15625 @smallexample
15626 @group
15627 ;;; @r{Second version.}
15628 (defun column-of-graph (max-graph-height actual-height)
15629   "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15631 @end group
15632 @group
15633 The graph-symbols are contiguous entries at the end
15634 of the list.
15635 The list will be inserted as one column of a graph.
15636 The strings are either graph-blank or graph-symbol."
15637 @end group
15639 @group
15640   (let ((insert-list nil)
15641         (number-of-top-blanks
15642          (- max-graph-height actual-height)))
15643 @end group
15645 @group
15646     ;; @r{Fill in @code{graph-symbols}.}
15647     (while (> actual-height 0)
15648       (setq insert-list (cons graph-symbol insert-list))
15649       (setq actual-height (1- actual-height)))
15650 @end group
15652 @group
15653     ;; @r{Fill in @code{graph-blanks}.}
15654     (while (> number-of-top-blanks 0)
15655       (setq insert-list (cons graph-blank insert-list))
15656       (setq number-of-top-blanks
15657             (1- number-of-top-blanks)))
15659     ;; @r{Return whole list.}
15660     insert-list))
15661 @end group
15662 @end smallexample
15664 If we wished, we could rewrite @code{column-of-graph} a third time to
15665 provide optionally for a line graph as well as for a bar graph.  This
15666 would not be hard to do.  One way to think of a line graph is that it
15667 is no more than a bar graph in which the part of each bar that is
15668 below the top is blank.  To construct a column for a line graph, the
15669 function first constructs a list of blanks that is one shorter than
15670 the value, then it uses @code{cons} to attach a graph symbol to the
15671 list; then it uses @code{cons} again to attach the `top blanks' to
15672 the list.
15674 It is easy to see how to write such a function, but since we don't
15675 need it, we will not do it.  But the job could be done, and if it were
15676 done, it would be done with @code{column-of-graph}.  Even more
15677 important, it is worth noting that few changes would have to be made
15678 anywhere else.  The enhancement, if we ever wish to make it, is
15679 simple.
15681 Now, finally, we come to our first actual graph printing function.
15682 This prints the body of a graph, not the labels for the vertical and
15683 horizontal axes, so we can call this @code{graph-body-print}.
15685 @node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15686 @section The @code{graph-body-print} Function
15687 @findex graph-body-print
15689 After our preparation in the preceding section, the
15690 @code{graph-body-print} function is straightforward.  The function
15691 will print column after column of asterisks and blanks, using the
15692 elements of a numbers' list to specify the number of asterisks in each
15693 column.  This is a repetitive act, which means we can use a
15694 decrementing @code{while} loop or recursive function for the job.  In
15695 this section, we will write the definition using a @code{while} loop.
15697 The @code{column-of-graph} function requires the height of the graph
15698 as an argument, so we should determine and record that as a local variable.
15700 This leads us to the following template for the @code{while} loop
15701 version of this function:
15703 @smallexample
15704 @group
15705 (defun graph-body-print (numbers-list)
15706   "@var{documentation}@dots{}"
15707   (let ((height  @dots{}
15708          @dots{}))
15709 @end group
15711 @group
15712     (while numbers-list
15713       @var{insert-columns-and-reposition-point}
15714       (setq numbers-list (cdr numbers-list)))))
15715 @end group
15716 @end smallexample
15718 @noindent
15719 We need to fill in the slots of the template.
15721 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15722 determine the height of the graph.
15724 The @code{while} loop will cycle through the @code{numbers-list} one
15725 element at a time.  As it is shortened by the @code{(setq numbers-list
15726 (cdr numbers-list))} expression, the @sc{car} of each instance of the
15727 list is the value of the argument for @code{column-of-graph}.
15729 At each cycle of the @code{while} loop, the @code{insert-rectangle}
15730 function inserts the list returned by @code{column-of-graph}.  Since
15731 the @code{insert-rectangle} function moves point to the lower right of
15732 the inserted rectangle, we need to save the location of point at the
15733 time the rectangle is inserted, move back to that position after the
15734 rectangle is inserted, and then move horizontally to the next place
15735 from which @code{insert-rectangle} is called.
15737 If the inserted columns are one character wide, as they will be if
15738 single blanks and asterisks are used, the repositioning command is
15739 simply @code{(forward-char 1)}; however, the width of a column may be
15740 greater than one.  This means that the repositioning command should be
15741 written @code{(forward-char symbol-width)}.  The @code{symbol-width}
15742 itself is the length of a @code{graph-blank} and can be found using
15743 the expression @code{(length graph-blank)}.  The best place to bind
15744 the @code{symbol-width} variable to the value of the width of graph
15745 column is in the varlist of the @code{let} expression.
15747 @need 1250
15748 These considerations lead to the following function definition:
15750 @smallexample
15751 @group
15752 (defun graph-body-print (numbers-list)
15753   "Print a bar graph of the NUMBERS-LIST.
15754 The numbers-list consists of the Y-axis values."
15756   (let ((height (apply 'max numbers-list))
15757         (symbol-width (length graph-blank))
15758         from-position)
15759 @end group
15761 @group
15762     (while numbers-list
15763       (setq from-position (point))
15764       (insert-rectangle
15765        (column-of-graph height (car numbers-list)))
15766       (goto-char from-position)
15767       (forward-char symbol-width)
15768 @end group
15769 @group
15770       ;; @r{Draw graph column by column.}
15771       (sit-for 0)
15772       (setq numbers-list (cdr numbers-list)))
15773 @end group
15774 @group
15775     ;; @r{Place point for X axis labels.}
15776     (forward-line height)
15777     (insert "\n")
15779 @end group
15780 @end smallexample
15782 @noindent
15783 The one unexpected expression in this function is the
15784 @w{@code{(sit-for 0)}} expression in the @code{while} loop.  This
15785 expression makes the graph printing operation more interesting to
15786 watch than it would be otherwise.  The expression causes Emacs to
15787 `sit' or do nothing for a zero length of time and then redraw the
15788 screen.  Placed here, it causes Emacs to redraw the screen column by
15789 column.  Without it, Emacs would not redraw the screen until the
15790 function exits.
15792 We can test @code{graph-body-print} with a short list of numbers.
15794 @enumerate
15795 @item
15796 Install @code{graph-symbol}, @code{graph-blank},
15797 @code{column-of-graph}, which are in
15798 @iftex
15799 @ref{Readying a Graph, , Readying a Graph},
15800 @end iftex
15801 @ifinfo
15802 @ref{Columns of a graph},
15803 @end ifinfo
15804 and @code{graph-body-print}.
15806 @need 800
15807 @item
15808 Copy the following expression:
15810 @smallexample
15811 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15812 @end smallexample
15814 @item
15815 Switch to the @file{*scratch*} buffer and place the cursor where you
15816 want the graph to start.
15818 @item
15819 Type @kbd{M-:} (@code{eval-expression}).
15821 @item
15822 Yank the @code{graph-body-print} expression into the minibuffer
15823 with @kbd{C-y} (@code{yank)}.
15825 @item
15826 Press @key{RET} to evaluate the @code{graph-body-print} expression.
15827 @end enumerate
15829 @need 800
15830 Emacs will print a graph like this:
15832 @smallexample
15833 @group
15834                     *
15835                 *   **
15836                 *  ****
15837                *** ****
15838               ********* *
15839              ************
15840             *************
15841 @end group
15842 @end smallexample
15844 @node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15845 @section The @code{recursive-graph-body-print} Function
15846 @findex recursive-graph-body-print
15848 The @code{graph-body-print} function may also be written recursively.
15849 The recursive solution is divided into two parts: an outside `wrapper'
15850 that uses a @code{let} expression to determine the values of several
15851 variables that need only be found once, such as the maximum height of
15852 the graph, and an inside function that is called recursively to print
15853 the graph.
15855 @need 1250
15856 The `wrapper' is uncomplicated:
15858 @smallexample
15859 @group
15860 (defun recursive-graph-body-print (numbers-list)
15861   "Print a bar graph of the NUMBERS-LIST.
15862 The numbers-list consists of the Y-axis values."
15863   (let ((height (apply 'max numbers-list))
15864         (symbol-width (length graph-blank))
15865         from-position)
15866     (recursive-graph-body-print-internal
15867      numbers-list
15868      height
15869      symbol-width)))
15870 @end group
15871 @end smallexample
15873 The recursive function is a little more difficult.  It has four parts:
15874 the `do-again-test', the printing code, the recursive call, and the
15875 `next-step-expression'.  The `do-again-test' is an @code{if}
15876 expression that determines whether the @code{numbers-list} contains
15877 any remaining elements; if it does, the function prints one column of
15878 the graph using the printing code and calls itself again.  The
15879 function calls itself again according to the value produced by the
15880 `next-step-expression' which causes the call to act on a shorter
15881 version of the @code{numbers-list}.
15883 @smallexample
15884 @group
15885 (defun recursive-graph-body-print-internal
15886   (numbers-list height symbol-width)
15887   "Print a bar graph.
15888 Used within recursive-graph-body-print function."
15889 @end group
15891 @group
15892   (if numbers-list
15893       (progn
15894         (setq from-position (point))
15895         (insert-rectangle
15896          (column-of-graph height (car numbers-list)))
15897 @end group
15898 @group
15899         (goto-char from-position)
15900         (forward-char symbol-width)
15901         (sit-for 0)     ; @r{Draw graph column by column.}
15902         (recursive-graph-body-print-internal
15903          (cdr numbers-list) height symbol-width))))
15904 @end group
15905 @end smallexample
15907 @need 1250
15908 After installation, this expression can be tested; here is a sample:
15910 @smallexample
15911 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15912 @end smallexample
15914 @need 800
15915 Here is what @code{recursive-graph-body-print} produces:
15917 @smallexample
15918 @group
15919                 *
15920                **   *
15921               ****  *
15922               **** ***
15923             * *********
15924             ************
15925             *************
15926 @end group
15927 @end smallexample
15929 Either of these two functions, @code{graph-body-print} or
15930 @code{recursive-graph-body-print}, create the body of a graph.
15932 @node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15933 @section Need for Printed Axes
15935 A graph needs printed axes, so you can orient yourself.  For a do-once
15936 project, it may be reasonable to draw the axes by hand using Emacs'
15937 Picture mode; but a graph drawing function may be used more than once.
15939 For this reason, I have written enhancements to the basic
15940 @code{print-graph-body} function that automatically print labels for
15941 the horizontal and vertical axes.  Since the label printing functions
15942 do not contain much new material, I have placed their description in
15943 an appendix.  @xref{Full Graph, , A Graph with Labelled Axes}.
15945 @node Line Graph Exercise,  , Printed Axes, Readying a Graph
15946 @section Exercise
15948 Write a line graph version of the graph printing functions.
15950 @node Emacs Initialization, Debugging, Readying a Graph, Top
15951 @chapter Your @file{.emacs} File
15952 @cindex @file{.emacs} file
15953 @cindex Customizing your @file{.emacs} file
15954 @cindex Initialization file
15956 ``You don't have to like Emacs to like it'' -- this seemingly
15957 paradoxical statement is the secret of GNU Emacs.  The plain, `out of
15958 the box' Emacs is a generic tool.  Most people who use it, customize
15959 it to suit themselves.
15961 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15962 expressions in Emacs Lisp you can change or extend Emacs.
15964 @menu
15965 * Default Configuration::
15966 * Site-wide Init::              You can write site-wide init files.
15967 * defcustom::                   Emacs will write code for you.
15968 * Beginning a .emacs File::     How to write a @code{.emacs file}.
15969 * Text and Auto-fill::          Automatically wrap lines.
15970 * Mail Aliases::                Use abbreviations for email addresses.
15971 * Indent Tabs Mode::            Don't use tabs with @TeX{}
15972 * Keybindings::                 Create some personal keybindings.
15973 * Keymaps::                     More about key binding.
15974 * Loading Files::               Load (i.e., evaluate) files automatically.
15975 * Autoload::                    Make functions available.
15976 * Simple Extension::            Define a function; bind it to a key.
15977 * X11 Colors::                  Colors in version 19 in X.
15978 * Miscellaneous::
15979 * Mode Line::                   How to customize your mode line.
15980 @end menu
15982 @node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15983 @ifnottex
15984 @unnumberedsec Emacs' Default Configuration
15985 @end ifnottex
15987 There are those who appreciate Emacs' default configuration.  After
15988 all, Emacs starts you in C mode when you edit a C file, starts you in
15989 Fortran mode when you edit a Fortran file, and starts you in
15990 Fundamental mode when you edit an unadorned file.  This all makes
15991 sense, if you do not know who is going to use Emacs.  Who knows what a
15992 person hopes to do with an unadorned file?  Fundamental mode is the
15993 right default for such a file, just as C mode is the right default for
15994 editing C code.  But when you do know who is going to use Emacs---you,
15995 yourself---then it makes sense to customize Emacs.
15997 For example, I seldom want Fundamental mode when I edit an
15998 otherwise undistinguished file; I want Text mode.  This is why I
15999 customize Emacs: so it suits me.
16001 You can customize and extend Emacs by writing or adapting a
16002 @file{~/.emacs} file.  This is your personal initialization file; its
16003 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16004 may also add @file{.el} to @file{~/.emacs} and call it a
16005 @file{~/.emacs.el} file.  In the past, you were forbidden to type the
16006 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16007 you may.  The new format is consistent with the Emacs Lisp file
16008 naming conventions; the old format saves typing.}
16010 A @file{~/.emacs} file contains Emacs Lisp code.  You can write this
16011 code yourself; or you can use Emacs' @code{customize} feature to write
16012 the code for you.  You can combine your own expressions and
16013 auto-written Customize expressions in your @file{.emacs} file.
16015 (I myself prefer to write my own expressions, except for those,
16016 particularly fonts, that I find easier to manipulate using the
16017 @code{customize} command.  I combine the two methods.)
16019 Most of this chapter is about writing expressions yourself.  It
16020 describes a simple @file{.emacs} file; for more information, see
16021 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16022 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16023 Manual}.
16025 @node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16026 @section Site-wide Initialization Files
16028 @cindex @file{default.el} init file
16029 @cindex @file{site-init.el} init file
16030 @cindex @file{site-load.el} init file
16031 In addition to your personal initialization file, Emacs automatically
16032 loads various site-wide initialization files, if they exist.  These
16033 have the same form as your @file{.emacs} file, but are loaded by
16034 everyone.
16036 Two site-wide initialization files, @file{site-load.el} and
16037 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16038 `dumped' version of Emacs is created, as is most common.  (Dumped
16039 copies of Emacs load more quickly.  However, once a file is loaded and
16040 dumped, a change to it does not lead to a change in Emacs unless you
16041 load it yourself or re-dump Emacs.  @xref{Building Emacs, , Building
16042 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16043 @file{INSTALL} file.)
16045 Three other site-wide initialization files are loaded automatically
16046 each time you start Emacs, if they exist.  These are
16047 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16048 file, and @file{default.el}, and the terminal type file, which are both
16049 loaded @emph{after} your @file{.emacs} file.
16051 Settings and definitions in your @file{.emacs} file will overwrite
16052 conflicting settings and definitions in a @file{site-start.el} file,
16053 if it exists; but the settings and definitions in a @file{default.el}
16054 or terminal type file will overwrite those in your @file{.emacs} file.
16055 (You can prevent interference from a terminal type file by setting
16056 @code{term-file-prefix} to @code{nil}.  @xref{Simple Extension, , A
16057 Simple Extension}.)
16059 @c Rewritten to avoid overfull hbox.
16060 The @file{INSTALL} file that comes in the distribution contains
16061 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16063 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16064 control loading.  These files are in the @file{lisp} directory of the
16065 Emacs distribution and are worth perusing.
16067 The @file{loaddefs.el} file contains a good many suggestions as to
16068 what to put into your own @file{.emacs} file, or into a site-wide
16069 initialization file.
16071 @node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16072 @section Specifying Variables using @code{defcustom}
16073 @findex defcustom
16075 You can specify variables using @code{defcustom} so that you and
16076 others can then use Emacs' @code{customize} feature to set their
16077 values.  (You cannot use @code{customize} to write function
16078 definitions; but you can write @code{defuns} in your @file{.emacs}
16079 file.  Indeed, you can write any Lisp expression in your @file{.emacs}
16080 file.)
16082 The @code{customize} feature depends on the @code{defcustom} special
16083 form.  Although you can use @code{defvar} or @code{setq} for variables
16084 that users set, the @code{defcustom} special form is designed for the
16085 job.
16087 You can use your knowledge of @code{defvar} for writing the
16088 first three arguments for @code{defcustom}.  The first argument to
16089 @code{defcustom} is the name of the variable.  The second argument is
16090 the variable's initial value, if any; and this value is set only if
16091 the value has not already been set.  The third argument is the
16092 documentation.
16094 The fourth and subsequent arguments to @code{defcustom} specify types
16095 and options; these are not featured in @code{defvar}.  (These
16096 arguments are optional.)
16098 Each of these arguments consists of a keyword followed by a value.
16099 Each keyword starts with the character @code{:}.
16101 @need 1250
16102 For example, the customizable user option variable
16103 @code{text-mode-hook} looks like this:
16105 @smallexample
16106 @group
16107 (defcustom text-mode-hook nil
16108   "Normal hook run when entering Text mode and many related modes."
16109   :type 'hook
16110   :options '(turn-on-auto-fill flyspell-mode)
16111   :group 'data)
16112 @end group
16113 @end smallexample
16115 @noindent
16116 The name of the variable is @code{text-mode-hook}; it has no default
16117 value; and its documentation string tells you what it does.
16119 The @code{:type} keyword tells Emacs what kind of data
16120 @code{text-mode-hook} should be set to and how to display the value in
16121 a Customization buffer.
16123 The @code{:options} keyword specifies a suggested list of values for
16124 the variable.  Currently, you can use @code{:options} only for a hook.
16125 The list is only a suggestion; it is not exclusive; a person who sets
16126 the variable may set it to other values; the list shown following the
16127 @code{:options} keyword is intended to offer convenient choices to a
16128 user.
16130 Finally, the @code{:group} keyword tells the Emacs Customization
16131 command in which group the variable is located.  This tells where to
16132 find it.
16134 For more information, see @ref{Customization, , Writing Customization
16135 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16137 Consider @code{text-mode-hook} as an example.
16139 There are two ways to customize this variable.  You can use the
16140 customization command or write the appropriate expressions yourself.
16142 @need 800
16143 Using the customization command,  you can type:
16145 @smallexample
16146 M-x customize
16147 @end smallexample
16149 @noindent
16150 and find that the group for editing files of data is called `data'.
16151 Enter that group.  Text Mode Hook is the first member.  You can click
16152 on its various options to set the values.  After you click on the
16153 button to
16155 @smallexample
16156 Save for Future Sessions
16157 @end smallexample
16159 @noindent
16160 Emacs will write an expression into your @file{.emacs} file.
16161 It will look like this:
16163 @smallexample
16164 @group
16165 (custom-set-variables
16166   ;; custom-set-variables was added by Custom --
16167   ;;                           don't edit or cut/paste it!
16168   ;; Your init file should contain only one such instance.
16169  '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16170 @end group
16171 @end smallexample
16173 @noindent
16174 (The @code{text-mode-hook-identify} function tells
16175 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16177 In spite of the warning, you certainly may edit, cut, and paste the
16178 expression!  I do all time.  The purpose of the warning is to scare
16179 those who do not know what they are doing, so they do not
16180 inadvertently generate an error.
16182 The @code{custom-set-variables} works somewhat differently than a
16183 @code{setq}.  While I have never learned the differences, I do modify
16184 the @code{custom-set-variables} expressions in my @file{.emacs} file
16185 by hand:  I make the changes in what appears to me to be a reasonable
16186 manner and have not had any problems.  Others prefer to use the
16187 Customization command and let Emacs do the work for them.
16189 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16190 This function sets the various font faces.  Over time, I have set a
16191 considerable number of faces.  Some of the time, I re-set them using
16192 @code{customize}; other times, I simply edit the
16193 @code{custom-set-faces} expression in my @file{.emacs} file itself.
16195 The second way to customize your @code{text-mode-hook} is to set it
16196 yourself in your @file{.emacs} file using code that has nothing to do
16197 with the @code{custom-set-@dots{}} functions.
16199 @need 800
16200 When you do this, and later use @code{customize}, you will see a
16201 message that says
16203 @smallexample
16204 this option has been changed outside the customize buffer.
16205 @end smallexample
16207 @need 800
16208 This message is only a warning.  If you click on the button to
16210 @smallexample
16211 Save for Future Sessions
16212 @end smallexample
16214 @noindent
16215 Emacs will write a @code{custom-set-@dots{}} expression near the end
16216 of your @file{.emacs} file that will be evaluated after your
16217 hand-written expression.  It will, therefore, overrule your
16218 hand-written expression.  No harm will be done.  When you do this,
16219 however, be careful to remember which expression is active; if you
16220 forget, you may confuse yourself.
16222 So long as you remember where the values are set, you will have no
16223 trouble.  In any event, the values are always set in your
16224 initialization file, which is usually called @file{.emacs}.
16226 I myself use @code{customize} for hardly anything.  Mostly, I write
16227 expressions myself.
16229 @node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16230 @section Beginning a @file{.emacs} File
16231 @cindex @file{.emacs} file, beginning of
16233 When you start Emacs, it loads your @file{.emacs} file unless you tell
16234 it not to by specifying @samp{-q} on the command line.  (The
16235 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16237 A @file{.emacs} file contains Lisp expressions.  Often, these are no
16238 more than expressions to set values; sometimes they are function
16239 definitions.
16241 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16242 Manual}, for a short description of initialization files.
16244 This chapter goes over some of the same ground, but is a walk among
16245 extracts from a complete, long-used @file{.emacs} file---my own.
16247 The first part of the file consists of comments: reminders to myself.
16248 By now, of course, I remember these things, but when I started, I did
16249 not.
16251 @smallexample
16252 @group
16253 ;;;; Bob's .emacs file
16254 ; Robert J. Chassell
16255 ; 26 September 1985
16256 @end group
16257 @end smallexample
16259 @noindent
16260 Look at that date!  I started this file a long time ago.  I have been
16261 adding to it ever since.
16263 @smallexample
16264 @group
16265 ; Each section in this file is introduced by a
16266 ; line beginning with four semicolons; and each
16267 ; entry is introduced by a line beginning with
16268 ; three semicolons.
16269 @end group
16270 @end smallexample
16272 @noindent
16273 This describes the usual conventions for comments in Emacs Lisp.
16274 Everything on a line that follows a semicolon is a comment.  Two,
16275 three, and four semicolons are used as section and subsection
16276 markers.  (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16277 Manual}, for more about comments.)
16279 @smallexample
16280 @group
16281 ;;;; The Help Key
16282 ; Control-h is the help key;
16283 ; after typing control-h, type a letter to
16284 ; indicate the subject about which you want help.
16285 ; For an explanation of the help facility,
16286 ; type control-h two times in a row.
16287 @end group
16288 @end smallexample
16290 @noindent
16291 Just remember: type @kbd{C-h} two times for help.
16293 @smallexample
16294 @group
16295 ; To find out about any mode, type control-h m
16296 ; while in that mode.  For example, to find out
16297 ; about mail mode, enter mail mode and then type
16298 ; control-h m.
16299 @end group
16300 @end smallexample
16302 @noindent
16303 `Mode help', as I call this, is very helpful.  Usually, it tells you
16304 all you need to know.
16306 Of course, you don't need to include comments like these in your
16307 @file{.emacs} file.  I included them in mine because I kept forgetting
16308 about Mode help or the conventions for comments---but I was able to
16309 remember to look here to remind myself.
16311 @node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16312 @section Text and Auto Fill Mode
16314 Now we come to the part that `turns on' Text mode and
16315 Auto Fill mode.
16317 @smallexample
16318 @group
16319 ;;; Text mode and Auto Fill mode
16320 ; The next three lines put Emacs into Text mode
16321 ; and Auto Fill mode, and are for writers who
16322 ; want to start writing prose rather than code.
16324 (setq default-major-mode 'text-mode)
16325 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16326 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16327 @end group
16328 @end smallexample
16330 Here is the first part of this @file{.emacs} file that does something
16331 besides remind a forgetful human!
16333 The first of the two lines in parentheses tells Emacs to turn on Text
16334 mode when you find a file, @emph{unless} that file should go into some
16335 other mode, such as C mode.
16337 @cindex Per-buffer, local variables list
16338 @cindex Local variables list, per-buffer,
16339 @cindex Automatic mode selection
16340 @cindex Mode selection, automatic
16341 When Emacs reads a file, it looks at the extension to the file name,
16342 if any.  (The extension is the part that comes after a @samp{.}.)  If
16343 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16344 on C mode.  Also, Emacs looks at first nonblank line of the file; if
16345 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode.  Emacs
16346 possesses a list of extensions and specifications that it uses
16347 automatically.  In addition, Emacs looks near the last page for a
16348 per-buffer, ``local variables list'', if any.
16350 @ifinfo
16351 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16352 Emacs Manual}.
16354 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16355 Manual}.
16356 @end ifinfo
16357 @iftex
16358 See sections ``How Major Modes are Chosen'' and ``Local Variables in
16359 Files'' in @cite{The GNU Emacs Manual}.
16360 @end iftex
16362 Now, back to the @file{.emacs} file.
16364 @need 800
16365 Here is the line again; how does it work?
16367 @cindex Text Mode turned on
16368 @smallexample
16369 (setq default-major-mode 'text-mode)
16370 @end smallexample
16372 @noindent
16373 This line is a short, but complete Emacs Lisp expression.
16375 We are already familiar with @code{setq}.  It sets the following variable,
16376 @code{default-major-mode}, to the subsequent value, which is
16377 @code{text-mode}.  The single quote mark before @code{text-mode} tells
16378 Emacs to deal directly with the @code{text-mode} variable, not with
16379 whatever it might stand for.  @xref{set & setq, , Setting the Value of
16380 a Variable}, for a reminder of how @code{setq} works.  The main point
16381 is that there is no difference between the procedure you use to set
16382 a value in your @file{.emacs} file and the procedure you use anywhere
16383 else in Emacs.
16385 @need 800
16386 Here are the next two lines:
16388 @cindex Auto Fill mode turned on
16389 @findex add-hook
16390 @smallexample
16391 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16392 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16393 @end smallexample
16395 @noindent
16396 In these two lines, the @code{add-hook} command first adds
16397 @code{text-mode-hook-identify} to the variable called
16398 @code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16399 variable.
16401 @code{turn-on-auto-fill} is the name of a program, that, you guessed
16402 it!, turns on Auto Fill mode.  @code{text-mode-hook-identify} is a
16403 function that tells @code{toggle-text-mode-auto-fill} which buffers
16404 are in Text mode.
16406 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16407 onto Text mode.  So every time Emacs turns on Text mode, Emacs also
16408 turns on Auto Fill mode.
16410 In brief, the first line causes Emacs to enter Text mode when you edit
16411 a file, unless the file name extension, first non-blank line, or local
16412 variables tell Emacs otherwise.
16414 Text mode among other actions, sets the syntax table to work
16415 conveniently for writers.  In Text mode, Emacs considers an apostrophe
16416 as part of a word like a letter; but Emacs does not consider a period
16417 or a space as part of a word.  Thus, @kbd{M-f} moves you over
16418 @samp{it's}.  On the other hand, in C mode, @kbd{M-f} stops just after
16419 the @samp{t} of @samp{it's}.
16421 The second and third lines causes Emacs to turn on Auto Fill mode when
16422 it turns on Text mode.  In Auto Fill mode, Emacs automatically breaks
16423 a line that is too wide and brings the excessively wide part of the
16424 line down to the next line.  Emacs breaks lines between words, not
16425 within them.
16427 When Auto Fill mode is turned off, lines continue to the right as you
16428 type them.  Depending on how you set the value of
16429 @code{truncate-lines}, the words you type either disappear off the
16430 right side of the screen, or else are shown, in a rather ugly and
16431 unreadable manner, as a continuation line on the screen.
16433 @need 1250
16434 In addition, in this part of my @file{.emacs} file, I tell the Emacs
16435 fill commands to insert two spaces after a colon:
16437 @smallexample
16438 (setq colon-double-space t)
16439 @end smallexample
16441 @node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16442 @section Mail Aliases
16444 Here is a @code{setq} that `turns on' mail aliases, along with more
16445 reminders.
16447 @smallexample
16448 @group
16449 ;;; Mail mode
16450 ; To enter mail mode, type `C-x m'
16451 ; To enter RMAIL (for reading mail),
16452 ; type `M-x rmail'
16454 (setq mail-aliases t)
16455 @end group
16456 @end smallexample
16458 @cindex Mail aliases
16459 @noindent
16460 This @code{setq} command sets the value of the variable
16461 @code{mail-aliases} to @code{t}.  Since @code{t} means true, the line
16462 says, in effect, ``Yes, use mail aliases.''
16464 Mail aliases are convenient short names for long email addresses or
16465 for lists of email addresses.  The file where you keep your `aliases'
16466 is @file{~/.mailrc}.  You write an alias like this:
16468 @smallexample
16469 alias geo george@@foobar.wiz.edu
16470 @end smallexample
16472 @noindent
16473 When you write a message to George, address it to @samp{geo}; the
16474 mailer will automatically expand @samp{geo} to the full address.
16476 @node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16477 @section Indent Tabs Mode
16478 @cindex Tabs, preventing
16479 @findex indent-tabs-mode
16481 By default, Emacs inserts tabs in place of multiple spaces when it
16482 formats a region.  (For example, you might indent many lines of text
16483 all at once with the @code{indent-region} command.)  Tabs look fine on
16484 a terminal or with ordinary printing, but they produce badly indented
16485 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16487 @need 1250
16488 The following turns off Indent Tabs mode:
16490 @smallexample
16491 @group
16492 ;;; Prevent Extraneous Tabs
16493 (setq-default indent-tabs-mode nil)
16494 @end group
16495 @end smallexample
16497 Note that this line uses @code{setq-default} rather than the
16498 @code{setq} command that we have seen before.  The @code{setq-default}
16499 command sets values only in buffers that do not have their own local
16500 values for the variable.
16502 @ifinfo
16503 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16505 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16506 Manual}.
16507 @end ifinfo
16508 @iftex
16509 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16510 Files'' in @cite{The GNU Emacs Manual}.
16511 @end iftex
16513 @node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16514 @section Some Keybindings
16516 Now for some personal keybindings:
16518 @smallexample
16519 @group
16520 ;;; Compare windows
16521 (global-set-key "\C-cw" 'compare-windows)
16522 @end group
16523 @end smallexample
16525 @findex compare-windows
16526 @code{compare-windows} is a nifty command that compares the text in
16527 your current window with text in the next window.  It makes the
16528 comparison by starting at point in each window, moving over text in
16529 each window as far as they match.  I use this command all the time.
16531 This also shows how to set a key globally, for all modes.
16533 @cindex Setting a key globally
16534 @cindex Global set key
16535 @cindex Key setting globally
16536 @findex global-set-key
16537 The command is @code{global-set-key}.  It is followed by the
16538 keybinding.  In a @file{.emacs} file, the keybinding is written as
16539 shown: @code{\C-c} stands for `control-c', which means `press the
16540 control key and the @kbd{c} key at the same time'.  The @code{w} means
16541 `press the @kbd{w} key'.  The keybinding is surrounded by double
16542 quotation marks.  In documentation, you would write this as @kbd{C-c
16543 w}.  (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16544 than a @key{CTL} key, you would write @code{\M-c}.  @xref{Init
16545 Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16546 Manual}, for details.)
16548 The command invoked by the keys is @code{compare-windows}.  Note that
16549 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
16550 would first try to evaluate the symbol to determine its value.
16552 These three things, the double quotation marks, the backslash before
16553 the @samp{C}, and the single quote mark are necessary parts of
16554 keybinding that I tend to forget.  Fortunately, I have come to
16555 remember that I should look at my existing @file{.emacs} file, and
16556 adapt what is there.
16558 As for the keybinding itself: @kbd{C-c w}.  This combines the prefix
16559 key, @kbd{C-c}, with a single character, in this case, @kbd{w}.  This
16560 set of keys, @kbd{C-c} followed by a single character, is strictly
16561 reserved for individuals' own use.  (I call these `own' keys, since
16562 these are for my own use.)  You should always be able to create such a
16563 keybinding for your own use without stomping on someone else's
16564 keybinding.  If you ever write an extension to Emacs, please avoid
16565 taking any of these keys for public use.  Create a key like @kbd{C-c
16566 C-w} instead.  Otherwise, we will run out of `own' keys.
16568 @need 1250
16569 Here is another keybinding, with a comment:
16571 @smallexample
16572 @group
16573 ;;; Keybinding for `occur'
16574 ; I use occur a lot, so let's bind it to a key:
16575 (global-set-key "\C-co" 'occur)
16576 @end group
16577 @end smallexample
16579 @findex occur
16580 The @code{occur} command shows all the lines in the current buffer
16581 that contain a match for a regular expression.  Matching lines are
16582 shown in a buffer called @file{*Occur*}.  That buffer serves as a menu
16583 to jump to occurrences.
16585 @findex global-unset-key
16586 @cindex Unbinding key
16587 @cindex Key unbinding
16588 @need 1250
16589 Here is how to unbind a key, so it does not
16590 work:
16592 @smallexample
16593 @group
16594 ;;; Unbind `C-x f'
16595 (global-unset-key "\C-xf")
16596 @end group
16597 @end smallexample
16599 There is a reason for this unbinding: I found I inadvertently typed
16600 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}.  Rather than find a
16601 file, as I intended, I accidentally set the width for filled text,
16602 almost always to a width I did not want.  Since I hardly ever reset my
16603 default width, I simply unbound the key.
16605 @findex list-buffers, @r{rebound}
16606 @findex buffer-menu, @r{bound to key}
16607 @need 1250
16608 The following rebinds an existing key:
16610 @smallexample
16611 @group
16612 ;;; Rebind `C-x C-b' for `buffer-menu'
16613 (global-set-key "\C-x\C-b" 'buffer-menu)
16614 @end group
16615 @end smallexample
16617 By default, @kbd{C-x C-b} runs the
16618 @code{list-buffers} command.  This command lists
16619 your buffers in @emph{another} window.  Since I
16620 almost always want to do something in that
16621 window, I prefer the  @code{buffer-menu}
16622 command, which not only lists the buffers,
16623 but moves point into that window.
16625 @node Keymaps, Loading Files, Keybindings, Emacs Initialization
16626 @section Keymaps
16627 @cindex Keymaps
16628 @cindex Rebinding keys
16630 Emacs uses @dfn{keymaps} to record which keys call which commands.
16631 When you use @code{global-set-key} to set the keybinding for a single
16632 command in all parts of Emacs, you are specifying the keybinding in
16633 @code{current-global-map}.
16635 Specific modes, such as C mode or Text mode, have their own keymaps;
16636 the mode-specific keymaps override the global map that is shared by
16637 all buffers.
16639 The @code{global-set-key} function binds, or rebinds, the global
16640 keymap.  For example, the following binds the key @kbd{C-x C-b} to the
16641 function @code{buffer-menu}:
16643 @smallexample
16644 (global-set-key "\C-x\C-b" 'buffer-menu)
16645 @end smallexample
16647 Mode-specific keymaps are bound using the @code{define-key} function,
16648 which takes a specific keymap as an argument, as well as the key and
16649 the command.  For example, my @file{.emacs} file contains the
16650 following expression to bind the @code{texinfo-insert-@@group} command
16651 to @kbd{C-c C-c g}:
16653 @smallexample
16654 @group
16655 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16656 @end group
16657 @end smallexample
16659 @noindent
16660 The @code{texinfo-insert-@@group} function itself is a little extension
16661 to Texinfo mode that inserts @samp{@@group} into a Texinfo file.  I
16662 use this command all the time and prefer to type the three strokes
16663 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16664 (@samp{@@group} and its matching @samp{@@end group} are commands that
16665 keep all enclosed text together on one page; many multi-line examples
16666 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16668 @need 1250
16669 Here is the @code{texinfo-insert-@@group} function definition:
16671 @smallexample
16672 @group
16673 (defun texinfo-insert-@@group ()
16674   "Insert the string @@group in a Texinfo buffer."
16675   (interactive)
16676   (beginning-of-line)
16677   (insert "@@group\n"))
16678 @end group
16679 @end smallexample
16681 (Of course, I could have used Abbrev mode to save typing, rather than
16682 write a function to insert a word; but I prefer key strokes consistent
16683 with other Texinfo mode key bindings.)
16685 You will see numerous @code{define-key} expressions in
16686 @file{loaddefs.el} as well as in the various mode libraries, such as
16687 @file{cc-mode.el} and @file{lisp-mode.el}.
16689 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16690 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16691 Reference Manual}, for more information about keymaps.
16693 @node Loading Files, Autoload, Keymaps, Emacs Initialization
16694 @section Loading Files
16695 @cindex Loading files
16696 @c findex load
16698 Many people in the GNU Emacs community have written extensions to
16699 Emacs.  As time goes by, these extensions are often included in new
16700 releases.  For example, the Calendar and Diary packages are now part
16701 of the standard GNU Emacs.
16703 (Calc, which I consider a vital part of Emacs, would be part of the
16704 standard distribution except that it was so large it was packaged
16705 separately and no one has changed that.)
16707 You can use a @code{load} command to evaluate a complete file and
16708 thereby install all the functions and variables in the file into Emacs.
16709 For example:
16711 @c (auto-compression-mode t)
16713 @smallexample
16714 (load "~/emacs/slowsplit")
16715 @end smallexample
16717 This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16718 exists, the faster, byte compiled @file{slowsplit.elc} file from the
16719 @file{emacs} sub-directory of your home directory.  The file contains
16720 the function @code{split-window-quietly}, which John Robinson wrote in
16721 1989.
16723 The @code{split-window-quietly} function splits a window with the
16724 minimum of redisplay.  I installed it in 1989 because it worked well
16725 with the slow 1200 baud terminals I was then using.  Nowadays, I only
16726 occasionally come across such a slow connection, but I continue to use
16727 the function because I like the way it leaves the bottom half of a
16728 buffer in the lower of the new windows and the top half in the upper
16729 window.
16731 @need 1250
16732 To replace the key binding for the default
16733 @code{split-window-vertically}, you must also unset that key and bind
16734 the keys to @code{split-window-quietly}, like this:
16736 @smallexample
16737 @group
16738 (global-unset-key "\C-x2")
16739 (global-set-key "\C-x2" 'split-window-quietly)
16740 @end group
16741 @end smallexample
16743 @vindex load-path
16744 If you load many extensions, as I do, then instead of specifying the
16745 exact location of the extension file, as shown above, you can specify
16746 that directory as part of Emacs' @code{load-path}.  Then, when Emacs
16747 loads a file, it will search that directory as well as its default
16748 list of directories.  (The default list is specified in @file{paths.h}
16749 when Emacs is built.)
16751 @need 1250
16752 The following command adds your @file{~/emacs} directory to the
16753 existing load path:
16755 @smallexample
16756 @group
16757 ;;; Emacs Load Path
16758 (setq load-path (cons "~/emacs" load-path))
16759 @end group
16760 @end smallexample
16762 Incidentally, @code{load-library} is an interactive interface to the
16763 @code{load} function.  The complete function looks like this:
16765 @findex load-library
16766 @smallexample
16767 @group
16768 (defun load-library (library)
16769   "Load the library named LIBRARY.
16770 This is an interface to the function `load'."
16771   (interactive "sLoad library: ")
16772   (load library))
16773 @end group
16774 @end smallexample
16776 The name of the function, @code{load-library}, comes from the use of
16777 `library' as a conventional synonym for `file'.  The source for the
16778 @code{load-library} command is in the @file{files.el} library.
16780 Another interactive command that does a slightly different job is
16781 @code{load-file}.  @xref{Lisp Libraries, , Libraries of Lisp Code for
16782 Emacs, emacs, The GNU Emacs Manual}, for information on the
16783 distinction between @code{load-library} and this command.
16785 @node Autoload, Simple Extension, Loading Files, Emacs Initialization
16786 @section Autoloading
16787 @findex autoload
16789 Instead of installing a function by loading the file that contains it,
16790 or by evaluating the function definition, you can make the function
16791 available but not actually install it until it is first called.  This
16792 is called @dfn{autoloading}.
16794 When you execute an autoloaded function, Emacs automatically evaluates
16795 the file that contains the definition, and then calls the function.
16797 Emacs starts quicker with autoloaded functions, since their libraries
16798 are not loaded right away; but you need to wait a moment when you
16799 first use such a function, while its containing file is evaluated.
16801 Rarely used functions are frequently autoloaded.  The
16802 @file{loaddefs.el} library contains hundreds of autoloaded functions,
16803 from @code{bookmark-set} to @code{wordstar-mode}.  Of course, you may
16804 come to use a `rare' function frequently.  When you do, you should
16805 load that function's file with a @code{load} expression in your
16806 @file{.emacs} file.
16808 In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16809 that contain functions that would otherwise be autoloaded.  (Actually,
16810 it would have been better to include these files in my `dumped' Emacs
16811 when I built it, but I forgot.  @xref{Building Emacs, , Building
16812 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16813 file for more about dumping.)
16815 You may also want to include autoloaded expressions in your @file{.emacs}
16816 file.  @code{autoload} is a built-in function that takes up to five
16817 arguments, the final three of which are optional.  The first argument
16818 is the name of the function to be autoloaded; the second is the name
16819 of the file to be loaded.  The third argument is documentation for the
16820 function, and the fourth tells whether the function can be called
16821 interactively.  The fifth argument tells what type of
16822 object---@code{autoload} can handle a keymap or macro as well as a
16823 function (the default is a function).
16825 @need 800
16826 Here is a typical example:
16828 @smallexample
16829 @group
16830 (autoload 'html-helper-mode
16831   "html-helper-mode" "Edit HTML documents" t)
16832 @end group
16833 @end smallexample
16835 @noindent
16836 (@code{html-helper-mode} is an alternative to @code{html-mode}, which
16837 is a standard part of the distribution).
16839 @noindent
16840 This expression autoloads the @code{html-helper-mode} function.  It
16841 takes it from the @file{html-helper-mode.el} file (or from the byte
16842 compiled file @file{html-helper-mode.elc}, if it exists.)  The file
16843 must be located in a directory specified by @code{load-path}.  The
16844 documentation says that this is a mode to help you edit documents
16845 written in the HyperText Markup Language.  You can call this mode
16846 interactively by typing @kbd{M-x html-helper-mode}.  (You need to
16847 duplicate the function's regular documentation in the autoload
16848 expression because the regular function is not yet loaded, so its
16849 documentation is not available.)
16851 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16852 Manual}, for more information.
16854 @node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16855 @section A Simple Extension: @code{line-to-top-of-window}
16856 @findex line-to-top-of-window
16857 @cindex Simple extension in @file{.emacs} file
16859 Here is a simple extension to Emacs that moves the line point is on to
16860 the top of the window.  I use this all the time, to make text easier
16861 to read.
16863 You can put the following code into a separate file and then load it
16864 from your @file{.emacs} file, or you can include it within your
16865 @file{.emacs} file.
16867 @need 1250
16868 Here is the definition:
16870 @smallexample
16871 @group
16872 ;;; Line to top of window;
16873 ;;; replace three keystroke sequence  C-u 0 C-l
16874 (defun line-to-top-of-window ()
16875   "Move the line point is on to top of window."
16876   (interactive)
16877   (recenter 0))
16878 @end group
16879 @end smallexample
16881 @need 1250
16882 Now for the keybinding.
16884 Nowadays, function keys as well as mouse button events and
16885 non-@sc{ascii} characters are written within square brackets, without
16886 quotation marks.  (In Emacs version 18 and before, you had to write
16887 different function key bindings for each different make of terminal.)
16889 I bind @code{line-to-top-of-window} to my @key{F6} function key like
16890 this:
16892 @smallexample
16893 (global-set-key [f6] 'line-to-top-of-window)
16894 @end smallexample
16896 For more information, see @ref{Init Rebinding, , Rebinding Keys in
16897 Your Init File, emacs, The GNU Emacs Manual}.
16899 @cindex Conditional 'twixt two versions of Emacs
16900 @cindex Version of Emacs, choosing
16901 @cindex Emacs version, choosing
16902 If you run two versions of GNU Emacs, such as versions 20 and 21, and
16903 use one @file{.emacs} file, you can select which code to evaluate with
16904 the following conditional:
16906 @smallexample
16907 @group
16908 (cond
16909  ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16910   ;; evaluate version 20 code
16911   ( @dots{} ))
16912  ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16913   ;; evaluate version 21 code
16914   ( @dots{} )))
16915 @end group
16916 @end smallexample
16918 For example, in contrast to version 20, version 21 blinks its cursor
16919 by default.  I hate such blinking, as well as some other features in
16920 version 21, so I placed the following in my @file{.emacs}
16921 file@footnote{When I start instances of Emacs that do not load my
16922 @file{.emacs} file or any site file, I also turn off blinking:
16924 @smallexample
16925 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16926 @end smallexample
16929 @smallexample
16930 @group
16931 (if (string-equal "21" (substring (emacs-version) 10 12))
16932     (progn
16933       (blink-cursor-mode 0)
16934       ;; Insert newline when you press `C-n' (next-line)
16935       ;; at the end of the buffer
16936       (setq next-line-add-newlines t)
16937 @end group
16938 @group
16939       ;; Turn on image viewing
16940       (auto-image-file-mode t)
16941 @end group
16942 @group
16943       ;; Turn on menu bar (this bar has text)
16944       ;; (Use numeric argument to turn on)
16945       (menu-bar-mode 1)
16946 @end group
16947 @group
16948       ;; Turn off tool bar (this bar has icons)
16949       ;; (Use numeric argument to turn on)
16950       (tool-bar-mode nil)
16951 @end group
16952 @group
16953       ;; Turn off tooltip mode for tool bar
16954       ;; (This mode causes icon explanations to pop up)
16955       ;; (Use numeric argument to turn on)
16956       (tooltip-mode nil)
16957       ;; If tooltips turned on, make tips appear promptly
16958       (setq tooltip-delay 0.1)  ; default is one second
16959        ))
16960 @end group
16961 @end smallexample
16963 @noindent
16964 (You will note that instead of typing @code{(number-to-string 21)}, I
16965 decided to save typing and wrote `21' as a string, @code{"21"}, rather
16966 than convert it from an integer to a string.  In this instance, this
16967 expression is better than the longer, but more general
16968 @code{(number-to-string 21)}.  However, if you do not know ahead of
16969 time what type of information will be returned, then the
16970 @code{number-to-string} function will be needed.)
16972 @node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16973 @section X11 Colors
16975 You can specify colors when you use Emacs with the MIT X Windowing
16976 system.
16978 I dislike the default colors and specify my own.
16980 @need 1250
16981 Here are the expressions in my @file{.emacs}
16982 file that set values:
16984 @smallexample
16985 @group
16986 ;; Set cursor color
16987 (set-cursor-color "white")
16989 ;; Set mouse color
16990 (set-mouse-color "white")
16992 ;; Set foreground and background
16993 (set-foreground-color "white")
16994 (set-background-color "darkblue")
16995 @end group
16997 @group
16998 ;;; Set highlighting colors for isearch and drag
16999 (set-face-foreground 'highlight "white")
17000 (set-face-background 'highlight "blue")
17001 @end group
17003 @group
17004 (set-face-foreground 'region "cyan")
17005 (set-face-background 'region "blue")
17006 @end group
17008 @group
17009 (set-face-foreground 'secondary-selection "skyblue")
17010 (set-face-background 'secondary-selection "darkblue")
17011 @end group
17013 @group
17014 ;; Set calendar highlighting colors
17015 (setq calendar-load-hook
17016       '(lambda ()
17017          (set-face-foreground 'diary-face   "skyblue")
17018          (set-face-background 'holiday-face "slate blue")
17019          (set-face-foreground 'holiday-face "white")))
17020 @end group
17021 @end smallexample
17023 The various shades of blue soothe my eye and prevent me from seeing
17024 the screen flicker.
17026 Alternatively, I could have set my specifications in various X
17027 initialization files.  For example, I could set the foreground,
17028 background, cursor, and pointer (i.e., mouse) colors in my
17029 @file{~/.Xresources} file like this:
17031 @smallexample
17032 @group
17033 Emacs*foreground:   white
17034 Emacs*background:   darkblue
17035 Emacs*cursorColor:  white
17036 Emacs*pointerColor: white
17037 @end group
17038 @end smallexample
17040 In any event, since it is not part of Emacs, I set the root color of
17041 my X window in my @file{~/.xinitrc} file, like this@footnote{I
17042 occasionally run more modern window managers, such as Sawfish with
17043 GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17044 image rather than a plain color.}:
17046 @smallexample
17047 @group
17048 # I use TWM for window manager.
17049 xsetroot -solid Navy -fg white &
17050 @end group
17051 @end smallexample
17053 @node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17054 @section Miscellaneous Settings for a @file{.emacs} File
17056 Here are a few miscellaneous settings:
17057 @sp 1
17059 @itemize @minus
17060 @item
17061 Set the shape and color of the mouse cursor:
17062 @smallexample
17063 @group
17064 ; Cursor shapes are defined in
17065 ; `/usr/include/X11/cursorfont.h';
17066 ; for example, the `target' cursor is number 128;
17067 ; the `top_left_arrow' cursor is number 132.
17068 @end group
17070 @group
17071 (let ((mpointer (x-get-resource "*mpointer"
17072                                 "*emacs*mpointer")))
17073   ;; If you have not set your mouse pointer
17074   ;;     then set it, otherwise leave as is:
17075   (if (eq mpointer nil)
17076       (setq mpointer "132")) ; top_left_arrow
17077 @end group
17078 @group
17079   (setq x-pointer-shape (string-to-int mpointer))
17080   (set-mouse-color "white"))
17081 @end group
17082 @end smallexample
17083 @end itemize
17085 @node Mode Line,  , Miscellaneous, Emacs Initialization
17086 @section A Modified Mode Line
17087 @vindex default-mode-line-format
17088 @cindex Mode line format
17090 Finally, a feature I really like: a modified mode line.
17092 When I work over a network, I forget which machine I am using.  Also,
17093 I tend to I lose track of where I am, and which line point is on.
17095 So I reset my mode line to look like this:
17097 @smallexample
17098 -:-- foo.texi   rattlesnake:/home/bob/  Line 1  (Texinfo Fill) Top
17099 @end smallexample
17101 I am visiting a file called @file{foo.texi}, on my machine
17102 @file{rattlesnake} in my @file{/home/bob} buffer.  I am on line 1, in
17103 Texinfo mode, and am at the top of the buffer.
17105 @need 1200
17106 My @file{.emacs} file has a section that looks like this:
17108 @smallexample
17109 @group
17110 ;; Set a Mode Line that tells me which machine, which directory,
17111 ;; and which line I am on, plus the other customary information.
17112 (setq default-mode-line-format
17113  (quote
17114   (#("-" 0 1
17115      (help-echo
17116       "mouse-1: select window, mouse-2: delete others ..."))
17117    mode-line-mule-info
17118    mode-line-modified
17119    mode-line-frame-identification
17120    "    "
17121 @end group
17122 @group
17123    mode-line-buffer-identification
17124    "    "
17125    (:eval (substring
17126            (system-name) 0 (string-match "\\..+" (system-name))))
17127    ":"
17128    default-directory
17129    #(" " 0 1
17130      (help-echo
17131       "mouse-1: select window, mouse-2: delete others ..."))
17132    (line-number-mode " Line %l ")
17133    global-mode-string
17134 @end group
17135 @group
17136    #("   %[(" 0 6
17137      (help-echo
17138       "mouse-1: select window, mouse-2: delete others ..."))
17139    (:eval (mode-line-mode-name))
17140    mode-line-process
17141    minor-mode-alist
17142    #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17143    ")%] "
17144    (-3 . "%P")
17145    ;;   "-%-"
17146    )))
17147 @end group
17148 @end smallexample
17150 @noindent
17151 Here, I redefine the default mode line.  Most of the parts are from
17152 the original; but I make a few changes.  I set the @emph{default} mode
17153 line format so as to permit various modes, such as Info, to override
17156 Many elements in the list are self-explanatory:
17157 @code{mode-line-modified} is a variable that tells whether the buffer
17158 has been modified, @code{mode-name} tells the name of the mode, and so
17159 on.  However, the format looks complicated because of two features we
17160 have not discussed.
17162 The first string in the mode line is a dash or hyphen, @samp{-}.  In
17163 the old days, it would have been specified simply as @code{"-"}.  But
17164 nowadays, Emacs can add properties to a string, such as highlighting
17165 or, as in this case, a help feature.  If you place your mouse cursor
17166 over the hyphen, some help information appears  (By default, you must
17167 wait one second before the information appears.  You can change that
17168 timing by changing the value of @code{tooltip-delay}.)
17170 @need 1000
17171 The new string format has a special syntax:
17173 @smallexample
17174 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
17175 @end smallexample
17177 @noindent
17178 The @code{#(} begins a list.  The first element of the list is the
17179 string itself, just one @samp{-}.  The second and third
17180 elements specify the range over which the fourth element applies.  A
17181 range starts @emph{after} a character, so a zero means the range
17182 starts just before the first character; a 1 means that the range ends
17183 just after the first character.  The third element is the property for
17184 the range.  It consists of a property list,  a
17185 property name, in this case, @samp{help-echo}, followed by a value, in this
17186 case, a string.  The second, third, and fourth elements of this new
17187 string format can be repeated.
17189 @xref{Text Props and Strings, , Text Properties in String, elisp, The
17190 GNU Emacs Lisp Reference Manual}, and see @ref{Mode Line Format, , Mode
17191 Line Format, elisp, The GNU Emacs Lisp Reference Manual}, for more
17192 information.
17194 @code{mode-line-buffer-identification}
17195 displays the current buffer name.  It is a list
17196 beginning @code{(#("%12b" 0 4 @dots{}}.
17197 The @code{#(} begins the list.
17199 The @samp{"%12b"} displays the current buffer name, using the
17200 @code{buffer-name} function with which we are familiar; the `12'
17201 specifies the maximum number of characters that will be displayed.
17202 When a name has fewer characters, whitespace is added to fill out to
17203 this number.  (Buffer names can and often should be longer than 12
17204 characters; this length works well in a typical 80 column wide
17205 window.)
17207 @code{:eval} is a new feature in GNU Emacs version 21.  It says to
17208 evaluate the following form and use the result as a string to display.
17209 In this case, the expression displays the first component of the full
17210 system name.  The end of the first component is a @samp{.} (`period'),
17211 so I use the @code{string-match} function to tell me the length of the
17212 first component.  The substring from the zeroth character to that
17213 length is the name of the machine.
17215 @need 1250
17216 This is the expression:
17218 @smallexample
17219 @group
17220 (:eval (substring
17221         (system-name) 0 (string-match "\\..+" (system-name))))
17222 @end group
17223 @end smallexample
17225 @samp{%[} and @samp{%]} cause a pair of square brackets
17226 to appear for each recursive editing level.  @samp{%n} says `Narrow'
17227 when narrowing is in effect.  @samp{%P} tells you the percentage of
17228 the buffer that is above the bottom of the window, or `Top', `Bottom',
17229 or `All'.  (A lower case @samp{p} tell you the percentage above the
17230 @emph{top} of the window.)  @samp{%-} inserts enough dashes to fill
17231 out the line.
17233 Remember, ``You don't have to like Emacs to like it'' --- your own
17234 Emacs can have different colors, different commands, and different
17235 keys than a default Emacs.
17237 On the other hand, if you want to bring up a plain `out of the box'
17238 Emacs, with no customization, type:
17240 @smallexample
17241 emacs -q
17242 @end smallexample
17244 @noindent
17245 This will start an Emacs that does @emph{not} load your
17246 @file{~/.emacs} initialization file.  A plain, default Emacs.  Nothing
17247 more.
17249 @node Debugging, Conclusion, Emacs Initialization, Top
17250 @chapter Debugging
17251 @cindex debugging
17253 GNU Emacs has two debuggers, @code{debug} and @code{edebug}.  The
17254 first is built into the internals of Emacs and is always with you;
17255 the second requires that you instrument a function before you can use it.
17257 Both debuggers are described extensively in @ref{Debugging, ,
17258 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17259 In this chapter, I will walk through a short example of each.
17261 @menu
17262 * debug::                       How to use the built-in debugger.
17263 * debug-on-entry::              Start debugging when you call a function.
17264 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
17265 * edebug::                      How to use Edebug, a source level debugger.
17266 * Debugging Exercises::
17267 @end menu
17269 @node debug, debug-on-entry, Debugging, Debugging
17270 @section @code{debug}
17271 @findex debug
17273 Suppose you have written a function definition that is intended to
17274 return the sum of the numbers 1 through a given number.  (This is the
17275 @code{triangle} function discussed earlier.  @xref{Decrementing
17276 Example, , Example with Decrementing Counter}, for a discussion.)
17277 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17279 However, your function definition has a bug.  You have mistyped
17280 @samp{1=} for @samp{1-}.  Here is the broken definition:
17282 @findex triangle-bugged
17283 @smallexample
17284 @group
17285 (defun triangle-bugged (number)
17286   "Return sum of numbers 1 through NUMBER inclusive."
17287   (let ((total 0))
17288     (while (> number 0)
17289       (setq total (+ total number))
17290       (setq number (1= number)))      ; @r{Error here.}
17291     total))
17292 @end group
17293 @end smallexample
17295 If you are reading this in Info, you can evaluate this definition in
17296 the normal fashion.  You will see @code{triangle-bugged} appear in the
17297 echo area.
17299 @need 1250
17300 Now evaluate the @code{triangle-bugged} function with an
17301 argument of 4:
17303 @smallexample
17304 (triangle-bugged 4)
17305 @end smallexample
17307 @noindent
17308 In GNU Emacs version 21, you will create and enter a
17309 @file{*Backtrace*} buffer that says:
17311 @noindent
17312 @smallexample
17313 @group
17314 ---------- Buffer: *Backtrace* ----------
17315 Debugger entered--Lisp error: (void-function 1=)
17316   (1= number)
17317   (setq number (1= number))
17318   (while (> number 0) (setq total (+ total number))
17319         (setq number (1= number)))
17320   (let ((total 0)) (while (> number 0) (setq total ...)
17321     (setq number ...)) total)
17322   triangle-bugged(4)
17323 @end group
17324 @group
17325   eval((triangle-bugged 4))
17326   eval-last-sexp-1(nil)
17327   eval-last-sexp(nil)
17328   call-interactively(eval-last-sexp)
17329 ---------- Buffer: *Backtrace* ----------
17330 @end group
17331 @end smallexample
17333 @noindent
17334 (I have reformatted this example slightly; the debugger does not fold
17335 long lines.  As usual, you can quit the debugger by typing @kbd{q} in
17336 the @file{*Backtrace*} buffer.)
17338 In practice, for a bug as simple as this, the `Lisp error' line will
17339 tell you what you need to know to correct the definition.  The
17340 function @code{1=} is `void'.
17342 @need 800
17343 In GNU Emacs 20 and before, you will see:
17345 @smallexample
17346 Symbol's function definition is void:@: 1=
17347 @end smallexample
17349 @noindent
17350 which has the same meaning as the @file{*Backtrace*} buffer line in
17351 version 21.
17353 However, suppose you are not quite certain what is going on?
17354 You can read the complete backtrace.
17356 In this case, you need to run GNU Emacs 21, which automatically starts
17357 the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17358 you need to start the debugger manually as described below.
17360 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17361 what Emacs did that led to the error.  Emacs made an interactive call
17362 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17363 of the @code{triangle-bugged} expression.  Each line above tells you
17364 what the Lisp interpreter evaluated next.
17366 @need 1250
17367 The third line from the top of the buffer is
17369 @smallexample
17370 (setq number (1= number))
17371 @end smallexample
17373 @noindent
17374 Emacs tried to evaluate this expression; in order to do so, it tried
17375 to evaluate the inner expression shown on the second line from the
17376 top:
17378 @smallexample
17379 (1= number)
17380 @end smallexample
17382 @need 1250
17383 @noindent
17384 This is where the error occurred; as the top line says:
17386 @smallexample
17387 Debugger entered--Lisp error: (void-function 1=)
17388 @end smallexample
17390 @noindent
17391 You can correct the mistake, re-evaluate the function definition, and
17392 then run your test again.
17394 @node debug-on-entry, debug-on-quit, debug, Debugging
17395 @section @code{debug-on-entry}
17396 @findex debug-on-entry
17398 GNU Emacs 21 starts the debugger automatically when your function has
17399 an error.  GNU Emacs version 20 and before did not; it simply
17400 presented you with an error message.  You had to start the debugger
17401 manually.
17403 You can start the debugger manually for all versions of Emacs; the
17404 advantage is that the debugger runs even if you do not have a bug in
17405 your code.  Sometimes your code will be free of bugs!
17407 You can enter the debugger when you call the function by calling
17408 @code{debug-on-entry}.
17410 @need 1250
17411 @noindent
17412 Type:
17414 @smallexample
17415 M-x debug-on-entry RET triangle-bugged RET
17416 @end smallexample
17418 @need 1250
17419 @noindent
17420 Now, evaluate the following:
17422 @smallexample
17423 (triangle-bugged 5)
17424 @end smallexample
17426 @noindent
17427 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17428 you that it is beginning to evaluate the @code{triangle-bugged}
17429 function:
17431 @smallexample
17432 @group
17433 ---------- Buffer: *Backtrace* ----------
17434 Debugger entered--entering a function:
17435 * triangle-bugged(5)
17436   eval((triangle-bugged 5))
17437 @end group
17438 @group
17439   eval-last-sexp-1(nil)
17440   eval-last-sexp(nil)
17441   call-interactively(eval-last-sexp)
17442 ---------- Buffer: *Backtrace* ----------
17443 @end group
17444 @end smallexample
17446 In the @file{*Backtrace*} buffer, type @kbd{d}.  Emacs will evaluate
17447 the first expression in @code{triangle-bugged}; the buffer will look
17448 like this:
17450 @smallexample
17451 @group
17452 ---------- Buffer: *Backtrace* ----------
17453 Debugger entered--beginning evaluation of function call form:
17454 * (let ((total 0)) (while (> number 0) (setq total ...)
17455         (setq number ...)) total)
17456 * triangle-bugged(5)
17457   eval((triangle-bugged 5))
17458 @end group
17459 @group
17460   eval-last-sexp-1(nil)
17461   eval-last-sexp(nil)
17462   call-interactively(eval-last-sexp)
17463 ---------- Buffer: *Backtrace* ----------
17464 @end group
17465 @end smallexample
17467 @noindent
17468 Now, type @kbd{d} again, eight times, slowly.  Each time you type
17469 @kbd{d}, Emacs will evaluate another expression in the function
17470 definition.
17472 @need 1750
17473 Eventually, the buffer will look like this:
17475 @smallexample
17476 @group
17477 ---------- Buffer: *Backtrace* ----------
17478 Debugger entered--beginning evaluation of function call form:
17479 * (setq number (1= number))
17480 * (while (> number 0) (setq total (+ total number))
17481         (setq number (1= number)))
17482 @group
17483 @end group
17484 * (let ((total 0)) (while (> number 0) (setq total ...)
17485         (setq number ...)) total)
17486 * triangle-bugged(5)
17487   eval((triangle-bugged 5))
17488 @group
17489 @end group
17490   eval-last-sexp-1(nil)
17491   eval-last-sexp(nil)
17492   call-interactively(eval-last-sexp)
17493 ---------- Buffer: *Backtrace* ----------
17494 @end group
17495 @end smallexample
17497 @noindent
17498 Finally, after you type @kbd{d} two more times, Emacs will reach the
17499 error, and the top two lines of the @file{*Backtrace*} buffer will look
17500 like this:
17502 @smallexample
17503 @group
17504 ---------- Buffer: *Backtrace* ----------
17505 Debugger entered--Lisp error: (void-function 1=)
17506 * (1= number)
17507 @dots{}
17508 ---------- Buffer: *Backtrace* ----------
17509 @end group
17510 @end smallexample
17512 By typing @kbd{d}, you were able to step through the function.
17514 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17515 quits the trace, but does not cancel @code{debug-on-entry}.
17517 @findex cancel-debug-on-entry
17518 To cancel the effect of @code{debug-on-entry}, call
17519 @code{cancel-debug-on-entry} and the name of the function, like this:
17521 @smallexample
17522 M-x cancel-debug-on-entry RET triangle-bugged RET
17523 @end smallexample
17525 @noindent
17526 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
17528 @node debug-on-quit, edebug, debug-on-entry, Debugging
17529 @section @code{debug-on-quit} and @code{(debug)}
17531 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17532 there are two other ways to start @code{debug}.
17534 @findex debug-on-quit
17535 You can start @code{debug} whenever you type @kbd{C-g}
17536 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17537 @code{t}.  This is useful for debugging infinite loops.
17539 @need 1500
17540 @cindex @code{(debug)} in code
17541 Or, you can insert a line that says @code{(debug)} into your code
17542 where you want the debugger to start, like this:
17544 @smallexample
17545 @group
17546 (defun triangle-bugged (number)
17547   "Return sum of numbers 1 through NUMBER inclusive."
17548   (let ((total 0))
17549     (while (> number 0)
17550       (setq total (+ total number))
17551       (debug)                         ; @r{Start debugger.}
17552       (setq number (1= number)))      ; @r{Error here.}
17553     total))
17554 @end group
17555 @end smallexample
17557 The @code{debug} function is described in detail in @ref{Debugger, ,
17558 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17560 @node edebug, Debugging Exercises, debug-on-quit, Debugging
17561 @section The @code{edebug} Source Level Debugger
17562 @cindex Source level debugger
17563 @findex edebug
17565 Edebug is a source level debugger.  Edebug normally displays the
17566 source of the code you are debugging, with an arrow at the left that
17567 shows which line you are currently executing.
17569 You can walk through the execution of a function, line by line, or run
17570 quickly until reaching a @dfn{breakpoint} where execution stops.
17572 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17573 Lisp Reference Manual}.
17575 Here is a bugged function definition for @code{triangle-recursively}.
17576 @xref{Recursive triangle function, , Recursion in place of a counter},
17577 for a review of it.
17579 @smallexample
17580 @group
17581 (defun triangle-recursively-bugged (number)
17582   "Return sum of numbers 1 through NUMBER inclusive.
17583 Uses recursion."
17584   (if (= number 1)
17585       1
17586     (+ number
17587        (triangle-recursively-bugged
17588         (1= number)))))               ; @r{Error here.}
17589 @end group
17590 @end smallexample
17592 @noindent
17593 Normally, you would install this definition by positioning your cursor
17594 after the function's closing parenthesis and typing @kbd{C-x C-e}
17595 (@code{eval-last-sexp}) or else by positioning your cursor within the
17596 definition and typing @kbd{C-M-x} (@code{eval-defun}).  (By default,
17597 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17598 Interactive mode.)
17600 @need 1500
17601 However, to prepare this function definition for Edebug, you must
17602 first @dfn{instrument} the code using a different command.  You can do
17603 this by positioning your cursor within the definition and typing
17605 @smallexample
17606 M-x edebug-defun RET
17607 @end smallexample
17609 @noindent
17610 This will cause Emacs to load Edebug automatically if it is not
17611 already loaded, and properly instrument the function.
17613 After instrumenting the function, place your cursor after the
17614 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17616 @smallexample
17617 (triangle-recursively-bugged 3)
17618 @end smallexample
17620 @noindent
17621 You will be jumped back to the source for
17622 @code{triangle-recursively-bugged} and the cursor positioned at the
17623 beginning of the @code{if} line of the function.  Also, you will see
17624 an arrowhead at the left hand side of that line.  The arrowhead marks
17625 the line where the function is executing.  (In the following examples,
17626 we show the arrowhead with @samp{=>}; in a windowing system, you may
17627 see the arrowhead as a solid triangle in the window `fringe'.)
17629 @smallexample
17630 =>@point{}(if (= number 1)
17631 @end smallexample
17633 @noindent
17634 @iftex
17635 In the example, the location of point is displayed with a star,
17636 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17637 @end iftex
17638 @ifnottex
17639 In the example, the location of point is displayed as @samp{@point{}}
17640 (in a printed book, it is displayed with a five pointed star).
17641 @end ifnottex
17643 If you now press @key{SPC}, point will move to the next expression to
17644 be executed; the line will look like this:
17646 @smallexample
17647 =>(if @point{}(= number 1)
17648 @end smallexample
17650 @noindent
17651 As you continue to press @key{SPC}, point will move from expression to
17652 expression.  At the same time, whenever an expression returns a value,
17653 that value will be displayed in the echo area.  For example, after you
17654 move point past @code{number}, you will see the following:
17656 @smallexample
17657 Result: 3 = C-c
17658 @end smallexample
17660 @noindent
17661 This means the value of @code{number} is 3, which is @sc{ascii}
17662 `control-c' (the third letter of the alphabet).
17664 You can continue moving through the code until you reach the line with
17665 the error.  Before evaluation, that line looks like this:
17667 @smallexample
17668 =>        @point{}(1= number)))))               ; @r{Error here.}
17669 @end smallexample
17671 @need 1250
17672 @noindent
17673 When you press @key{SPC} once again, you will produce an error message
17674 that says:
17676 @smallexample
17677 Symbol's function definition is void:@: 1=
17678 @end smallexample
17680 @noindent
17681 This is the bug.
17683 Press @kbd{q} to quit Edebug.
17685 To remove instrumentation from a function definition, simply
17686 re-evaluate it with a command that does not instrument it.
17687 For example, you could place your cursor after the definition's
17688 closing parenthesis and type @kbd{C-x C-e}.
17690 Edebug does a great deal more than walk with you through a function.
17691 You can set it so it races through on its own, stopping only at an
17692 error or at specified stopping points; you can cause it to display the
17693 changing values of various expressions; you can find out how many
17694 times a function is called, and more.
17696 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17697 Lisp Reference Manual}.
17699 @need 1500
17700 @node Debugging Exercises,  , edebug, Debugging
17701 @section Debugging Exercises
17703 @itemize @bullet
17704 @item
17705 Install the @code{count-words-region} function and then cause it to
17706 enter the built-in debugger when you call it.  Run the command on a
17707 region containing two words.  You will need to press @kbd{d} a
17708 remarkable number of times.  On your system, is a `hook' called after
17709 the command finishes?  (For information on hooks, see @ref{Command
17710 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17711 Manual}.)
17713 @item
17714 Copy @code{count-words-region} into the @file{*scratch*} buffer,
17715 instrument the function for Edebug, and walk through its execution.
17716 The function does not need to have a bug, although you can introduce
17717 one if you wish.  If the function lacks a bug, the walk-through
17718 completes without problems.
17720 @item
17721 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17722 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17723 @kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17724 for commands made outside of the Edebug debugging buffer.)
17726 @item
17727 In the Edebug debugging buffer, use the @kbd{p}
17728 (@code{edebug-bounce-point}) command to see where in the region the
17729 @code{count-words-region} is working.
17731 @item
17732 Move point to some spot further down function and then type the
17733 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17735 @item
17736 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17737 walk through the function on its own; use an upper case @kbd{T} for
17738 @code{edebug-Trace-fast-mode}.
17740 @item
17741 Set a breakpoint, then run Edebug in Trace mode until it reaches the
17742 stopping point.
17743 @end itemize
17745 @node Conclusion, the-the, Debugging, Top
17746 @chapter Conclusion
17748 We have now reached the end of this Introduction.  You have now
17749 learned enough about programming in Emacs Lisp to set values, to write
17750 simple @file{.emacs} files for yourself and your friends, and write
17751 simple customizations and extensions to Emacs.
17753 This is a place to stop.  Or, if you wish, you can now go onward, and
17754 teach yourself.
17756 You have learned some of the basic nuts and bolts of programming.  But
17757 only some.  There are a great many more brackets and hinges that are
17758 easy to use that we have not touched.
17760 A path you can follow right now lies among the sources to GNU Emacs
17761 and in
17762 @ifnotinfo
17763 @cite{The GNU Emacs Lisp Reference Manual}.
17764 @end ifnotinfo
17765 @ifinfo
17766 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17767 Emacs Lisp Reference Manual}.
17768 @end ifinfo
17770 The Emacs Lisp sources are an adventure.  When you read the sources and
17771 come across a function or expression that is unfamiliar, you need to
17772 figure out or find out what it does.
17774 Go to the Reference Manual.  It is a thorough, complete, and fairly
17775 easy-to-read description of Emacs Lisp.  It is written not only for
17776 experts, but for people who know what you know.  (The @cite{Reference
17777 Manual} comes with the standard GNU Emacs distribution.  Like this
17778 introduction, it comes as a Texinfo source file, so you can read it
17779 on-line and as a typeset, printed book.)
17781 Go to the other on-line help that is part of GNU Emacs: the on-line
17782 documentation for all functions, and @code{find-tags}, the program
17783 that takes you to sources.
17785 Here is an example of how I explore the sources.  Because of its name,
17786 @file{simple.el} is the file I looked at first, a long time ago.  As
17787 it happens some of the functions in @file{simple.el} are complicated,
17788 or at least look complicated at first sight.  The @code{open-line}
17789 function, for example, looks complicated.
17791 You may want to walk through this function slowly, as we did with the
17792 @code{forward-sentence} function.
17793 @ifnottex
17794 (@xref{forward-sentence}.)
17795 @end ifnottex
17796 @iftex
17797 (@xref{forward-sentence, , @code{forward-sentence}}.)
17798 @end iftex
17799 Or you may want to skip that function and look at another, such as
17800 @code{split-line}.  You don't need to read all the functions.
17801 According to @code{count-words-in-defun}, the @code{split-line}
17802 function contains 27 words and symbols.
17804 Even though it is short, @code{split-line} contains four expressions
17805 we have not studied: @code{skip-chars-forward}, @code{indent-to},
17806 @code{current-column} and @samp{?\n}.
17808 Consider the @code{skip-chars-forward} function.  (It is part of the
17809 function definition for @code{back-to-indentation}, which is shown in
17810 @ref{Review, , Review}.)
17812 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17813 typing @kbd{C-h f} (@code{describe-function}) and the name of the
17814 function.  This gives you the function documentation.
17816 You may be able to guess what is done by a well named function such as
17817 @code{indent-to}; or you can look it up, too.  Incidentally, the
17818 @code{describe-function} function itself is in @file{help.el}; it is
17819 one of those long, but decipherable functions.  You can look up
17820 @code{describe-function} using the @kbd{C-h f} command!
17822 In this instance, since the code is Lisp, the @file{*Help*} buffer
17823 contains the name of the library containing the function's source.
17824 You can put point over the name of the library and press the RET key,
17825 which in this situation is bound to @code{help-follow}, and be taken
17826 directly to the source, in the same way as @kbd{M-.}
17827 (@code{find-tag}).
17829 The definition for @code{describe-function} illustrates how to
17830 customize the @code{interactive} expression without using the standard
17831 character codes; and it shows how to create a temporary buffer.
17833 (The @code{indent-to} function is written in C rather than Emacs Lisp;
17834 it is a `built-in' function.  @code{help-follow} only provides you
17835 with the documentation of a built-in function; it does not take you to
17836 the source.  But @code{find-tag} will take you to the source, if
17837 properly set up.)
17839 You can look at a function's source using @code{find-tag}, which is
17840 bound to @kbd{M-.}  Finally, you can find out what the Reference
17841 Manual has to say by visiting the manual in Info, and typing @kbd{i}
17842 (@code{Info-index}) and the name of the function, or by looking up
17843 @code{skip-chars-forward} in the index to a printed copy of the
17844 manual.
17846 Similarly, you can find out what is meant by @samp{?\n}.  You can try
17847 using @code{Info-index} with @samp{?\n}.  It turns out that this
17848 action won't help; but don't give up.  If you search the index for
17849 @samp{\n} without the @samp{?}, you will be taken directly to the
17850 relevant section of the manual.  (@xref{Character Type, , Character
17851 Type, elisp, The GNU Emacs Lisp Reference Manual}.  @samp{?\n} stands
17852 for the newline character.)
17854 Other interesting source files include @file{paragraphs.el},
17855 @file{loaddefs.el}, and @file{loadup.el}.  The @file{paragraphs.el}
17856 file includes short, easily understood functions as well as longer
17857 ones.  The @file{loaddefs.el} file contains the many standard
17858 autoloads and many keymaps.  I have never looked at it all; only at
17859 parts.  @file{loadup.el} is the file that loads the standard parts of
17860 Emacs; it tells you a great deal about how Emacs is built.
17861 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17862 Reference Manual}, for more about building.)
17864 As I said, you have learned some nuts and bolts; however, and very
17865 importantly, we have hardly touched major aspects of programming; I
17866 have said nothing about how to sort information, except to use the
17867 predefined @code{sort} function; I have said nothing about how to store
17868 information, except to use variables and lists; I have said nothing
17869 about how to write programs that write programs.  These are topics for
17870 another, and different kind of book, a different kind of learning.
17872 What you have done is learn enough for much practical work with GNU
17873 Emacs.  What you have done is get started.  This is the end of a
17874 beginning.
17876 @c ================ Appendix ================
17878 @node the-the, Kill Ring, Conclusion, Top
17879 @appendix The @code{the-the} Function
17880 @findex the-the
17881 @cindex Duplicated words function
17882 @cindex Words, duplicated
17884 Sometimes when you you write text, you duplicate words---as with ``you
17885 you'' near the beginning of this sentence.  I find that most
17886 frequently, I duplicate ``the'; hence, I call the function for
17887 detecting duplicated words, @code{the-the}.
17889 @need 1250
17890 As a first step, you could use the following regular expression to
17891 search for duplicates:
17893 @smallexample
17894 \\(\\w+[ \t\n]+\\)\\1
17895 @end smallexample
17897 @noindent
17898 This regexp matches one or more word-constituent characters followed
17899 by one or more spaces, tabs, or newlines.  However, it does not detect
17900 duplicated words on different lines, since the ending of the first
17901 word, the end of the line, is different from the ending of the second
17902 word, a space.  (For more information about regular expressions, see
17903 @ref{Regexp Search, , Regular Expression Searches}, as well as
17904 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
17905 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
17906 The GNU Emacs Lisp Reference Manual}.)
17908 You might try searching just for duplicated word-constituent
17909 characters but that does not work since the pattern detects doubles
17910 such as the two occurrences of `th' in `with the'.
17912 Another possible regexp searches for word-constituent characters
17913 followed by non-word-constituent characters, reduplicated.  Here,
17914 @w{@samp{\\w+}} matches one or more word-constituent characters and
17915 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
17917 @smallexample
17918 \\(\\(\\w+\\)\\W*\\)\\1
17919 @end smallexample
17921 @noindent
17922 Again, not useful.
17924 Here is the pattern that I use.  It is not perfect, but good enough.
17925 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
17926 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
17927 any characters that are @emph{not} an @@-sign, space, newline, or tab.
17929 @smallexample
17930 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
17931 @end smallexample
17933 One can write more complicated expressions, but I found that this
17934 expression is good enough, so I use it.
17936 Here is the @code{the-the} function, as I include it in my
17937 @file{.emacs} file, along with a handy global key binding:
17939 @smallexample
17940 @group
17941 (defun the-the ()
17942   "Search forward for for a duplicated word."
17943   (interactive)
17944   (message "Searching for for duplicated words ...")
17945   (push-mark)
17946 @end group
17947 @group
17948   ;; This regexp is not perfect
17949   ;; but is fairly good over all:
17950   (if (re-search-forward
17951        "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
17952       (message "Found duplicated word.")
17953     (message "End of buffer")))
17954 @end group
17956 @group
17957 ;; Bind `the-the' to  C-c \
17958 (global-set-key "\C-c\\" 'the-the)
17959 @end group
17960 @end smallexample
17962 @sp 1
17963 Here is test text:
17965 @smallexample
17966 @group
17967 one two two three four five
17968 five six seven
17969 @end group
17970 @end smallexample
17972 You can substitute the other regular expressions shown above in the
17973 function definition and try each of them on this list.
17975 @node Kill Ring, Full Graph, the-the, Top
17976 @appendix Handling the Kill Ring
17977 @cindex Kill ring handling
17978 @cindex Handling the kill ring
17979 @cindex Ring, making a list like a
17981 The kill ring is a list that is transformed into a ring by the
17982 workings of the @code{rotate-yank-pointer} function.  The @code{yank}
17983 and @code{yank-pop} commands use the @code{rotate-yank-pointer}
17984 function.  This appendix describes the @code{rotate-yank-pointer}
17985 function as well as both the @code{yank} and the @code{yank-pop}
17986 commands.
17988 @menu
17989 * rotate-yank-pointer::         Move a pointer along a list and around.
17990 * yank::                        Paste a copy of a clipped element.
17991 * yank-pop::                    Insert first element pointed to.
17992 @end menu
17994 @node rotate-yank-pointer, yank, Kill Ring, Kill Ring
17995 @comment  node-name,  next,  previous,  up
17996 @appendixsec The @code{rotate-yank-pointer} Function
17997 @findex rotate-yank-pointer
17999 The @code{rotate-yank-pointer} function changes the element in the kill
18000 ring to which @code{kill-ring-yank-pointer} points.  For example, it can
18001 change  @code{kill-ring-yank-pointer} from pointing to the second
18002 element to point to the third element.
18004 @need 800
18005 Here is the code for @code{rotate-yank-pointer}:
18007 @smallexample
18008 @group
18009 (defun rotate-yank-pointer (arg)
18010   "Rotate the yanking point in the kill ring."
18011   (interactive "p")
18012   (let ((length (length kill-ring)))
18013 @end group
18014 @group
18015     (if (zerop length)
18016         ;; @r{then-part}
18017         (error "Kill ring is empty")
18018 @end group
18019 @group
18020       ;; @r{else-part}
18021       (setq kill-ring-yank-pointer
18022             (nthcdr (% (+ arg
18023                           (- length
18024                              (length
18025                               kill-ring-yank-pointer)))
18026                        length)
18027                     kill-ring)))))
18028 @end group
18029 @end smallexample
18031 @menu
18032 * Understanding rotate-yk-ptr::
18033 * rotate-yk-ptr body::          The body of @code{rotate-yank-pointer}.
18034 @end menu
18036 @node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18037 @ifnottex
18038 @unnumberedsubsec @code{rotate-yank-pointer} in Outline
18039 @end ifnottex
18041 The @code{rotate-yank-pointer} function looks complex, but as usual,
18042 it can be understood by taking it apart piece by piece.  First look at
18043 it in skeletal form:
18045 @smallexample
18046 @group
18047 (defun rotate-yank-pointer (arg)
18048   "Rotate the yanking point in the kill ring."
18049   (interactive "p")
18050   (let @var{varlist}
18051     @var{body}@dots{})
18052 @end group
18053 @end smallexample
18055 This function takes one argument, called @code{arg}.  It has a brief
18056 documentation string; and it is interactive with a small @samp{p}, which
18057 means that the argument must be a processed prefix passed to the
18058 function as a number.
18060 The body of the function definition is a @code{let} expression, which
18061 itself has a body as well as a @var{varlist}.
18063 The @code{let} expression declares a variable that will be only usable
18064 within the bounds of this function.  This variable is called
18065 @code{length} and is bound to a value that is equal to the number of
18066 items in the kill ring.  This is done by using the function called
18067 @code{length}.  (Note that this function has the same name as the
18068 variable called @code{length}; but one use of the word is to name the
18069 function and the other is to name the variable.  The two are quite
18070 distinct.  Similarly, an English speaker will distinguish between the
18071 meanings of the word @samp{ship} when he says: "I must ship this package
18072 immediately." and "I must get aboard the ship immediately.")
18074 The function @code{length} tells the number of items there are in a list,
18075 so @code{(length kill-ring)} returns the number of items there are in the
18076 kill ring.
18078 @node rotate-yk-ptr body,  , Understanding rotate-yk-ptr, rotate-yank-pointer
18079 @comment  node-name,  next,  previous,  up
18080 @appendixsubsec The Body of @code{rotate-yank-pointer}
18082 The body of @code{rotate-yank-pointer} is a @code{let} expression and
18083 the body of the @code{let} expression is an @code{if} expression.
18085 The purpose of the @code{if} expression is to find out whether there is
18086 anything in the kill ring.  If the kill ring is empty, the @code{error}
18087 function stops evaluation of the function and prints a message in the
18088 echo area.  On the other hand, if the kill ring has something in it, the
18089 work of the function is done.
18091 Here is the if-part and then-part of the @code{if} expression:
18093 @findex zerop
18094 @findex error
18095 @smallexample
18096 @group
18097 (if (zerop length)                      ; @r{if-part}
18098     (error "Kill ring is empty")        ; @r{then-part}
18099   @dots{}
18100 @end group
18101 @end smallexample
18103 @noindent
18104 If there is not anything in the kill ring, its length must be zero and
18105 an error message sent to the user: @samp{Kill ring is empty}.  The
18106 @code{if} expression uses the function @code{zerop} which returns true
18107 if the value it is testing is zero.  When @code{zerop} tests true, the
18108 then-part of the @code{if} is evaluated.  The then-part is a list
18109 starting with the function @code{error}, which is a function that is
18110 similar to the @code{message} function (@pxref{message}), in that it
18111 prints a one-line message in the echo area.  However, in addition to
18112 printing a message, @code{error} also stops evaluation of the function
18113 within which it is embedded.  This means that the rest of the function
18114 will not be evaluated if the length of the kill ring is zero.
18116 @menu
18117 * Digression concerning error::  How to mislead humans, but not computers.
18118 * rotate-yk-ptr else-part::     The else-part of the @code{if} expression.
18119 * Remainder Function::          The remainder, @code{%}, function.
18120 * rotate-yk-ptr remainder::     Using @code{%} in @code{rotate-yank-pointer}.
18121 * kill-rng-yk-ptr last elt::    Pointing to the last element.
18122 @end menu
18124 @node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18125 @ifnottex
18126 @unnumberedsubsubsec Digression about the word `error'
18127 @end ifnottex
18129 (In my opinion, it is slightly misleading, at least to humans, to use
18130 the term `error' as the name of the @code{error} function.  A better
18131 term would be `cancel'.  Strictly speaking, of course, you cannot
18132 point to, much less rotate a pointer to a list that has no length, so
18133 from the point of view of the computer, the word `error' is correct.
18134 But a human expects to attempt this sort of thing, if only to find out
18135 whether the kill ring is full or empty.  This is an act of
18136 exploration.
18138 (From the human point of view, the act of exploration and discovery is
18139 not necessarily an error, and therefore should not be labelled as one,
18140 even in the bowels of a computer.  As it is, the code in Emacs implies
18141 that a human who is acting virtuously, by exploring his or her
18142 environment, is making an error.  This is bad.  Even though the computer
18143 takes the same steps as it does when there is an `error', a term such as
18144 `cancel' would have a clearer connotation.)
18146 @node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18147 @unnumberedsubsubsec The else-part of the @code{if} expression
18149 The else-part of the @code{if} expression is dedicated to setting the
18150 value of @code{kill-ring-yank-pointer} when the kill ring has something
18151 in it.  The code looks like this:
18153 @smallexample
18154 @group
18155 (setq kill-ring-yank-pointer
18156       (nthcdr (% (+ arg
18157                     (- length
18158                        (length kill-ring-yank-pointer)))
18159                  length)
18160               kill-ring)))))
18161 @end group
18162 @end smallexample
18164 This needs some examination.  Clearly, @code{kill-ring-yank-pointer}
18165 is being set to be equal to some @sc{cdr} of the kill ring, using the
18166 @code{nthcdr} function that is described in an earlier section.
18167 (@xref{copy-region-as-kill}.)  But exactly how does it do this?
18169 Before looking at the details of the code let's first consider the
18170 purpose of the @code{rotate-yank-pointer} function.
18172 The @code{rotate-yank-pointer} function changes what
18173 @code{kill-ring-yank-pointer} points to.  If
18174 @code{kill-ring-yank-pointer} starts by pointing to the first element
18175 of a list, a call to @code{rotate-yank-pointer} causes it to point to
18176 the second element; and if @code{kill-ring-yank-pointer} points to the
18177 second element, a call to @code{rotate-yank-pointer} causes it to
18178 point to the third element.  (And if @code{rotate-yank-pointer} is
18179 given an argument greater than 1, it jumps the pointer that many
18180 elements.)
18182 The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18183 the @code{kill-ring-yank-pointer} points to.  If
18184 @code{kill-ring-yank-pointer} points to the first element of the kill
18185 ring, then, in the simplest case, the @code{rotate-yank-pointer}
18186 function must cause it to point to the second element.  Put another
18187 way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18188 to the @sc{cdr} of the kill ring.
18190 @need 1250
18191 That is, under these circumstances,
18193 @smallexample
18194 @group
18195 (setq kill-ring-yank-pointer
18196    ("some text" "a different piece of text" "yet more text"))
18198 (setq kill-ring
18199    ("some text" "a different piece of text" "yet more text"))
18200 @end group
18201 @end smallexample
18203 @need 800
18204 @noindent
18205 the code should do this:
18207 @smallexample
18208 (setq kill-ring-yank-pointer (cdr kill-ring))
18209 @end smallexample
18211 @need 1000
18212 @noindent
18213 As a result, the @code{kill-ring-yank-pointer} will look like this:
18215 @smallexample
18216 @group
18217 kill-ring-yank-pointer
18218      @result{} ("a different piece of text" "yet more text"))
18219 @end group
18220 @end smallexample
18222 The actual @code{setq} expression uses the @code{nthcdr} function to do
18223 the job.
18225 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18226 works by repeatedly taking the @sc{cdr} of a list---it takes the
18227 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18229 @need 800
18230 The two following expressions produce the same result:
18232 @smallexample
18233 @group
18234 (setq kill-ring-yank-pointer (cdr kill-ring))
18236 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18237 @end group
18238 @end smallexample
18240 In the @code{rotate-yank-pointer} function, however, the first
18241 argument to @code{nthcdr} is a rather complex looking expression with
18242 lots of arithmetic inside of it:
18244 @smallexample
18245 @group
18246 (% (+ arg
18247       (- length
18248          (length kill-ring-yank-pointer)))
18249    length)
18250 @end group
18251 @end smallexample
18253 As usual, we need to look at the most deeply embedded expression first
18254 and then work our way towards the light.
18256 The most deeply embedded expression is @code{(length
18257 kill-ring-yank-pointer)}.  This finds the length of the current value of
18258 the @code{kill-ring-yank-pointer}.  (Remember that the
18259 @code{kill-ring-yank-pointer} is the name of a variable whose value is a
18260 list.)
18262 @need 800
18263 The measurement of the length is inside the expression:
18265 @smallexample
18266 (- length (length kill-ring-yank-pointer))
18267 @end smallexample
18269 @noindent
18270 In this expression, the first @code{length} is the variable that was
18271 assigned the length of the kill ring in the @code{let} statement at the
18272 beginning of the function.  (One might think this function would be
18273 clearer if the variable @code{length} were named
18274 @code{length-of-kill-ring} instead; but if you look at the text of the
18275 whole function, you will see that it is so short that naming this
18276 variable @code{length} is not a bother, unless you are pulling the
18277 function apart into very tiny pieces as we are doing here.)
18279 So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18280 difference between the length of the kill ring and the length of the list
18281 whose name is @code{kill-ring-yank-pointer}.
18283 To see how all this fits into the @code{rotate-yank-pointer}
18284 function, let's begin by analyzing the case where
18285 @code{kill-ring-yank-pointer} points to the first element of the kill
18286 ring, just as @code{kill-ring} does, and see what happens when
18287 @code{rotate-yank-pointer} is called with an argument of 1.
18289 The variable @code{length} and the value of the expression
18290 @code{(length kill-ring-yank-pointer)} will be the same since the
18291 variable @code{length} is the length of the kill ring and the
18292 @code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18293 Consequently, the value of
18295 @smallexample
18296 (- length (length kill-ring-yank-pointer))
18297 @end smallexample
18299 @noindent
18300 will be zero.  Since the value of @code{arg} will be 1, this will mean
18301 that the value of the whole expression
18303 @smallexample
18304 (+ arg (- length (length kill-ring-yank-pointer)))
18305 @end smallexample
18307 @noindent
18308 will be 1.
18310 Consequently, the argument to @code{nthcdr} will be found as the result of
18311 the expression
18313 @smallexample
18314 (% 1 length)
18315 @end smallexample
18317 @node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18318 @unnumberedsubsubsec The @code{%} remainder function
18320 To understand @code{(% 1 length)}, we need to understand @code{%}.
18321 According to its documentation (which I just found by typing @kbd{C-h
18322 f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18323 its first argument divided by its second argument.  For example, the
18324 remainder of 5 divided by 2 is 1.  (2 goes into 5 twice with a
18325 remainder of 1.)
18327 What surprises people who don't often do arithmetic is that a smaller
18328 number can be divided by a larger number and have a remainder.  In the
18329 example we just used, 5 was divided by 2.  We can reverse that and ask,
18330 what is the result of dividing 2 by 5?  If you can use fractions, the
18331 answer is obviously 2/5 or .4; but if, as here, you can only use whole
18332 numbers, the result has to be something different.  Clearly, 5 can go into
18333 2 zero times, but what of the remainder?  To see what the answer is,
18334 consider a case that has to be familiar from childhood:
18336 @itemize @bullet
18337 @item
18338 5 divided by 5 is 1 with a remainder of 0;
18340 @item
18341 6 divided by 5 is 1 with a remainder of 1;
18343 @item
18344 7 divided by 5 is 1 with a remainder of 2.
18346 @item
18347 Similarly, 10 divided by 5 is 2 with a remainder of 0;
18349 @item
18350 11 divided by 5 is 2 with a remainder of 1;
18352 @item
18353 12 divided by 5 is 1 with a remainder of 2.
18354 @end itemize
18356 @need 1250
18357 @noindent
18358 By considering the cases as parallel, we can see that
18360 @itemize @bullet
18361 @item
18362 zero divided by 5 must be zero with a remainder of zero;
18364 @item
18365 1 divided by 5 must be zero with a remainder of 1;
18367 @item
18368 2 divided by 5 must be zero with a remainder of 2;
18369 @end itemize
18371 @noindent
18372 and so on.
18374 @need 1250
18375 So, in this code, if the value of @code{length} is 5, then the result of
18376 evaluating
18378 @smallexample
18379 (% 1 5)
18380 @end smallexample
18382 @noindent
18383 is 1.  (I just checked this by placing the cursor after the expression
18384 and typing @kbd{C-x C-e}.  Indeed, 1 is printed in the echo area.)
18386 @node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18387 @unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18389 When the @code{kill-ring-yank-pointer} points to the
18390 beginning of the kill ring, and the argument passed to
18391 @code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18393 @smallexample
18394 @group
18395 (- length (length kill-ring-yank-pointer))
18396      @result{} 0
18397 @end group
18398 @end smallexample
18400 @need 1250
18401 @noindent
18402 therefore,
18404 @smallexample
18405 @group
18406 (+ arg (- length (length kill-ring-yank-pointer)))
18407      @result{} 1
18408 @end group
18409 @end smallexample
18411 @need 1250
18412 @noindent
18413 and consequently:
18415 @smallexample
18416 @group
18417 (% (+ arg (- length (length kill-ring-yank-pointer)))
18418    length)
18419      @result{} 1
18420 @end group
18421 @end smallexample
18423 @noindent
18424 regardless of the value of @code{length}.
18426 @need 1250
18427 @noindent
18428 As a result of this, the @code{setq kill-ring-yank-pointer} expression
18429 simplifies to:
18431 @smallexample
18432 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18433 @end smallexample
18435 @noindent
18436 What it does is now easy to understand.  Instead of pointing as it did
18437 to the first element of the kill ring, the
18438 @code{kill-ring-yank-pointer} is set to point to the second element.
18440 Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18441 the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18442 and so on for different values of the argument.
18444 Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18445 the second element of the kill ring, its length is shorter than the
18446 length of the kill ring by 1, so the computation of the remainder is
18447 based on the expression @code{(% (+ arg 1) length)}.  This means that
18448 the @code{kill-ring-yank-pointer} is moved from the second element of
18449 the kill ring to the third element if the argument passed to
18450 @code{rotate-yank-pointer} is 1.
18452 @node kill-rng-yk-ptr last elt,  , rotate-yk-ptr remainder, rotate-yk-ptr body
18453 @unnumberedsubsubsec Pointing to the last element
18455 The final question is, what happens if the @code{kill-ring-yank-pointer}
18456 is set to the @emph{last} element of the kill ring?  Will a call to
18457 @code{rotate-yank-pointer} mean that nothing more can be taken from the
18458 kill ring?  The answer is no.  What happens is different and useful.
18459 The @code{kill-ring-yank-pointer} is set to point to the beginning of
18460 the kill ring instead.
18462 Let's see how this works by looking at the code, assuming the length of the
18463 kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18464 When the @code{kill-ring-yank-pointer} points to the last element of
18465 the kill ring, its length is 1.  The code looks like this:
18467 @smallexample
18468 (% (+ arg (- length (length kill-ring-yank-pointer))) length)
18469 @end smallexample
18471 @need 1250
18472 When the variables are replaced by their numeric values, the expression
18473 looks like this:
18475 @smallexample
18476 (% (+ 1 (- 5 1)) 5)
18477 @end smallexample
18479 @noindent
18480 This expression can be evaluated by looking at the most embedded inner
18481 expression first and working outwards:  The value of @code{(- 5 1)} is 4;
18482 the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18483 zero.  So what @code{rotate-yank-pointer} will do is
18485 @smallexample
18486 (setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18487 @end smallexample
18489 @noindent
18490 which will set the @code{kill-ring-yank-pointer} to point to the beginning
18491 of the kill ring.
18493 So what happens with successive calls to @code{rotate-yank-pointer} is that
18494 it moves the @code{kill-ring-yank-pointer} from element to element in the
18495 kill ring until it reaches the end; then it jumps back to the beginning.
18496 And this is why the kill ring is called a ring, since by jumping back to
18497 the beginning, it is as if the list has no end!  (And what is a ring, but
18498 an entity with no end?)
18500 @node yank, yank-pop, rotate-yank-pointer, Kill Ring
18501 @comment  node-name,  next,  previous,  up
18502 @appendixsec @code{yank}
18503 @findex yank
18505 After learning about @code{rotate-yank-pointer}, the code for the
18506 @code{yank} function is almost easy.  It has only one tricky part, which is
18507 the computation of the argument to be passed to @code{rotate-yank-pointer}.
18509 @need 1250
18510 The code looks like this:
18512 @smallexample
18513 @group
18514 (defun yank (&optional arg)
18515   "Reinsert the last stretch of killed text.
18516 More precisely, reinsert the stretch of killed text most
18517 recently killed OR yanked.
18518 With just C-U as argument, same but put point in front
18519 (and mark at end).  With argument n, reinsert the nth
18520 most recently killed stretch of killed text.
18521 See also the command \\[yank-pop]."
18522 @end group
18523 @group
18525   (interactive "*P")
18526   (rotate-yank-pointer (if (listp arg) 0
18527                          (if (eq arg '-) -1
18528                            (1- arg))))
18529   (push-mark (point))
18530   (insert (car kill-ring-yank-pointer))
18531   (if (consp arg)
18532       (exchange-point-and-mark)))
18533 @end group
18534 @end smallexample
18536 Glancing over this code, we can understand the last few lines readily
18537 enough.  The mark is pushed, that is, remembered; then the first element
18538 (the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18539 inserted; and then, if the argument passed the function is a
18540 @code{cons}, point and mark are exchanged so the point is put in the
18541 front of the inserted text rather than at the end.  This option is
18542 explained in the documentation.  The function itself is interactive with
18543 @code{"*P"}.  This means it will not work on a read-only buffer, and that
18544 the unprocessed prefix argument is passed to the function.
18546 @menu
18547 * rotate-yk-ptr arg::           Pass the argument to @code{rotate-yank-pointer}.
18548 * rotate-yk-ptr negative arg::  Pass a negative argument.
18549 @end menu
18551 @node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18552 @unnumberedsubsubsec Passing the argument
18554 The hard part of @code{yank} is understanding the computation that
18555 determines the value of the argument passed to
18556 @code{rotate-yank-pointer}.  Fortunately, it is not so difficult as it
18557 looks at first sight.
18559 What happens is that the result of evaluating one or both of the
18560 @code{if} expressions will be a number and that number will be the
18561 argument passed to @code{rotate-yank-pointer}.
18563 @need 1250
18564 Laid out with comments, the code looks like this:
18566 @smallexample
18567 @group
18568 (if (listp arg)                         ; @r{if-part}
18569     0                                   ; @r{then-part}
18570   (if (eq arg '-)                       ; @r{else-part, inner if}
18571       -1                                ; @r{inner if's then-part}
18572     (1- arg))))                         ; @r{inner if's else-part}
18573 @end group
18574 @end smallexample
18576 @noindent
18577 This code consists of two @code{if} expression, one the else-part of
18578 the other.
18580 The first or outer @code{if} expression tests whether the argument
18581 passed to @code{yank} is a list.  Oddly enough, this will be true if
18582 @code{yank} is called without an argument---because then it will be
18583 passed the value of @code{nil} for the optional argument and an
18584 evaluation of @code{(listp nil)} returns true!  So, if no argument is
18585 passed to @code{yank}, the argument passed to
18586 @code{rotate-yank-pointer} inside of @code{yank} is zero.  This means
18587 the pointer is not moved and the first element to which
18588 @code{kill-ring-yank-pointer} points is inserted, as we expect.
18589 Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18590 read as a list, so again, a zero will be passed to
18591 @code{rotate-yank-pointer}.  (@kbd{C-u} produces an unprocessed prefix
18592 argument of @code{(4)}, which is a list of one element.)  At the same
18593 time, later in the function, this argument will be read as a
18594 @code{cons} so point will be put in the front and mark at the end of
18595 the insertion.  (The @code{P} argument to @code{interactive} is
18596 designed to provide these values for the case when an optional
18597 argument is not provided or when it is @kbd{C-u}.)
18599 The then-part of the outer @code{if} expression handles the case when
18600 there is no argument or when it is @kbd{C-u}.  The else-part handles the
18601 other situations.  The else-part is itself another @code{if} expression.
18603 The inner @code{if} expression tests whether the argument is a minus
18604 sign.  (This is done by pressing the @key{META} and @kbd{-} keys at the
18605 same time, or the @key{ESC} key and then the @kbd{-} key).  In this
18606 case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18607 argument.  This moves the @code{kill-ring-yank-pointer} backwards, which
18608 is what is desired.
18610 If the true-or-false-test of the inner @code{if} expression is false
18611 (that is, if the argument is not a minus sign), the else-part of the
18612 expression is evaluated.  This is the expression @code{(1- arg)}.
18613 Because of the two @code{if} expressions, it will only occur when the
18614 argument is a positive number or when it is a negative number (not
18615 just a minus sign on its own).  What @code{(1- arg)} does is decrement
18616 the number and return it.  (The @code{1-} function subtracts one from
18617 its argument.)  This means that if the argument to
18618 @code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18619 the first element to which @code{kill-ring-yank-pointer} points is
18620 yanked back, as you would expect.
18622 @node rotate-yk-ptr negative arg,  , rotate-yk-ptr arg, yank
18623 @unnumberedsubsubsec Passing a negative argument
18625 Finally, the question arises, what happens if either the remainder
18626 function, @code{%}, or the @code{nthcdr} function is passed a negative
18627 argument, as they quite well may?
18629 The answers can be found by a quick test.  When @code{(% -1 5)} is
18630 evaluated, a negative number is returned; and if @code{nthcdr} is
18631 called with a negative number, it returns the same value as if it were
18632 called with a first argument of zero.  This can be seen by evaluating
18633 the following code.
18635 Here the @samp{@result{}} points to the result of evaluating the code
18636 preceding it.  This was done by positioning the cursor after the code
18637 and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18638 You can do this if you are reading this in Info inside of GNU Emacs.
18640 @smallexample
18641 @group
18642 (% -1 5)
18643      @result{} -1
18644 @end group
18646 @group
18647 (setq animals '(cats dogs elephants))
18648      @result{} (cats dogs elephants)
18649 @end group
18651 @group
18652 (nthcdr 1 animals)
18653      @result{} (dogs elephants)
18654 @end group
18656 @group
18657 (nthcdr 0 animals)
18658      @result{} (cats dogs elephants)
18659 @end group
18661 @group
18662 (nthcdr -1 animals)
18663      @result{} (cats dogs elephants)
18664 @end group
18665 @end smallexample
18667 So, if a minus sign or a negative number is passed to @code{yank}, the
18668 @code{kill-ring-yank-point} is rotated backwards until it reaches the
18669 beginning of the list.  Then it stays there.  Unlike the other case,
18670 when it jumps from the end of the list to the beginning of the list,
18671 making a ring, it stops.  This makes sense.  You often want to get back
18672 to the most recently clipped out piece of text, but you don't usually
18673 want to insert text from as many as thirty kill commands ago.  So you
18674 need to work through the ring to get to the end, but won't cycle around
18675 it inadvertently if you are trying to come back to the beginning.
18677 Incidentally, any number passed to @code{yank} with a minus sign
18678 preceding it will be treated as @minus{}1.  This is evidently a
18679 simplification for writing the program.  You don't need to jump back
18680 towards the beginning of the kill ring more than one place at a time
18681 and doing this is easier than writing a function to determine the
18682 magnitude of the number that follows the minus sign.
18684 @node yank-pop,  , yank, Kill Ring
18685 @comment  node-name,  next,  previous,  up
18686 @appendixsec @code{yank-pop}
18687 @findex yank-pop
18689 After understanding @code{yank}, the @code{yank-pop} function is easy.
18690 Leaving out the documentation to save space, it looks like this:
18692 @smallexample
18693 @group
18694 (defun yank-pop (arg)
18695   (interactive "*p")
18696   (if (not (eq last-command 'yank))
18697       (error "Previous command was not a yank"))
18698 @end group
18699 @group
18700   (setq this-command 'yank)
18701   (let ((before (< (point) (mark))))
18702     (delete-region (point) (mark))
18703     (rotate-yank-pointer arg)
18704 @end group
18705 @group
18706     (set-mark (point))
18707     (insert (car kill-ring-yank-pointer))
18708     (if before (exchange-point-and-mark))))
18709 @end group
18710 @end smallexample
18712 The function is interactive with a small @samp{p} so the prefix
18713 argument is processed and passed to the function.  The command can
18714 only be used after a previous yank; otherwise an error message is
18715 sent.  This check uses the variable @code{last-command} which is
18716 discussed elsewhere.  (@xref{copy-region-as-kill}.)
18718 The @code{let} clause sets the variable @code{before} to true or false
18719 depending whether point is before or after mark and then the region
18720 between point and mark is deleted.  This is the region that was just
18721 inserted by the previous yank and it is this text that will be
18722 replaced.  Next the @code{kill-ring-yank-pointer} is rotated so that
18723 the previously inserted text is not reinserted yet again.  Mark is set
18724 at the beginning of the place the new text will be inserted and then
18725 the first element to which @code{kill-ring-yank-pointer} points is
18726 inserted.  This leaves point after the new text.  If in the previous
18727 yank, point was left before the inserted text, point and mark are now
18728 exchanged so point is again left in front of the newly inserted text.
18729 That is all there is to it!
18731 @node Full Graph, GNU Free Documentation License, Kill Ring, Top
18732 @appendix A Graph with Labelled Axes
18734 Printed axes help you understand a graph.  They convey scale.  In an
18735 earlier chapter (@pxref{Readying a Graph, ,  Readying a Graph}), we
18736 wrote the code to print the body of a graph.  Here we write the code
18737 for printing and labelling vertical and horizontal axes, along with the
18738 body itself.
18740 @menu
18741 * Labelled Example::
18742 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
18743 * print-Y-axis::                Print a label for the vertical axis.
18744 * print-X-axis::                Print a horizontal label.
18745 * Print Whole Graph::           The function to print a complete graph.
18746 @end menu
18748 @node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18749 @ifnottex
18750 @unnumberedsec Labelled Example Graph
18751 @end ifnottex
18753 Since insertions fill a buffer to the right and below point, the new
18754 graph printing function should first print the Y or vertical axis,
18755 then the body of the graph, and finally the X or horizontal axis.
18756 This sequence lays out for us the contents of the function:
18758 @enumerate
18759 @item
18760 Set up code.
18762 @item
18763 Print Y axis.
18765 @item
18766 Print body of graph.
18768 @item
18769 Print X axis.
18770 @end enumerate
18772 @need 800
18773 Here is an example of how a finished graph should look:
18775 @smallexample
18776 @group
18777     10 -
18778                   *
18779                   *  *
18780                   *  **
18781                   *  ***
18782      5 -      *   *******
18783             * *** *******
18784             *************
18785           ***************
18786      1 - ****************
18787          |   |    |    |
18788          1   5   10   15
18789 @end group
18790 @end smallexample
18792 @noindent
18793 In this graph, both the vertical and the horizontal axes are labelled
18794 with numbers.  However, in some graphs, the horizontal axis is time
18795 and would be better labelled with months, like this:
18797 @smallexample
18798 @group
18799      5 -      *
18800             * ** *
18801             *******
18802           ********** **
18803      1 - **************
18804          |    ^      |
18805          Jan  June   Jan
18806 @end group
18807 @end smallexample
18809 Indeed, with a little thought, we can easily come up with a variety of
18810 vertical and horizontal labelling schemes.  Our task could become
18811 complicated.  But complications breed confusion.  Rather than permit
18812 this, it is better choose a simple labelling scheme for our first
18813 effort, and to modify or replace it later.
18815 @need 1200
18816 These considerations suggest the following outline for the
18817 @code{print-graph} function:
18819 @smallexample
18820 @group
18821 (defun print-graph (numbers-list)
18822   "@var{documentation}@dots{}"
18823   (let ((height  @dots{}
18824         @dots{}))
18825 @end group
18826 @group
18827     (print-Y-axis height @dots{} )
18828     (graph-body-print numbers-list)
18829     (print-X-axis @dots{} )))
18830 @end group
18831 @end smallexample
18833 We can work on each part of the @code{print-graph} function definition
18834 in turn.
18836 @node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18837 @comment  node-name,  next,  previous,  up
18838 @appendixsec The @code{print-graph} Varlist
18839 @cindex @code{print-graph} varlist
18841 In writing the @code{print-graph} function, the first task is to write
18842 the varlist in the @code{let} expression.  (We will leave aside for the
18843 moment any thoughts about making the function interactive or about the
18844 contents of its documentation string.)
18846 The varlist should set several values.  Clearly, the top of the label
18847 for the vertical axis must be at least the height of the graph, which
18848 means that we must obtain this information here.  Note that the
18849 @code{print-graph-body} function also requires this information.  There
18850 is no reason to calculate the height of the graph in two different
18851 places, so we should change @code{print-graph-body} from the way we
18852 defined it earlier to take advantage of the calculation.
18854 Similarly, both the function for printing the X axis labels and the
18855 @code{print-graph-body} function need to learn the value of the width of
18856 each symbol.  We can perform the calculation here and change the
18857 definition for @code{print-graph-body} from the way we defined it in the
18858 previous chapter.
18860 The length of the label for the horizontal axis must be at least as long
18861 as the graph.  However, this information is used only in the function
18862 that prints the horizontal axis, so it does not need to be calculated here.
18864 These thoughts lead us directly to the following form for the varlist
18865 in the @code{let} for @code{print-graph}:
18867 @smallexample
18868 @group
18869 (let ((height (apply 'max numbers-list)) ; @r{First version.}
18870       (symbol-width (length graph-blank)))
18871 @end group
18872 @end smallexample
18874 @noindent
18875 As we shall see, this expression is not quite right.
18877 @node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
18878 @comment  node-name,  next,  previous,  up
18879 @appendixsec The @code{print-Y-axis} Function
18880 @cindex Axis, print vertical
18881 @cindex Y axis printing
18882 @cindex Vertical axis printing
18883 @cindex Print vertical axis
18885 The job of the @code{print-Y-axis} function is to print a label for
18886 the vertical axis that looks like this:
18888 @smallexample
18889 @group
18890     10 -
18895      5 -
18899      1 -
18900 @end group
18901 @end smallexample
18903 @noindent
18904 The function should be passed the height of the graph, and then should
18905 construct and insert the appropriate numbers and marks.
18907 It is easy enough to see in the figure what the Y axis label should
18908 look like; but to say in words, and then to write a function
18909 definition to do the job is another matter.  It is not quite true to
18910 say that we want a number and a tic every five lines: there are only
18911 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
18912 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
18913 and 9).  It is better to say that we want a number and a tic mark on
18914 the base line (number 1) and then that we want a number and a tic on
18915 the fifth line from the bottom and on every line that is a multiple of
18916 five.
18918 @menu
18919 * Height of label::             What height for the Y axis?
18920 * Compute a Remainder::         How to compute the remainder of a division.
18921 * Y Axis Element::              Construct a line for the Y axis.
18922 * Y-axis-column::               Generate a list of Y axis labels.
18923 * print-Y-axis Penultimate::    A not quite final version.
18924 @end menu
18926 @node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
18927 @ifnottex
18928 @unnumberedsubsec What height should the label be?
18929 @end ifnottex
18931 The next issue is what height the label should be?  Suppose the maximum
18932 height of tallest column of the graph is seven.  Should the highest
18933 label on the Y axis be @samp{5 -}, and should the graph stick up above
18934 the label?  Or should the highest label be @samp{7 -}, and mark the peak
18935 of the graph?  Or should the highest label be @code{10 -}, which is a
18936 multiple of five, and be higher than the topmost value of the graph?
18938 The latter form is preferred.  Most graphs are drawn within rectangles
18939 whose sides are an integral number of steps long---5, 10, 15, and so
18940 on for a step distance of five.  But as soon as we decide to use a
18941 step height for the vertical axis, we discover that the simple
18942 expression in the varlist for computing the height is wrong.  The
18943 expression is @code{(apply 'max numbers-list)}.  This returns the
18944 precise height, not the maximum height plus whatever is necessary to
18945 round up to the nearest multiple of five.  A more complex expression
18946 is required.
18948 As usual in cases like this, a complex problem becomes simpler if it is
18949 divided into several smaller problems.
18951 First, consider the case when the highest value of the graph is an
18952 integral multiple of five---when it is 5, 10, 15 ,or some higher
18953 multiple of five.  We can use this value as the Y axis height.
18955 A fairly simply way to determine whether a number is a multiple of
18956 five is to divide it by five and see if the division results in a
18957 remainder.  If there is no remainder, the number is a multiple of
18958 five.  Thus, seven divided by five has a remainder of two, and seven
18959 is not an integral multiple of five.  Put in slightly different
18960 language, more reminiscent of the classroom, five goes into seven
18961 once, with a remainder of two.  However, five goes into ten twice,
18962 with no remainder: ten is an integral multiple of five.
18964 @node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
18965 @appendixsubsec Side Trip: Compute a Remainder
18967 @findex % @r{(remainder function)}
18968 @cindex Remainder function, @code{%}
18969 In Lisp, the function for computing a remainder is @code{%}.  The
18970 function returns the remainder of its first argument divided by its
18971 second argument.  As it happens, @code{%} is a function in Emacs Lisp
18972 that you cannot discover using @code{apropos}: you find nothing if you
18973 type @kbd{M-x apropos @key{RET} remainder @key{RET}}.  The only way to
18974 learn of the existence of @code{%} is to read about it in a book such
18975 as this or in the Emacs Lisp sources.  The @code{%} function is used
18976 in the code for @code{rotate-yank-pointer}, which is described in an
18977 appendix.  (@xref{rotate-yk-ptr body, , The Body of
18978 @code{rotate-yank-pointer}}.)
18980 You can try the @code{%} function by evaluating the following two
18981 expressions:
18983 @smallexample
18984 @group
18985 (% 7 5)
18987 (% 10 5)
18988 @end group
18989 @end smallexample
18991 @noindent
18992 The first expression returns 2 and the second expression returns 0.
18994 To test whether the returned value is zero or some other number, we
18995 can use the @code{zerop} function.  This function returns @code{t} if
18996 its argument, which must be a number, is zero.
18998 @smallexample
18999 @group
19000 (zerop (% 7 5))
19001      @result{} nil
19003 (zerop (% 10 5))
19004      @result{} t
19005 @end group
19006 @end smallexample
19008 Thus, the following expression will return @code{t} if the height
19009 of the graph is evenly divisible by five:
19011 @smallexample
19012 (zerop (% height 5))
19013 @end smallexample
19015 @noindent
19016 (The value of @code{height}, of course, can be found from @code{(apply
19017 'max numbers-list)}.)
19019 On the other hand, if the value of @code{height} is not a multiple of
19020 five, we want to reset the value to the next higher multiple of five.
19021 This is straightforward arithmetic using functions with which we are
19022 already familiar.  First, we divide the value of @code{height} by five
19023 to determine how many times five goes into the number.  Thus, five
19024 goes into twelve twice.  If we add one to this quotient and multiply by
19025 five, we will obtain the value of the next multiple of five that is
19026 larger than the height.  Five goes into twelve twice.  Add one to two,
19027 and multiply by five; the result is fifteen, which is the next multiple
19028 of five that is higher than twelve.  The Lisp expression for this is:
19030 @smallexample
19031 (* (1+ (/ height 5)) 5)
19032 @end smallexample
19034 @noindent
19035 For example, if you evaluate the following, the result is 15:
19037 @smallexample
19038 (* (1+ (/ 12 5)) 5)
19039 @end smallexample
19041 All through this discussion, we have been using `five' as the value
19042 for spacing labels on the Y axis; but we may want to use some other
19043 value.  For generality, we should replace `five' with a variable to
19044 which we can assign a value.  The best name I can think of for this
19045 variable is @code{Y-axis-label-spacing}.
19047 @need 1250
19048 Using this term, and an @code{if} expression, we produce the
19049 following:
19051 @smallexample
19052 @group
19053 (if (zerop (% height Y-axis-label-spacing))
19054     height
19055   ;; @r{else}
19056   (* (1+ (/ height Y-axis-label-spacing))
19057      Y-axis-label-spacing))
19058 @end group
19059 @end smallexample
19061 @noindent
19062 This expression returns the value of @code{height} itself if the height
19063 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19064 else it computes and returns a value of @code{height} that is equal to
19065 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19067 We can now include this expression in the @code{let} expression of the
19068 @code{print-graph} function (after first setting the value of
19069 @code{Y-axis-label-spacing}):
19070 @vindex Y-axis-label-spacing
19072 @smallexample
19073 @group
19074 (defvar Y-axis-label-spacing 5
19075   "Number of lines from one Y axis label to next.")
19076 @end group
19078 @group
19079 @dots{}
19080 (let* ((height (apply 'max numbers-list))
19081        (height-of-top-line
19082         (if (zerop (% height Y-axis-label-spacing))
19083             height
19084 @end group
19085 @group
19086           ;; @r{else}
19087           (* (1+ (/ height Y-axis-label-spacing))
19088              Y-axis-label-spacing)))
19089        (symbol-width (length graph-blank))))
19090 @dots{}
19091 @end group
19092 @end smallexample
19094 @noindent
19095 (Note use of the  @code{let*} function: the initial value of height is
19096 computed once by the @code{(apply 'max numbers-list)} expression and
19097 then the resulting value of  @code{height} is used to compute its
19098 final value.  @xref{fwd-para let, , The @code{let*} expression}, for
19099 more about @code{let*}.)
19101 @node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19102 @appendixsubsec Construct a Y Axis Element
19104 When we print the vertical axis, we want to insert strings such as
19105 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19106 Moreover, we want the numbers and dashes to line up, so shorter
19107 numbers must be padded with leading spaces.  If some of the strings
19108 use two digit numbers, the strings with single digit numbers must
19109 include a leading blank space before the number.
19111 @findex number-to-string
19112 To figure out the length of the number, the @code{length} function is
19113 used.  But the @code{length} function works only with a string, not with
19114 a number.  So the number has to be converted from being a number to
19115 being a string.  This is done with the @code{number-to-string} function.
19116 For example,
19118 @smallexample
19119 @group
19120 (length (number-to-string 35))
19121      @result{} 2
19123 (length (number-to-string 100))
19124      @result{} 3
19125 @end group
19126 @end smallexample
19128 @noindent
19129 (@code{number-to-string} is also called @code{int-to-string}; you will
19130 see this alternative name in various sources.)
19132 In addition, in each label, each number is followed by a string such
19133 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19134 This variable is defined with @code{defvar}:
19136 @vindex Y-axis-tic
19137 @smallexample
19138 @group
19139 (defvar Y-axis-tic " - "
19140    "String that follows number in a Y axis label.")
19141 @end group
19142 @end smallexample
19144 The length of the Y label is the sum of the length of the Y axis tic
19145 mark and the length of the number of the top of the graph.
19147 @smallexample
19148 (length (concat (number-to-string height) Y-axis-tic)))
19149 @end smallexample
19151 This value will be calculated by the @code{print-graph} function in
19152 its varlist as @code{full-Y-label-width} and passed on.  (Note that we
19153 did not think to include this in the varlist when we first proposed it.)
19155 To make a complete vertical axis label, a tic mark is concatenated
19156 with a number; and the two together may be preceded by one or more
19157 spaces depending on how long the number is.  The label consists of
19158 three parts: the (optional) leading spaces, the number, and the tic
19159 mark.  The function is passed the value of the number for the specific
19160 row, and the value of the width of the top line, which is calculated
19161 (just once) by @code{print-graph}.
19163 @smallexample
19164 @group
19165 (defun Y-axis-element (number full-Y-label-width)
19166   "Construct a NUMBERed label element.
19167 A numbered element looks like this `  5 - ',
19168 and is padded as needed so all line up with
19169 the element for the largest number."
19170 @end group
19171 @group
19172   (let* ((leading-spaces
19173          (- full-Y-label-width
19174             (length
19175              (concat (number-to-string number)
19176                      Y-axis-tic)))))
19177 @end group
19178 @group
19179     (concat
19180      (make-string leading-spaces ? )
19181      (number-to-string number)
19182      Y-axis-tic)))
19183 @end group
19184 @end smallexample
19186 The @code{Y-axis-element} function concatenates together the leading
19187 spaces, if any; the number, as a string; and the tic mark.
19189 To figure out how many leading spaces the label will need, the
19190 function subtracts the actual length of the label---the length of the
19191 number plus the length of the tic mark---from the desired label width.
19193 @findex make-string
19194 Blank spaces are inserted using the @code{make-string} function.  This
19195 function takes two arguments: the first tells it how long the string
19196 will be and the second is a symbol for the character to insert, in a
19197 special format.  The format is a question mark followed by a blank
19198 space, like this, @samp{? }.  @xref{Character Type, , Character Type,
19199 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19200 syntax for characters.
19202 The @code{number-to-string} function is used in the concatenation
19203 expression, to convert the number to a string that is concatenated
19204 with the leading spaces and the tic mark.
19206 @node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19207 @appendixsubsec Create a Y Axis Column
19209 The preceding functions provide all the tools needed to construct a
19210 function that generates a list of numbered and blank strings to insert
19211 as the label for the vertical axis:
19213 @findex Y-axis-column
19214 @smallexample
19215 @group
19216 (defun Y-axis-column (height width-of-label)
19217   "Construct list of Y axis labels and blank strings.
19218 For HEIGHT of line above base and WIDTH-OF-LABEL."
19219   (let (Y-axis)
19220 @group
19221 @end group
19222     (while (> height 1)
19223       (if (zerop (% height Y-axis-label-spacing))
19224           ;; @r{Insert label.}
19225           (setq Y-axis
19226                 (cons
19227                  (Y-axis-element height width-of-label)
19228                  Y-axis))
19229 @group
19230 @end group
19231         ;; @r{Else, insert blanks.}
19232         (setq Y-axis
19233               (cons
19234                (make-string width-of-label ? )
19235                Y-axis)))
19236       (setq height (1- height)))
19237     ;; @r{Insert base line.}
19238     (setq Y-axis
19239           (cons (Y-axis-element 1 width-of-label) Y-axis))
19240     (nreverse Y-axis)))
19241 @end group
19242 @end smallexample
19244 In this function, we start with the value of @code{height} and
19245 repetitively subtract one from its value.  After each subtraction, we
19246 test to see whether the value is an integral multiple of the
19247 @code{Y-axis-label-spacing}.  If it is, we construct a numbered label
19248 using the @code{Y-axis-element} function; if not, we construct a
19249 blank label using the @code{make-string} function.  The base line
19250 consists of the number one followed by a tic mark.
19252 @node print-Y-axis Penultimate,  , Y-axis-column, print-Y-axis
19253 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19255 The list constructed by the @code{Y-axis-column} function is passed to
19256 the @code{print-Y-axis} function, which inserts the list as a column.
19258 @findex print-Y-axis
19259 @smallexample
19260 @group
19261 (defun print-Y-axis (height full-Y-label-width)
19262   "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19263 Height must be the maximum height of the graph.
19264 Full width is the width of the highest label element."
19265 ;; Value of height and full-Y-label-width
19266 ;; are passed by `print-graph'.
19267 @end group
19268 @group
19269   (let ((start (point)))
19270     (insert-rectangle
19271      (Y-axis-column height full-Y-label-width))
19272     ;; @r{Place point ready for inserting graph.}
19273     (goto-char start)
19274     ;; @r{Move point forward by value of} full-Y-label-width
19275     (forward-char full-Y-label-width)))
19276 @end group
19277 @end smallexample
19279 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19280 insert the Y axis labels created by the @code{Y-axis-column} function.
19281 In addition, it places point at the correct position for printing the body of
19282 the graph.
19284 You can test @code{print-Y-axis}:
19286 @enumerate
19287 @item
19288 Install
19290 @smallexample
19291 @group
19292 Y-axis-label-spacing
19293 Y-axis-tic
19294 Y-axis-element
19295 Y-axis-column
19296 print-Y-axis
19297 @end group
19298 @end smallexample
19300 @item
19301 Copy the following expression:
19303 @smallexample
19304 (print-Y-axis 12 5)
19305 @end smallexample
19307 @item
19308 Switch to the @file{*scratch*} buffer and place the cursor where you
19309 want the axis labels to start.
19311 @item
19312 Type @kbd{M-:} (@code{eval-expression}).
19314 @item
19315 Yank the @code{graph-body-print} expression into the minibuffer
19316 with @kbd{C-y} (@code{yank)}.
19318 @item
19319 Press @key{RET} to evaluate the expression.
19320 @end enumerate
19322 Emacs will print labels vertically, the top one being
19323 @w{@samp{10 -@w{ }}}.  (The @code{print-graph} function
19324 will pass the value of @code{height-of-top-line}, which
19325 in this case would end up as 15.)
19327 @node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19328 @appendixsec The @code{print-X-axis} Function
19329 @cindex Axis, print horizontal
19330 @cindex X axis printing
19331 @cindex Print horizontal axis
19332 @cindex Horizontal axis printing
19334 X axis labels are much like Y axis labels, except that the tics are on a
19335 line above the numbers.  Labels should look like this:
19337 @smallexample
19338 @group
19339     |   |    |    |
19340     1   5   10   15
19341 @end group
19342 @end smallexample
19344 The first tic is under the first column of the graph and is preceded by
19345 several blank spaces.  These spaces provide room in rows above for the Y
19346 axis labels.  The second, third, fourth, and subsequent tics are all
19347 spaced equally, according to the value of @code{X-axis-label-spacing}.
19349 The second row of the X axis consists of numbers, preceded by several
19350 blank spaces and also separated according to the value of the variable
19351 @code{X-axis-label-spacing}.
19353 The value of the variable @code{X-axis-label-spacing} should itself be
19354 measured in units of @code{symbol-width}, since you may want to change
19355 the width of the symbols that you are using to print the body of the
19356 graph without changing the ways the graph is labelled.
19358 @menu
19359 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
19360 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
19361 @end menu
19363 @node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19364 @ifnottex
19365 @unnumberedsubsec Similarities and differences
19366 @end ifnottex
19368 The @code{print-X-axis} function is constructed in more or less the
19369 same fashion as the @code{print-Y-axis} function except that it has
19370 two lines: the line of tic marks and the numbers.  We will write a
19371 separate function to print each line and then combine them within the
19372 @code{print-X-axis} function.
19374 This is a three step process:
19376 @enumerate
19377 @item
19378 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19380 @item
19381 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19383 @item
19384 Write a function to print both lines, the @code{print-X-axis} function,
19385 using @code{print-X-axis-tic-line} and
19386 @code{print-X-axis-numbered-line}.
19387 @end enumerate
19389 @node X Axis Tic Marks,  , Similarities differences, print-X-axis
19390 @appendixsubsec X Axis Tic Marks
19392 The first function should print the X axis tic marks.  We must specify
19393 the tic marks themselves and their spacing:
19395 @smallexample
19396 @group
19397 (defvar X-axis-label-spacing
19398   (if (boundp 'graph-blank)
19399       (* 5 (length graph-blank)) 5)
19400   "Number of units from one X axis label to next.")
19401 @end group
19402 @end smallexample
19404 @noindent
19405 (Note that the value of @code{graph-blank} is set by another
19406 @code{defvar}.  The @code{boundp} predicate checks whether it has
19407 already been set; @code{boundp} returns @code{nil} if it has not.
19408 If @code{graph-blank} were unbound and we did not use this conditional
19409 construction, in GNU Emacs 21, we would enter the debugger and see an
19410 error message saying
19411 @samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19413 @need 1200
19414 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19416 @smallexample
19417 @group
19418 (defvar X-axis-tic-symbol "|"
19419   "String to insert to point to a column in X axis.")
19420 @end group
19421 @end smallexample
19423 @need 1250
19424 The goal is to make a line that looks like this:
19426 @smallexample
19427        |   |    |    |
19428 @end smallexample
19430 The first tic is indented so that it is under the first column, which is
19431 indented to provide space for the Y axis labels.
19433 A tic element consists of the blank spaces that stretch from one tic to
19434 the next plus a tic symbol.  The number of blanks is determined by the
19435 width of the tic symbol and the @code{X-axis-label-spacing}.
19437 @need 1250
19438 The code looks like this:
19440 @smallexample
19441 @group
19442 ;;; X-axis-tic-element
19443 @dots{}
19444 (concat
19445  (make-string
19446   ;; @r{Make a string of blanks.}
19447   (-  (* symbol-width X-axis-label-spacing)
19448       (length X-axis-tic-symbol))
19449   ? )
19450  ;; @r{Concatenate blanks with tic symbol.}
19451  X-axis-tic-symbol)
19452 @dots{}
19453 @end group
19454 @end smallexample
19456 Next, we determine how many blanks are needed to indent the first tic
19457 mark to the first column of the graph.  This uses the value of
19458 @code{full-Y-label-width} passed it by the @code{print-graph} function.
19460 @need 1250
19461 The code to make @code{X-axis-leading-spaces}
19462 looks like this:
19464 @smallexample
19465 @group
19466 ;; X-axis-leading-spaces
19467 @dots{}
19468 (make-string full-Y-label-width ? )
19469 @dots{}
19470 @end group
19471 @end smallexample
19473 We also need to determine the length of the horizontal axis, which is
19474 the length of the numbers list, and the number of tics in the horizontal
19475 axis:
19477 @smallexample
19478 @group
19479 ;; X-length
19480 @dots{}
19481 (length numbers-list)
19482 @end group
19484 @group
19485 ;; tic-width
19486 @dots{}
19487 (* symbol-width X-axis-label-spacing)
19488 @end group
19490 @group
19491 ;; number-of-X-tics
19492 (if (zerop (% (X-length tic-width)))
19493     (/ (X-length tic-width))
19494   (1+ (/ (X-length tic-width))))
19495 @end group
19496 @end smallexample
19498 @need 1250
19499 All this leads us directly to the function for printing the X axis tic line:
19501 @findex print-X-axis-tic-line
19502 @smallexample
19503 @group
19504 (defun print-X-axis-tic-line
19505   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19506   "Print tics for X axis."
19507     (insert X-axis-leading-spaces)
19508     (insert X-axis-tic-symbol)  ; @r{Under first column.}
19509 @end group
19510 @group
19511     ;; @r{Insert second tic in the right spot.}
19512     (insert (concat
19513              (make-string
19514               (-  (* symbol-width X-axis-label-spacing)
19515                   ;; @r{Insert white space up to second tic symbol.}
19516                   (* 2 (length X-axis-tic-symbol)))
19517               ? )
19518              X-axis-tic-symbol))
19519 @end group
19520 @group
19521     ;; @r{Insert remaining tics.}
19522     (while (> number-of-X-tics 1)
19523       (insert X-axis-tic-element)
19524       (setq number-of-X-tics (1- number-of-X-tics))))
19525 @end group
19526 @end smallexample
19528 The line of numbers is equally straightforward:
19530 @need 1250
19531 First, we create a numbered element with blank spaces before each number:
19533 @findex X-axis-element
19534 @smallexample
19535 @group
19536 (defun X-axis-element (number)
19537   "Construct a numbered X axis element."
19538   (let ((leading-spaces
19539          (-  (* symbol-width X-axis-label-spacing)
19540              (length (number-to-string number)))))
19541     (concat (make-string leading-spaces ? )
19542             (number-to-string number))))
19543 @end group
19544 @end smallexample
19546 Next, we create the function to print the numbered line, starting with
19547 the number ``1'' under the first column:
19549 @findex print-X-axis-numbered-line
19550 @smallexample
19551 @group
19552 (defun print-X-axis-numbered-line
19553   (number-of-X-tics X-axis-leading-spaces)
19554   "Print line of X-axis numbers"
19555   (let ((number X-axis-label-spacing))
19556     (insert X-axis-leading-spaces)
19557     (insert "1")
19558 @end group
19559 @group
19560     (insert (concat
19561              (make-string
19562               ;; @r{Insert white space up to next number.}
19563               (-  (* symbol-width X-axis-label-spacing) 2)
19564               ? )
19565              (number-to-string number)))
19566 @end group
19567 @group
19568     ;; @r{Insert remaining numbers.}
19569     (setq number (+ number X-axis-label-spacing))
19570     (while (> number-of-X-tics 1)
19571       (insert (X-axis-element number))
19572       (setq number (+ number X-axis-label-spacing))
19573       (setq number-of-X-tics (1- number-of-X-tics)))))
19574 @end group
19575 @end smallexample
19577 Finally, we need to write the @code{print-X-axis} that uses
19578 @code{print-X-axis-tic-line} and
19579 @code{print-X-axis-numbered-line}.
19581 The function must determine the local values of the variables used by both
19582 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19583 then it must call them.  Also, it must print the carriage return that
19584 separates the two lines.
19586 The function consists of a varlist that specifies five local variables,
19587 and calls to each of the two line printing functions:
19589 @findex print-X-axis
19590 @smallexample
19591 @group
19592 (defun print-X-axis (numbers-list)
19593   "Print X axis labels to length of NUMBERS-LIST."
19594   (let* ((leading-spaces
19595           (make-string full-Y-label-width ? ))
19596 @end group
19597 @group
19598        ;; symbol-width @r{is provided by} graph-body-print
19599        (tic-width (* symbol-width X-axis-label-spacing))
19600        (X-length (length numbers-list))
19601 @end group
19602 @group
19603        (X-tic
19604         (concat
19605          (make-string
19606 @end group
19607 @group
19608           ;; @r{Make a string of blanks.}
19609           (-  (* symbol-width X-axis-label-spacing)
19610               (length X-axis-tic-symbol))
19611           ? )
19612 @end group
19613 @group
19614          ;; @r{Concatenate blanks with tic symbol.}
19615          X-axis-tic-symbol))
19616 @end group
19617 @group
19618        (tic-number
19619         (if (zerop (% X-length tic-width))
19620             (/ X-length tic-width)
19621           (1+ (/ X-length tic-width)))))
19622 @end group
19623 @group
19624     (print-X-axis-tic-line tic-number leading-spaces X-tic)
19625     (insert "\n")
19626     (print-X-axis-numbered-line tic-number leading-spaces)))
19627 @end group
19628 @end smallexample
19630 @need 1250
19631 You can test @code{print-X-axis}:
19633 @enumerate
19634 @item
19635 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19636 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19637 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19639 @item
19640 Copy the following expression:
19642 @smallexample
19643 @group
19644 (progn
19645  (let ((full-Y-label-width 5)
19646        (symbol-width 1))
19647    (print-X-axis
19648     '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19649 @end group
19650 @end smallexample
19652 @item
19653 Switch to the @file{*scratch*} buffer and place the cursor where you
19654 want the axis labels to start.
19656 @item
19657 Type @kbd{M-:} (@code{eval-expression}).
19659 @item
19660 Yank the test expression into the minibuffer
19661 with @kbd{C-y} (@code{yank)}.
19663 @item
19664 Press @key{RET} to evaluate the expression.
19665 @end enumerate
19667 @need 1250
19668 Emacs will print the horizontal axis like this:
19670 @smallexample
19671 @group
19672      |   |    |    |    |
19673      1   5   10   15   20
19674 @end group
19675 @end smallexample
19677 @node Print Whole Graph,  , print-X-axis, Full Graph
19678 @appendixsec Printing the Whole Graph
19679 @cindex Printing the whole graph
19680 @cindex Whole graph printing
19681 @cindex Graph, printing all
19683 Now we are nearly ready to print the whole graph.
19685 The function to print the graph with the proper labels follows the
19686 outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19687 Axes}), but with additions.
19689 @need 1250
19690 Here is the outline:
19692 @smallexample
19693 @group
19694 (defun print-graph (numbers-list)
19695   "@var{documentation}@dots{}"
19696   (let ((height  @dots{}
19697         @dots{}))
19698 @end group
19699 @group
19700     (print-Y-axis height @dots{} )
19701     (graph-body-print numbers-list)
19702     (print-X-axis @dots{} )))
19703 @end group
19704 @end smallexample
19706 @menu
19707 * The final version::           A few changes.
19708 * Test print-graph::            Run a short test.
19709 * Graphing words in defuns::    Executing the final code.
19710 * lambda::                      How to write an anonymous function.
19711 * mapcar::                      Apply a function to elements of a list.
19712 * Another Bug::                 Yet another bug @dots{} most insidious.
19713 * Final printed graph::         The graph itself!
19714 @end menu
19716 @node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19717 @ifnottex
19718 @unnumberedsubsec Changes for the Final Version
19719 @end ifnottex
19721 The final version is different from what we planned in two ways:
19722 first, it contains additional values calculated once in the varlist;
19723 second, it carries an option to specify the labels' increment per row.
19724 This latter feature turns out to be essential; otherwise, a graph may
19725 have more rows than fit on a display or on a sheet of paper.
19727 @need 1500
19728 This new feature requires a change to the @code{Y-axis-column}
19729 function, to add @code{vertical-step} to it.  The function looks like
19730 this:
19732 @findex Y-axis-column @r{Final version.}
19733 @smallexample
19734 @group
19735 ;;; @r{Final version.}
19736 (defun Y-axis-column
19737   (height width-of-label &optional vertical-step)
19738   "Construct list of labels for Y axis.
19739 HEIGHT is maximum height of graph.
19740 WIDTH-OF-LABEL is maximum width of label.
19741 VERTICAL-STEP, an option, is a positive integer
19742 that specifies how much a Y axis label increments
19743 for each line.  For example, a step of 5 means
19744 that each line is five units of the graph."
19745 @end group
19746 @group
19747   (let (Y-axis
19748         (number-per-line (or vertical-step 1)))
19749     (while (> height 1)
19750       (if (zerop (% height Y-axis-label-spacing))
19751 @end group
19752 @group
19753           ;; @r{Insert label.}
19754           (setq Y-axis
19755                 (cons
19756                  (Y-axis-element
19757                   (* height number-per-line)
19758                   width-of-label)
19759                  Y-axis))
19760 @end group
19761 @group
19762         ;; @r{Else, insert blanks.}
19763         (setq Y-axis
19764               (cons
19765                (make-string width-of-label ? )
19766                Y-axis)))
19767       (setq height (1- height)))
19768 @end group
19769 @group
19770     ;; @r{Insert base line.}
19771     (setq Y-axis (cons (Y-axis-element
19772                         (or vertical-step 1)
19773                         width-of-label)
19774                        Y-axis))
19775     (nreverse Y-axis)))
19776 @end group
19777 @end smallexample
19779 The values for the maximum height of graph and the width of a symbol
19780 are computed by @code{print-graph} in its @code{let} expression; so
19781 @code{graph-body-print} must be changed to accept them.
19783 @findex graph-body-print @r{Final version.}
19784 @smallexample
19785 @group
19786 ;;; @r{Final version.}
19787 (defun graph-body-print (numbers-list height symbol-width)
19788   "Print a bar graph of the NUMBERS-LIST.
19789 The numbers-list consists of the Y-axis values.
19790 HEIGHT is maximum height of graph.
19791 SYMBOL-WIDTH is number of each column."
19792 @end group
19793 @group
19794   (let (from-position)
19795     (while numbers-list
19796       (setq from-position (point))
19797       (insert-rectangle
19798        (column-of-graph height (car numbers-list)))
19799       (goto-char from-position)
19800       (forward-char symbol-width)
19801 @end group
19802 @group
19803       ;; @r{Draw graph column by column.}
19804       (sit-for 0)
19805       (setq numbers-list (cdr numbers-list)))
19806     ;; @r{Place point for X axis labels.}
19807     (forward-line height)
19808     (insert "\n")))
19809 @end group
19810 @end smallexample
19812 @need 1250
19813 Finally, the code for the @code{print-graph} function:
19815 @findex print-graph @r{Final version.}
19816 @smallexample
19817 @group
19818 ;;; @r{Final version.}
19819 (defun print-graph
19820   (numbers-list &optional vertical-step)
19821   "Print labelled bar graph of the NUMBERS-LIST.
19822 The numbers-list consists of the Y-axis values.
19823 @end group
19825 @group
19826 Optionally, VERTICAL-STEP, a positive integer,
19827 specifies how much a Y axis label increments for
19828 each line.  For example, a step of 5 means that
19829 each row is five units."
19830 @end group
19831 @group
19832   (let* ((symbol-width (length graph-blank))
19833          ;; @code{height} @r{is both the largest number}
19834          ;; @r{and the number with the most digits.}
19835          (height (apply 'max numbers-list))
19836 @end group
19837 @group
19838          (height-of-top-line
19839           (if (zerop (% height Y-axis-label-spacing))
19840               height
19841             ;; @r{else}
19842             (* (1+ (/ height Y-axis-label-spacing))
19843                Y-axis-label-spacing)))
19844 @end group
19845 @group
19846          (vertical-step (or vertical-step 1))
19847          (full-Y-label-width
19848           (length
19849 @end group
19850 @group
19851            (concat
19852             (number-to-string
19853              (* height-of-top-line vertical-step))
19854             Y-axis-tic))))
19855 @end group
19857 @group
19858     (print-Y-axis
19859      height-of-top-line full-Y-label-width vertical-step)
19860 @end group
19861 @group
19862     (graph-body-print
19863      numbers-list height-of-top-line symbol-width)
19864     (print-X-axis numbers-list)))
19865 @end group
19866 @end smallexample
19868 @node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
19869 @appendixsubsec Testing @code{print-graph}
19871 @need 1250
19872 We can test the @code{print-graph} function with a short list of numbers:
19874 @enumerate
19875 @item
19876 Install the final versions of @code{Y-axis-column},
19877 @code{graph-body-print}, and @code{print-graph} (in addition to the
19878 rest of the code.)
19880 @item
19881 Copy the following expression:
19883 @smallexample
19884 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
19885 @end smallexample
19887 @item
19888 Switch to the @file{*scratch*} buffer and place the cursor where you
19889 want the axis labels to start.
19891 @item
19892 Type @kbd{M-:} (@code{eval-expression}).
19894 @item
19895 Yank the test expression into the minibuffer
19896 with @kbd{C-y} (@code{yank)}.
19898 @item
19899 Press @key{RET} to evaluate the expression.
19900 @end enumerate
19902 @need 1250
19903 Emacs will print a graph that looks like this:
19905 @smallexample
19906 @group
19907 10 -
19910          *
19911         **   *
19912  5 -   ****  *
19913        **** ***
19914      * *********
19915      ************
19916  1 - *************
19918      |   |    |    |
19919      1   5   10   15
19920 @end group
19921 @end smallexample
19923 On the other hand, if you pass @code{print-graph} a
19924 @code{vertical-step} value of 2, by evaluating this expression:
19926 @smallexample
19927 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
19928 @end smallexample
19930 @need 1250
19931 @noindent
19932 The graph looks like this:
19934 @smallexample
19935 @group
19936 20 -
19939          *
19940         **   *
19941 10 -   ****  *
19942        **** ***
19943      * *********
19944      ************
19945  2 - *************
19947      |   |    |    |
19948      1   5   10   15
19949 @end group
19950 @end smallexample
19952 @noindent
19953 (A question: is the `2' on the bottom of the vertical axis a bug or a
19954 feature?  If you think it is a bug, and should be a `1' instead, (or
19955 even a `0'), you can modify the sources.)
19957 @node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
19958 @appendixsubsec Graphing Numbers of Words and Symbols
19960 Now for the graph for which all this code was written: a graph that
19961 shows how many function definitions contain fewer than 10 words and
19962 symbols, how many contain between 10 and 19 words and symbols, how
19963 many contain between 20 and 29 words and symbols, and so on.
19965 This is a multi-step process.  First make sure you have loaded all the
19966 requisite code.
19968 @need 1500
19969 It is a good idea to reset the value of @code{top-of-ranges} in case
19970 you have set it to some different value.  You can evaluate the
19971 following:
19973 @smallexample
19974 @group
19975 (setq top-of-ranges
19976  '(10  20  30  40  50
19977    60  70  80  90 100
19978   110 120 130 140 150
19979   160 170 180 190 200
19980   210 220 230 240 250
19981   260 270 280 290 300)
19982 @end group
19983 @end smallexample
19985 @noindent
19986 Next create a list of the number of words and symbols in each range.
19988 @need 1500
19989 @noindent
19990 Evaluate the following:
19992 @smallexample
19993 @group
19994 (setq list-for-graph
19995        (defuns-per-range
19996          (sort
19997           (recursive-lengths-list-many-files
19998            (directory-files "/usr/local/emacs/lisp"
19999                             t ".+el$"))
20000           '<)
20001          top-of-ranges))
20002 @end group
20003 @end smallexample
20005 @noindent
20006 On my machine, this takes about an hour.  It looks though 303 Lisp
20007 files in my copy of Emacs version 19.23.  After all that computing,
20008 the @code{list-for-graph} has this value:
20010 @smallexample
20011 @group
20012 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20013 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20014 @end group
20015 @end smallexample
20017 @noindent
20018 This means that my copy of Emacs has 537 function definitions with
20019 fewer than 10 words or symbols in them, 1,027 function definitions
20020 with 10 to 19 words or symbols in them, 955 function definitions with
20021 20 to 29 words or symbols in them, and so on.
20023 Clearly, just by looking at this list we can see that most function
20024 definitions contain ten to thirty words and symbols.
20026 Now for printing.  We do @emph{not} want to print a graph that is
20027 1,030 lines high @dots{}  Instead, we should print a graph that is
20028 fewer than twenty-five lines high.  A graph that height can be
20029 displayed on almost any monitor, and easily printed on a sheet of paper.
20031 This means that each value in @code{list-for-graph} must be reduced to
20032 one-fiftieth its present value.
20034 Here is a short function to do just that, using two functions we have
20035 not yet seen, @code{mapcar} and @code{lambda}.
20037 @smallexample
20038 @group
20039 (defun one-fiftieth (full-range)
20040   "Return list, each number one-fiftieth of previous."
20041  (mapcar '(lambda (arg) (/ arg 50)) full-range))
20042 @end group
20043 @end smallexample
20045 @node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20046 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20047 @cindex Anonymous function
20048 @findex lambda
20050 @code{lambda} is the symbol for an anonymous function, a function
20051 without a name.  Every time you use an anonymous function, you need to
20052 include its whole body.
20054 @need 1250
20055 @noindent
20056 Thus,
20058 @smallexample
20059 (lambda (arg) (/ arg 50))
20060 @end smallexample
20062 @noindent
20063 is a function definition that says `return the value resulting from
20064 dividing whatever is passed to me as @code{arg} by 50'.
20066 Earlier, for example, we had a function @code{multiply-by-seven}; it
20067 multiplied its argument by 7.  This function is similar, except it
20068 divides its argument by 50; and, it has no name.  The anonymous
20069 equivalent of @code{multiply-by-seven} is:
20071 @smallexample
20072 (lambda (number) (* 7 number))
20073 @end smallexample
20075 @noindent
20076 (@xref{defun, ,  The @code{defun} Special Form}.)
20078 @need 1250
20079 @noindent
20080 If we want to multiply 3 by 7, we can write:
20082 @c !!! Clear print-postscript-figures if the computer formatting this
20083 @c     document is too small and cannot handle all the diagrams and figures.
20084 @c clear print-postscript-figures
20085 @c set print-postscript-figures
20086 @c lambda example diagram #1
20087 @ifnottex
20088 @smallexample
20089 @group
20090 (multiply-by-seven 3)
20091  \_______________/ ^
20092          |         |
20093       function  argument
20094 @end group
20095 @end smallexample
20096 @end ifnottex
20097 @ifset print-postscript-figures
20098 @sp 1
20099 @tex
20100 @image{lambda-1}
20101 %%%% old method of including an image
20102 % \input /usr/local/lib/tex/inputs/psfig.tex
20103 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20104 % \catcode`\@=0 %
20105 @end tex
20106 @sp 1
20107 @end ifset
20108 @ifclear print-postscript-figures
20109 @iftex
20110 @smallexample
20111 @group
20112 (multiply-by-seven 3)
20113  \_______________/ ^
20114          |         |
20115       function  argument
20116 @end group
20117 @end smallexample
20118 @end iftex
20119 @end ifclear
20121 @noindent
20122 This expression returns 21.
20124 @need 1250
20125 @noindent
20126 Similarly, we can write:
20128 @c lambda example diagram #2
20129 @ifnottex
20130 @smallexample
20131 @group
20132 ((lambda (number) (* 7 number)) 3)
20133  \____________________________/ ^
20134                |                |
20135       anonymous function     argument
20136 @end group
20137 @end smallexample
20138 @end ifnottex
20139 @ifset print-postscript-figures
20140 @sp 1
20141 @tex
20142 @image{lambda-2}
20143 %%%% old method of including an image
20144 % \input /usr/local/lib/tex/inputs/psfig.tex
20145 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20146 % \catcode`\@=0 %
20147 @end tex
20148 @sp 1
20149 @end ifset
20150 @ifclear print-postscript-figures
20151 @iftex
20152 @smallexample
20153 @group
20154 ((lambda (number) (* 7 number)) 3)
20155  \____________________________/ ^
20156                |                |
20157       anonymous function     argument
20158 @end group
20159 @end smallexample
20160 @end iftex
20161 @end ifclear
20163 @need 1250
20164 @noindent
20165 If we want to divide 100 by 50, we can write:
20167 @c lambda example diagram #3
20168 @ifnottex
20169 @smallexample
20170 @group
20171 ((lambda (arg) (/ arg 50)) 100)
20172  \______________________/  \_/
20173              |              |
20174     anonymous function   argument
20175 @end group
20176 @end smallexample
20177 @end ifnottex
20178 @ifset print-postscript-figures
20179 @sp 1
20180 @tex
20181 @image{lambda-3}
20182 %%%% old method of including an image
20183 % \input /usr/local/lib/tex/inputs/psfig.tex
20184 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20185 % \catcode`\@=0 %
20186 @end tex
20187 @sp 1
20188 @end ifset
20189 @ifclear print-postscript-figures
20190 @iftex
20191 @smallexample
20192 @group
20193 ((lambda (arg) (/ arg 50)) 100)
20194  \______________________/  \_/
20195              |              |
20196     anonymous function   argument
20197 @end group
20198 @end smallexample
20199 @end iftex
20200 @end ifclear
20202 @noindent
20203 This expression returns 2.  The 100 is passed to the function, which
20204 divides that number by 50.
20206 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20207 Lisp Reference Manual}, for more about @code{lambda}.  Lisp and lambda
20208 expressions derive from the Lambda Calculus.
20210 @node mapcar, Another Bug, lambda, Print Whole Graph
20211 @appendixsubsec The @code{mapcar} Function
20212 @findex mapcar
20214 @code{mapcar} is a function that calls its first argument with each
20215 element of its second argument, in turn.  The second argument must be
20216 a sequence.
20218 The @samp{map} part of the name comes from the mathematical phrase,
20219 `mapping over a domain', meaning to apply a function to each of the
20220 elements in a domain.  The mathematical phrase is based on the
20221 metaphor of a surveyor walking, one step at a time, over an area he is
20222 mapping.  And @samp{car}, of course, comes from the Lisp notion of the
20223 first of a list.
20225 @need 1250
20226 @noindent
20227 For example,
20229 @smallexample
20230 @group
20231 (mapcar '1+ '(2 4 6))
20232      @result{} (3 5 7)
20233 @end group
20234 @end smallexample
20236 @noindent
20237 The function @code{1+} which adds one to its argument, is executed on
20238 @emph{each} element of the list, and a new list is returned.
20240 Contrast this with @code{apply}, which applies its first argument to
20241 all the remaining.
20242 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20243 @code{apply}.)
20245 @need 1250
20246 In the definition of @code{one-fiftieth}, the first argument is the
20247 anonymous function:
20249 @smallexample
20250 (lambda (arg) (/ arg 50))
20251 @end smallexample
20253 @noindent
20254 and the second argument is @code{full-range}, which will be bound to
20255 @code{list-for-graph}.
20257 @need 1250
20258 The whole expression looks like this:
20260 @smallexample
20261 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20262 @end smallexample
20264 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20265 Lisp Reference Manual}, for more about @code{mapcar}.
20267 Using the @code{one-fiftieth} function, we can generate a list in
20268 which each element is one-fiftieth the size of the corresponding
20269 element in @code{list-for-graph}.
20271 @smallexample
20272 @group
20273 (setq fiftieth-list-for-graph
20274       (one-fiftieth list-for-graph))
20275 @end group
20276 @end smallexample
20278 @need 1250
20279 The resulting list looks like this:
20281 @smallexample
20282 @group
20283 (10 20 19 15 11 9 6 5 4 3 3 2 2
20284 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20285 @end group
20286 @end smallexample
20288 @noindent
20289 This, we are almost ready to print!  (We also notice the loss of
20290 information: many of the higher ranges are 0, meaning that fewer than
20291 50 defuns had that many words or symbols---but not necessarily meaning
20292 that none had that many words or symbols.)
20294 @node Another Bug, Final printed graph, mapcar, Print Whole Graph
20295 @appendixsubsec Another Bug @dots{} Most Insidious
20296 @cindex Bug, most insidious type
20297 @cindex Insidious type of bug
20299 I said `almost ready to print'!  Of course, there is a bug in the
20300 @code{print-graph} function @dots{}  It has a @code{vertical-step}
20301 option, but not a @code{horizontal-step} option.  The
20302 @code{top-of-range} scale goes from 10 to 300 by tens.  But the
20303 @code{print-graph} function will print only by ones.
20305 This is a classic example of what some consider the most insidious
20306 type of bug, the bug of omission.  This is not the kind of bug you can
20307 find by studying the code, for it is not in the code; it is an omitted
20308 feature.  Your best actions are to try your program early and often;
20309 and try to arrange, as much as you can, to write code that is easy to
20310 understand and easy to change.  Try to be aware, whenever you can,
20311 that whatever you have written, @emph{will} be rewritten, if not soon,
20312 eventually.  A hard maxim to follow.
20314 It is the @code{print-X-axis-numbered-line} function that needs the
20315 work; and then the @code{print-X-axis} and the @code{print-graph}
20316 functions need to be adapted.  Not much needs to be done; there is one
20317 nicety: the numbers ought to line up under the tic marks.  This takes
20318 a little thought.
20320 @need 1250
20321 Here is the corrected @code{print-X-axis-numbered-line}:
20323 @smallexample
20324 @group
20325 (defun print-X-axis-numbered-line
20326   (number-of-X-tics X-axis-leading-spaces
20327    &optional horizontal-step)
20328   "Print line of X-axis numbers"
20329   (let ((number X-axis-label-spacing)
20330         (horizontal-step (or horizontal-step 1)))
20331 @end group
20332 @group
20333     (insert X-axis-leading-spaces)
20334     ;; @r{Delete extra leading spaces.}
20335     (delete-char
20336      (- (1-
20337          (length (number-to-string horizontal-step)))))
20338     (insert (concat
20339              (make-string
20340 @end group
20341 @group
20342               ;; @r{Insert white space.}
20343               (-  (* symbol-width
20344                      X-axis-label-spacing)
20345                   (1-
20346                    (length
20347                     (number-to-string horizontal-step)))
20348                   2)
20349               ? )
20350              (number-to-string
20351               (* number horizontal-step))))
20352 @end group
20353 @group
20354     ;; @r{Insert remaining numbers.}
20355     (setq number (+ number X-axis-label-spacing))
20356     (while (> number-of-X-tics 1)
20357       (insert (X-axis-element
20358                (* number horizontal-step)))
20359       (setq number (+ number X-axis-label-spacing))
20360       (setq number-of-X-tics (1- number-of-X-tics)))))
20361 @end group
20362 @end smallexample
20364 @need 1500
20365 If you are reading this in Info, you can see the new versions of
20366 @code{print-X-axis} @code{print-graph} and evaluate them.  If you are
20367 reading this in a printed book, you can see the changed lines here
20368 (the full text is too much to print).
20370 @iftex
20371 @smallexample
20372 @group
20373 (defun print-X-axis (numbers-list horizontal-step)
20374   @dots{}
20375     (print-X-axis-numbered-line
20376      tic-number leading-spaces horizontal-step))
20377 @end group
20378 @end smallexample
20380 @smallexample
20381 @group
20382 (defun print-graph
20383   (numbers-list
20384    &optional vertical-step horizontal-step)
20385   @dots{}
20386     (print-X-axis numbers-list horizontal-step))
20387 @end group
20388 @end smallexample
20389 @end iftex
20391 @ifnottex
20392 @smallexample
20393 @group
20394 (defun print-X-axis (numbers-list horizontal-step)
20395   "Print X axis labels to length of NUMBERS-LIST.
20396 Optionally, HORIZONTAL-STEP, a positive integer,
20397 specifies how much an X  axis label increments for
20398 each column."
20399 @end group
20400 @group
20401 ;; Value of symbol-width and full-Y-label-width
20402 ;; are passed by `print-graph'.
20403   (let* ((leading-spaces
20404           (make-string full-Y-label-width ? ))
20405        ;; symbol-width @r{is provided by} graph-body-print
20406        (tic-width (* symbol-width X-axis-label-spacing))
20407        (X-length (length numbers-list))
20408 @end group
20409 @group
20410        (X-tic
20411         (concat
20412          (make-string
20413           ;; @r{Make a string of blanks.}
20414           (-  (* symbol-width X-axis-label-spacing)
20415               (length X-axis-tic-symbol))
20416           ? )
20417 @end group
20418 @group
20419          ;; @r{Concatenate blanks with tic symbol.}
20420          X-axis-tic-symbol))
20421        (tic-number
20422         (if (zerop (% X-length tic-width))
20423             (/ X-length tic-width)
20424           (1+ (/ X-length tic-width)))))
20425 @end group
20427 @group
20428     (print-X-axis-tic-line
20429      tic-number leading-spaces X-tic)
20430     (insert "\n")
20431     (print-X-axis-numbered-line
20432      tic-number leading-spaces horizontal-step)))
20433 @end group
20434 @end smallexample
20436 @smallexample
20437 @group
20438 (defun print-graph
20439   (numbers-list &optional vertical-step horizontal-step)
20440   "Print labelled bar graph of the NUMBERS-LIST.
20441 The numbers-list consists of the Y-axis values.
20442 @end group
20444 @group
20445 Optionally, VERTICAL-STEP, a positive integer,
20446 specifies how much a Y axis label increments for
20447 each line.  For example, a step of 5 means that
20448 each row is five units.
20449 @end group
20451 @group
20452 Optionally, HORIZONTAL-STEP, a positive integer,
20453 specifies how much an X  axis label increments for
20454 each column."
20455   (let* ((symbol-width (length graph-blank))
20456          ;; @code{height} @r{is both the largest number}
20457          ;; @r{and the number with the most digits.}
20458          (height (apply 'max numbers-list))
20459 @end group
20460 @group
20461          (height-of-top-line
20462           (if (zerop (% height Y-axis-label-spacing))
20463               height
20464             ;; @r{else}
20465             (* (1+ (/ height Y-axis-label-spacing))
20466                Y-axis-label-spacing)))
20467 @end group
20468 @group
20469          (vertical-step (or vertical-step 1))
20470          (full-Y-label-width
20471           (length
20472            (concat
20473             (number-to-string
20474              (* height-of-top-line vertical-step))
20475             Y-axis-tic))))
20476 @end group
20477 @group
20478     (print-Y-axis
20479      height-of-top-line full-Y-label-width vertical-step)
20480     (graph-body-print
20481         numbers-list height-of-top-line symbol-width)
20482     (print-X-axis numbers-list horizontal-step)))
20483 @end group
20484 @end smallexample
20485 @end ifnottex
20487 @ignore
20488 Graphing Definitions Re-listed
20490 @need 1250
20491 Here are all the graphing definitions in their final form:
20493 @smallexample
20494 @group
20495 (defvar top-of-ranges
20496  '(10  20  30  40  50
20497    60  70  80  90 100
20498   110 120 130 140 150
20499   160 170 180 190 200
20500   210 220 230 240 250)
20501  "List specifying ranges for `defuns-per-range'.")
20502 @end group
20504 @group
20505 (defvar graph-symbol "*"
20506   "String used as symbol in graph, usually an asterisk.")
20507 @end group
20509 @group
20510 (defvar graph-blank " "
20511   "String used as blank in graph, usually a blank space.
20512 graph-blank must be the same number of columns wide
20513 as graph-symbol.")
20514 @end group
20516 @group
20517 (defvar Y-axis-tic " - "
20518    "String that follows number in a Y axis label.")
20519 @end group
20521 @group
20522 (defvar Y-axis-label-spacing 5
20523   "Number of lines from one Y axis label to next.")
20524 @end group
20526 @group
20527 (defvar X-axis-tic-symbol "|"
20528   "String to insert to point to a column in X axis.")
20529 @end group
20531 @group
20532 (defvar X-axis-label-spacing
20533   (if (boundp 'graph-blank)
20534       (* 5 (length graph-blank)) 5)
20535   "Number of units from one X axis label to next.")
20536 @end group
20537 @end smallexample
20539 @smallexample
20540 @group
20541 (defun count-words-in-defun ()
20542   "Return the number of words and symbols in a defun."
20543   (beginning-of-defun)
20544   (let ((count 0)
20545         (end (save-excursion (end-of-defun) (point))))
20546 @end group
20548 @group
20549     (while
20550         (and (< (point) end)
20551              (re-search-forward
20552               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20553               end t))
20554       (setq count (1+ count)))
20555     count))
20556 @end group
20557 @end smallexample
20559 @smallexample
20560 @group
20561 (defun lengths-list-file (filename)
20562   "Return list of definitions' lengths within FILE.
20563 The returned list is a list of numbers.
20564 Each number is the number of words or
20565 symbols in one function definition."
20566 @end group
20568 @group
20569   (message "Working on `%s' ... " filename)
20570   (save-excursion
20571     (let ((buffer (find-file-noselect filename))
20572           (lengths-list))
20573       (set-buffer buffer)
20574       (setq buffer-read-only t)
20575       (widen)
20576       (goto-char (point-min))
20577 @end group
20579 @group
20580       (while (re-search-forward "^(defun" nil t)
20581         (setq lengths-list
20582               (cons (count-words-in-defun) lengths-list)))
20583       (kill-buffer buffer)
20584       lengths-list)))
20585 @end group
20586 @end smallexample
20588 @smallexample
20589 @group
20590 (defun lengths-list-many-files (list-of-files)
20591   "Return list of lengths of defuns in LIST-OF-FILES."
20592   (let (lengths-list)
20593 ;;; @r{true-or-false-test}
20594     (while list-of-files
20595       (setq lengths-list
20596             (append
20597              lengths-list
20598 @end group
20599 @group
20600 ;;; @r{Generate a lengths' list.}
20601              (lengths-list-file
20602               (expand-file-name (car list-of-files)))))
20603 ;;; @r{Make files' list shorter.}
20604       (setq list-of-files (cdr list-of-files)))
20605 ;;; @r{Return final value of lengths' list.}
20606     lengths-list))
20607 @end group
20608 @end smallexample
20610 @smallexample
20611 @group
20612 (defun defuns-per-range (sorted-lengths top-of-ranges)
20613   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20614   (let ((top-of-range (car top-of-ranges))
20615         (number-within-range 0)
20616         defuns-per-range-list)
20617 @end group
20619 @group
20620     ;; @r{Outer loop.}
20621     (while top-of-ranges
20623       ;; @r{Inner loop.}
20624       (while (and
20625               ;; @r{Need number for numeric test.}
20626               (car sorted-lengths)
20627               (< (car sorted-lengths) top-of-range))
20629         ;; @r{Count number of definitions within current range.}
20630         (setq number-within-range (1+ number-within-range))
20631         (setq sorted-lengths (cdr sorted-lengths)))
20632 @end group
20634 @group
20635       ;; @r{Exit inner loop but remain within outer loop.}
20637       (setq defuns-per-range-list
20638             (cons number-within-range defuns-per-range-list))
20639       (setq number-within-range 0)      ; @r{Reset count to zero.}
20641       ;; @r{Move to next range.}
20642       (setq top-of-ranges (cdr top-of-ranges))
20643       ;; @r{Specify next top of range value.}
20644       (setq top-of-range (car top-of-ranges)))
20645 @end group
20647 @group
20648     ;; @r{Exit outer loop and count the number of defuns larger than}
20649     ;; @r{  the largest top-of-range value.}
20650     (setq defuns-per-range-list
20651           (cons
20652            (length sorted-lengths)
20653            defuns-per-range-list))
20655     ;; @r{Return a list of the number of definitions within each range,}
20656     ;; @r{  smallest to largest.}
20657     (nreverse defuns-per-range-list)))
20658 @end group
20659 @end smallexample
20661 @smallexample
20662 @group
20663 (defun column-of-graph (max-graph-height actual-height)
20664   "Return list of MAX-GRAPH-HEIGHT strings;
20665 ACTUAL-HEIGHT are graph-symbols.
20666 The graph-symbols are contiguous entries at the end
20667 of the list.
20668 The list will be inserted as one column of a graph.
20669 The strings are either graph-blank or graph-symbol."
20670 @end group
20672 @group
20673   (let ((insert-list nil)
20674         (number-of-top-blanks
20675          (- max-graph-height actual-height)))
20677     ;; @r{Fill in @code{graph-symbols}.}
20678     (while (> actual-height 0)
20679       (setq insert-list (cons graph-symbol insert-list))
20680       (setq actual-height (1- actual-height)))
20681 @end group
20683 @group
20684     ;; @r{Fill in @code{graph-blanks}.}
20685     (while (> number-of-top-blanks 0)
20686       (setq insert-list (cons graph-blank insert-list))
20687       (setq number-of-top-blanks
20688             (1- number-of-top-blanks)))
20690     ;; @r{Return whole list.}
20691     insert-list))
20692 @end group
20693 @end smallexample
20695 @smallexample
20696 @group
20697 (defun Y-axis-element (number full-Y-label-width)
20698   "Construct a NUMBERed label element.
20699 A numbered element looks like this `  5 - ',
20700 and is padded as needed so all line up with
20701 the element for the largest number."
20702 @end group
20703 @group
20704   (let* ((leading-spaces
20705          (- full-Y-label-width
20706             (length
20707              (concat (number-to-string number)
20708                      Y-axis-tic)))))
20709 @end group
20710 @group
20711     (concat
20712      (make-string leading-spaces ? )
20713      (number-to-string number)
20714      Y-axis-tic)))
20715 @end group
20716 @end smallexample
20718 @smallexample
20719 @group
20720 (defun print-Y-axis
20721   (height full-Y-label-width &optional vertical-step)
20722   "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20723 Height must be the  maximum height of the graph.
20724 Full width is the width of the highest label element.
20725 Optionally, print according to VERTICAL-STEP."
20726 @end group
20727 @group
20728 ;; Value of height and full-Y-label-width
20729 ;; are passed by `print-graph'.
20730   (let ((start (point)))
20731     (insert-rectangle
20732      (Y-axis-column height full-Y-label-width vertical-step))
20733 @end group
20734 @group
20735     ;; @r{Place point ready for inserting graph.}
20736     (goto-char start)
20737     ;; @r{Move point forward by value of} full-Y-label-width
20738     (forward-char full-Y-label-width)))
20739 @end group
20740 @end smallexample
20742 @smallexample
20743 @group
20744 (defun print-X-axis-tic-line
20745   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20746   "Print tics for X axis."
20747     (insert X-axis-leading-spaces)
20748     (insert X-axis-tic-symbol)  ; @r{Under first column.}
20749 @end group
20750 @group
20751     ;; @r{Insert second tic in the right spot.}
20752     (insert (concat
20753              (make-string
20754               (-  (* symbol-width X-axis-label-spacing)
20755                   ;; @r{Insert white space up to second tic symbol.}
20756                   (* 2 (length X-axis-tic-symbol)))
20757               ? )
20758              X-axis-tic-symbol))
20759 @end group
20760 @group
20761     ;; @r{Insert remaining tics.}
20762     (while (> number-of-X-tics 1)
20763       (insert X-axis-tic-element)
20764       (setq number-of-X-tics (1- number-of-X-tics))))
20765 @end group
20766 @end smallexample
20768 @smallexample
20769 @group
20770 (defun X-axis-element (number)
20771   "Construct a numbered X axis element."
20772   (let ((leading-spaces
20773          (-  (* symbol-width X-axis-label-spacing)
20774              (length (number-to-string number)))))
20775     (concat (make-string leading-spaces ? )
20776             (number-to-string number))))
20777 @end group
20778 @end smallexample
20780 @smallexample
20781 @group
20782 (defun graph-body-print (numbers-list height symbol-width)
20783   "Print a bar graph of the NUMBERS-LIST.
20784 The numbers-list consists of the Y-axis values.
20785 HEIGHT is maximum height of graph.
20786 SYMBOL-WIDTH is number of each column."
20787 @end group
20788 @group
20789   (let (from-position)
20790     (while numbers-list
20791       (setq from-position (point))
20792       (insert-rectangle
20793        (column-of-graph height (car numbers-list)))
20794       (goto-char from-position)
20795       (forward-char symbol-width)
20796 @end group
20797 @group
20798       ;; @r{Draw graph column by column.}
20799       (sit-for 0)
20800       (setq numbers-list (cdr numbers-list)))
20801     ;; @r{Place point for X axis labels.}
20802     (forward-line height)
20803     (insert "\n")))
20804 @end group
20805 @end smallexample
20807 @smallexample
20808 @group
20809 (defun Y-axis-column
20810   (height width-of-label &optional vertical-step)
20811   "Construct list of labels for Y axis.
20812 HEIGHT is maximum height of graph.
20813 WIDTH-OF-LABEL is maximum width of label.
20814 @end group
20815 @group
20816 VERTICAL-STEP, an option, is a positive integer
20817 that specifies how much a Y axis label increments
20818 for each line.  For example, a step of 5 means
20819 that each line is five units of the graph."
20820   (let (Y-axis
20821         (number-per-line (or vertical-step 1)))
20822 @end group
20823 @group
20824     (while (> height 1)
20825       (if (zerop (% height Y-axis-label-spacing))
20826           ;; @r{Insert label.}
20827           (setq Y-axis
20828                 (cons
20829                  (Y-axis-element
20830                   (* height number-per-line)
20831                   width-of-label)
20832                  Y-axis))
20833 @end group
20834 @group
20835         ;; @r{Else, insert blanks.}
20836         (setq Y-axis
20837               (cons
20838                (make-string width-of-label ? )
20839                Y-axis)))
20840       (setq height (1- height)))
20841 @end group
20842 @group
20843     ;; @r{Insert base line.}
20844     (setq Y-axis (cons (Y-axis-element
20845                         (or vertical-step 1)
20846                         width-of-label)
20847                        Y-axis))
20848     (nreverse Y-axis)))
20849 @end group
20850 @end smallexample
20852 @smallexample
20853 @group
20854 (defun print-X-axis-numbered-line
20855   (number-of-X-tics X-axis-leading-spaces
20856    &optional horizontal-step)
20857   "Print line of X-axis numbers"
20858   (let ((number X-axis-label-spacing)
20859         (horizontal-step (or horizontal-step 1)))
20860 @end group
20861 @group
20862     (insert X-axis-leading-spaces)
20863     ;; line up number
20864     (delete-char (- (1- (length (number-to-string horizontal-step)))))
20865     (insert (concat
20866              (make-string
20867               ;; @r{Insert white space up to next number.}
20868               (-  (* symbol-width X-axis-label-spacing)
20869                   (1- (length (number-to-string horizontal-step)))
20870                   2)
20871               ? )
20872              (number-to-string (* number horizontal-step))))
20873 @end group
20874 @group
20875     ;; @r{Insert remaining numbers.}
20876     (setq number (+ number X-axis-label-spacing))
20877     (while (> number-of-X-tics 1)
20878       (insert (X-axis-element (* number horizontal-step)))
20879       (setq number (+ number X-axis-label-spacing))
20880       (setq number-of-X-tics (1- number-of-X-tics)))))
20881 @end group
20882 @end smallexample
20884 @smallexample
20885 @group
20886 (defun print-X-axis (numbers-list horizontal-step)
20887   "Print X axis labels to length of NUMBERS-LIST.
20888 Optionally, HORIZONTAL-STEP, a positive integer,
20889 specifies how much an X  axis label increments for
20890 each column."
20891 @end group
20892 @group
20893 ;; Value of symbol-width and full-Y-label-width
20894 ;; are passed by `print-graph'.
20895   (let* ((leading-spaces
20896           (make-string full-Y-label-width ? ))
20897        ;; symbol-width @r{is provided by} graph-body-print
20898        (tic-width (* symbol-width X-axis-label-spacing))
20899        (X-length (length numbers-list))
20900 @end group
20901 @group
20902        (X-tic
20903         (concat
20904          (make-string
20905           ;; @r{Make a string of blanks.}
20906           (-  (* symbol-width X-axis-label-spacing)
20907               (length X-axis-tic-symbol))
20908           ? )
20909 @end group
20910 @group
20911          ;; @r{Concatenate blanks with tic symbol.}
20912          X-axis-tic-symbol))
20913        (tic-number
20914         (if (zerop (% X-length tic-width))
20915             (/ X-length tic-width)
20916           (1+ (/ X-length tic-width)))))
20917 @end group
20919 @group
20920     (print-X-axis-tic-line
20921      tic-number leading-spaces X-tic)
20922     (insert "\n")
20923     (print-X-axis-numbered-line
20924      tic-number leading-spaces horizontal-step)))
20925 @end group
20926 @end smallexample
20928 @smallexample
20929 @group
20930 (defun one-fiftieth (full-range)
20931   "Return list, each number of which is 1/50th previous."
20932  (mapcar '(lambda (arg) (/ arg 50)) full-range))
20933 @end group
20934 @end smallexample
20936 @smallexample
20937 @group
20938 (defun print-graph
20939   (numbers-list &optional vertical-step horizontal-step)
20940   "Print labelled bar graph of the NUMBERS-LIST.
20941 The numbers-list consists of the Y-axis values.
20942 @end group
20944 @group
20945 Optionally, VERTICAL-STEP, a positive integer,
20946 specifies how much a Y axis label increments for
20947 each line.  For example, a step of 5 means that
20948 each row is five units.
20949 @end group
20951 @group
20952 Optionally, HORIZONTAL-STEP, a positive integer,
20953 specifies how much an X  axis label increments for
20954 each column."
20955   (let* ((symbol-width (length graph-blank))
20956          ;; @code{height} @r{is both the largest number}
20957          ;; @r{and the number with the most digits.}
20958          (height (apply 'max numbers-list))
20959 @end group
20960 @group
20961          (height-of-top-line
20962           (if (zerop (% height Y-axis-label-spacing))
20963               height
20964             ;; @r{else}
20965             (* (1+ (/ height Y-axis-label-spacing))
20966                Y-axis-label-spacing)))
20967 @end group
20968 @group
20969          (vertical-step (or vertical-step 1))
20970          (full-Y-label-width
20971           (length
20972            (concat
20973             (number-to-string
20974              (* height-of-top-line vertical-step))
20975             Y-axis-tic))))
20976 @end group
20977 @group
20979     (print-Y-axis
20980      height-of-top-line full-Y-label-width vertical-step)
20981     (graph-body-print
20982         numbers-list height-of-top-line symbol-width)
20983     (print-X-axis numbers-list horizontal-step)))
20984 @end group
20985 @end smallexample
20986 @end ignore
20988 @page
20989 @node Final printed graph,  , Another Bug, Print Whole Graph
20990 @appendixsubsec The Printed Graph
20992 When made and installed, you can call the @code{print-graph} command
20993 like this:
20995 @smallexample
20996 @group
20997 (print-graph fiftieth-list-for-graph 50 10)
20998 @end group
20999 @end smallexample
21001 Here is the graph:
21003 @sp 2
21005 @smallexample
21006 @group
21007 1000 -  *
21008         **
21009         **
21010         **
21011         **
21012  750 -  ***
21013         ***
21014         ***
21015         ***
21016         ****
21017  500 - *****
21018        ******
21019        ******
21020        ******
21021        *******
21022  250 - ********
21023        *********                     *
21024        ***********                   *
21025        *************                 *
21026   50 - ***************** *           *
21027        |   |    |    |    |    |    |    |
21028       10  50  100  150  200  250  300  350
21029 @end group
21030 @end smallexample
21032 @sp 2
21034 The largest group of functions contain 10 -- 19 words and symbols each.
21036 @node GNU Free Documentation License, Index, Full Graph, Top
21037 @appendix GNU Free Documentation License
21039 @cindex FDL, GNU Free Documentation License
21040 @center Version 1.1, March 2000
21042 @display
21043 Copyright @copyright{} 2000 Free Software Foundation, Inc.
21044 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
21046 Everyone is permitted to copy and distribute verbatim copies
21047 of this license document, but changing it is not allowed.
21048 @end display
21050 @enumerate 0
21051 @item
21052 PREAMBLE
21054 The purpose of this License is to make a manual, textbook, or other
21055 written document @dfn{free} in the sense of freedom: to assure everyone
21056 the effective freedom to copy and redistribute it, with or without
21057 modifying it, either commercially or noncommercially.  Secondarily,
21058 this License preserves for the author and publisher a way to get
21059 credit for their work, while not being considered responsible for
21060 modifications made by others.
21062 This License is a kind of ``copyleft'', which means that derivative
21063 works of the document must themselves be free in the same sense.  It
21064 complements the GNU General Public License, which is a copyleft
21065 license designed for free software.
21067 We have designed this License in order to use it for manuals for free
21068 software, because free software needs free documentation: a free
21069 program should come with manuals providing the same freedoms that the
21070 software does.  But this License is not limited to software manuals;
21071 it can be used for any textual work, regardless of subject matter or
21072 whether it is published as a printed book.  We recommend this License
21073 principally for works whose purpose is instruction or reference.
21075 @item
21076 APPLICABILITY AND DEFINITIONS
21078 This License applies to any manual or other work that contains a
21079 notice placed by the copyright holder saying it can be distributed
21080 under the terms of this License.  The ``Document'', below, refers to any
21081 such manual or work.  Any member of the public is a licensee, and is
21082 addressed as ``you''.
21084 A ``Modified Version'' of the Document means any work containing the
21085 Document or a portion of it, either copied verbatim, or with
21086 modifications and/or translated into another language.
21088 A ``Secondary Section'' is a named appendix or a front-matter section of
21089 the Document that deals exclusively with the relationship of the
21090 publishers or authors of the Document to the Document's overall subject
21091 (or to related matters) and contains nothing that could fall directly
21092 within that overall subject.  (For example, if the Document is in part a
21093 textbook of mathematics, a Secondary Section may not explain any
21094 mathematics.)  The relationship could be a matter of historical
21095 connection with the subject or with related matters, or of legal,
21096 commercial, philosophical, ethical or political position regarding
21097 them.
21099 The ``Invariant Sections'' are certain Secondary Sections whose titles
21100 are designated, as being those of Invariant Sections, in the notice
21101 that says that the Document is released under this License.
21103 The ``Cover Texts'' are certain short passages of text that are listed,
21104 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
21105 the Document is released under this License.
21107 A ``Transparent'' copy of the Document means a machine-readable copy,
21108 represented in a format whose specification is available to the
21109 general public, whose contents can be viewed and edited directly and
21110 straightforwardly with generic text editors or (for images composed of
21111 pixels) generic paint programs or (for drawings) some widely available
21112 drawing editor, and that is suitable for input to text formatters or
21113 for automatic translation to a variety of formats suitable for input
21114 to text formatters.  A copy made in an otherwise Transparent file
21115 format whose markup has been designed to thwart or discourage
21116 subsequent modification by readers is not Transparent.  A copy that is
21117 not ``Transparent'' is called ``Opaque''.
21119 Examples of suitable formats for Transparent copies include plain
21120 @sc{ascii} without markup, Texinfo input format, La@TeX{} input format,
21121 @acronym{SGML} or @acronym{XML} using a publicly available
21122 @acronym{DTD}, and standard-conforming simple @acronym{HTML} designed
21123 for human modification.  Opaque formats include PostScript,
21124 @acronym{PDF}, proprietary formats that can be read and edited only by
21125 proprietary word processors, @acronym{SGML} or @acronym{XML} for which
21126 the @acronym{DTD} and/or processing tools are not generally available,
21127 and the machine-generated @acronym{HTML} produced by some word
21128 processors for output purposes only.
21130 The ``Title Page'' means, for a printed book, the title page itself,
21131 plus such following pages as are needed to hold, legibly, the material
21132 this License requires to appear in the title page.  For works in
21133 formats which do not have any title page as such, ``Title Page'' means
21134 the text near the most prominent appearance of the work's title,
21135 preceding the beginning of the body of the text.
21137 @item
21138 VERBATIM COPYING
21140 You may copy and distribute the Document in any medium, either
21141 commercially or noncommercially, provided that this License, the
21142 copyright notices, and the license notice saying this License applies
21143 to the Document are reproduced in all copies, and that you add no other
21144 conditions whatsoever to those of this License.  You may not use
21145 technical measures to obstruct or control the reading or further
21146 copying of the copies you make or distribute.  However, you may accept
21147 compensation in exchange for copies.  If you distribute a large enough
21148 number of copies you must also follow the conditions in section 3.
21150 You may also lend copies, under the same conditions stated above, and
21151 you may publicly display copies.
21153 @item
21154 COPYING IN QUANTITY
21156 If you publish printed copies of the Document numbering more than 100,
21157 and the Document's license notice requires Cover Texts, you must enclose
21158 the copies in covers that carry, clearly and legibly, all these Cover
21159 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21160 the back cover.  Both covers must also clearly and legibly identify
21161 you as the publisher of these copies.  The front cover must present
21162 the full title with all words of the title equally prominent and
21163 visible.  You may add other material on the covers in addition.
21164 Copying with changes limited to the covers, as long as they preserve
21165 the title of the Document and satisfy these conditions, can be treated
21166 as verbatim copying in other respects.
21168 If the required texts for either cover are too voluminous to fit
21169 legibly, you should put the first ones listed (as many as fit
21170 reasonably) on the actual cover, and continue the rest onto adjacent
21171 pages.
21173 If you publish or distribute Opaque copies of the Document numbering
21174 more than 100, you must either include a machine-readable Transparent
21175 copy along with each Opaque copy, or state in or with each Opaque copy
21176 a publicly-accessible computer-network location containing a complete
21177 Transparent copy of the Document, free of added material, which the
21178 general network-using public has access to download anonymously at no
21179 charge using public-standard network protocols.  If you use the latter
21180 option, you must take reasonably prudent steps, when you begin
21181 distribution of Opaque copies in quantity, to ensure that this
21182 Transparent copy will remain thus accessible at the stated location
21183 until at least one year after the last time you distribute an Opaque
21184 copy (directly or through your agents or retailers) of that edition to
21185 the public.
21187 It is requested, but not required, that you contact the authors of the
21188 Document well before redistributing any large number of copies, to give
21189 them a chance to provide you with an updated version of the Document.
21191 @item
21192 MODIFICATIONS
21194 You may copy and distribute a Modified Version of the Document under
21195 the conditions of sections 2 and 3 above, provided that you release
21196 the Modified Version under precisely this License, with the Modified
21197 Version filling the role of the Document, thus licensing distribution
21198 and modification of the Modified Version to whoever possesses a copy
21199 of it.  In addition, you must do these things in the Modified Version:
21201 @enumerate A
21202 @item
21203 Use in the Title Page (and on the covers, if any) a title distinct
21204 from that of the Document, and from those of previous versions
21205 (which should, if there were any, be listed in the History section
21206 of the Document).  You may use the same title as a previous version
21207 if the original publisher of that version gives permission.
21209 @item
21210 List on the Title Page, as authors, one or more persons or entities
21211 responsible for authorship of the modifications in the Modified
21212 Version, together with at least five of the principal authors of the
21213 Document (all of its principal authors, if it has less than five).
21215 @item
21216 State on the Title page the name of the publisher of the
21217 Modified Version, as the publisher.
21219 @item
21220 Preserve all the copyright notices of the Document.
21222 @item
21223 Add an appropriate copyright notice for your modifications
21224 adjacent to the other copyright notices.
21226 @item
21227 Include, immediately after the copyright notices, a license notice
21228 giving the public permission to use the Modified Version under the
21229 terms of this License, in the form shown in the Addendum below.
21231 @item
21232 Preserve in that license notice the full lists of Invariant Sections
21233 and required Cover Texts given in the Document's license notice.
21235 @item
21236 Include an unaltered copy of this License.
21238 @item
21239 Preserve the section entitled ``History'', and its title, and add to
21240 it an item stating at least the title, year, new authors, and
21241 publisher of the Modified Version as given on the Title Page.  If
21242 there is no section entitled ``History'' in the Document, create one
21243 stating the title, year, authors, and publisher of the Document as
21244 given on its Title Page, then add an item describing the Modified
21245 Version as stated in the previous sentence.
21247 @item
21248 Preserve the network location, if any, given in the Document for
21249 public access to a Transparent copy of the Document, and likewise
21250 the network locations given in the Document for previous versions
21251 it was based on.  These may be placed in the ``History'' section.
21252 You may omit a network location for a work that was published at
21253 least four years before the Document itself, or if the original
21254 publisher of the version it refers to gives permission.
21256 @item
21257 In any section entitled ``Acknowledgments'' or ``Dedications'',
21258 preserve the section's title, and preserve in the section all the
21259 substance and tone of each of the contributor acknowledgments
21260 and/or dedications given therein.
21262 @item
21263 Preserve all the Invariant Sections of the Document,
21264 unaltered in their text and in their titles.  Section numbers
21265 or the equivalent are not considered part of the section titles.
21267 @item
21268 Delete any section entitled ``Endorsements''.  Such a section
21269 may not be included in the Modified Version.
21271 @item
21272 Do not retitle any existing section as ``Endorsements''
21273 or to conflict in title with any Invariant Section.
21274 @end enumerate
21276 If the Modified Version includes new front-matter sections or
21277 appendices that qualify as Secondary Sections and contain no material
21278 copied from the Document, you may at your option designate some or all
21279 of these sections as invariant.  To do this, add their titles to the
21280 list of Invariant Sections in the Modified Version's license notice.
21281 These titles must be distinct from any other section titles.
21283 You may add a section entitled ``Endorsements'', provided it contains
21284 nothing but endorsements of your Modified Version by various
21285 parties---for example, statements of peer review or that the text has
21286 been approved by an organization as the authoritative definition of a
21287 standard.
21289 You may add a passage of up to five words as a Front-Cover Text, and a
21290 passage of up to 25 words as a Back-Cover Text, to the end of the list
21291 of Cover Texts in the Modified Version.  Only one passage of
21292 Front-Cover Text and one of Back-Cover Text may be added by (or
21293 through arrangements made by) any one entity.  If the Document already
21294 includes a cover text for the same cover, previously added by you or
21295 by arrangement made by the same entity you are acting on behalf of,
21296 you may not add another; but you may replace the old one, on explicit
21297 permission from the previous publisher that added the old one.
21299 The author(s) and publisher(s) of the Document do not by this License
21300 give permission to use their names for publicity for or to assert or
21301 imply endorsement of any Modified Version.
21303 @item
21304 COMBINING DOCUMENTS
21306 You may combine the Document with other documents released under this
21307 License, under the terms defined in section 4 above for modified
21308 versions, provided that you include in the combination all of the
21309 Invariant Sections of all of the original documents, unmodified, and
21310 list them all as Invariant Sections of your combined work in its
21311 license notice.
21313 The combined work need only contain one copy of this License, and
21314 multiple identical Invariant Sections may be replaced with a single
21315 copy.  If there are multiple Invariant Sections with the same name but
21316 different contents, make the title of each such section unique by
21317 adding at the end of it, in parentheses, the name of the original
21318 author or publisher of that section if known, or else a unique number.
21319 Make the same adjustment to the section titles in the list of
21320 Invariant Sections in the license notice of the combined work.
21322 In the combination, you must combine any sections entitled ``History''
21323 in the various original documents, forming one section entitled
21324 ``History''; likewise combine any sections entitled ``Acknowledgments'',
21325 and any sections entitled ``Dedications''.  You must delete all sections
21326 entitled ``Endorsements.''
21328 @item
21329 COLLECTIONS OF DOCUMENTS
21331 You may make a collection consisting of the Document and other documents
21332 released under this License, and replace the individual copies of this
21333 License in the various documents with a single copy that is included in
21334 the collection, provided that you follow the rules of this License for
21335 verbatim copying of each of the documents in all other respects.
21337 You may extract a single document from such a collection, and distribute
21338 it individually under this License, provided you insert a copy of this
21339 License into the extracted document, and follow this License in all
21340 other respects regarding verbatim copying of that document.
21342 @item
21343 AGGREGATION WITH INDEPENDENT WORKS
21345 A compilation of the Document or its derivatives with other separate
21346 and independent documents or works, in or on a volume of a storage or
21347 distribution medium, does not as a whole count as a Modified Version
21348 of the Document, provided no compilation copyright is claimed for the
21349 compilation.  Such a compilation is called an ``aggregate'', and this
21350 License does not apply to the other self-contained works thus compiled
21351 with the Document, on account of their being thus compiled, if they
21352 are not themselves derivative works of the Document.
21354 If the Cover Text requirement of section 3 is applicable to these
21355 copies of the Document, then if the Document is less than one quarter
21356 of the entire aggregate, the Document's Cover Texts may be placed on
21357 covers that surround only the Document within the aggregate.
21358 Otherwise they must appear on covers around the whole aggregate.
21360 @item
21361 TRANSLATION
21363 Translation is considered a kind of modification, so you may
21364 distribute translations of the Document under the terms of section 4.
21365 Replacing Invariant Sections with translations requires special
21366 permission from their copyright holders, but you may include
21367 translations of some or all Invariant Sections in addition to the
21368 original versions of these Invariant Sections.  You may include a
21369 translation of this License provided that you also include the
21370 original English version of this License.  In case of a disagreement
21371 between the translation and the original English version of this
21372 License, the original English version will prevail.
21374 @item
21375 TERMINATION
21377 You may not copy, modify, sublicense, or distribute the Document except
21378 as expressly provided for under this License.  Any other attempt to
21379 copy, modify, sublicense or distribute the Document is void, and will
21380 automatically terminate your rights under this License.  However,
21381 parties who have received copies, or rights, from you under this
21382 License will not have their licenses terminated so long as such
21383 parties remain in full compliance.
21385 @item
21386 FUTURE REVISIONS OF THIS LICENSE
21388 The Free Software Foundation may publish new, revised versions
21389 of the GNU Free Documentation License from time to time.  Such new
21390 versions will be similar in spirit to the present version, but may
21391 differ in detail to address new problems or concerns.  See
21392 @uref{http://www.gnu.org/copyleft/}.
21394 Each version of the License is given a distinguishing version number.
21395 If the Document specifies that a particular numbered version of this
21396 License ``or any later version'' applies to it, you have the option of
21397 following the terms and conditions either of that specified version or
21398 of any later version that has been published (not as a draft) by the
21399 Free Software Foundation.  If the Document does not specify a version
21400 number of this License, you may choose any version ever published (not
21401 as a draft) by the Free Software Foundation.
21402 @end enumerate
21404 @node Index, About the Author, GNU Free Documentation License, Top
21405 @comment  node-name,  next,  previous,  up
21406 @unnumbered Index
21408 @ignore
21409 MENU ENTRY: NODE NAME.
21410 @end ignore
21412 @printindex cp
21414 @iftex
21415 @c Place biographical information on right-hand (verso) page
21417 @tex
21418 \ifodd\pageno
21419     \par\vfill\supereject
21420     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21421     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21422     \page\hbox{}\page
21423 \else
21424     \par\vfill\supereject
21425     \par\vfill\supereject
21426     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21427     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21428     \page\hbox{}\page
21429     \page\hbox{}\page
21431 @end tex
21433 @page
21434 @w{ }
21436 @c ================ Biographical information ================
21438 @w{ }
21439 @sp 8
21440 @center About the Author
21441 @sp 1
21442 @end iftex
21444 @ifnottex
21445 @node About the Author,  , Index, Top
21446 @unnumbered About the Author
21447 @end ifnottex
21449 @quotation
21450 Robert J. Chassell has worked with GNU Emacs since 1985.  He writes
21451 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21452 world on software freedom.  Chassell was a founding Director and
21453 Treasurer of the Free Software Foundation, Inc.  He is co-author of
21454 the @cite{Texinfo} manual, and has edited more than a dozen other
21455 books.  He graduated from Cambridge University, in England.  He has an
21456 abiding interest in social and economic history and flies his own
21457 airplane.
21458 @end quotation
21460 @page
21461 @w{ }
21463 @c Prevent page number on blank verso, so eject it first.
21464 @tex
21465 \par\vfill\supereject
21466 @end tex
21468 @iftex
21469 @headings off
21470 @evenheading @thispage @| @| @thistitle
21471 @oddheading            @| @| @thispage
21472 @end iftex
21474 @bye