]> code.delx.au - gnu-emacs/blob - lispintro/emacs-lisp-intro.texi
(Index): @ignore extraneous text.
[gnu-emacs] / lispintro / emacs-lisp-intro.texi
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
10
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 ---------
21
22 @comment %**end of header
23
24 @set edition-number 2.02
25 @set update-date 2001 Nov 25
26
27 @ignore
28 ## Summary of shell commands to create various output formats:
29
30 ## Info output
31 makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
32
33 ## DVI output
34 texi2dvi emacs-lisp-intro.texi
35
36 ## HTML output
37 makeinfo --html --no-split --verbose emacs-lisp-intro.texi
38
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
42
43 @end ignore
44
45 @c ================ Included Figures ================
46
47 @c Set print-postscript-figures if you print PostScript figures.
48 @c If you clear this, the ten figures will be printed as ASCII diagrams.
49 @c (This is not relevant to Info, since Info only handles ASCII.)
50 @c Your site may require editing changes to print PostScript; in this
51 @c case, search for `print-postscript-figures' and make appropriate changes.
52
53
54 @c ================ How to Create an Info file ================
55
56 @c If you have `makeinfo' installed, run the following command
57
58 @c makeinfo emacs-lisp-intro.texi
59
60 @c or, if you want a single, large Info file, and no paragraph indents:
61 @c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
62
63 @c After creating the Info file, edit your Info `dir' file, if the
64 @c START-INFO-DIR-ENTRY section below does not enable your system to
65 @c install the manual automatically.
66 @c (The `dir' file is often in the `/usr/local/info/' directory.)
67
68 @c ================ How to Create an HTML file ================
69
70 @c To convert to HTML format
71 @c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
72
73 @c ================ How to Print a Book in Various Sizes ================
74
75 @c This book can be printed in any of three different sizes.
76 @c In the above header, set @-commands appropriately.
77
78 @c 7 by 9.25 inches:
79 @c @smallbook
80 @c @clear largebook
81
82 @c 8.5 by 11 inches:
83 @c @c smallbook
84 @c @set largebook
85
86 @c European A4 size paper:
87 @c @c smallbook
88 @c @afourpaper
89 @c @set largebook
90
91 @c ================ How to Typeset and Print ================
92
93 @c If you do not include PostScript figures, run either of the
94 @c following command sequences, or similar commands suited to your
95 @c system:
96
97 @c texi2dvi emacs-lisp-intro.texi
98 @c lpr -d emacs-lisp-intro.dvi
99
100 @c or else:
101
102 @c tex emacs-lisp-intro.texi
103 @c texindex emacs-lisp-intro.??
104 @c tex emacs-lisp-intro.texi
105 @c lpr -d emacs-lisp-intro.dvi
106
107 @c If you include the PostScript figures, and you have old software,
108 @c you may need to convert the .dvi file to a .ps file before
109 @c printing. Run either of the following command sequences, or one
110 @c similar:
111 @c
112 @c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
113 @c
114 @c or else:
115 @c
116 @c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
117 @c
118
119 @c (Note: if you edit the book so as to change the length of the
120 @c table of contents, you may have to change the value of `pageno' below.)
121
122 @c ================ End of Formatting Sections ================
123
124 @c For next or subsequent edition:
125 @c create function using with-output-to-temp-buffer
126 @c create a major mode, with keymaps
127 @c run an asynchronous process, like grep or diff
128
129 @c For smallbook format, use smaller than normal amounts of
130 @c whitespace between chapters, sections, and paragraphs.
131 @tex
132 \global\chapheadingskip = 15pt plus 4pt minus 2pt
133 \global\secheadingskip = 12pt plus 3pt minus 2pt
134 \global\subsecheadingskip = 9pt plus 2pt minus 2pt \global\parskip 2pt
135 plus 1pt
136 @end tex
137
138 @c For 8.5 by 11 inch format: do not use such a small amount of
139 @c whitespace between paragraphs as above:
140 @ifset largebook
141 @tex
142 \global\parskip 6pt plus 1pt
143 @end tex
144 @end ifset
145
146 @c For all sized formats: print within-book cross
147 @c reference with ``...'' rather than [...]
148 @tex
149 % Need following so comma appears after section numbers.
150 \global\def\Ysectionnumberandtype{%
151 \ifnum\secno=0 \putwordChapter\xreftie\the\chapno, \space %
152 \else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno, \space %
153 \else \ifnum \subsubsecno=0 %
154 \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno, \space %
155 \else %
156 \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno, \space%
157 \fi \fi \fi }
158
159 \global\def\Yappendixletterandtype{%
160 \ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}, \space%
161 \else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno, \space %
162 \else \ifnum \subsubsecno=0 %
163 \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno, \space %
164 \else %
165 \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno, \space %
166 \fi \fi \fi }
167
168 \global\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
169 \def\printedmanual{\ignorespaces #5}%
170 \def\printednodename{\ignorespaces #3}%
171 \setbox1=\hbox{\printedmanual}%
172 \setbox0=\hbox{\printednodename}%
173 \ifdim \wd0 = 0pt
174 % No printed node name was explicitly given.
175 \ifx\SETxref-automatic-section-title\relax %
176 % Use the actual chapter/section title appear inside
177 % the square brackets. Use the real section title if we have it.
178 \ifdim \wd1>0pt%
179 % It is in another manual, so we don't have it.
180 \def\printednodename{\ignorespaces #1}%
181 \else
182 \ifhavexrefs
183 % We know the real title if we have the xref values.
184 \def\printednodename{\refx{#1-title}}%
185 \else
186 % Otherwise just copy the Info node name.
187 \def\printednodename{\ignorespaces #1}%
188 \fi%
189 \fi
190 \def\printednodename{#1-title}%
191 \else
192 % Use the node name inside the square brackets.
193 \def\printednodename{\ignorespaces #1}%
194 \fi
195 \fi
196 %
197 % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not
198 % insert empty discretionaries after hyphens, which means that it will
199 % not find a line break at a hyphen in a node names. Since some manuals
200 % are best written with fairly long node names, containing hyphens, this
201 % is a loss. Therefore, we give the text of the node name again, so it
202 % is as if TeX is seeing it for the first time.
203 \ifdim \wd1 > 0pt
204 \putwordsection{} ``\printednodename'' in \cite{\printedmanual}%
205 \else
206 % _ (for example) has to be the character _ for the purposes of the
207 % control sequence corresponding to the node, but it has to expand
208 % into the usual \leavevmode...\vrule stuff for purposes of
209 % printing. So we \turnoffactive for the \refx-snt, back on for the
210 % printing, back off for the \refx-pg.
211 {\turnoffactive \refx{#1-snt}{}}%
212 % \space [\printednodename],\space % <= original
213 % \putwordsection{} ``\printednodename'',\space
214 ``\printednodename'',\space
215 \turnoffactive \putwordpage\tie\refx{#1-pg}{}%
216 \fi
217 \endgroup}
218 @end tex
219
220 @c ----------------------------------------------------
221
222 @dircategory Emacs
223 @direntry
224 * Emacs Lisp Intro: (eintr).
225 A simple introduction to Emacs Lisp programming.
226 @end direntry
227
228 @ifinfo
229 This is an introduction to @cite{Programming in Emacs Lisp}, for
230 people who are not programmers.
231
232 Edition @value{edition-number}, @value{update-date}
233
234 Copyright (C) 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software Foundation, Inc.
235
236 Permission is granted to copy, distribute and/or modify this document
237 under the terms of the GNU Free Documentation License, Version 1.1 or
238 any later version published by the Free Software Foundation; with the
239 Invariant Section being the Preface, with the Front-Cover Texts being
240 no Front-Cover Texts, and with the Back-Cover Texts being no
241 Back-Cover Texts. A copy of the license is included in the section
242 entitled ``GNU Free Documentation License''.
243 @end ifinfo
244
245 @c half title; two lines here, so do not use `shorttitlepage'
246 @tex
247 {\begingroup%
248 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
249 \endgroup}%
250 {\begingroup\hbox{}\vskip 0.25in \chaprm%
251 \centerline{Programming in Emacs Lisp}%
252 \endgroup\page\hbox{}\page}
253 @end tex
254
255 @titlepage
256 @sp 6
257 @center @titlefont{An Introduction to}
258 @sp 2
259 @center @titlefont{Programming in Emacs Lisp}
260 @sp 2
261 @center Second Edition
262 @sp 4
263 @center by Robert J. Chassell
264
265 @page
266 @vskip 0pt plus 1filll
267 Copyright @copyright{} 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software Foundation, Inc.
268 @sp 2
269
270 Published by the Free Software Foundation, Inc.@*
271 59 Temple Place, Suite 330@*
272 Boston, MA 02111-1307 USA@*
273
274 Edition @value{edition-number}, @value{update-date}
275
276 @c Printed copies are available for $20 each.@*
277 ISBN-1882114-41-8
278
279 Permission is granted to copy, distribute and/or modify this document
280 under the terms of the GNU Free Documentation License, Version 1.1 or
281 any later version published by the Free Software Foundation; with the
282 Invariant Section being the Preface, with the Front-Cover Texts being
283 no Front-Cover Texts, and with the Back-Cover Texts being no
284 Back-Cover Texts. A copy of the license is included in the section
285 entitled ``GNU Free Documentation License''.
286 @end titlepage
287
288 @iftex
289 @headings off
290 @evenheading @thispage @| @| @thischapter
291 @oddheading @thissection @| @| @thispage
292 @end iftex
293
294 @ifnothtml
295
296 @c Keep T.O.C. short by tightening up.
297 @ifset largebook
298 @tex
299 \global\parskip 2pt plus 1pt
300 \global\advance\baselineskip by -1pt
301 @end tex
302 @end ifset
303
304 @shortcontents
305 @contents
306
307 @ifset largebook
308 @tex
309 \global\parskip 6pt plus 1pt
310 \global\advance\baselineskip by 1pt
311 @end tex
312 @end ifset
313
314 @end ifnothtml
315
316 @c >>>> Set pageno appropriately <<<<
317
318 @c The first page of the Preface is a roman numeral; it is the first
319 @c right handed page after the Table of Contents; hence the following
320 @c setting must be for an odd negative number.
321
322 @c if largebook, there are 8 pages in Table of Contents
323 @ifset largebook
324 @iftex
325 @pageno = -9
326 @end iftex
327 @end ifset
328
329 @c if smallbook, there are 10 pages in Table of Contents
330 @ifclear largebook
331 @iftex
332 @pageno = -11
333 @end iftex
334 @end ifclear
335
336 @ifnottex
337 @node Top, Preface, (dir), (dir)
338 @top An Introduction to Programming in Emacs Lisp
339
340 This is an introduction to @cite{Programming in Emacs Lisp}, for
341 people who are not programmers.
342
343 This master menu first lists each chapter and index; then it lists
344 every node in every chapter.
345 @end ifnottex
346
347 @menu
348 * Preface:: What to look for.
349 * List Processing:: What is Lisp?
350 * Practicing Evaluation:: Running several programs.
351 * Writing Defuns:: How to write function definitions.
352 * Buffer Walk Through:: Exploring a few buffer-related functions.
353 * More Complex:: A few, even more complex functions.
354 * Narrowing & Widening:: Restricting your and Emacs attention to
355 a region.
356 * car cdr & cons:: Fundamental functions in Lisp.
357 * Cutting & Storing Text:: Removing text and saving it.
358 * List Implementation:: How lists are implemented in the computer.
359 * Yanking:: Pasting stored text.
360 * Loops & Recursion:: How to repeat a process.
361 * Regexp Search:: Regular expression searches.
362 * Counting Words:: A review of repetition and regexps.
363 * Words in a defun:: Counting words in a @code{defun}.
364 * Readying a Graph:: A prototype graph printing function.
365 * Emacs Initialization:: How to write a @file{.emacs} file.
366 * Debugging:: How to run the Emacs Lisp debuggers.
367 * Conclusion:: Now you have the basics.
368 * the-the:: An appendix: how to find reduplicated words.
369 * Kill Ring:: An appendix: how the kill ring works.
370 * Full Graph:: How to create a graph with labelled axes.
371 * GNU Free Documentation License::
372 * Index::
373 * About the Author::
374
375 @detailmenu
376 --- The Detailed Node Listing ---
377
378 Preface
379
380 * Why:: Why learn Emacs Lisp?
381 * On Reading this Text:: Read, gain familiarity, pick up habits....
382 * Who You Are:: For whom this is written.
383 * Lisp History::
384 * Note for Novices:: You can read this as a novice.
385 * Thank You::
386
387 List Processing
388
389 * Lisp Lists:: What are lists?
390 * Run a Program:: Any list in Lisp is a program ready to run.
391 * Making Errors:: Generating an error message.
392 * Names & Definitions:: Names of symbols and function definitions.
393 * Lisp Interpreter:: What the Lisp interpreter does.
394 * Evaluation:: Running a program.
395 * Variables:: Returning a value from a variable.
396 * Arguments:: Passing information to a function.
397 * set & setq:: Setting the value of a variable.
398 * Summary:: The major points.
399 * Error Message Exercises::
400
401 Lisp Lists
402
403 * Numbers Lists:: List have numbers, other lists, in them.
404 * Lisp Atoms:: Elemental entities.
405 * Whitespace in Lists:: Formating lists to be readable.
406 * Typing Lists:: How GNU Emacs helps you type lists.
407
408 The Lisp Interpreter
409
410 * Complications:: Variables, Special forms, Lists within.
411 * Byte Compiling:: Specially processing code for speed.
412
413 Evaluation
414
415 * Evaluating Inner Lists:: Lists within lists...
416
417 Variables
418
419 * fill-column Example::
420 * Void Function:: The error message for a symbol
421 without a function.
422 * Void Variable:: The error message for a symbol without a value.
423
424 Arguments
425
426 * Data types:: Types of data passed to a function.
427 * Args as Variable or List:: An argument can be the value
428 of a variable or list.
429 * Variable Number of Arguments:: Some functions may take a
430 variable number of arguments.
431 * Wrong Type of Argument:: Passing an argument of the wrong type
432 to a function.
433 * message:: A useful function for sending messages.
434
435 Setting the Value of a Variable
436
437 * Using set:: Setting values.
438 * Using setq:: Setting a quoted value.
439 * Counting:: Using @code{setq} to count.
440
441 Practicing Evaluation
442
443 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
444 causes evaluation.
445 * Buffer Names:: Buffers and files are different.
446 * Getting Buffers:: Getting a buffer itself, not merely its name.
447 * Switching Buffers:: How to change to another buffer.
448 * Buffer Size & Locations:: Where point is located and the size of
449 the buffer.
450 * Evaluation Exercise::
451
452 How To Write Function Definitions
453
454 * Primitive Functions::
455 * defun:: The @code{defun} special form.
456 * Install:: Install a function definition.
457 * Interactive:: Making a function interactive.
458 * Interactive Options:: Different options for @code{interactive}.
459 * Permanent Installation:: Installing code permanently.
460 * let:: Creating and initializing local variables.
461 * if:: What if?
462 * else:: If--then--else expressions.
463 * Truth & Falsehood:: What Lisp considers false and true.
464 * save-excursion:: Keeping track of point, mark, and buffer.
465 * Review::
466 * defun Exercises::
467
468 Install a Function Definition
469
470 * Effect of installation::
471 * Change a defun:: How to change a function definition.
472
473 Make a Function Interactive
474
475 * Interactive multiply-by-seven:: An overview.
476 * multiply-by-seven in detail:: The interactive version.
477
478 @code{let}
479
480 * Prevent confusion::
481 * Parts of let Expression::
482 * Sample let Expression::
483 * Uninitialized let Variables::
484
485 The @code{if} Special Form
486
487 * if in more detail::
488 * type-of-animal in detail:: An example of an @code{if} expression.
489
490 Truth and Falsehood in Emacs Lisp
491
492 * nil explained:: @code{nil} has two meanings.
493
494 @code{save-excursion}
495
496 * Point and mark:: A review of various locations.
497 * Template for save-excursion::
498
499 A Few Buffer--Related Functions
500
501 * Finding More:: How to find more information.
502 * simplified-beginning-of-buffer:: Shows @code{goto-char},
503 @code{point-min}, and @code{push-mark}.
504 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
505 * append-to-buffer:: Uses @code{save-excursion} and
506 @code{insert-buffer-substring}.
507 * Buffer Related Review:: Review.
508 * Buffer Exercises::
509
510 The Definition of @code{mark-whole-buffer}
511
512 * mark-whole-buffer overview::
513 * Body of mark-whole-buffer:: Only three lines of code.
514
515 The Definition of @code{append-to-buffer}
516
517 * append-to-buffer overview::
518 * append interactive:: A two part interactive expression.
519 * append-to-buffer body:: Incorporates a @code{let} expression.
520 * append save-excursion:: How the @code{save-excursion} works.
521
522 A Few More Complex Functions
523
524 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
525 * insert-buffer:: Read-only, and with @code{or}.
526 * beginning-of-buffer:: Shows @code{goto-char},
527 @code{point-min}, and @code{push-mark}.
528 * Second Buffer Related Review::
529 * optional Exercise::
530
531 The Definition of @code{insert-buffer}
532
533 * insert-buffer code::
534 * insert-buffer interactive:: When you can read, but not write.
535 * insert-buffer body:: The body has an @code{or} and a @code{let}.
536 * if & or:: Using an @code{if} instead of an @code{or}.
537 * Insert or:: How the @code{or} expression works.
538 * Insert let:: Two @code{save-excursion} expressions.
539
540 The Interactive Expression in @code{insert-buffer}
541
542 * Read-only buffer:: When a buffer cannot be modified.
543 * b for interactive:: An existing buffer or else its name.
544
545 Complete Definition of @code{beginning-of-buffer}
546
547 * Optional Arguments::
548 * beginning-of-buffer opt arg:: Example with optional argument.
549 * beginning-of-buffer complete::
550
551 @code{beginning-of-buffer} with an Argument
552
553 * Disentangle beginning-of-buffer::
554 * Large buffer case::
555 * Small buffer case::
556
557 Narrowing and Widening
558
559 * Narrowing advantages:: The advantages of narrowing
560 * save-restriction:: The @code{save-restriction} special form.
561 * what-line:: The number of the line that point is on.
562 * narrow Exercise::
563
564 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
565
566 * Strange Names:: An historical aside: why the strange names?
567 * car & cdr:: Functions for extracting part of a list.
568 * cons:: Constructing a list.
569 * nthcdr:: Calling @code{cdr} repeatedly.
570 * nth::
571 * setcar:: Changing the first element of a list.
572 * setcdr:: Changing the rest of a list.
573 * cons Exercise::
574
575 @code{cons}
576
577 * Build a list::
578 * length:: How to find the length of a list.
579
580 Cutting and Storing Text
581
582 * Storing Text:: Text is stored in a list.
583 * zap-to-char:: Cutting out text up to a character.
584 * kill-region:: Cutting text out of a region.
585 * Digression into C:: Minor note on C programming language macros.
586 * defvar:: How to give a variable an initial value.
587 * copy-region-as-kill:: A definition for copying text.
588 * cons & search-fwd Review::
589 * search Exercises::
590
591 @code{zap-to-char}
592
593 * Complete zap-to-char:: The complete implementation.
594 * zap-to-char interactive:: A three part interactive expression.
595 * zap-to-char body:: A short overview.
596 * search-forward:: How to search for a string.
597 * progn:: The @code{progn} special form.
598 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
599
600 @code{kill-region}
601
602 * Complete kill-region:: The function definition.
603 * condition-case:: Dealing with a problem.
604 * delete-and-extract-region:: Doing the work.
605
606 Initializing a Variable with @code{defvar}
607
608 * See variable current value::
609 * defvar and asterisk:: An old-time convention.
610
611 @code{copy-region-as-kill}
612
613 * Complete copy-region-as-kill:: The complete function definition.
614 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
615
616 The Body of @code{copy-region-as-kill}
617
618 * last-command & this-command::
619 * kill-append function::
620 * kill-new function::
621
622 How Lists are Implemented
623
624 * Lists diagrammed::
625 * Symbols as Chest:: Exploring a powerful metaphor.
626 * List Exercise::
627
628 Yanking Text Back
629
630 * Kill Ring Overview:: The kill ring is a list.
631 * kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
632 * yank nthcdr Exercises::
633
634 Loops and Recursion
635
636 * while:: Causing a stretch of code to repeat.
637 * dolist dotimes::
638 * Recursion:: Causing a function to call itself.
639 * Looping exercise::
640
641 @code{while}
642
643 * Looping with while:: Repeat so long as test returns true.
644 * Loop Example:: A @code{while} loop that uses a list.
645 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
646 * Incrementing Loop:: A loop with an incrementing counter.
647 * Decrementing Loop:: A loop with a decrementing counter.
648
649 A Loop with an Incrementing Counter
650
651 * Incrementing Example:: Counting pebbles in a triangle.
652 * Inc Example parts:: The parts of the function definition.
653 * Inc Example altogether:: Putting the function definition together.
654
655 Loop with a Decrementing Counter
656
657 * Decrementing Example:: More pebbles on the beach.
658 * Dec Example parts:: The parts of the function definition.
659 * Dec Example altogether:: Putting the function definition together.
660
661 Save your time: @code{dolist} and @code{dotimes}
662
663 * dolist::
664 * dotimes::
665
666 Recursion
667
668 * Building Robots:: Same model, different serial number ...
669 * Recursive Definition Parts:: Walk until you stop ...
670 * Recursion with list:: Using a list as the test whether to recurse.
671 * Recursive triangle function::
672 * Recursion with cond::
673 * Recursive Patterns:: Often used templates.
674 * No Deferment:: Don't store up work ...
675 * No deferment solution::
676
677 Recursion in Place of a Counter
678
679 * Recursive Example arg of 1 or 2::
680 * Recursive Example arg of 3 or 4::
681
682 Recursive Patterns
683
684 * Every::
685 * Accumulate::
686 * Keep::
687
688 Regular Expression Searches
689
690 * sentence-end:: The regular expression for @code{sentence-end}.
691 * re-search-forward:: Very similar to @code{search-forward}.
692 * forward-sentence:: A straightforward example of regexp search.
693 * forward-paragraph:: A somewhat complex example.
694 * etags:: How to create your own @file{TAGS} table.
695 * Regexp Review::
696 * re-search Exercises::
697
698 @code{forward-sentence}
699
700 * Complete forward-sentence::
701 * fwd-sentence while loops:: Two @code{while} loops.
702 * fwd-sentence re-search:: A regular expression search.
703
704 @code{forward-paragraph}: a Goldmine of Functions
705
706 * forward-paragraph in brief:: Key parts of the function definition.
707 * fwd-para let:: The @code{let*} expression.
708 * fwd-para while:: The forward motion @code{while} loop.
709 * fwd-para between paragraphs:: Movement between paragraphs.
710 * fwd-para within paragraph:: Movement within paragraphs.
711 * fwd-para no fill prefix:: When there is no fill prefix.
712 * fwd-para with fill prefix:: When there is a fill prefix.
713 * fwd-para summary:: Summary of @code{forward-paragraph} code.
714
715 Counting: Repetition and Regexps
716
717 * Why Count Words::
718 * count-words-region:: Use a regexp, but find a problem.
719 * recursive-count-words:: Start with case of no words in region.
720 * Counting Exercise::
721
722 The @code{count-words-region} Function
723
724 * Design count-words-region:: The definition using a @code{while} loop.
725 * Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
726
727 Counting Words in a @code{defun}
728
729 * Divide and Conquer::
730 * Words and Symbols:: What to count?
731 * Syntax:: What constitutes a word or symbol?
732 * count-words-in-defun:: Very like @code{count-words}.
733 * Several defuns:: Counting several defuns in a file.
734 * Find a File:: Do you want to look at a file?
735 * lengths-list-file:: A list of the lengths of many definitions.
736 * Several files:: Counting in definitions in different files.
737 * Several files recursively:: Recursively counting in different files.
738 * Prepare the data:: Prepare the data for display in a graph.
739
740 Count Words in @code{defuns} in Different Files
741
742 * lengths-list-many-files:: Return a list of the lengths of defuns.
743 * append:: Attach one list to another.
744
745 Prepare the Data for Display in a Graph
746
747 * Sorting:: Sorting lists.
748 * Files List:: Making a list of files.
749 * Counting function definitions::
750
751 Readying a Graph
752
753 * Columns of a graph::
754 * graph-body-print:: How to print the body of a graph.
755 * recursive-graph-body-print::
756 * Printed Axes::
757 * Line Graph Exercise::
758
759 Your @file{.emacs} File
760
761 * Default Configuration::
762 * Site-wide Init:: You can write site-wide init files.
763 * defcustom:: Emacs will write code for you.
764 * Beginning a .emacs File:: How to write a @code{.emacs file}.
765 * Text and Auto-fill:: Automatically wrap lines.
766 * Mail Aliases:: Use abbreviations for email addresses.
767 * Indent Tabs Mode:: Don't use tabs with @TeX{}
768 * Keybindings:: Create some personal keybindings.
769 * Keymaps:: More about key binding.
770 * Loading Files:: Load (i.e., evaluate) files automatically.
771 * Autoload:: Make functions available.
772 * Simple Extension:: Define a function; bind it to a key.
773 * X11 Colors:: Colors in version 19 in X.
774 * Miscellaneous::
775 * Mode Line:: How to customize your mode line.
776
777 Debugging
778
779 * debug:: How to use the built-in debugger.
780 * debug-on-entry:: Start debugging when you call a function.
781 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
782 * edebug:: How to use Edebug, a source level debugger.
783 * Debugging Exercises::
784
785 Handling the Kill Ring
786
787 * rotate-yank-pointer:: Move a pointer along a list and around.
788 * yank:: Paste a copy of a clipped element.
789 * yank-pop:: Insert first element pointed to.
790
791 The @code{rotate-yank-pointer} Function
792
793 * Understanding rotate-yk-ptr::
794 * rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
795
796 The Body of @code{rotate-yank-pointer}
797
798 * Digression concerning error:: How to mislead humans, but not computers.
799 * rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
800 * Remainder Function:: The remainder, @code{%}, function.
801 * rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
802 * kill-rng-yk-ptr last elt:: Pointing to the last element.
803
804 @code{yank}
805
806 * rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
807 * rotate-yk-ptr negative arg:: Pass a negative argument.
808
809 A Graph with Labelled Axes
810
811 * Labelled Example::
812 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
813 * print-Y-axis:: Print a label for the vertical axis.
814 * print-X-axis:: Print a horizontal label.
815 * Print Whole Graph:: The function to print a complete graph.
816
817 The @code{print-Y-axis} Function
818
819 * Height of label:: What height for the Y axis?
820 * Compute a Remainder:: How to compute the remainder of a division.
821 * Y Axis Element:: Construct a line for the Y axis.
822 * Y-axis-column:: Generate a list of Y axis labels.
823 * print-Y-axis Penultimate:: A not quite final version.
824
825 The @code{print-X-axis} Function
826
827 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
828 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
829
830 Printing the Whole Graph
831
832 * The final version:: A few changes.
833 * Test print-graph:: Run a short test.
834 * Graphing words in defuns:: Executing the final code.
835 * lambda:: How to write an anonymous function.
836 * mapcar:: Apply a function to elements of a list.
837 * Another Bug:: Yet another bug @dots{} most insidious.
838 * Final printed graph:: The graph itself!
839
840 @end detailmenu
841 @end menu
842
843 @node Preface, List Processing, Top, Top
844 @comment node-name, next, previous, up
845 @unnumbered Preface
846
847 Most of the GNU Emacs integrated environment is written in the programming
848 language called Emacs Lisp. The code written in this programming
849 language is the software---the sets of instructions---that tell the
850 computer what to do when you give it commands. Emacs is designed so
851 that you can write new code in Emacs Lisp and easily install it as an
852 extension to the editor.
853
854 (GNU Emacs is sometimes called an ``extensible editor'', but it does
855 much more than provide editing capabilities. It is better to refer to
856 Emacs as an ``extensible computing environment''. However, that
857 phrase is quite a mouthful. It is easier to refer to Emacs simply as
858 an editor. Moreover, everything you do in Emacs---find the Mayan date
859 and phases of the moon, simplify polynomials, debug code, manage
860 files, read letters, write books---all these activities are kinds of
861 editing in the most general sense of the word.)
862
863 @menu
864 * Why:: Why learn Emacs Lisp?
865 * On Reading this Text:: Read, gain familiarity, pick up habits....
866 * Who You Are:: For whom this is written.
867 * Lisp History::
868 * Note for Novices:: You can read this as a novice.
869 * Thank You::
870 @end menu
871
872 @node Why, On Reading this Text, Preface, Preface
873 @ifnottex
874 @unnumberedsec Why Study Emacs Lisp?
875 @end ifnottex
876
877 Although Emacs Lisp is usually thought of in association only with Emacs,
878 it is a full computer programming language. You can use Emacs Lisp as
879 you would any other programming language.
880
881 Perhaps you want to understand programming; perhaps you want to extend
882 Emacs; or perhaps you want to become a programmer. This introduction to
883 Emacs Lisp is designed to get you started: to guide you in learning the
884 fundamentals of programming, and more importantly, to show you how you
885 can teach yourself to go further.
886
887 @node On Reading this Text, Who You Are, Why, Preface
888 @comment node-name, next, previous, up
889 @unnumberedsec On Reading this Text
890
891 All through this document, you will see little sample programs you can
892 run inside of Emacs. If you read this document in Info inside of GNU
893 Emacs, you can run the programs as they appear. (This is easy to do and
894 is explained when the examples are presented.) Alternatively, you can
895 read this introduction as a printed book while sitting beside a computer
896 running Emacs. (This is what I like to do; I like printed books.) If
897 you don't have a running Emacs beside you, you can still read this book,
898 but in this case, it is best to treat it as a novel or as a travel guide
899 to a country not yet visited: interesting, but not the same as being
900 there.
901
902 Much of this introduction is dedicated to walk-throughs or guided tours
903 of code used in GNU Emacs. These tours are designed for two purposes:
904 first, to give you familiarity with real, working code (code you use
905 every day); and, second, to give you familiarity with the way Emacs
906 works. It is interesting to see how a working environment is
907 implemented.
908 Also, I
909 hope that you will pick up the habit of browsing through source code.
910 You can learn from it and mine it for ideas. Having GNU Emacs is like
911 having a dragon's cave of treasures.
912
913 In addition to learning about Emacs as an editor and Emacs Lisp as a
914 programming language, the examples and guided tours will give you an
915 opportunity to get acquainted with Emacs as a Lisp programming
916 environment. GNU Emacs supports programming and provides tools that
917 you will want to become comfortable using, such as @kbd{M-.} (the key
918 which invokes the @code{find-tag} command). You will also learn about
919 buffers and other objects that are part of the environment.
920 Learning about these features of Emacs is like learning new routes
921 around your home town.
922
923 @ignore
924 In addition, I have written several programs as extended examples.
925 Although these are examples, the programs are real. I use them.
926 Other people use them. You may use them. Beyond the fragments of
927 programs used for illustrations, there is very little in here that is
928 `just for teaching purposes'; what you see is used. This is a great
929 advantage of Emacs Lisp: it is easy to learn to use it for work.
930 @end ignore
931
932 Finally, I hope to convey some of the skills for using Emacs to
933 learn aspects of programming that you don't know. You can often use
934 Emacs to help you understand what puzzles you or to find out how to do
935 something new. This self-reliance is not only a pleasure, but an
936 advantage.
937
938 @node Who You Are, Lisp History, On Reading this Text, Preface
939 @comment node-name, next, previous, up
940 @unnumberedsec For Whom This is Written
941
942 This text is written as an elementary introduction for people who are
943 not programmers. If you are a programmer, you may not be satisfied with
944 this primer. The reason is that you may have become expert at reading
945 reference manuals and be put off by the way this text is organized.
946
947 An expert programmer who reviewed this text said to me:
948
949 @quotation
950 @i{I prefer to learn from reference manuals. I ``dive into'' each
951 paragraph, and ``come up for air'' between paragraphs.}
952
953 @i{When I get to the end of a paragraph, I assume that that subject is
954 done, finished, that I know everything I need (with the
955 possible exception of the case when the next paragraph starts talking
956 about it in more detail). I expect that a well written reference manual
957 will not have a lot of redundancy, and that it will have excellent
958 pointers to the (one) place where the information I want is.}
959 @end quotation
960
961 This introduction is not written for this person!
962
963 Firstly, I try to say everything at least three times: first, to
964 introduce it; second, to show it in context; and third, to show it in a
965 different context, or to review it.
966
967 Secondly, I hardly ever put all the information about a subject in one
968 place, much less in one paragraph. To my way of thinking, that imposes
969 too heavy a burden on the reader. Instead I try to explain only what
970 you need to know at the time. (Sometimes I include a little extra
971 information so you won't be surprised later when the additional
972 information is formally introduced.)
973
974 When you read this text, you are not expected to learn everything the
975 first time. Frequently, you need only make, as it were, a `nodding
976 acquaintance' with some of the items mentioned. My hope is that I have
977 structured the text and given you enough hints that you will be alert to
978 what is important, and concentrate on it.
979
980 You will need to ``dive into'' some paragraphs; there is no other way
981 to read them. But I have tried to keep down the number of such
982 paragraphs. This book is intended as an approachable hill, rather than
983 as a daunting mountain.
984
985 This introduction to @cite{Programming in Emacs Lisp} has a companion
986 document,
987 @iftex
988 @cite{The GNU Emacs Lisp Reference Manual}.
989 @end iftex
990 @ifnottex
991 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
992 Emacs Lisp Reference Manual}.
993 @end ifnottex
994 The reference manual has more detail than this introduction. In the
995 reference manual, all the information about one topic is concentrated
996 in one place. You should turn to it if you are like the programmer
997 quoted above. And, of course, after you have read this
998 @cite{Introduction}, you will find the @cite{Reference Manual} useful
999 when you are writing your own programs.
1000
1001 @node Lisp History, Note for Novices, Who You Are, Preface
1002 @unnumberedsec Lisp History
1003 @cindex Lisp history
1004
1005 Lisp was first developed in the late 1950s at the Massachusetts
1006 Institute of Technology for research in artificial intelligence. The
1007 great power of the Lisp language makes it superior for other purposes as
1008 well, such as writing editor commands and integrated environments.
1009
1010 @cindex Maclisp
1011 @cindex Common Lisp
1012 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1013 in the 1960s. It is somewhat inspired by Common Lisp, which became a
1014 standard in the 1980s. However, Emacs Lisp is much simpler than Common
1015 Lisp. (The standard Emacs distribution contains an optional extensions
1016 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1017
1018 @node Note for Novices, Thank You, Lisp History, Preface
1019 @comment node-name, next, previous, up
1020 @unnumberedsec A Note for Novices
1021
1022 If you don't know GNU Emacs, you can still read this document
1023 profitably. However, I recommend you learn Emacs, if only to learn to
1024 move around your computer screen. You can teach yourself how to use
1025 Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1026 means you press and release the @key{CTRL} key and the @kbd{h} at the
1027 same time, and then press and release @kbd{t}.)
1028
1029 Also, I often refer to one of Emacs' standard commands by listing the
1030 keys which you press to invoke the command and then giving the name of
1031 the command in parentheses, like this: @kbd{M-C-\}
1032 (@code{indent-region}). What this means is that the
1033 @code{indent-region} command is customarily invoked by typing
1034 @kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1035 invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1036 Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1037 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1038 (On many modern keyboards the @key{META} key is labelled
1039 @key{ALT}.)
1040 Sometimes a combination like this is called a keychord, since it is
1041 similar to the way you play a chord on a piano. If your keyboard does
1042 not have a @key{META} key, the @key{ESC} key prefix is used in place
1043 of it. In this case, @kbd{M-C-\} means that you press and release your
1044 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1045 the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
1046 along with the key that is labelled @key{ALT} and, at the same time,
1047 press the @key{\} key.
1048
1049 In addition to typing a lone keychord, you can prefix what you type
1050 with @kbd{C-u}, which is called the `universal argument'. The
1051 @kbd{C-u} keychord passes an argument to the subsequent command.
1052 Thus, to indent a region of plain text by 6 spaces, mark the region,
1053 and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1054 Emacs either passes the number 4 to the command or otherwise runs the
1055 command differently than it would otherwise.) @xref{Arguments, ,
1056 Numeric Arguments, emacs, The GNU Emacs Manual}.
1057
1058 If you are reading this in Info using GNU Emacs, you can read through
1059 this whole document just by pressing the space bar, @key{SPC}.
1060 (To learn about Info, type @kbd{C-h i} and then select Info.)
1061
1062 A note on terminology: when I use the word Lisp alone, I often am
1063 referring to the various dialects of Lisp in general, but when I speak
1064 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1065
1066 @node Thank You, , Note for Novices, Preface
1067 @comment node-name, next, previous, up
1068 @unnumberedsec Thank You
1069
1070 My thanks to all who helped me with this book. My especial thanks to
1071 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1072 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1073 Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1074 @w{Philip Johnson} and @w{David Stampe} for their patient
1075 encouragement. My mistakes are my own.
1076
1077 @flushright
1078 Robert J. Chassell
1079 @end flushright
1080
1081 @c ================ Beginning of main text ================
1082
1083 @c Start main text on right-hand (verso) page
1084
1085 @tex
1086 \par\vfill\supereject
1087 \headings off
1088 \ifodd\pageno
1089 \par\vfill\supereject
1090 \else
1091 \par\vfill\supereject
1092 \page\hbox{}\page
1093 \par\vfill\supereject
1094 \fi
1095 @end tex
1096
1097 @iftex
1098 @headings off
1099 @evenheading @thispage @| @| @thischapter
1100 @oddheading @thissection @| @| @thispage
1101 @pageno = 1
1102 @end iftex
1103
1104 @node List Processing, Practicing Evaluation, Preface, Top
1105 @comment node-name, next, previous, up
1106 @chapter List Processing
1107
1108 To the untutored eye, Lisp is a strange programming language. In Lisp
1109 code there are parentheses everywhere. Some people even claim that the
1110 name stands for `Lots of Isolated Silly Parentheses'. But the claim is
1111 unwarranted. Lisp stands for LISt Processing, and the programming
1112 language handles @emph{lists} (and lists of lists) by putting them
1113 between parentheses. The parentheses mark the boundaries of the list.
1114 Sometimes a list is preceded by a single apostrophe or quotation mark,
1115 @samp{'}. Lists are the basis of Lisp.
1116
1117 @menu
1118 * Lisp Lists:: What are lists?
1119 * Run a Program:: Any list in Lisp is a program ready to run.
1120 * Making Errors:: Generating an error message.
1121 * Names & Definitions:: Names of symbols and function definitions.
1122 * Lisp Interpreter:: What the Lisp interpreter does.
1123 * Evaluation:: Running a program.
1124 * Variables:: Returning a value from a variable.
1125 * Arguments:: Passing information to a function.
1126 * set & setq:: Setting the value of a variable.
1127 * Summary:: The major points.
1128 * Error Message Exercises::
1129 @end menu
1130
1131 @node Lisp Lists, Run a Program, List Processing, List Processing
1132 @comment node-name, next, previous, up
1133 @section Lisp Lists
1134 @cindex Lisp Lists
1135
1136 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1137 This list is preceded by a single apostrophe. It could just as well be
1138 written as follows, which looks more like the kind of list you are likely
1139 to be familiar with:
1140
1141 @smallexample
1142 @group
1143 '(rose
1144 violet
1145 daisy
1146 buttercup)
1147 @end group
1148 @end smallexample
1149
1150 @noindent
1151 The elements of this list are the names of the four different flowers,
1152 separated from each other by whitespace and surrounded by parentheses,
1153 like flowers in a field with a stone wall around them.
1154 @cindex Flowers in a field
1155
1156 @menu
1157 * Numbers Lists:: List have numbers, other lists, in them.
1158 * Lisp Atoms:: Elemental entities.
1159 * Whitespace in Lists:: Formating lists to be readable.
1160 * Typing Lists:: How GNU Emacs helps you type lists.
1161 @end menu
1162
1163 @node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1164 @ifnottex
1165 @unnumberedsubsec Numbers, Lists inside of Lists
1166 @end ifnottex
1167
1168 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1169 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1170 separated by whitespace.
1171
1172 In Lisp, both data and programs are represented the same way; that is,
1173 they are both lists of words, numbers, or other lists, separated by
1174 whitespace and surrounded by parentheses. (Since a program looks like
1175 data, one program may easily serve as data for another; this is a very
1176 powerful feature of Lisp.) (Incidentally, these two parenthetical
1177 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1178 @samp{.} as punctuation marks.)
1179
1180 @need 1200
1181 Here is another list, this time with a list inside of it:
1182
1183 @smallexample
1184 '(this list has (a list inside of it))
1185 @end smallexample
1186
1187 The components of this list are the words @samp{this}, @samp{list},
1188 @samp{has}, and the list @samp{(a list inside of it)}. The interior
1189 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1190 @samp{of}, @samp{it}.
1191
1192 @node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1193 @comment node-name, next, previous, up
1194 @subsection Lisp Atoms
1195 @cindex Lisp Atoms
1196
1197 In Lisp, what we have been calling words are called @dfn{atoms}. This
1198 term comes from the historical meaning of the word atom, which means
1199 `indivisible'. As far as Lisp is concerned, the words we have been
1200 using in the lists cannot be divided into any smaller parts and still
1201 mean the same thing as part of a program; likewise with numbers and
1202 single character symbols like @samp{+}. On the other hand, unlike an
1203 atom, a list can be split into parts. (@xref{car cdr & cons, ,
1204 @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1205
1206 In a list, atoms are separated from each other by whitespace. They can be
1207 right next to a parenthesis.
1208
1209 @cindex @samp{empty list} defined
1210 Technically speaking, a list in Lisp consists of parentheses surrounding
1211 atoms separated by whitespace or surrounding other lists or surrounding
1212 both atoms and other lists. A list can have just one atom in it or
1213 have nothing in it at all. A list with nothing in it looks like this:
1214 @code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1215 empty list is considered both an atom and a list at the same time.
1216
1217 @cindex Symbolic expressions, introduced
1218 @cindex @samp{expression} defined
1219 @cindex @samp{form} defined
1220 The printed representation of both atoms and lists are called
1221 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1222 The word @dfn{expression} by itself can refer to either the printed
1223 representation, or to the atom or list as it is held internally in the
1224 computer. Often, people use the term @dfn{expression}
1225 indiscriminately. (Also, in many texts, the word @dfn{form} is used
1226 as a synonym for expression.)
1227
1228 Incidentally, the atoms that make up our universe were named such when
1229 they were thought to be indivisible; but it has been found that physical
1230 atoms are not indivisible. Parts can split off an atom or it can
1231 fission into two parts of roughly equal size. Physical atoms were named
1232 prematurely, before their truer nature was found. In Lisp, certain
1233 kinds of atom, such as an array, can be separated into parts; but the
1234 mechanism for doing this is different from the mechanism for splitting a
1235 list. As far as list operations are concerned, the atoms of a list are
1236 unsplittable.
1237
1238 As in English, the meanings of the component letters of a Lisp atom
1239 are different from the meaning the letters make as a word. For
1240 example, the word for the South American sloth, the @samp{ai}, is
1241 completely different from the two words, @samp{a}, and @samp{i}.
1242
1243 There are many kinds of atom in nature but only a few in Lisp: for
1244 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1245 as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1246 listed in the examples above are all symbols. In everyday Lisp
1247 conversation, the word ``atom'' is not often used, because programmers
1248 usually try to be more specific about what kind of atom they are dealing
1249 with. Lisp programming is mostly about symbols (and sometimes numbers)
1250 within lists. (Incidentally, the preceding three word parenthetical
1251 remark is a proper list in Lisp, since it consists of atoms, which in
1252 this case are symbols, separated by whitespace and enclosed by
1253 parentheses, without any non-Lisp punctuation.)
1254
1255 @need 1250
1256 In addition, text between double quotation marks---even sentences or
1257 paragraphs---is an atom. Here is an example:
1258 @cindex Text between double quotation marks
1259
1260 @smallexample
1261 '(this list includes "text between quotation marks.")
1262 @end smallexample
1263
1264 @cindex @samp{string} defined
1265 @noindent
1266 In Lisp, all of the quoted text including the punctuation mark and the
1267 blank spaces is a single atom. This kind of atom is called a
1268 @dfn{string} (for `string of characters') and is the sort of thing that
1269 is used for messages that a computer can print for a human to read.
1270 Strings are a different kind of atom than numbers or symbols and are
1271 used differently.
1272
1273 @node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1274 @comment node-name, next, previous, up
1275 @subsection Whitespace in Lists
1276 @cindex Whitespace in lists
1277
1278 @need 1200
1279 The amount of whitespace in a list does not matter. From the point of view
1280 of the Lisp language,
1281
1282 @smallexample
1283 @group
1284 '(this list
1285 looks like this)
1286 @end group
1287 @end smallexample
1288
1289 @need 800
1290 @noindent
1291 is exactly the same as this:
1292
1293 @smallexample
1294 '(this list looks like this)
1295 @end smallexample
1296
1297 Both examples show what to Lisp is the same list, the list made up of
1298 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1299 @samp{this} in that order.
1300
1301 Extra whitespace and newlines are designed to make a list more readable
1302 by humans. When Lisp reads the expression, it gets rid of all the extra
1303 whitespace (but it needs to have at least one space between atoms in
1304 order to tell them apart.)
1305
1306 Odd as it seems, the examples we have seen cover almost all of what Lisp
1307 lists look like! Every other list in Lisp looks more or less like one
1308 of these examples, except that the list may be longer and more complex.
1309 In brief, a list is between parentheses, a string is between quotation
1310 marks, a symbol looks like a word, and a number looks like a number.
1311 (For certain situations, square brackets, dots and a few other special
1312 characters may be used; however, we will go quite far without them.)
1313
1314 @node Typing Lists, , Whitespace in Lists, Lisp Lists
1315 @comment node-name, next, previous, up
1316 @subsection GNU Emacs Helps You Type Lists
1317 @cindex Help typing lists
1318 @cindex Formatting help
1319
1320 When you type a Lisp expression in GNU Emacs using either Lisp
1321 Interaction mode or Emacs Lisp mode, you have available to you several
1322 commands to format the Lisp expression so it is easy to read. For
1323 example, pressing the @key{TAB} key automatically indents the line the
1324 cursor is on by the right amount. A command to properly indent the
1325 code in a region is customarily bound to @kbd{M-C-\}. Indentation is
1326 designed so that you can see which elements of a list belongs to which
1327 list---elements of a sub-list are indented more than the elements of
1328 the enclosing list.
1329
1330 In addition, when you type a closing parenthesis, Emacs momentarily
1331 jumps the cursor back to the matching opening parenthesis, so you can
1332 see which one it is. This is very useful, since every list you type
1333 in Lisp must have its closing parenthesis match its opening
1334 parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1335 Manual}, for more information about Emacs' modes.)
1336
1337 @node Run a Program, Making Errors, Lisp Lists, List Processing
1338 @comment node-name, next, previous, up
1339 @section Run a Program
1340 @cindex Run a program
1341 @cindex Program, running one
1342
1343 @cindex @samp{evaluate} defined
1344 A list in Lisp---any list---is a program ready to run. If you run it
1345 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1346 of three things: do nothing except return to you the list itself; send
1347 you an error message; or, treat the first symbol in the list as a
1348 command to do something. (Usually, of course, it is the last of these
1349 three things that you really want!)
1350
1351 @c use code for the single apostrophe, not samp.
1352 The single apostrophe, @code{'}, that I put in front of some of the
1353 example lists in preceding sections is called a @dfn{quote}; when it
1354 precedes a list, it tells Lisp to do nothing with the list, other than
1355 take it as it is written. But if there is no quote preceding a list,
1356 the first item of the list is special: it is a command for the computer
1357 to obey. (In Lisp, these commands are called @emph{functions}.) The list
1358 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1359 understands that the @code{+} is an instruction to do something with the
1360 rest of the list: add the numbers that follow.
1361
1362 @need 1250
1363 If you are reading this inside of GNU Emacs in Info, here is how you can
1364 evaluate such a list: place your cursor immediately after the right
1365 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1366
1367 @smallexample
1368 (+ 2 2)
1369 @end smallexample
1370
1371 @c use code for the number four, not samp.
1372 @noindent
1373 You will see the number @code{4} appear in the echo area. (In the
1374 jargon, what you have just done is ``evaluate the list.'' The echo area
1375 is the line at the bottom of the screen that displays or ``echoes''
1376 text.) Now try the same thing with a quoted list: place the cursor
1377 right after the following list and type @kbd{C-x C-e}:
1378
1379 @smallexample
1380 '(this is a quoted list)
1381 @end smallexample
1382
1383 @noindent
1384 You will see @code{(this is a quoted list)} appear in the echo area.
1385
1386 @cindex Lisp interpreter, explained
1387 @cindex Interpreter, Lisp, explained
1388 In both cases, what you are doing is giving a command to the program
1389 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1390 interpreter a command to evaluate the expression. The name of the Lisp
1391 interpreter comes from the word for the task done by a human who comes
1392 up with the meaning of an expression---who ``interprets'' it.
1393
1394 You can also evaluate an atom that is not part of a list---one that is
1395 not surrounded by parentheses; again, the Lisp interpreter translates
1396 from the humanly readable expression to the language of the computer.
1397 But before discussing this (@pxref{Variables}), we will discuss what the
1398 Lisp interpreter does when you make an error.
1399
1400 @node Making Errors, Names & Definitions, Run a Program, List Processing
1401 @comment node-name, next, previous, up
1402 @section Generate an Error Message
1403 @cindex Generate an error message
1404 @cindex Error message generation
1405
1406 Partly so you won't worry if you do it accidentally, we will now give
1407 a command to the Lisp interpreter that generates an error message.
1408 This is a harmless activity; and indeed, we will often try to generate
1409 error messages intentionally. Once you understand the jargon, error
1410 messages can be informative. Instead of being called ``error''
1411 messages, they should be called ``help'' messages. They are like
1412 signposts to a traveller in a strange country; deciphering them can be
1413 hard, but once understood, they can point the way.
1414
1415 The error message is generated by a built-in GNU Emacs debugger. We
1416 will `enter the debugger'. You get out of the debugger by typing @code{q}.
1417
1418 What we will do is evaluate a list that is not quoted and does not
1419 have a meaningful command as its first element. Here is a list almost
1420 exactly the same as the one we just used, but without the single-quote
1421 in front of it. Position the cursor right after it and type @kbd{C-x
1422 C-e}:
1423
1424 @smallexample
1425 (this is an unquoted list)
1426 @end smallexample
1427
1428 @noindent
1429 What you see depends on which version of Emacs you are running. GNU
1430 Emacs version 21 provides more information than version 20 and before.
1431 First, the more recent result of generating an error; then the
1432 earlier, version 20 result.
1433
1434 @need 1250
1435 @noindent
1436 In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1437 you will see the following in it:
1438
1439 @smallexample
1440 @group
1441 ---------- Buffer: *Backtrace* ----------
1442 Debugger entered--Lisp error: (void-function this)
1443 (this is an unquoted list)
1444 eval((this is an unquoted list))
1445 eval-last-sexp-1(nil)
1446 eval-last-sexp(nil)
1447 call-interactively(eval-last-sexp)
1448 ---------- Buffer: *Backtrace* ----------
1449 @end group
1450 @end smallexample
1451
1452 @need 1200
1453 @noindent
1454 Your cursor will be in this window (you may have to wait a few seconds
1455 before it becomes visible). To quit the debugger and make the
1456 debugger window go away, type:
1457
1458 @smallexample
1459 q
1460 @end smallexample
1461
1462 @noindent
1463 Please type @kbd{q} right now, so you become confident that you can
1464 get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1465 it.
1466
1467 @cindex @samp{function} defined
1468 Based on what we already know, we can almost read this error message.
1469
1470 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1471 you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1472 interactive call to the command @code{eval-last-sexp}. @code{eval} is
1473 an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1474 `symbolic expression'. The command means `evaluate last symbolic
1475 expression', which is the expression just before your cursor.
1476
1477 Each line above tells you what the Lisp interpreter evaluated next.
1478 The most recent action is at the top. The buffer is called the
1479 @file{*Backtrace*} buffer because it enables you to track Emacs
1480 backwards.
1481
1482 @need 800
1483 At the top of the @file{*Backtrace*} buffer, you see the line:
1484
1485 @smallexample
1486 Debugger entered--Lisp error: (void-function this)
1487 @end smallexample
1488
1489 @noindent
1490 The Lisp interpreter tried to evaluate the first atom of the list, the
1491 word @samp{this}. It is this action that generated the error message
1492 @samp{void-function this}.
1493
1494 The message contains the words @samp{void-function} and @samp{this}.
1495
1496 @cindex @samp{function} defined
1497 The word @samp{function} was mentioned once before. It is a very
1498 important word. For our purposes, we can define it by saying that a
1499 @dfn{function} is a set of instructions to the computer that tell the
1500 computer to do something.
1501
1502 Now we can begin to understand the error message: @samp{void-function
1503 this}. The function (that is, the word @samp{this}) does not have a
1504 definition of any set of instructions for the computer to carry out.
1505
1506 The slightly odd word, @samp{void-function}, is designed to cover the
1507 way Emacs Lisp is implemented, which is that when a symbol does not
1508 have a function definition attached to it, the place that should
1509 contain the instructions is `void'.
1510
1511 On the other hand, since we were able to add 2 plus 2 successfully, by
1512 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1513 have a set of instructions for the computer to obey and those
1514 instructions must be to add the numbers that follow the @code{+}.
1515
1516 @need 1250
1517 In GNU Emacs version 20, and in earlier versions, you will see only
1518 one line of error message; it will appear in the echo area and look
1519 like this:
1520
1521 @smallexample
1522 Symbol's function definition is void:@: this
1523 @end smallexample
1524
1525 @noindent
1526 (Also, your terminal may beep at you---some do, some don't; and others
1527 blink. This is just a device to get your attention.) The message goes
1528 away as soon as you type another key, even just to move the cursor.
1529
1530 We know the meaning of the word @samp{Symbol}. It refers to the first
1531 atom of the list, the word @samp{this}. The word @samp{function}
1532 refers to the instructions that tell the computer what to do.
1533 (Technically, the symbol tells the computer where to find the
1534 instructions, but this is a complication we can ignore for the
1535 moment.)
1536
1537 The error message can be understood: @samp{Symbol's function
1538 definition is void:@: this}. The symbol (that is, the word
1539 @samp{this}) lacks instructions for the computer to carry out.
1540
1541 @node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1542 @comment node-name, next, previous, up
1543 @section Symbol Names and Function Definitions
1544 @cindex Symbol names
1545
1546 We can articulate another characteristic of Lisp based on what we have
1547 discussed so far---an important characteristic: a symbol, like
1548 @code{+}, is not itself the set of instructions for the computer to
1549 carry out. Instead, the symbol is used, perhaps temporarily, as a way
1550 of locating the definition or set of instructions. What we see is the
1551 name through which the instructions can be found. Names of people
1552 work the same way. I can be referred to as @samp{Bob}; however, I am
1553 not the letters @samp{B}, @samp{o}, @samp{b} but am the consciousness
1554 consistently associated with a particular life-form. The name is not
1555 me, but it can be used to refer to me.
1556
1557 In Lisp, one set of instructions can be attached to several names.
1558 For example, the computer instructions for adding numbers can be
1559 linked to the symbol @code{plus} as well as to the symbol @code{+}
1560 (and are in some dialects of Lisp). Among humans, I can be referred
1561 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1562
1563 On the other hand, a symbol can have only one function definition
1564 attached to it at a time. Otherwise, the computer would be confused as
1565 to which definition to use. If this were the case among people, only
1566 one person in the world could be named @samp{Bob}. However, the function
1567 definition to which the name refers can be changed readily.
1568 (@xref{Install, , Install a Function Definition}.)
1569
1570 Since Emacs Lisp is large, it is customary to name symbols in a way
1571 that identifies the part of Emacs to which the function belongs.
1572 Thus, all the names for functions that deal with Texinfo start with
1573 @samp{texinfo-} and those for functions that deal with reading mail
1574 start with @samp{rmail-}.
1575
1576 @node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1577 @comment node-name, next, previous, up
1578 @section The Lisp Interpreter
1579 @cindex Lisp interpreter, what it does
1580 @cindex Interpreter, what it does
1581
1582 Based on what we have seen, we can now start to figure out what the
1583 Lisp interpreter does when we command it to evaluate a list.
1584 First, it looks to see whether there is a quote before the list; if
1585 there is, the interpreter just gives us the list. On the other
1586 hand, if there is no quote, the interpreter looks at the first element
1587 in the list and sees whether it has a function definition. If it does,
1588 the interpreter carries out the instructions in the function definition.
1589 Otherwise, the interpreter prints an error message.
1590
1591 This is how Lisp works. Simple. There are added complications which we
1592 will get to in a minute, but these are the fundamentals. Of course, to
1593 write Lisp programs, you need to know how to write function definitions
1594 and attach them to names, and how to do this without confusing either
1595 yourself or the computer.
1596
1597 @menu
1598 * Complications:: Variables, Special forms, Lists within.
1599 * Byte Compiling:: Specially processing code for speed.
1600 @end menu
1601
1602 @node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1603 @ifnottex
1604 @unnumberedsubsec Complications
1605 @end ifnottex
1606
1607 Now, for the first complication. In addition to lists, the Lisp
1608 interpreter can evaluate a symbol that is not quoted and does not have
1609 parentheses around it. The Lisp interpreter will attempt to determine
1610 the symbol's value as a @dfn{variable}. This situation is described
1611 in the section on variables. (@xref{Variables}.)
1612
1613 @cindex Special form
1614 The second complication occurs because some functions are unusual and do
1615 not work in the usual manner. Those that don't are called @dfn{special
1616 forms}. They are used for special jobs, like defining a function, and
1617 there are not many of them. In the next few chapters, you will be
1618 introduced to several of the more important special forms.
1619
1620 The third and final complication is this: if the function that the
1621 Lisp interpreter is looking at is not a special form, and if it is part
1622 of a list, the Lisp interpreter looks to see whether the list has a list
1623 inside of it. If there is an inner list, the Lisp interpreter first
1624 figures out what it should do with the inside list, and then it works on
1625 the outside list. If there is yet another list embedded inside the
1626 inner list, it works on that one first, and so on. It always works on
1627 the innermost list first. The interpreter works on the innermost list
1628 first, to evaluate the result of that list. The result may be
1629 used by the enclosing expression.
1630
1631 Otherwise, the interpreter works left to right, from one expression to
1632 the next.
1633
1634 @node Byte Compiling, , Complications, Lisp Interpreter
1635 @subsection Byte Compiling
1636 @cindex Byte compiling
1637
1638 One other aspect of interpreting: the Lisp interpreter is able to
1639 interpret two kinds of entity: humanly readable code, on which we will
1640 focus exclusively, and specially processed code, called @dfn{byte
1641 compiled} code, which is not humanly readable. Byte compiled code
1642 runs faster than humanly readable code.
1643
1644 You can transform humanly readable code into byte compiled code by
1645 running one of the compile commands such as @code{byte-compile-file}.
1646 Byte compiled code is usually stored in a file that ends with a
1647 @file{.elc} extension rather than a @file{.el} extension. You will
1648 see both kinds of file in the @file{emacs/lisp} directory; the files
1649 to read are those with @file{.el} extensions.
1650
1651 As a practical matter, for most things you might do to customize or
1652 extend Emacs, you do not need to byte compile; and I will not discuss
1653 the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1654 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1655 compilation.
1656
1657 @node Evaluation, Variables, Lisp Interpreter, List Processing
1658 @comment node-name, next, previous, up
1659 @section Evaluation
1660 @cindex Evaluation
1661
1662 When the Lisp interpreter works on an expression, the term for the
1663 activity is called @dfn{evaluation}. We say that the interpreter
1664 `evaluates the expression'. I've used this term several times before.
1665 The word comes from its use in everyday language, `to ascertain the
1666 value or amount of; to appraise', according to @cite{Webster's New
1667 Collegiate Dictionary}.
1668
1669 After evaluating an expression, the Lisp interpreter will most likely
1670 @dfn{return} the value that the computer produces by carrying out the
1671 instructions it found in the function definition, or perhaps it will
1672 give up on that function and produce an error message. (The interpreter
1673 may also find itself tossed, so to speak, to a different function or it
1674 may attempt to repeat continually what it is doing for ever and ever in
1675 what is called an `infinite loop'. These actions are less common; and
1676 we can ignore them.) Most frequently, the interpreter returns a value.
1677
1678 @cindex @samp{side effect} defined
1679 At the same time the interpreter returns a value, it may do something
1680 else as well, such as move a cursor or copy a file; this other kind of
1681 action is called a @dfn{side effect}. Actions that we humans think are
1682 important, such as printing results, are often ``side effects'' to the
1683 Lisp interpreter. The jargon can sound peculiar, but it turns out that
1684 it is fairly easy to learn to use side effects.
1685
1686 In summary, evaluating a symbolic expression most commonly causes the
1687 Lisp interpreter to return a value and perhaps carry out a side effect;
1688 or else produce an error.
1689
1690 @menu
1691 * Evaluating Inner Lists:: Lists within lists...
1692 @end menu
1693
1694 @node Evaluating Inner Lists, , Evaluation, Evaluation
1695 @comment node-name, next, previous, up
1696 @subsection Evaluating Inner Lists
1697 @cindex Inner list evaluation
1698 @cindex Evaluating inner lists
1699
1700 If evaluation applies to a list that is inside another list, the outer
1701 list may use the value returned by the first evaluation as information
1702 when the outer list is evaluated. This explains why inner expressions
1703 are evaluated first: the values they return are used by the outer
1704 expressions.
1705
1706 @need 1250
1707 We can investigate this process by evaluating another addition example.
1708 Place your cursor after the following expression and type @kbd{C-x C-e}:
1709
1710 @smallexample
1711 (+ 2 (+ 3 3))
1712 @end smallexample
1713
1714 @noindent
1715 The number 8 will appear in the echo area.
1716
1717 What happens is that the Lisp interpreter first evaluates the inner
1718 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1719 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1720 returns the value 8. Since there are no more enclosing expressions to
1721 evaluate, the interpreter prints that value in the echo area.
1722
1723 Now it is easy to understand the name of the command invoked by the
1724 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1725 letters @code{sexp} are an abbreviation for `symbolic expression', and
1726 @code{eval} is an abbreviation for `evaluate'. The command means
1727 `evaluate last symbolic expression'.
1728
1729 As an experiment, you can try evaluating the expression by putting the
1730 cursor at the beginning of the next line immediately following the
1731 expression, or inside the expression.
1732
1733 @need 800
1734 Here is another copy of the expression:
1735
1736 @smallexample
1737 (+ 2 (+ 3 3))
1738 @end smallexample
1739
1740 @noindent
1741 If you place the cursor at the beginning of the blank line that
1742 immediately follows the expression and type @kbd{C-x C-e}, you will
1743 still get the value 8 printed in the echo area. Now try putting the
1744 cursor inside the expression. If you put it right after the next to
1745 last parenthesis (so it appears to sit on top of the last parenthesis),
1746 you will get a 6 printed in the echo area! This is because the command
1747 evaluates the expression @code{(+ 3 3)}.
1748
1749 Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1750 you will get the number itself. In Lisp, if you evaluate a number, you
1751 get the number itself---this is how numbers differ from symbols. If you
1752 evaluate a list starting with a symbol like @code{+}, you will get a
1753 value returned that is the result of the computer carrying out the
1754 instructions in the function definition attached to that name. If a
1755 symbol by itself is evaluated, something different happens, as we will
1756 see in the next section.
1757
1758 @node Variables, Arguments, Evaluation, List Processing
1759 @comment node-name, next, previous, up
1760 @section Variables
1761 @cindex Variables
1762
1763 In Emacs Lisp, a symbol can have a value attached to it just as it can
1764 have a function definition attached to it. The two are different.
1765 The function definition is a set of instructions that a computer will
1766 obey. A value, on the other hand, is something, such as number or a
1767 name, that can vary (which is why such a symbol is called a variable).
1768 The value of a symbol can be any expression in Lisp, such as a symbol,
1769 number, list, or string. A symbol that has a value is often called a
1770 @dfn{variable}.
1771
1772 A symbol can have both a function definition and a value attached to
1773 it at the same time. Or it can have just one or the other.
1774 The two are separate. This is somewhat similar
1775 to the way the name Cambridge can refer to the city in Massachusetts
1776 and have some information attached to the name as well, such as
1777 ``great programming center''.
1778
1779 @ignore
1780 (Incidentally, in Emacs Lisp, a symbol can have two
1781 other things attached to it, too: a property list and a documentation
1782 string; these are discussed later.)
1783 @end ignore
1784
1785 Another way to think about this is to imagine a symbol as being a chest
1786 of drawers. The function definition is put in one drawer, the value in
1787 another, and so on. What is put in the drawer holding the value can be
1788 changed without affecting the contents of the drawer holding the
1789 function definition, and vice-versa.
1790
1791 @menu
1792 * fill-column Example::
1793 * Void Function:: The error message for a symbol
1794 without a function.
1795 * Void Variable:: The error message for a symbol without a value.
1796 @end menu
1797
1798 @node fill-column Example, Void Function, Variables, Variables
1799 @ifnottex
1800 @unnumberedsubsec @code{fill-column}, an Example Variable
1801 @end ifnottex
1802
1803 @findex fill-column, @r{an example variable}
1804 @cindex Example variable, @code{fill-column}
1805 @cindex Variable, example of, @code{fill-column}
1806 The variable @code{fill-column} illustrates a symbol with a value
1807 attached to it: in every GNU Emacs buffer, this symbol is set to some
1808 value, usually 72 or 70, but sometimes to some other value. To find the
1809 value of this symbol, evaluate it by itself. If you are reading this in
1810 Info inside of GNU Emacs, you can do this by putting the cursor after
1811 the symbol and typing @kbd{C-x C-e}:
1812
1813 @smallexample
1814 fill-column
1815 @end smallexample
1816
1817 @noindent
1818 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1819 area. This is the value for which @code{fill-column} is set for me as I
1820 write this. It may be different for you in your Info buffer. Notice
1821 that the value returned as a variable is printed in exactly the same way
1822 as the value returned by a function carrying out its instructions. From
1823 the point of view of the Lisp interpreter, a value returned is a value
1824 returned. What kind of expression it came from ceases to matter once
1825 the value is known.
1826
1827 A symbol can have any value attached to it or, to use the jargon, we can
1828 @dfn{bind} the variable to a value: to a number, such as 72; to a
1829 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1830 oak)}; we can even bind a variable to a function definition.
1831
1832 A symbol can be bound to a value in several ways. @xref{set & setq, ,
1833 Setting the Value of a Variable}, for information about one way to do
1834 this.
1835
1836 @node Void Function, Void Variable, fill-column Example, Variables
1837 @comment node-name, next, previous, up
1838 @subsection Error Message for a Symbol Without a Function
1839 @cindex Symbol without function error
1840 @cindex Error for symbol without function
1841
1842 When we evaluated @code{fill-column} to find its value as a variable,
1843 we did not place parentheses around the word. This is because we did
1844 not intend to use it as a function name.
1845
1846 If @code{fill-column} were the first or only element of a list, the
1847 Lisp interpreter would attempt to find the function definition
1848 attached to it. But @code{fill-column} has no function definition.
1849 Try evaluating this:
1850
1851 @smallexample
1852 (fill-column)
1853 @end smallexample
1854
1855 @need 1250
1856 @noindent
1857 In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1858 that says:
1859
1860 @smallexample
1861 @group
1862 ---------- Buffer: *Backtrace* ----------
1863 Debugger entered--Lisp error: (void-function fill-column)
1864 (fill-column)
1865 eval((fill-column))
1866 eval-last-sexp-1(nil)
1867 eval-last-sexp(nil)
1868 call-interactively(eval-last-sexp)
1869 ---------- Buffer: *Backtrace* ----------
1870 @end group
1871 @end smallexample
1872
1873 @noindent
1874 (Remember, to quit the debugger and make the debugger window go away,
1875 type @kbd{q} in the @file{*Backtrace*} buffer.)
1876
1877 @need 800
1878 In GNU Emacs 20 and before, you will produce an error message that says:
1879
1880 @smallexample
1881 Symbol's function definition is void:@: fill-column
1882 @end smallexample
1883
1884 @noindent
1885 (The message will go away away as soon as you move the cursor or type
1886 another key.)
1887
1888 @node Void Variable, , Void Function, Variables
1889 @comment node-name, next, previous, up
1890 @subsection Error Message for a Symbol Without a Value
1891 @cindex Symbol without value error
1892 @cindex Error for symbol without value
1893
1894 If you attempt to evaluate a symbol that does not have a value bound to
1895 it, you will receive an error message. You can see this by
1896 experimenting with our 2 plus 2 addition. In the following expression,
1897 put your cursor right after the @code{+}, before the first number 2,
1898 type @kbd{C-x C-e}:
1899
1900 @smallexample
1901 (+ 2 2)
1902 @end smallexample
1903
1904 @need 1500
1905 @noindent
1906 In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1907 says:
1908
1909 @smallexample
1910 @group
1911 ---------- Buffer: *Backtrace* ----------
1912 Debugger entered--Lisp error: (void-variable +)
1913 eval(+)
1914 eval-last-sexp-1(nil)
1915 eval-last-sexp(nil)
1916 call-interactively(eval-last-sexp)
1917 ---------- Buffer: *Backtrace* ----------
1918 @end group
1919 @end smallexample
1920
1921 @noindent
1922 (As with the other times we entered the debugger, you can quit by
1923 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1924
1925 This backtrace is different from the very first error message we saw,
1926 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1927 In this case, the function does not have a value as a variable; while
1928 in the other error message, the function (the word `this') did not
1929 have a definition.
1930
1931 In this experiment with the @code{+}, what we did was cause the Lisp
1932 interpreter to evaluate the @code{+} and look for the value of the
1933 variable instead of the function definition. We did this by placing the
1934 cursor right after the symbol rather than after the parenthesis of the
1935 enclosing list as we did before. As a consequence, the Lisp interpreter
1936 evaluated the preceding s-expression, which in this case was the
1937 @code{+} by itself.
1938
1939 Since @code{+} does not have a value bound to it, just the function
1940 definition, the error message reported that the symbol's value as a
1941 variable was void.
1942
1943 @need 800
1944 In GNU Emacs version 20 and before, your error message will say:
1945
1946 @example
1947 Symbol's value as variable is void:@: +
1948 @end example
1949
1950 @noindent
1951 The meaning is the same as in GNU Emacs 21.
1952
1953 @node Arguments, set & setq, Variables, List Processing
1954 @comment node-name, next, previous, up
1955 @section Arguments
1956 @cindex Arguments
1957 @cindex Passing information to functions
1958
1959 To see how information is passed to functions, let's look again at
1960 our old standby, the addition of two plus two. In Lisp, this is written
1961 as follows:
1962
1963 @smallexample
1964 (+ 2 2)
1965 @end smallexample
1966
1967 If you evaluate this expression, the number 4 will appear in your echo
1968 area. What the Lisp interpreter does is add the numbers that follow
1969 the @code{+}.
1970
1971 @cindex @samp{argument} defined
1972 The numbers added by @code{+} are called the @dfn{arguments} of the
1973 function @code{+}. These numbers are the information that is given to
1974 or @dfn{passed} to the function.
1975
1976 The word `argument' comes from the way it is used in mathematics and
1977 does not refer to a disputation between two people; instead it refers to
1978 the information presented to the function, in this case, to the
1979 @code{+}. In Lisp, the arguments to a function are the atoms or lists
1980 that follow the function. The values returned by the evaluation of
1981 these atoms or lists are passed to the function. Different functions
1982 require different numbers of arguments; some functions require none at
1983 all.@footnote{It is curious to track the path by which the word `argument'
1984 came to have two different meanings, one in mathematics and the other in
1985 everyday English. According to the @cite{Oxford English Dictionary},
1986 the word derives from the Latin for @samp{to make clear, prove}; thus it
1987 came to mean, by one thread of derivation, `the evidence offered as
1988 proof', which is to say, `the information offered', which led to its
1989 meaning in Lisp. But in the other thread of derivation, it came to mean
1990 `to assert in a manner against which others may make counter
1991 assertions', which led to the meaning of the word as a disputation.
1992 (Note here that the English word has two different definitions attached
1993 to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1994 have two different function definitions at the same time.)}
1995
1996 @menu
1997 * Data types:: Types of data passed to a function.
1998 * Args as Variable or List:: An argument can be the value
1999 of a variable or list.
2000 * Variable Number of Arguments:: Some functions may take a
2001 variable number of arguments.
2002 * Wrong Type of Argument:: Passing an argument of the wrong type
2003 to a function.
2004 * message:: A useful function for sending messages.
2005 @end menu
2006
2007 @node Data types, Args as Variable or List, Arguments, Arguments
2008 @comment node-name, next, previous, up
2009 @subsection Arguments' Data Types
2010 @cindex Data types
2011 @cindex Types of data
2012 @cindex Arguments' data types
2013
2014 The type of data that should be passed to a function depends on what
2015 kind of information it uses. The arguments to a function such as
2016 @code{+} must have values that are numbers, since @code{+} adds numbers.
2017 Other functions use different kinds of data for their arguments.
2018
2019 @findex concat
2020 For example, the @code{concat} function links together or unites two or
2021 more strings of text to produce a string. The arguments are strings.
2022 Concatenating the two character strings @code{abc}, @code{def} produces
2023 the single string @code{abcdef}. This can be seen by evaluating the
2024 following:
2025
2026 @smallexample
2027 (concat "abc" "def")
2028 @end smallexample
2029
2030 @noindent
2031 The value produced by evaluating this expression is @code{"abcdef"}.
2032
2033 A function such as @code{substring} uses both a string and numbers as
2034 arguments. The function returns a part of the string, a substring of
2035 the first argument. This function takes three arguments. Its first
2036 argument is the string of characters, the second and third arguments are
2037 numbers that indicate the beginning and end of the substring. The
2038 numbers are a count of the number of characters (including spaces and
2039 punctuations) from the beginning of the string.
2040
2041 @need 800
2042 For example, if you evaluate the following:
2043
2044 @smallexample
2045 (substring "The quick brown fox jumped." 16 19)
2046 @end smallexample
2047
2048 @noindent
2049 you will see @code{"fox"} appear in the echo area. The arguments are the
2050 string and the two numbers.
2051
2052 Note that the string passed to @code{substring} is a single atom even
2053 though it is made up of several words separated by spaces. Lisp counts
2054 everything between the two quotation marks as part of the string,
2055 including the spaces. You can think of the @code{substring} function as
2056 a kind of `atom smasher' since it takes an otherwise indivisible atom
2057 and extracts a part. However, @code{substring} is only able to extract
2058 a substring from an argument that is a string, not from another type of
2059 atom such as a number or symbol.
2060
2061 @node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2062 @comment node-name, next, previous, up
2063 @subsection An Argument as the Value of a Variable or List
2064
2065 An argument can be a symbol that returns a value when it is evaluated.
2066 For example, when the symbol @code{fill-column} by itself is evaluated,
2067 it returns a number. This number can be used in an addition.
2068
2069 @need 1250
2070 Position the cursor after the following expression and type @kbd{C-x
2071 C-e}:
2072
2073 @smallexample
2074 (+ 2 fill-column)
2075 @end smallexample
2076
2077 @noindent
2078 The value will be a number two more than what you get by evaluating
2079 @code{fill-column} alone. For me, this is 74, because the value of
2080 @code{fill-column} is 72.
2081
2082 As we have just seen, an argument can be a symbol that returns a value
2083 when evaluated. In addition, an argument can be a list that returns a
2084 value when it is evaluated. For example, in the following expression,
2085 the arguments to the function @code{concat} are the strings
2086 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2087 @code{(number-to-string (+ 2 fill-column))}.
2088
2089 @c For Emacs 21, need number-to-string
2090 @smallexample
2091 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2092 @end smallexample
2093
2094 @noindent
2095 If you evaluate this expression---and if, as with my Emacs,
2096 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2097 appear in the echo area. (Note that you must put spaces after the
2098 word @samp{The} and before the word @samp{red} so they will appear in
2099 the final string. The function @code{number-to-string} converts the
2100 integer that the addition function returns to a string.
2101 @code{number-to-string} is also known as @code{int-to-string}.)
2102
2103 @node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2104 @comment node-name, next, previous, up
2105 @subsection Variable Number of Arguments
2106 @cindex Variable number of arguments
2107 @cindex Arguments, variable number of
2108
2109 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2110 number of arguments. (The @code{*} is the symbol for multiplication.)
2111 This can be seen by evaluating each of the following expressions in
2112 the usual way. What you will see in the echo area is printed in this
2113 text after @samp{@result{}}, which you may read as `evaluates to'.
2114
2115 @need 1250
2116 In the first set, the functions have no arguments:
2117
2118 @smallexample
2119 @group
2120 (+) @result{} 0
2121
2122 (*) @result{} 1
2123 @end group
2124 @end smallexample
2125
2126 @need 1250
2127 In this set, the functions have one argument each:
2128
2129 @smallexample
2130 @group
2131 (+ 3) @result{} 3
2132
2133 (* 3) @result{} 3
2134 @end group
2135 @end smallexample
2136
2137 @need 1250
2138 In this set, the functions have three arguments each:
2139
2140 @smallexample
2141 @group
2142 (+ 3 4 5) @result{} 12
2143
2144 (* 3 4 5) @result{} 60
2145 @end group
2146 @end smallexample
2147
2148 @node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2149 @comment node-name, next, previous, up
2150 @subsection Using the Wrong Type Object as an Argument
2151 @cindex Wrong type of argument
2152 @cindex Argument, wrong type of
2153
2154 When a function is passed an argument of the wrong type, the Lisp
2155 interpreter produces an error message. For example, the @code{+}
2156 function expects the values of its arguments to be numbers. As an
2157 experiment we can pass it the quoted symbol @code{hello} instead of a
2158 number. Position the cursor after the following expression and type
2159 @kbd{C-x C-e}:
2160
2161 @smallexample
2162 (+ 2 'hello)
2163 @end smallexample
2164
2165 @noindent
2166 When you do this you will generate an error message. What has happened
2167 is that @code{+} has tried to add the 2 to the value returned by
2168 @code{'hello}, but the value returned by @code{'hello} is the symbol
2169 @code{hello}, not a number. Only numbers can be added. So @code{+}
2170 could not carry out its addition.
2171
2172 @need 1250
2173 In GNU Emacs version 21, you will create and enter a
2174 @file{*Backtrace*} buffer that says:
2175
2176 @noindent
2177 @smallexample
2178 @group
2179 ---------- Buffer: *Backtrace* ----------
2180 Debugger entered--Lisp error:
2181 (wrong-type-argument number-or-marker-p hello)
2182 +(2 hello)
2183 eval((+ 2 (quote hello)))
2184 eval-last-sexp-1(nil)
2185 eval-last-sexp(nil)
2186 call-interactively(eval-last-sexp)
2187 ---------- Buffer: *Backtrace* ----------
2188 @end group
2189 @end smallexample
2190
2191 @need 1250
2192 As usual, the error message tries to be helpful and makes sense after you
2193 learn how to read it.
2194
2195 The first part of the error message is straightforward; it says
2196 @samp{wrong type argument}. Next comes the mysterious jargon word
2197 @w{@samp{number-or-marker-p}}. This word is trying to tell you what
2198 kind of argument the @code{+} expected.
2199
2200 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2201 trying to determine whether the information presented it (the value of
2202 the argument) is a number or a marker (a special object representing a
2203 buffer position). What it does is test to see whether the @code{+} is
2204 being given numbers to add. It also tests to see whether the
2205 argument is something called a marker, which is a specific feature of
2206 Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2207 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2208 its position is kept as a marker. The mark can be considered a
2209 number---the number of characters the location is from the beginning
2210 of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2211 numeric value of marker positions as numbers.
2212
2213 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2214 practice started in the early days of Lisp programming. The @samp{p}
2215 stands for `predicate'. In the jargon used by the early Lisp
2216 researchers, a predicate refers to a function to determine whether some
2217 property is true or false. So the @samp{p} tells us that
2218 @code{number-or-marker-p} is the name of a function that determines
2219 whether it is true or false that the argument supplied is a number or
2220 a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2221 a function that tests whether its argument has the value of zero, and
2222 @code{listp}, a function that tests whether its argument is a list.
2223
2224 Finally, the last part of the error message is the symbol @code{hello}.
2225 This is the value of the argument that was passed to @code{+}. If the
2226 addition had been passed the correct type of object, the value passed
2227 would have been a number, such as 37, rather than a symbol like
2228 @code{hello}. But then you would not have got the error message.
2229
2230 @need 1250
2231 In GNU Emacs version 20 and before, the echo area displays an error
2232 message that says:
2233
2234 @smallexample
2235 Wrong type argument:@: number-or-marker-p, hello
2236 @end smallexample
2237
2238 This says, in different words, the same as the top line of the
2239 @file{*Backtrace*} buffer.
2240
2241 @node message, , Wrong Type of Argument, Arguments
2242 @comment node-name, next, previous, up
2243 @subsection The @code{message} Function
2244 @findex message
2245
2246 Like @code{+}, the @code{message} function takes a variable number of
2247 arguments. It is used to send messages to the user and is so useful
2248 that we will describe it here.
2249
2250 @need 1250
2251 A message is printed in the echo area. For example, you can print a
2252 message in your echo area by evaluating the following list:
2253
2254 @smallexample
2255 (message "This message appears in the echo area!")
2256 @end smallexample
2257
2258 The whole string between double quotation marks is a single argument
2259 and is printed @i{in toto}. (Note that in this example, the message
2260 itself will appear in the echo area within double quotes; that is
2261 because you see the value returned by the @code{message} function. In
2262 most uses of @code{message} in programs that you write, the text will
2263 be printed in the echo area as a side-effect, without the quotes.
2264 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2265 detail}, for an example of this.)
2266
2267 However, if there is a @samp{%s} in the quoted string of characters, the
2268 @code{message} function does not print the @samp{%s} as such, but looks
2269 to the argument that follows the string. It evaluates the second
2270 argument and prints the value at the location in the string where the
2271 @samp{%s} is.
2272
2273 @need 1250
2274 You can see this by positioning the cursor after the following
2275 expression and typing @kbd{C-x C-e}:
2276
2277 @smallexample
2278 (message "The name of this buffer is: %s." (buffer-name))
2279 @end smallexample
2280
2281 @noindent
2282 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2283 echo area. The function @code{buffer-name} returns the name of the
2284 buffer as a string, which the @code{message} function inserts in place
2285 of @code{%s}.
2286
2287 To print a value as an integer, use @samp{%d} in the same way as
2288 @samp{%s}. For example, to print a message in the echo area that
2289 states the value of the @code{fill-column}, evaluate the following:
2290
2291 @smallexample
2292 (message "The value of fill-column is %d." fill-column)
2293 @end smallexample
2294
2295 @noindent
2296 On my system, when I evaluate this list, @code{"The value of
2297 fill-column is 72."} appears in my echo area@footnote{Actually, you
2298 can use @code{%s} to print a number. It is non-specific. @code{%d}
2299 prints only the part of a number left of a decimal point, and not
2300 anything that is not a number.}.
2301
2302 If there is more than one @samp{%s} in the quoted string, the value of
2303 the first argument following the quoted string is printed at the
2304 location of the first @samp{%s} and the value of the second argument is
2305 printed at the location of the second @samp{%s}, and so on.
2306
2307 @need 1250
2308 For example, if you evaluate the following,
2309
2310 @smallexample
2311 @group
2312 (message "There are %d %s in the office!"
2313 (- fill-column 14) "pink elephants")
2314 @end group
2315 @end smallexample
2316
2317 @noindent
2318 a rather whimsical message will appear in your echo area. On my system
2319 it says, @code{"There are 58 pink elephants in the office!"}.
2320
2321 The expression @code{(- fill-column 14)} is evaluated and the resulting
2322 number is inserted in place of the @samp{%d}; and the string in double
2323 quotes, @code{"pink elephants"}, is treated as a single argument and
2324 inserted in place of the @samp{%s}. (That is to say, a string between
2325 double quotes evaluates to itself, like a number.)
2326
2327 Finally, here is a somewhat complex example that not only illustrates
2328 the computation of a number, but also shows how you can use an
2329 expression within an expression to generate the text that is substituted
2330 for @samp{%s}:
2331
2332 @smallexample
2333 @group
2334 (message "He saw %d %s"
2335 (- fill-column 34)
2336 (concat "red "
2337 (substring
2338 "The quick brown foxes jumped." 16 21)
2339 " leaping."))
2340 @end group
2341 @end smallexample
2342
2343 In this example, @code{message} has three arguments: the string,
2344 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2345 the expression beginning with the function @code{concat}. The value
2346 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2347 in place of the @samp{%d}; and the value returned by the expression
2348 beginning with @code{concat} is inserted in place of the @samp{%s}.
2349
2350 When I evaluate the expression, the message @code{"He saw 38 red
2351 foxes leaping."} appears in my echo area.
2352
2353 @node set & setq, Summary, Arguments, List Processing
2354 @comment node-name, next, previous, up
2355 @section Setting the Value of a Variable
2356 @cindex Variable, setting value
2357 @cindex Setting value of variable
2358
2359 @cindex @samp{bind} defined
2360 There are several ways by which a variable can be given a value. One of
2361 the ways is to use either the function @code{set} or the function
2362 @code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2363 jargon for this process is to @dfn{bind} a variable to a value.)
2364
2365 The following sections not only describe how @code{set} and @code{setq}
2366 work but also illustrate how arguments are passed.
2367
2368 @menu
2369 * Using set:: Setting values.
2370 * Using setq:: Setting a quoted value.
2371 * Counting:: Using @code{setq} to count.
2372 @end menu
2373
2374 @node Using set, Using setq, set & setq, set & setq
2375 @comment node-name, next, previous, up
2376 @subsection Using @code{set}
2377 @findex set
2378
2379 To set the value of the symbol @code{flowers} to the list @code{'(rose
2380 violet daisy buttercup)}, evaluate the following expression by
2381 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2382
2383 @smallexample
2384 (set 'flowers '(rose violet daisy buttercup))
2385 @end smallexample
2386
2387 @noindent
2388 The list @code{(rose violet daisy buttercup)} will appear in the echo
2389 area. This is what is @emph{returned} by the @code{set} function. As a
2390 side effect, the symbol @code{flowers} is bound to the list ; that is,
2391 the symbol @code{flowers}, which can be viewed as a variable, is given
2392 the list as its value. (This process, by the way, illustrates how a
2393 side effect to the Lisp interpreter, setting the value, can be the
2394 primary effect that we humans are interested in. This is because every
2395 Lisp function must return a value if it does not get an error, but it
2396 will only have a side effect if it is designed to have one.)
2397
2398 After evaluating the @code{set} expression, you can evaluate the symbol
2399 @code{flowers} and it will return the value you just set. Here is the
2400 symbol. Place your cursor after it and type @kbd{C-x C-e}.
2401
2402 @smallexample
2403 flowers
2404 @end smallexample
2405
2406 @noindent
2407 When you evaluate @code{flowers}, the list
2408 @code{(rose violet daisy buttercup)} appears in the echo area.
2409
2410 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2411 in front of it, what you will see in the echo area is the symbol itself,
2412 @code{flowers}. Here is the quoted symbol, so you can try this:
2413
2414 @smallexample
2415 'flowers
2416 @end smallexample
2417
2418 Note also, that when you use @code{set}, you need to quote both
2419 arguments to @code{set}, unless you want them evaluated. Since we do
2420 not want either argument evaluated, neither the variable
2421 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2422 are quoted. (When you use @code{set} without quoting its first
2423 argument, the first argument is evaluated before anything else is
2424 done. If you did this and @code{flowers} did not have a value
2425 already, you would get an error message that the @samp{Symbol's value
2426 as variable is void}; on the other hand, if @code{flowers} did return
2427 a value after it was evaluated, the @code{set} would attempt to set
2428 the value that was returned. There are situations where this is the
2429 right thing for the function to do; but such situations are rare.)
2430
2431 @node Using setq, Counting, Using set, set & setq
2432 @comment node-name, next, previous, up
2433 @subsection Using @code{setq}
2434 @findex setq
2435
2436 As a practical matter, you almost always quote the first argument to
2437 @code{set}. The combination of @code{set} and a quoted first argument
2438 is so common that it has its own name: the special form @code{setq}.
2439 This special form is just like @code{set} except that the first argument
2440 is quoted automatically, so you don't need to type the quote mark
2441 yourself. Also, as an added convenience, @code{setq} permits you to set
2442 several different variables to different values, all in one expression.
2443
2444 To set the value of the variable @code{carnivores} to the list
2445 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2446 is used:
2447
2448 @smallexample
2449 (setq carnivores '(lion tiger leopard))
2450 @end smallexample
2451
2452 @noindent
2453 This is exactly the same as using @code{set} except the first argument
2454 is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2455 means @code{quote}.)
2456
2457 @need 1250
2458 With @code{set}, the expression would look like this:
2459
2460 @smallexample
2461 (set 'carnivores '(lion tiger leopard))
2462 @end smallexample
2463
2464 Also, @code{setq} can be used to assign different values to
2465 different variables. The first argument is bound to the value
2466 of the second argument, the third argument is bound to the value of the
2467 fourth argument, and so on. For example, you could use the following to
2468 assign a list of trees to the symbol @code{trees} and a list of herbivores
2469 to the symbol @code{herbivores}:
2470
2471 @smallexample
2472 @group
2473 (setq trees '(pine fir oak maple)
2474 herbivores '(gazelle antelope zebra))
2475 @end group
2476 @end smallexample
2477
2478 @noindent
2479 (The expression could just as well have been on one line, but it might
2480 not have fit on a page; and humans find it easier to read nicely
2481 formatted lists.)
2482
2483 Although I have been using the term `assign', there is another way of
2484 thinking about the workings of @code{set} and @code{setq}; and that is to
2485 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2486 list. This latter way of thinking is very common and in forthcoming
2487 chapters we shall come upon at least one symbol that has `pointer' as
2488 part of its name. The name is chosen because the symbol has a value,
2489 specifically a list, attached to it; or, expressed another way,
2490 the symbol is set to ``point'' to the list.
2491
2492 @node Counting, , Using setq, set & setq
2493 @comment node-name, next, previous, up
2494 @subsection Counting
2495 @cindex Counting
2496
2497 Here is an example that shows how to use @code{setq} in a counter. You
2498 might use this to count how many times a part of your program repeats
2499 itself. First set a variable to zero; then add one to the number each
2500 time the program repeats itself. To do this, you need a variable that
2501 serves as a counter, and two expressions: an initial @code{setq}
2502 expression that sets the counter variable to zero; and a second
2503 @code{setq} expression that increments the counter each time it is
2504 evaluated.
2505
2506 @smallexample
2507 @group
2508 (setq counter 0) ; @r{Let's call this the initializer.}
2509
2510 (setq counter (+ counter 1)) ; @r{This is the incrementer.}
2511
2512 counter ; @r{This is the counter.}
2513 @end group
2514 @end smallexample
2515
2516 @noindent
2517 (The text following the @samp{;} are comments. @xref{Change a
2518 defun, , Change a Function Definition}.)
2519
2520 If you evaluate the first of these expressions, the initializer,
2521 @code{(setq counter 0)}, and then evaluate the third expression,
2522 @code{counter}, the number @code{0} will appear in the echo area. If
2523 you then evaluate the second expression, the incrementer, @code{(setq
2524 counter (+ counter 1))}, the counter will get the value 1. So if you
2525 again evaluate @code{counter}, the number @code{1} will appear in the
2526 echo area. Each time you evaluate the second expression, the value of
2527 the counter will be incremented.
2528
2529 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2530 the Lisp interpreter first evaluates the innermost list; this is the
2531 addition. In order to evaluate this list, it must evaluate the variable
2532 @code{counter} and the number @code{1}. When it evaluates the variable
2533 @code{counter}, it receives its current value. It passes this value and
2534 the number @code{1} to the @code{+} which adds them together. The sum
2535 is then returned as the value of the inner list and passed to the
2536 @code{setq} which sets the variable @code{counter} to this new value.
2537 Thus, the value of the variable, @code{counter}, is changed.
2538
2539 @node Summary, Error Message Exercises, set & setq, List Processing
2540 @comment node-name, next, previous, up
2541 @section Summary
2542
2543 Learning Lisp is like climbing a hill in which the first part is the
2544 steepest. You have now climbed the most difficult part; what remains
2545 becomes easier as you progress onwards.
2546
2547 In summary,
2548
2549 @itemize @bullet
2550
2551 @item
2552 Lisp programs are made up of expressions, which are lists or single atoms.
2553
2554 @item
2555 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2556 surrounded by parentheses. A list can be empty.
2557
2558 @item
2559 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2560 character symbols like @code{+}, strings of characters between double
2561 quotation marks, or numbers.
2562
2563 @item
2564 A number evaluates to itself.
2565
2566 @item
2567 A string between double quotes also evaluates to itself.
2568
2569 @item
2570 When you evaluate a symbol by itself, its value is returned.
2571
2572 @item
2573 When you evaluate a list, the Lisp interpreter looks at the first symbol
2574 in the list and then at the function definition bound to that symbol.
2575 Then the instructions in the function definition are carried out.
2576
2577 @item
2578 A single-quote, @code{'}, tells the Lisp interpreter that it should
2579 return the following expression as written, and not evaluate it as it
2580 would if the quote were not there.
2581
2582 @item
2583 Arguments are the information passed to a function. The arguments to a
2584 function are computed by evaluating the rest of the elements of the list
2585 of which the function is the first element.
2586
2587 @item
2588 A function always returns a value when it is evaluated (unless it gets
2589 an error); in addition, it may also carry out some action called a
2590 ``side effect''. In many cases, a function's primary purpose is to
2591 create a side effect.
2592 @end itemize
2593
2594 @node Error Message Exercises, , Summary, List Processing
2595 @comment node-name, next, previous, up
2596 @section Exercises
2597
2598 A few simple exercises:
2599
2600 @itemize @bullet
2601 @item
2602 Generate an error message by evaluating an appropriate symbol that is
2603 not within parentheses.
2604
2605 @item
2606 Generate an error message by evaluating an appropriate symbol that is
2607 between parentheses.
2608
2609 @item
2610 Create a counter that increments by two rather than one.
2611
2612 @item
2613 Write an expression that prints a message in the echo area when
2614 evaluated.
2615 @end itemize
2616
2617 @node Practicing Evaluation, Writing Defuns, List Processing, Top
2618 @comment node-name, next, previous, up
2619 @chapter Practicing Evaluation
2620 @cindex Practicing evaluation
2621 @cindex Evaluation practice
2622
2623 Before learning how to write a function definition in Emacs Lisp, it is
2624 useful to spend a little time evaluating various expressions that have
2625 already been written. These expressions will be lists with the
2626 functions as their first (and often only) element. Since some of the
2627 functions associated with buffers are both simple and interesting, we
2628 will start with those. In this section, we will evaluate a few of
2629 these. In another section, we will study the code of several other
2630 buffer-related functions, to see how they were written.
2631
2632 @menu
2633 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2634 causes evaluation.
2635 * Buffer Names:: Buffers and files are different.
2636 * Getting Buffers:: Getting a buffer itself, not merely its name.
2637 * Switching Buffers:: How to change to another buffer.
2638 * Buffer Size & Locations:: Where point is located and the size of
2639 the buffer.
2640 * Evaluation Exercise::
2641 @end menu
2642
2643 @node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2644 @ifnottex
2645 @unnumberedsec How to Evaluate
2646 @end ifnottex
2647
2648 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2649 command to move the cursor or to scroll the screen, @i{you are evaluating
2650 an expression,} the first element of which is a function. @i{This is
2651 how Emacs works.}
2652
2653 @cindex @samp{interactive function} defined
2654 @cindex @samp{command} defined
2655 When you type keys, you cause the Lisp interpreter to evaluate an
2656 expression and that is how you get your results. Even typing plain text
2657 involves evaluating an Emacs Lisp function, in this case, one that uses
2658 @code{self-insert-command}, which simply inserts the character you
2659 typed. The functions you evaluate by typing keystrokes are called
2660 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2661 interactive will be illustrated in the chapter on how to write function
2662 definitions. @xref{Interactive, , Making a Function Interactive}.
2663
2664 In addition to typing keyboard commands, we have seen a second way to
2665 evaluate an expression: by positioning the cursor after a list and
2666 typing @kbd{C-x C-e}. This is what we will do in the rest of this
2667 section. There are other ways to evaluate an expression as well; these
2668 will be described as we come to them.
2669
2670 Besides being used for practicing evaluation, the functions shown in the
2671 next few sections are important in their own right. A study of these
2672 functions makes clear the distinction between buffers and files, how to
2673 switch to a buffer, and how to determine a location within it.
2674
2675 @node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2676 @comment node-name, next, previous, up
2677 @section Buffer Names
2678 @findex buffer-name
2679 @findex buffer-file-name
2680
2681 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2682 the difference between a file and a buffer. When you evaluate the
2683 following expression, @code{(buffer-name)}, the name of the buffer
2684 appears in the echo area. When you evaluate @code{(buffer-file-name)},
2685 the name of the file to which the buffer refers appears in the echo
2686 area. Usually, the name returned by @code{(buffer-name)} is the same as
2687 the name of the file to which it refers, and the name returned by
2688 @code{(buffer-file-name)} is the full path-name of the file.
2689
2690 A file and a buffer are two different entities. A file is information
2691 recorded permanently in the computer (unless you delete it). A buffer,
2692 on the other hand, is information inside of Emacs that will vanish at
2693 the end of the editing session (or when you kill the buffer). Usually,
2694 a buffer contains information that you have copied from a file; we say
2695 the buffer is @dfn{visiting} that file. This copy is what you work on
2696 and modify. Changes to the buffer do not change the file, until you
2697 save the buffer. When you save the buffer, the buffer is copied to the file
2698 and is thus saved permanently.
2699
2700 @need 1250
2701 If you are reading this in Info inside of GNU Emacs, you can evaluate
2702 each of the following expressions by positioning the cursor after it and
2703 typing @kbd{C-x C-e}.
2704
2705 @smallexample
2706 @group
2707 (buffer-name)
2708
2709 (buffer-file-name)
2710 @end group
2711 @end smallexample
2712
2713 @noindent
2714 When I do this, @file{"introduction.texinfo"} is the value returned by
2715 evaluating @code{(buffer-name)}, and
2716 @file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2717 evaluating @code{(buffer-file-name)}. The former is the name of the
2718 buffer and the latter is the name of the file. (In the expressions, the
2719 parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2720 @code{buffer-file-name} as functions; without the parentheses, the
2721 interpreter would attempt to evaluate the symbols as variables.
2722 @xref{Variables}.)
2723
2724 In spite of the distinction between files and buffers, you will often
2725 find that people refer to a file when they mean a buffer and vice-versa.
2726 Indeed, most people say, ``I am editing a file,'' rather than saying,
2727 ``I am editing a buffer which I will soon save to a file.'' It is
2728 almost always clear from context what people mean. When dealing with
2729 computer programs, however, it is important to keep the distinction in mind,
2730 since the computer is not as smart as a person.
2731
2732 @cindex Buffer, history of word
2733 The word `buffer', by the way, comes from the meaning of the word as a
2734 cushion that deadens the force of a collision. In early computers, a
2735 buffer cushioned the interaction between files and the computer's
2736 central processing unit. The drums or tapes that held a file and the
2737 central processing unit were pieces of equipment that were very
2738 different from each other, working at their own speeds, in spurts. The
2739 buffer made it possible for them to work together effectively.
2740 Eventually, the buffer grew from being an intermediary, a temporary
2741 holding place, to being the place where work is done. This
2742 transformation is rather like that of a small seaport that grew into a
2743 great city: once it was merely the place where cargo was warehoused
2744 temporarily before being loaded onto ships; then it became a business
2745 and cultural center in its own right.
2746
2747 Not all buffers are associated with files. For example, when you start
2748 an Emacs session by typing the command @code{emacs} alone, without
2749 naming any files, Emacs will start with the @file{*scratch*} buffer on
2750 the screen. This buffer is not visiting any file. Similarly, a
2751 @file{*Help*} buffer is not associated with any file.
2752
2753 @cindex @code{nil}, history of word
2754 If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2755 position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2756 expression, the name @code{"*scratch*"} is returned and will appear in
2757 the echo area. @code{"*scratch*"} is the name of the buffer. However,
2758 if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2759 evaluate that, @code{nil} will appear in the echo area. @code{nil} is
2760 from the Latin word for `nothing'; in this case, it means that the
2761 @file{*scratch*} buffer is not associated with any file. (In Lisp,
2762 @code{nil} is also used to mean `false' and is a synonym for the empty
2763 list, @code{()}.)
2764
2765 Incidentally, if you are in the @file{*scratch*} buffer and want the
2766 value returned by an expression to appear in the @file{*scratch*}
2767 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2768 instead of @kbd{C-x C-e}. This causes the value returned to appear
2769 after the expression. The buffer will look like this:
2770
2771 @smallexample
2772 (buffer-name)"*scratch*"
2773 @end smallexample
2774
2775 @noindent
2776 You cannot do this in Info since Info is read-only and it will not allow
2777 you to change the contents of the buffer. But you can do this in any
2778 buffer you can edit; and when you write code or documentation (such as
2779 this book), this feature is very useful.
2780
2781 @node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2782 @comment node-name, next, previous, up
2783 @section Getting Buffers
2784 @findex current-buffer
2785 @findex other-buffer
2786 @cindex Getting a buffer
2787
2788 The @code{buffer-name} function returns the @emph{name} of the buffer;
2789 to get the buffer @emph{itself}, a different function is needed: the
2790 @code{current-buffer} function. If you use this function in code, what
2791 you get is the buffer itself.
2792
2793 A name and the object or entity to which the name refers are different
2794 from each other. You are not your name. You are a person to whom
2795 others refer by name. If you ask to speak to George and someone hands you
2796 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2797 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2798 not be satisfied. You do not want to speak to the name, but to the
2799 person to whom the name refers. A buffer is similar: the name of the
2800 scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2801 get a buffer itself, you need to use a function such as
2802 @code{current-buffer}.
2803
2804 However, there is a slight complication: if you evaluate
2805 @code{current-buffer} in an expression on its own, as we will do here,
2806 what you see is a printed representation of the name of the buffer
2807 without the contents of the buffer. Emacs works this way for two
2808 reasons: the buffer may be thousands of lines long---too long to be
2809 conveniently displayed; and, another buffer may have the same contents
2810 but a different name, and it is important to distinguish between them.
2811
2812 @need 800
2813 Here is an expression containing the function:
2814
2815 @smallexample
2816 (current-buffer)
2817 @end smallexample
2818
2819 @noindent
2820 If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2821 appears in the echo area. The special format indicates that the
2822 buffer itself is being returned, rather than just its name.
2823
2824 Incidentally, while you can type a number or symbol into a program, you
2825 cannot do that with the printed representation of a buffer: the only way
2826 to get a buffer itself is with a function such as @code{current-buffer}.
2827
2828 A related function is @code{other-buffer}. This returns the most
2829 recently selected buffer other than the one you are in currently. If
2830 you have recently switched back and forth from the @file{*scratch*}
2831 buffer, @code{other-buffer} will return that buffer.
2832
2833 @need 800
2834 You can see this by evaluating the expression:
2835
2836 @smallexample
2837 (other-buffer)
2838 @end smallexample
2839
2840 @noindent
2841 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2842 the name of whatever other buffer you switched back from most
2843 recently@footnote{Actually, by default, if the buffer from which you
2844 just switched is visible to you in another window, @code{other-buffer}
2845 will choose the most recent buffer that you cannot see; this is a
2846 subtlety that I often forget.}.
2847
2848 @node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2849 @comment node-name, next, previous, up
2850 @section Switching Buffers
2851 @findex switch-to-buffer
2852 @findex set-buffer
2853 @cindex Switching to a buffer
2854
2855 The @code{other-buffer} function actually provides a buffer when it is
2856 used as an argument to a function that requires one. We can see this
2857 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2858 different buffer.
2859
2860 But first, a brief introduction to the @code{switch-to-buffer}
2861 function. When you switched back and forth from Info to the
2862 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2863 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2864 rather, to save typing, you probably typed just part of the name, such
2865 as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2866 expand to the full name; and then typed your @kbd{RET} key.} when
2867 prompted in the minibuffer for the name of the buffer to which you
2868 wanted to switch. The keystrokes, @kbd{C-x b}, cause the Lisp
2869 interpreter to evaluate the interactive function
2870 @code{switch-to-buffer}. As we said before, this is how Emacs works:
2871 different keystrokes call or run different functions. For example,
2872 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2873 @code{forward-sentence}, and so on.
2874
2875 By writing @code{switch-to-buffer} in an expression, and giving it a
2876 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2877 does.
2878
2879 @need 1000
2880 Here is the Lisp expression:
2881
2882 @smallexample
2883 (switch-to-buffer (other-buffer))
2884 @end smallexample
2885
2886 @noindent
2887 The symbol @code{switch-to-buffer} is the first element of the list,
2888 so the Lisp interpreter will treat it as a function and carry out the
2889 instructions that are attached to it. But before doing that, the
2890 interpreter will note that @code{other-buffer} is inside parentheses
2891 and work on that symbol first. @code{other-buffer} is the first (and
2892 in this case, the only) element of this list, so the Lisp interpreter
2893 calls or runs the function. It returns another buffer. Next, the
2894 interpreter runs @code{switch-to-buffer}, passing to it, as an
2895 argument, the other buffer, which is what Emacs will switch to. If
2896 you are reading this in Info, try this now. Evaluate the expression.
2897 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2898 expression will move you to your most recent other buffer that you
2899 cannot see. If you really want to go to your most recently selected
2900 buffer, even if you can still see it, you need to evaluate the
2901 following more complex expression:
2902
2903 @smallexample
2904 (switch-to-buffer (other-buffer (current-buffer) t))
2905 @end smallexample
2906
2907 @noindent
2908 In this case, the first argument to @code{other-buffer} tells it which
2909 buffer to skip---the current one---and the second argument tells
2910 @code{other-buffer} it is OK to switch to a visible buffer.
2911 In regular use, @code{switch-to-buffer} takes you to an invisible
2912 window since you would most likely use @kbd{C-x o} (@code{other-window})
2913 to go to another visible buffer.}
2914
2915 In the programming examples in later sections of this document, you will
2916 see the function @code{set-buffer} more often than
2917 @code{switch-to-buffer}. This is because of a difference between
2918 computer programs and humans: humans have eyes and expect to see the
2919 buffer on which they are working on their computer terminals. This is
2920 so obvious, it almost goes without saying. However, programs do not
2921 have eyes. When a computer program works on a buffer, that buffer does
2922 not need to be visible on the screen.
2923
2924 @code{switch-to-buffer} is designed for humans and does two different
2925 things: it switches the buffer to which Emacs' attention is directed; and
2926 it switches the buffer displayed in the window to the new buffer.
2927 @code{set-buffer}, on the other hand, does only one thing: it switches
2928 the attention of the computer program to a different buffer. The buffer
2929 on the screen remains unchanged (of course, normally nothing happens
2930 there until the command finishes running).
2931
2932 @cindex @samp{call} defined
2933 Also, we have just introduced another jargon term, the word @dfn{call}.
2934 When you evaluate a list in which the first symbol is a function, you
2935 are calling that function. The use of the term comes from the notion of
2936 the function as an entity that can do something for you if you `call'
2937 it---just as a plumber is an entity who can fix a leak if you call him
2938 or her.
2939
2940 @node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2941 @comment node-name, next, previous, up
2942 @section Buffer Size and the Location of Point
2943 @cindex Size of buffer
2944 @cindex Buffer size
2945 @cindex Point location
2946 @cindex Location of point
2947
2948 Finally, let's look at several rather simple functions,
2949 @code{buffer-size}, @code{point}, @code{point-min}, and
2950 @code{point-max}. These give information about the size of a buffer and
2951 the location of point within it.
2952
2953 The function @code{buffer-size} tells you the size of the current
2954 buffer; that is, the function returns a count of the number of
2955 characters in the buffer.
2956
2957 @smallexample
2958 (buffer-size)
2959 @end smallexample
2960
2961 @noindent
2962 You can evaluate this in the usual way, by positioning the
2963 cursor after the expression and typing @kbd{C-x C-e}.
2964
2965 @cindex @samp{point} defined
2966 In Emacs, the current position of the cursor is called @dfn{point}.
2967 The expression @code{(point)} returns a number that tells you where the
2968 cursor is located as a count of the number of characters from the
2969 beginning of the buffer up to point.
2970
2971 @need 1250
2972 You can see the character count for point in this buffer by evaluating
2973 the following expression in the usual way:
2974
2975 @smallexample
2976 (point)
2977 @end smallexample
2978
2979 @noindent
2980 As I write this, the value of @code{point} is 65724. The @code{point}
2981 function is frequently used in some of the examples later in this
2982 book.
2983
2984 @need 1250
2985 The value of point depends, of course, on its location within the
2986 buffer. If you evaluate point in this spot, the number will be larger:
2987
2988 @smallexample
2989 (point)
2990 @end smallexample
2991
2992 @noindent
2993 For me, the value of point in this location is 66043, which means that
2994 there are 319 characters (including spaces) between the two expressions.
2995
2996 @cindex @samp{narrowing} defined
2997 The function @code{point-min} is somewhat similar to @code{point}, but
2998 it returns the value of the minimum permissible value of point in the
2999 current buffer. This is the number 1 unless @dfn{narrowing} is in
3000 effect. (Narrowing is a mechanism whereby you can restrict yourself,
3001 or a program, to operations on just a part of a buffer.
3002 @xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
3003 function @code{point-max} returns the value of the maximum permissible
3004 value of point in the current buffer.
3005
3006 @node Evaluation Exercise, , Buffer Size & Locations, Practicing Evaluation
3007 @section Exercise
3008
3009 Find a file with which you are working and move towards its middle.
3010 Find its buffer name, file name, length, and your position in the file.
3011
3012 @node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
3013 @comment node-name, next, previous, up
3014 @chapter How To Write Function Definitions
3015 @cindex Definition writing
3016 @cindex Function definition writing
3017 @cindex Writing a function definition
3018
3019 When the Lisp interpreter evaluates a list, it looks to see whether the
3020 first symbol on the list has a function definition attached to it; or,
3021 put another way, whether the symbol points to a function definition. If
3022 it does, the computer carries out the instructions in the definition. A
3023 symbol that has a function definition is called, simply, a function
3024 (although, properly speaking, the definition is the function and the
3025 symbol refers to it.)
3026
3027 @menu
3028 * Primitive Functions::
3029 * defun:: The @code{defun} special form.
3030 * Install:: Install a function definition.
3031 * Interactive:: Making a function interactive.
3032 * Interactive Options:: Different options for @code{interactive}.
3033 * Permanent Installation:: Installing code permanently.
3034 * let:: Creating and initializing local variables.
3035 * if:: What if?
3036 * else:: If--then--else expressions.
3037 * Truth & Falsehood:: What Lisp considers false and true.
3038 * save-excursion:: Keeping track of point, mark, and buffer.
3039 * Review::
3040 * defun Exercises::
3041 @end menu
3042
3043 @node Primitive Functions, defun, Writing Defuns, Writing Defuns
3044 @ifnottex
3045 @unnumberedsec An Aside about Primitive Functions
3046 @end ifnottex
3047 @cindex Primitive functions
3048 @cindex Functions, primitive
3049
3050 @cindex C language primitives
3051 @cindex Primitives written in C
3052 All functions are defined in terms of other functions, except for a few
3053 @dfn{primitive} functions that are written in the C programming
3054 language. When you write functions' definitions, you will write them in
3055 Emacs Lisp and use other functions as your building blocks. Some of the
3056 functions you will use will themselves be written in Emacs Lisp (perhaps
3057 by you) and some will be primitives written in C. The primitive
3058 functions are used exactly like those written in Emacs Lisp and behave
3059 like them. They are written in C so we can easily run GNU Emacs on any
3060 computer that has sufficient power and can run C.
3061
3062 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3063 distinguish between the use of functions written in C and the use of
3064 functions written in Emacs Lisp. The difference is irrelevant. I
3065 mention the distinction only because it is interesting to know. Indeed,
3066 unless you investigate, you won't know whether an already-written
3067 function is written in Emacs Lisp or C.
3068
3069 @node defun, Install, Primitive Functions, Writing Defuns
3070 @comment node-name, next, previous, up
3071 @section The @code{defun} Special Form
3072 @findex defun
3073 @cindex Special form of @code{defun}
3074
3075 @cindex @samp{function definition} defined
3076 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3077 it that tells the computer what to do when the function is called.
3078 This code is called the @dfn{function definition} and is created by
3079 evaluating a Lisp expression that starts with the symbol @code{defun}
3080 (which is an abbreviation for @emph{define function}). Because
3081 @code{defun} does not evaluate its arguments in the usual way, it is
3082 called a @dfn{special form}.
3083
3084 In subsequent sections, we will look at function definitions from the
3085 Emacs source code, such as @code{mark-whole-buffer}. In this section,
3086 we will describe a simple function definition so you can see how it
3087 looks. This function definition uses arithmetic because it makes for a
3088 simple example. Some people dislike examples using arithmetic; however,
3089 if you are such a person, do not despair. Hardly any of the code we
3090 will study in the remainder of this introduction involves arithmetic or
3091 mathematics. The examples mostly involve text in one way or another.
3092
3093 A function definition has up to five parts following the word
3094 @code{defun}:
3095
3096 @enumerate
3097 @item
3098 The name of the symbol to which the function definition should be
3099 attached.
3100
3101 @item
3102 A list of the arguments that will be passed to the function. If no
3103 arguments will be passed to the function, this is an empty list,
3104 @code{()}.
3105
3106 @item
3107 Documentation describing the function. (Technically optional, but
3108 strongly recommended.)
3109
3110 @item
3111 Optionally, an expression to make the function interactive so you can
3112 use it by typing @kbd{M-x} and then the name of the function; or by
3113 typing an appropriate key or keychord.
3114
3115 @cindex @samp{body} defined
3116 @item
3117 The code that instructs the computer what to do: the @dfn{body} of the
3118 function definition.
3119 @end enumerate
3120
3121 It is helpful to think of the five parts of a function definition as
3122 being organized in a template, with slots for each part:
3123
3124 @smallexample
3125 @group
3126 (defun @var{function-name} (@var{arguments}@dots{})
3127 "@var{optional-documentation}@dots{}"
3128 (interactive @var{argument-passing-info}) ; @r{optional}
3129 @var{body}@dots{})
3130 @end group
3131 @end smallexample
3132
3133 As an example, here is the code for a function that multiplies its
3134 argument by 7. (This example is not interactive. @xref{Interactive,
3135 , Making a Function Interactive}, for that information.)
3136
3137 @smallexample
3138 @group
3139 (defun multiply-by-seven (number)
3140 "Multiply NUMBER by seven."
3141 (* 7 number))
3142 @end group
3143 @end smallexample
3144
3145 This definition begins with a parenthesis and the symbol @code{defun},
3146 followed by the name of the function.
3147
3148 @cindex @samp{argument list} defined
3149 The name of the function is followed by a list that contains the
3150 arguments that will be passed to the function. This list is called
3151 the @dfn{argument list}. In this example, the list has only one
3152 element, the symbol, @code{number}. When the function is used, the
3153 symbol will be bound to the value that is used as the argument to the
3154 function.
3155
3156 Instead of choosing the word @code{number} for the name of the argument,
3157 I could have picked any other name. For example, I could have chosen
3158 the word @code{multiplicand}. I picked the word `number' because it
3159 tells what kind of value is intended for this slot; but I could just as
3160 well have chosen the word `multiplicand' to indicate the role that the
3161 value placed in this slot will play in the workings of the function. I
3162 could have called it @code{foogle}, but that would have been a bad
3163 choice because it would not tell humans what it means. The choice of
3164 name is up to the programmer and should be chosen to make the meaning of
3165 the function clear.
3166
3167 Indeed, you can choose any name you wish for a symbol in an argument
3168 list, even the name of a symbol used in some other function: the name
3169 you use in an argument list is private to that particular definition.
3170 In that definition, the name refers to a different entity than any use
3171 of the same name outside the function definition. Suppose you have a
3172 nick-name `Shorty' in your family; when your family members refer to
3173 `Shorty', they mean you. But outside your family, in a movie, for
3174 example, the name `Shorty' refers to someone else. Because a name in an
3175 argument list is private to the function definition, you can change the
3176 value of such a symbol inside the body of a function without changing
3177 its value outside the function. The effect is similar to that produced
3178 by a @code{let} expression. (@xref{let, , @code{let}}.)
3179
3180 @ignore
3181 Note also that we discuss the word `number' in two different ways: as a
3182 symbol that appears in the code, and as the name of something that will
3183 be replaced by a something else during the evaluation of the function.
3184 In the first case, @code{number} is a symbol, not a number; it happens
3185 that within the function, it is a variable who value is the number in
3186 question, but our primary interest in it is as a symbol. On the other
3187 hand, when we are talking about the function, our interest is that we
3188 will substitute a number for the word @var{number}. To keep this
3189 distinction clear, we use different typography for the two
3190 circumstances. When we talk about this function, or about how it works,
3191 we refer to this number by writing @var{number}. In the function
3192 itself, we refer to it by writing @code{number}.
3193 @end ignore
3194
3195 The argument list is followed by the documentation string that
3196 describes the function. This is what you see when you type
3197 @w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3198 write a documentation string like this, you should make the first line
3199 a complete sentence since some commands, such as @code{apropos}, print
3200 only the first line of a multi-line documentation string. Also, you
3201 should not indent the second line of a documentation string, if you
3202 have one, because that looks odd when you use @kbd{C-h f}
3203 (@code{describe-function}). The documentation string is optional, but
3204 it is so useful, it should be included in almost every function you
3205 write.
3206
3207 @findex * @r{(multiplication)}
3208 The third line of the example consists of the body of the function
3209 definition. (Most functions' definitions, of course, are longer than
3210 this.) In this function, the body is the list, @code{(* 7 number)}, which
3211 says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3212 @code{*} is the function for multiplication, just as @code{+} is the
3213 function for addition.)
3214
3215 When you use the @code{multiply-by-seven} function, the argument
3216 @code{number} evaluates to the actual number you want used. Here is an
3217 example that shows how @code{multiply-by-seven} is used; but don't try
3218 to evaluate this yet!
3219
3220 @smallexample
3221 (multiply-by-seven 3)
3222 @end smallexample
3223
3224 @noindent
3225 The symbol @code{number}, specified in the function definition in the
3226 next section, is given or ``bound to'' the value 3 in the actual use of
3227 the function. Note that although @code{number} was inside parentheses
3228 in the function definition, the argument passed to the
3229 @code{multiply-by-seven} function is not in parentheses. The
3230 parentheses are written in the function definition so the computer can
3231 figure out where the argument list ends and the rest of the function
3232 definition begins.
3233
3234 If you evaluate this example, you are likely to get an error message.
3235 (Go ahead, try it!) This is because we have written the function
3236 definition, but not yet told the computer about the definition---we have
3237 not yet installed (or `loaded') the function definition in Emacs.
3238 Installing a function is the process that tells the Lisp interpreter the
3239 definition of the function. Installation is described in the next
3240 section.
3241
3242 @node Install, Interactive, defun, Writing Defuns
3243 @comment node-name, next, previous, up
3244 @section Install a Function Definition
3245 @cindex Install a Function Definition
3246 @cindex Definition installation
3247 @cindex Function definition installation
3248
3249 If you are reading this inside of Info in Emacs, you can try out the
3250 @code{multiply-by-seven} function by first evaluating the function
3251 definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3252 the function definition follows. Place the cursor after the last
3253 parenthesis of the function definition and type @kbd{C-x C-e}. When you
3254 do this, @code{multiply-by-seven} will appear in the echo area. (What
3255 this means is that when a function definition is evaluated, the value it
3256 returns is the name of the defined function.) At the same time, this
3257 action installs the function definition.
3258
3259 @smallexample
3260 @group
3261 (defun multiply-by-seven (number)
3262 "Multiply NUMBER by seven."
3263 (* 7 number))
3264 @end group
3265 @end smallexample
3266
3267 @noindent
3268 By evaluating this @code{defun}, you have just installed
3269 @code{multiply-by-seven} in Emacs. The function is now just as much a
3270 part of Emacs as @code{forward-word} or any other editing function you
3271 use. (@code{multiply-by-seven} will stay installed until you quit
3272 Emacs. To reload code automatically whenever you start Emacs, see
3273 @ref{Permanent Installation, , Installing Code Permanently}.)
3274
3275
3276 @menu
3277 * Effect of installation::
3278 * Change a defun:: How to change a function definition.
3279 @end menu
3280
3281 @node Effect of installation, Change a defun, Install, Install
3282 @ifnottex
3283 @unnumberedsubsec The effect of installation
3284 @end ifnottex
3285
3286
3287 You can see the effect of installing @code{multiply-by-seven} by
3288 evaluating the following sample. Place the cursor after the following
3289 expression and type @kbd{C-x C-e}. The number 21 will appear in the
3290 echo area.
3291
3292 @smallexample
3293 (multiply-by-seven 3)
3294 @end smallexample
3295
3296 If you wish, you can read the documentation for the function by typing
3297 @kbd{C-h f} (@code{describe-function}) and then the name of the
3298 function, @code{multiply-by-seven}. When you do this, a
3299 @file{*Help*} window will appear on your screen that says:
3300
3301 @smallexample
3302 @group
3303 multiply-by-seven:
3304 Multiply NUMBER by seven.
3305 @end group
3306 @end smallexample
3307
3308 @noindent
3309 (To return to a single window on your screen, type @kbd{C-x 1}.)
3310
3311 @node Change a defun, , Effect of installation, Install
3312 @comment node-name, next, previous, up
3313 @subsection Change a Function Definition
3314 @cindex Changing a function definition
3315 @cindex Function definition, how to change
3316 @cindex Definition, how to change
3317
3318 If you want to change the code in @code{multiply-by-seven}, just rewrite
3319 it. To install the new version in place of the old one, evaluate the
3320 function definition again. This is how you modify code in Emacs. It is
3321 very simple.
3322
3323 As an example, you can change the @code{multiply-by-seven} function to
3324 add the number to itself seven times instead of multiplying the number
3325 by seven. It produces the same answer, but by a different path. At
3326 the same time, we will add a comment to the code; a comment is text
3327 that the Lisp interpreter ignores, but that a human reader may find
3328 useful or enlightening. The comment is that this is the ``second
3329 version''.
3330
3331 @smallexample
3332 @group
3333 (defun multiply-by-seven (number) ; @r{Second version.}
3334 "Multiply NUMBER by seven."
3335 (+ number number number number number number number))
3336 @end group
3337 @end smallexample
3338
3339 @cindex Comments in Lisp code
3340 The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3341 line that follows a semicolon is a comment. The end of the line is the
3342 end of the comment. To stretch a comment over two or more lines, begin
3343 each line with a semicolon.
3344
3345 @xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3346 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3347 Reference Manual}, for more about comments.
3348
3349 You can install this version of the @code{multiply-by-seven} function by
3350 evaluating it in the same way you evaluated the first function: place
3351 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3352
3353 In summary, this is how you write code in Emacs Lisp: you write a
3354 function; install it; test it; and then make fixes or enhancements and
3355 install it again.
3356
3357 @node Interactive, Interactive Options, Install, Writing Defuns
3358 @comment node-name, next, previous, up
3359 @section Make a Function Interactive
3360 @cindex Interactive functions
3361 @findex interactive
3362
3363 You make a function interactive by placing a list that begins with
3364 the special form @code{interactive} immediately after the
3365 documentation. A user can invoke an interactive function by typing
3366 @kbd{M-x} and then the name of the function; or by typing the keys to
3367 which it is bound, for example, by typing @kbd{C-n} for
3368 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3369
3370 Interestingly, when you call an interactive function interactively,
3371 the value returned is not automatically displayed in the echo area.
3372 This is because you often call an interactive function for its side
3373 effects, such as moving forward by a word or line, and not for the
3374 value returned. If the returned value were displayed in the echo area
3375 each time you typed a key, it would be very distracting.
3376
3377 @menu
3378 * Interactive multiply-by-seven:: An overview.
3379 * multiply-by-seven in detail:: The interactive version.
3380 @end menu
3381
3382 @node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3383 @ifnottex
3384 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3385 @end ifnottex
3386
3387 Both the use of the special form @code{interactive} and one way to
3388 display a value in the echo area can be illustrated by creating an
3389 interactive version of @code{multiply-by-seven}.
3390
3391 @need 1250
3392 Here is the code:
3393
3394 @smallexample
3395 @group
3396 (defun multiply-by-seven (number) ; @r{Interactive version.}
3397 "Multiply NUMBER by seven."
3398 (interactive "p")
3399 (message "The result is %d" (* 7 number)))
3400 @end group
3401 @end smallexample
3402
3403 @noindent
3404 You can install this code by placing your cursor after it and typing
3405 @kbd{C-x C-e}. The name of the function will appear in your echo area.
3406 Then, you can use this code by typing @kbd{C-u} and a number and then
3407 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3408 @samp{The result is @dots{}} followed by the product will appear in the
3409 echo area.
3410
3411 Speaking more generally, you invoke a function like this in either of two
3412 ways:
3413
3414 @enumerate
3415 @item
3416 By typing a prefix argument that contains the number to be passed, and
3417 then typing @kbd{M-x} and the name of the function, as with
3418 @kbd{C-u 3 M-x forward-sentence}; or,
3419
3420 @item
3421 By typing whatever key or keychord the function is bound to, as with
3422 @kbd{C-u 3 M-e}.
3423 @end enumerate
3424
3425 @noindent
3426 Both the examples just mentioned work identically to move point forward
3427 three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3428 it could not be used as an example of key binding.)
3429
3430 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3431 to a key.)
3432
3433 A prefix argument is passed to an interactive function by typing the
3434 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3435 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3436 type @kbd{C-u} without a number, it defaults to 4).
3437
3438 @node multiply-by-seven in detail, , Interactive multiply-by-seven, Interactive
3439 @comment node-name, next, previous, up
3440 @subsection An Interactive @code{multiply-by-seven}
3441
3442 Let's look at the use of the special form @code{interactive} and then at
3443 the function @code{message} in the interactive version of
3444 @code{multiply-by-seven}. You will recall that the function definition
3445 looks like this:
3446
3447 @smallexample
3448 @group
3449 (defun multiply-by-seven (number) ; @r{Interactive version.}
3450 "Multiply NUMBER by seven."
3451 (interactive "p")
3452 (message "The result is %d" (* 7 number)))
3453 @end group
3454 @end smallexample
3455
3456 In this function, the expression, @code{(interactive "p")}, is a list of
3457 two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3458 the function and use its value for the argument of the function.
3459
3460 @need 1000
3461 The argument will be a number. This means that the symbol
3462 @code{number} will be bound to a number in the line:
3463
3464 @smallexample
3465 (message "The result is %d" (* 7 number))
3466 @end smallexample
3467
3468 @need 1250
3469 @noindent
3470 For example, if your prefix argument is 5, the Lisp interpreter will
3471 evaluate the line as if it were:
3472
3473 @smallexample
3474 (message "The result is %d" (* 7 5))
3475 @end smallexample
3476
3477 @noindent
3478 (If you are reading this in GNU Emacs, you can evaluate this expression
3479 yourself.) First, the interpreter will evaluate the inner list, which
3480 is @code{(* 7 5)}. This returns a value of 35. Next, it
3481 will evaluate the outer list, passing the values of the second and
3482 subsequent elements of the list to the function @code{message}.
3483
3484 As we have seen, @code{message} is an Emacs Lisp function especially
3485 designed for sending a one line message to a user. (@xref{message, , The
3486 @code{message} function}.)
3487 In summary, the @code{message} function prints its first argument in the
3488 echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3489 @samp{%c}. When it sees one of these control sequences, the function
3490 looks to the second and subsequent arguments and prints the value of the
3491 argument in the location in the string where the control sequence is
3492 located.
3493
3494 In the interactive @code{multiply-by-seven} function, the control string
3495 is @samp{%d}, which requires a number, and the value returned by
3496 evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3497 is printed in place of the @samp{%d} and the message is @samp{The result
3498 is 35}.
3499
3500 (Note that when you call the function @code{multiply-by-seven}, the
3501 message is printed without quotes, but when you call @code{message}, the
3502 text is printed in double quotes. This is because the value returned by
3503 @code{message} is what appears in the echo area when you evaluate an
3504 expression whose first element is @code{message}; but when embedded in a
3505 function, @code{message} prints the text as a side effect without
3506 quotes.)
3507
3508 @node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3509 @comment node-name, next, previous, up
3510 @section Different Options for @code{interactive}
3511 @cindex Options for @code{interactive}
3512 @cindex Interactive options
3513
3514 In the example, @code{multiply-by-seven} used @code{"p"} as the
3515 argument to @code{interactive}. This argument told Emacs to interpret
3516 your typing either @kbd{C-u} followed by a number or @key{META}
3517 followed by a number as a command to pass that number to the function
3518 as its argument. Emacs has more than twenty characters predefined for
3519 use with @code{interactive}. In almost every case, one of these
3520 options will enable you to pass the right information interactively to
3521 a function. (@xref{Interactive Codes, , Code Characters for
3522 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3523
3524 @need 1250
3525 For example, the character @samp{r} causes Emacs to pass the beginning
3526 and end of the region (the current values of point and mark) to the
3527 function as two separate arguments. It is used as follows:
3528
3529 @smallexample
3530 (interactive "r")
3531 @end smallexample
3532
3533 On the other hand, a @samp{B} tells Emacs to ask for the name of a
3534 buffer that will be passed to the function. When it sees a @samp{B},
3535 Emacs will ask for the name by prompting the user in the minibuffer,
3536 using a string that follows the @samp{B}, as in @code{"BAppend to
3537 buffer:@: "}. Not only will Emacs prompt for the name, but Emacs will
3538 complete the name if you type enough of it and press @key{TAB}.
3539
3540 A function with two or more arguments can have information passed to
3541 each argument by adding parts to the string that follows
3542 @code{interactive}. When you do this, the information is passed to
3543 each argument in the same order it is specified in the
3544 @code{interactive} list. In the string, each part is separated from
3545 the next part by a @samp{\n}, which is a newline. For example, you
3546 could follow @code{"BAppend to buffer:@: "} with a @samp{\n}) and an
3547 @samp{r}. This would cause Emacs to pass the values of point and mark
3548 to the function as well as prompt you for the buffer---three arguments
3549 in all.
3550
3551 In this case, the function definition would look like the following,
3552 where @code{buffer}, @code{start}, and @code{end} are the symbols to
3553 which @code{interactive} binds the buffer and the current values of the
3554 beginning and ending of the region:
3555
3556 @smallexample
3557 @group
3558 (defun @var{name-of-function} (buffer start end)
3559 "@var{documentation}@dots{}"
3560 (interactive "BAppend to buffer:@: \nr")
3561 @var{body-of-function}@dots{})
3562 @end group
3563 @end smallexample
3564
3565 @noindent
3566 (The space after the colon in the prompt makes it look better when you
3567 are prompted. The @code{append-to-buffer} function looks exactly like
3568 this. @xref{append-to-buffer, , The Definition of
3569 @code{append-to-buffer}}.)
3570
3571 If a function does not have arguments, then @code{interactive} does not
3572 require any. Such a function contains the simple expression
3573 @code{(interactive)}. The @code{mark-whole-buffer} function is like
3574 this.
3575
3576 Alternatively, if the special letter-codes are not right for your
3577 application, you can pass your own arguments to @code{interactive} as
3578 a list. @xref{interactive, , Using @code{Interactive}, elisp, The
3579 GNU Emacs Lisp Reference Manual}, for more information about this advanced
3580 technique.
3581
3582 @node Permanent Installation, let, Interactive Options, Writing Defuns
3583 @comment node-name, next, previous, up
3584 @section Install Code Permanently
3585 @cindex Install code permanently
3586 @cindex Permanent code installation
3587 @cindex Code installation
3588
3589 When you install a function definition by evaluating it, it will stay
3590 installed until you quit Emacs. The next time you start a new session
3591 of Emacs, the function will not be installed unless you evaluate the
3592 function definition again.
3593
3594 At some point, you may want to have code installed automatically
3595 whenever you start a new session of Emacs. There are several ways of
3596 doing this:
3597
3598 @itemize @bullet
3599 @item
3600 If you have code that is just for yourself, you can put the code for the
3601 function definition in your @file{.emacs} initialization file. When you
3602 start Emacs, your @file{.emacs} file is automatically evaluated and all
3603 the function definitions within it are installed.
3604 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3605
3606 @item
3607 Alternatively, you can put the function definitions that you want
3608 installed in one or more files of their own and use the @code{load}
3609 function to cause Emacs to evaluate and thereby install each of the
3610 functions in the files.
3611 @xref{Loading Files, , Loading Files}.
3612
3613 @item
3614 On the other hand, if you have code that your whole site will use, it
3615 is usual to put it in a file called @file{site-init.el} that is loaded
3616 when Emacs is built. This makes the code available to everyone who
3617 uses your machine. (See the @file{INSTALL} file that is part of the
3618 Emacs distribution.)
3619 @end itemize
3620
3621 Finally, if you have code that everyone who uses Emacs may want, you
3622 can post it on a computer network or send a copy to the Free Software
3623 Foundation. (When you do this, please license the code and its
3624 documentation under a license that permits other people to run, copy,
3625 study, modify, and redistribute the code and which protects you from
3626 having your work taken from you.) If you send a copy of your code to
3627 the Free Software Foundation, and properly protect yourself and
3628 others, it may be included in the next release of Emacs. In large
3629 part, this is how Emacs has grown over the past years, by donations.
3630
3631 @node let, if, Permanent Installation, Writing Defuns
3632 @comment node-name, next, previous, up
3633 @section @code{let}
3634 @findex let
3635
3636 The @code{let} expression is a special form in Lisp that you will need
3637 to use in most function definitions.
3638
3639 @code{let} is used to attach or bind a symbol to a value in such a way
3640 that the Lisp interpreter will not confuse the variable with a
3641 variable of the same name that is not part of the function.
3642
3643 To understand why the @code{let} special form is necessary, consider
3644 the situation in which you own a home that you generally refer to as
3645 `the house', as in the sentence, ``The house needs painting.'' If you
3646 are visiting a friend and your host refers to `the house', he is
3647 likely to be referring to @emph{his} house, not yours, that is, to a
3648 different house.
3649
3650 If your friend is referring to his house and you think he is referring
3651 to your house, you may be in for some confusion. The same thing could
3652 happen in Lisp if a variable that is used inside of one function has
3653 the same name as a variable that is used inside of another function,
3654 and the two are not intended to refer to the same value. The
3655 @code{let} special form prevents this kind of confusion.
3656
3657 @menu
3658 * Prevent confusion::
3659 * Parts of let Expression::
3660 * Sample let Expression::
3661 * Uninitialized let Variables::
3662 @end menu
3663
3664 @node Prevent confusion, Parts of let Expression, let, let
3665 @ifnottex
3666 @unnumberedsubsec @code{let} Prevents Confusion
3667 @end ifnottex
3668
3669 @cindex @samp{local variable} defined
3670 The @code{let} special form prevents confusion. @code{let} creates a
3671 name for a @dfn{local variable} that overshadows any use of the same
3672 name outside the @code{let} expression. This is like understanding
3673 that whenever your host refers to `the house', he means his house, not
3674 yours. (Symbols used in argument lists work the same way.
3675 @xref{defun, , The @code{defun} Special Form}.)
3676
3677 Local variables created by a @code{let} expression retain their value
3678 @emph{only} within the @code{let} expression itself (and within
3679 expressions called within the @code{let} expression); the local
3680 variables have no effect outside the @code{let} expression.
3681
3682 Another way to think about @code{let} is that it is like a @code{setq}
3683 that is temporary and local. The values set by @code{let} are
3684 automatically undone when the @code{let} is finished. The setting
3685 only effects expressions that are inside the bounds of the @code{let}
3686 expression. In computer science jargon, we would say ``the binding of
3687 a symbol is visible only in functions called in the @code{let} form;
3688 in Emacs Lisp, scoping is dynamic, not lexical.''
3689
3690 @code{let} can create more than one variable at once. Also,
3691 @code{let} gives each variable it creates an initial value, either a
3692 value specified by you, or @code{nil}. (In the jargon, this is called
3693 `binding the variable to the value'.) After @code{let} has created
3694 and bound the variables, it executes the code in the body of the
3695 @code{let}, and returns the value of the last expression in the body,
3696 as the value of the whole @code{let} expression. (`Execute' is a jargon
3697 term that means to evaluate a list; it comes from the use of the word
3698 meaning `to give practical effect to' (@cite{Oxford English
3699 Dictionary}). Since you evaluate an expression to perform an action,
3700 `execute' has evolved as a synonym to `evaluate'.)
3701
3702 @node Parts of let Expression, Sample let Expression, Prevent confusion, let
3703 @comment node-name, next, previous, up
3704 @subsection The Parts of a @code{let} Expression
3705 @cindex @code{let} expression, parts of
3706 @cindex Parts of @code{let} expression
3707
3708 @cindex @samp{varlist} defined
3709 A @code{let} expression is a list of three parts. The first part is
3710 the symbol @code{let}. The second part is a list, called a
3711 @dfn{varlist}, each element of which is either a symbol by itself or a
3712 two-element list, the first element of which is a symbol. The third
3713 part of the @code{let} expression is the body of the @code{let}. The
3714 body usually consists of one or more lists.
3715
3716 @need 800
3717 A template for a @code{let} expression looks like this:
3718
3719 @smallexample
3720 (let @var{varlist} @var{body}@dots{})
3721 @end smallexample
3722
3723 @noindent
3724 The symbols in the varlist are the variables that are given initial
3725 values by the @code{let} special form. Symbols by themselves are given
3726 the initial value of @code{nil}; and each symbol that is the first
3727 element of a two-element list is bound to the value that is returned
3728 when the Lisp interpreter evaluates the second element.
3729
3730 Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3731 this case, in a @code{let} expression, Emacs binds the symbol
3732 @code{thread} to an initial value of @code{nil}, and binds the symbol
3733 @code{needles} to an initial value of 3.
3734
3735 When you write a @code{let} expression, what you do is put the
3736 appropriate expressions in the slots of the @code{let} expression
3737 template.
3738
3739 If the varlist is composed of two-element lists, as is often the case,
3740 the template for the @code{let} expression looks like this:
3741
3742 @smallexample
3743 @group
3744 (let ((@var{variable} @var{value})
3745 (@var{variable} @var{value})
3746 @dots{})
3747 @var{body}@dots{})
3748 @end group
3749 @end smallexample
3750
3751 @node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3752 @comment node-name, next, previous, up
3753 @subsection Sample @code{let} Expression
3754 @cindex Sample @code{let} expression
3755 @cindex @code{let} expression sample
3756
3757 The following expression creates and gives initial values
3758 to the two variables @code{zebra} and @code{tiger}. The body of the
3759 @code{let} expression is a list which calls the @code{message} function.
3760
3761 @smallexample
3762 @group
3763 (let ((zebra 'stripes)
3764 (tiger 'fierce))
3765 (message "One kind of animal has %s and another is %s."
3766 zebra tiger))
3767 @end group
3768 @end smallexample
3769
3770 Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3771
3772 The two variables are @code{zebra} and @code{tiger}. Each variable is
3773 the first element of a two-element list and each value is the second
3774 element of its two-element list. In the varlist, Emacs binds the
3775 variable @code{zebra} to the value @code{stripes}, and binds the
3776 variable @code{tiger} to the value @code{fierce}. In this example,
3777 both values are symbols preceded by a quote. The values could just as
3778 well have been another list or a string. The body of the @code{let}
3779 follows after the list holding the variables. In this example, the body
3780 is a list that uses the @code{message} function to print a string in
3781 the echo area.
3782
3783 @need 1500
3784 You may evaluate the example in the usual fashion, by placing the
3785 cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3786 this, the following will appear in the echo area:
3787
3788 @smallexample
3789 "One kind of animal has stripes and another is fierce."
3790 @end smallexample
3791
3792 As we have seen before, the @code{message} function prints its first
3793 argument, except for @samp{%s}. In this example, the value of the variable
3794 @code{zebra} is printed at the location of the first @samp{%s} and the
3795 value of the variable @code{tiger} is printed at the location of the
3796 second @samp{%s}.
3797
3798 @node Uninitialized let Variables, , Sample let Expression, let
3799 @comment node-name, next, previous, up
3800 @subsection Uninitialized Variables in a @code{let} Statement
3801 @cindex Uninitialized @code{let} variables
3802 @cindex @code{let} variables uninitialized
3803
3804 If you do not bind the variables in a @code{let} statement to specific
3805 initial values, they will automatically be bound to an initial value of
3806 @code{nil}, as in the following expression:
3807
3808 @smallexample
3809 @group
3810 (let ((birch 3)
3811 pine
3812 fir
3813 (oak 'some))
3814 (message
3815 "Here are %d variables with %s, %s, and %s value."
3816 birch pine fir oak))
3817 @end group
3818 @end smallexample
3819
3820 @noindent
3821 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3822
3823 @need 1250
3824 If you evaluate this expression in the usual way, the following will
3825 appear in your echo area:
3826
3827 @smallexample
3828 "Here are 3 variables with nil, nil, and some value."
3829 @end smallexample
3830
3831 @noindent
3832 In this example, Emacs binds the symbol @code{birch} to the number 3,
3833 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3834 the symbol @code{oak} to the value @code{some}.
3835
3836 Note that in the first part of the @code{let}, the variables @code{pine}
3837 and @code{fir} stand alone as atoms that are not surrounded by
3838 parentheses; this is because they are being bound to @code{nil}, the
3839 empty list. But @code{oak} is bound to @code{some} and so is a part of
3840 the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3841 number 3 and so is in a list with that number. (Since a number
3842 evaluates to itself, the number does not need to be quoted. Also, the
3843 number is printed in the message using a @samp{%d} rather than a
3844 @samp{%s}.) The four variables as a group are put into a list to
3845 delimit them from the body of the @code{let}.
3846
3847 @node if, else, let, Writing Defuns
3848 @comment node-name, next, previous, up
3849 @section The @code{if} Special Form
3850 @findex if
3851 @cindex Conditional with @code{if}
3852
3853 A third special form, in addition to @code{defun} and @code{let}, is the
3854 conditional @code{if}. This form is used to instruct the computer to
3855 make decisions. You can write function definitions without using
3856 @code{if}, but it is used often enough, and is important enough, to be
3857 included here. It is used, for example, in the code for the
3858 function @code{beginning-of-buffer}.
3859
3860 The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3861 @emph{then} an expression is evaluated.'' If the test is not true, the
3862 expression is not evaluated. For example, you might make a decision
3863 such as, ``if it is warm and sunny, then go to the beach!''
3864
3865 @menu
3866 * if in more detail::
3867 * type-of-animal in detail:: An example of an @code{if} expression.
3868 @end menu
3869
3870 @node if in more detail, type-of-animal in detail, if, if
3871 @ifnottex
3872 @unnumberedsubsec @code{if} in more detail
3873 @end ifnottex
3874
3875 @cindex @samp{if-part} defined
3876 @cindex @samp{then-part} defined
3877 An @code{if} expression written in Lisp does not use the word `then';
3878 the test and the action are the second and third elements of the list
3879 whose first element is @code{if}. Nonetheless, the test part of an
3880 @code{if} expression is often called the @dfn{if-part} and the second
3881 argument is often called the @dfn{then-part}.
3882
3883 Also, when an @code{if} expression is written, the true-or-false-test
3884 is usually written on the same line as the symbol @code{if}, but the
3885 action to carry out if the test is true, the ``then-part'', is written
3886 on the second and subsequent lines. This makes the @code{if}
3887 expression easier to read.
3888
3889 @smallexample
3890 @group
3891 (if @var{true-or-false-test}
3892 @var{action-to-carry-out-if-test-is-true})
3893 @end group
3894 @end smallexample
3895
3896 @noindent
3897 The true-or-false-test will be an expression that
3898 is evaluated by the Lisp interpreter.
3899
3900 Here is an example that you can evaluate in the usual manner. The test
3901 is whether the number 5 is greater than the number 4. Since it is, the
3902 message @samp{5 is greater than 4!} will be printed.
3903
3904 @smallexample
3905 @group
3906 (if (> 5 4) ; @r{if-part}
3907 (message "5 is greater than 4!")) ; @r{then-part}
3908 @end group
3909 @end smallexample
3910
3911 @noindent
3912 (The function @code{>} tests whether its first argument is greater than
3913 its second argument and returns true if it is.)
3914 @findex > (greater than)
3915
3916 Of course, in actual use, the test in an @code{if} expression will not
3917 be fixed for all time as it is by the expression @code{(> 5 4)}.
3918 Instead, at least one of the variables used in the test will be bound to
3919 a value that is not known ahead of time. (If the value were known ahead
3920 of time, we would not need to run the test!)
3921
3922 For example, the value may be bound to an argument of a function
3923 definition. In the following function definition, the character of the
3924 animal is a value that is passed to the function. If the value bound to
3925 @code{characteristic} is @code{fierce}, then the message, @samp{It's a
3926 tiger!} will be printed; otherwise, @code{nil} will be returned.
3927
3928 @smallexample
3929 @group
3930 (defun type-of-animal (characteristic)
3931 "Print message in echo area depending on CHARACTERISTIC.
3932 If the CHARACTERISTIC is the symbol `fierce',
3933 then warn of a tiger."
3934 (if (equal characteristic 'fierce)
3935 (message "It's a tiger!")))
3936 @end group
3937 @end smallexample
3938
3939 @need 1500
3940 @noindent
3941 If you are reading this inside of GNU Emacs, you can evaluate the
3942 function definition in the usual way to install it in Emacs, and then you
3943 can evaluate the following two expressions to see the results:
3944
3945 @smallexample
3946 @group
3947 (type-of-animal 'fierce)
3948
3949 (type-of-animal 'zebra)
3950
3951 @end group
3952 @end smallexample
3953
3954 @c Following sentences rewritten to prevent overfull hbox.
3955 @noindent
3956 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3957 following message printed in the echo area: @code{"It's a tiger!"}; and
3958 when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3959 printed in the echo area.
3960
3961 @node type-of-animal in detail, , if in more detail, if
3962 @comment node-name, next, previous, up
3963 @subsection The @code{type-of-animal} Function in Detail
3964
3965 Let's look at the @code{type-of-animal} function in detail.
3966
3967 The function definition for @code{type-of-animal} was written by filling
3968 the slots of two templates, one for a function definition as a whole, and
3969 a second for an @code{if} expression.
3970
3971 @need 1250
3972 The template for every function that is not interactive is:
3973
3974 @smallexample
3975 @group
3976 (defun @var{name-of-function} (@var{argument-list})
3977 "@var{documentation}@dots{}"
3978 @var{body}@dots{})
3979 @end group
3980 @end smallexample
3981
3982 @need 800
3983 The parts of the function that match this template look like this:
3984
3985 @smallexample
3986 @group
3987 (defun type-of-animal (characteristic)
3988 "Print message in echo area depending on CHARACTERISTIC.
3989 If the CHARACTERISTIC is the symbol `fierce',
3990 then warn of a tiger."
3991 @var{body: the} @code{if} @var{expression})
3992 @end group
3993 @end smallexample
3994
3995 The name of function is @code{type-of-animal}; it is passed the value
3996 of one argument. The argument list is followed by a multi-line
3997 documentation string. The documentation string is included in the
3998 example because it is a good habit to write documentation string for
3999 every function definition. The body of the function definition
4000 consists of the @code{if} expression.
4001
4002 @need 800
4003 The template for an @code{if} expression looks like this:
4004
4005 @smallexample
4006 @group
4007 (if @var{true-or-false-test}
4008 @var{action-to-carry-out-if-the-test-returns-true})
4009 @end group
4010 @end smallexample
4011
4012 @need 1250
4013 In the @code{type-of-animal} function, the code for the @code{if}
4014 looks like this:
4015
4016 @smallexample
4017 @group
4018 (if (equal characteristic 'fierce)
4019 (message "It's a tiger!")))
4020 @end group
4021 @end smallexample
4022
4023 @need 800
4024 Here, the true-or-false-test is the expression:
4025
4026 @smallexample
4027 (equal characteristic 'fierce)
4028 @end smallexample
4029
4030 @noindent
4031 In Lisp, @code{equal} is a function that determines whether its first
4032 argument is equal to its second argument. The second argument is the
4033 quoted symbol @code{'fierce} and the first argument is the value of the
4034 symbol @code{characteristic}---in other words, the argument passed to
4035 this function.
4036
4037 In the first exercise of @code{type-of-animal}, the argument
4038 @code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4039 is equal to @code{fierce}, the expression, @code{(equal characteristic
4040 'fierce)}, returns a value of true. When this happens, the @code{if}
4041 evaluates the second argument or then-part of the @code{if}:
4042 @code{(message "It's tiger!")}.
4043
4044 On the other hand, in the second exercise of @code{type-of-animal}, the
4045 argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4046 is not equal to @code{fierce}, so the then-part is not evaluated and
4047 @code{nil} is returned by the @code{if} expression.
4048
4049 @node else, Truth & Falsehood, if, Writing Defuns
4050 @comment node-name, next, previous, up
4051 @section If--then--else Expressions
4052 @cindex Else
4053
4054 An @code{if} expression may have an optional third argument, called
4055 the @dfn{else-part}, for the case when the true-or-false-test returns
4056 false. When this happens, the second argument or then-part of the
4057 overall @code{if} expression is @emph{not} evaluated, but the third or
4058 else-part @emph{is} evaluated. You might think of this as the cloudy
4059 day alternative for the decision `if it is warm and sunny, then go to
4060 the beach, else read a book!''.
4061
4062 The word ``else'' is not written in the Lisp code; the else-part of an
4063 @code{if} expression comes after the then-part. In the written Lisp, the
4064 else-part is usually written to start on a line of its own and is
4065 indented less than the then-part:
4066
4067 @smallexample
4068 @group
4069 (if @var{true-or-false-test}
4070 @var{action-to-carry-out-if-the-test-returns-true}
4071 @var{action-to-carry-out-if-the-test-returns-false})
4072 @end group
4073 @end smallexample
4074
4075 For example, the following @code{if} expression prints the message @samp{4
4076 is not greater than 5!} when you evaluate it in the usual way:
4077
4078 @smallexample
4079 @group
4080 (if (> 4 5) ; @r{if-part}
4081 (message "5 is greater than 4!") ; @r{then-part}
4082 (message "4 is not greater than 5!")) ; @r{else-part}
4083 @end group
4084 @end smallexample
4085
4086 @noindent
4087 Note that the different levels of indentation make it easy to
4088 distinguish the then-part from the else-part. (GNU Emacs has several
4089 commands that automatically indent @code{if} expressions correctly.
4090 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4091
4092 We can extend the @code{type-of-animal} function to include an
4093 else-part by simply incorporating an additional part to the @code{if}
4094 expression.
4095
4096 @need 1500
4097 You can see the consequences of doing this if you evaluate the following
4098 version of the @code{type-of-animal} function definition to install it
4099 and then evaluate the two subsequent expressions to pass different
4100 arguments to the function.
4101
4102 @smallexample
4103 @group
4104 (defun type-of-animal (characteristic) ; @r{Second version.}
4105 "Print message in echo area depending on CHARACTERISTIC.
4106 If the CHARACTERISTIC is the symbol `fierce',
4107 then warn of a tiger;
4108 else say it's not fierce."
4109 (if (equal characteristic 'fierce)
4110 (message "It's a tiger!")
4111 (message "It's not fierce!")))
4112 @end group
4113 @end smallexample
4114 @sp 1
4115
4116 @smallexample
4117 @group
4118 (type-of-animal 'fierce)
4119
4120 (type-of-animal 'zebra)
4121
4122 @end group
4123 @end smallexample
4124
4125 @c Following sentence rewritten to prevent overfull hbox.
4126 @noindent
4127 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4128 following message printed in the echo area: @code{"It's a tiger!"}; but
4129 when you evaluate @code{(type-of-animal 'zebra)}, you will see
4130 @code{"It's not fierce!"}.
4131
4132 (Of course, if the @var{characteristic} were @code{ferocious}, the
4133 message @code{"It's not fierce!"} would be printed; and it would be
4134 misleading! When you write code, you need to take into account the
4135 possibility that some such argument will be tested by the @code{if} and
4136 write your program accordingly.)
4137
4138 @node Truth & Falsehood, save-excursion, else, Writing Defuns
4139 @comment node-name, next, previous, up
4140 @section Truth and Falsehood in Emacs Lisp
4141 @cindex Truth and falsehood in Emacs Lisp
4142 @cindex Falsehood and truth in Emacs Lisp
4143 @findex nil
4144
4145 There is an important aspect to the truth test in an @code{if}
4146 expression. So far, we have spoken of `true' and `false' as values of
4147 predicates as if they were new kinds of Emacs Lisp objects. In fact,
4148 `false' is just our old friend @code{nil}. Anything else---anything
4149 at all---is `true'.
4150
4151 The expression that tests for truth is interpreted as @dfn{true}
4152 if the result of evaluating it is a value that is not @code{nil}. In
4153 other words, the result of the test is considered true if the value
4154 returned is a number such as 47, a string such as @code{"hello"}, or a
4155 symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4156 even a buffer!
4157
4158 @menu
4159 * nil explained:: @code{nil} has two meanings.
4160 @end menu
4161
4162 @node nil explained, , Truth & Falsehood, Truth & Falsehood
4163 @ifnottex
4164 @unnumberedsubsec An explanation of @code{nil}
4165 @end ifnottex
4166
4167 Before illustrating a test for truth, we need an explanation of @code{nil}.
4168
4169 In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4170 empty list. Second, it means false and is the value returned when a
4171 true-or-false-test tests false. @code{nil} can be written as an empty
4172 list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4173 concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4174 to use @code{nil} for false and @code{()} for the empty list.
4175
4176 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4177 list---is considered true. This means that if an evaluation returns
4178 something that is not an empty list, an @code{if} expression will test
4179 true. For example, if a number is put in the slot for the test, it
4180 will be evaluated and will return itself, since that is what numbers
4181 do when evaluated. In this conditional, the @code{if} expression will
4182 test true. The expression tests false only when @code{nil}, an empty
4183 list, is returned by evaluating the expression.
4184
4185 You can see this by evaluating the two expressions in the following examples.
4186
4187 In the first example, the number 4 is evaluated as the test in the
4188 @code{if} expression and returns itself; consequently, the then-part
4189 of the expression is evaluated and returned: @samp{true} appears in
4190 the echo area. In the second example, the @code{nil} indicates false;
4191 consequently, the else-part of the expression is evaluated and
4192 returned: @samp{false} appears in the echo area.
4193
4194 @smallexample
4195 @group
4196 (if 4
4197 'true
4198 'false)
4199 @end group
4200
4201 @group
4202 (if nil
4203 'true
4204 'false)
4205 @end group
4206 @end smallexample
4207
4208 @need 1250
4209 Incidentally, if some other useful value is not available for a test that
4210 returns true, then the Lisp interpreter will return the symbol @code{t}
4211 for true. For example, the expression @code{(> 5 4)} returns @code{t}
4212 when evaluated, as you can see by evaluating it in the usual way:
4213
4214 @smallexample
4215 (> 5 4)
4216 @end smallexample
4217
4218 @need 1250
4219 @noindent
4220 On the other hand, this function returns @code{nil} if the test is false.
4221
4222 @smallexample
4223 (> 4 5)
4224 @end smallexample
4225
4226 @node save-excursion, Review, Truth & Falsehood, Writing Defuns
4227 @comment node-name, next, previous, up
4228 @section @code{save-excursion}
4229 @findex save-excursion
4230 @cindex Region, what it is
4231 @cindex Preserving point, mark, and buffer
4232 @cindex Point, mark, buffer preservation
4233 @findex point
4234 @findex mark
4235
4236 The @code{save-excursion} function is the fourth and final special form
4237 that we will discuss in this chapter.
4238
4239 In Emacs Lisp programs used for editing, the @code{save-excursion}
4240 function is very common. It saves the location of point and mark,
4241 executes the body of the function, and then restores point and mark to
4242 their previous positions if their locations were changed. Its primary
4243 purpose is to keep the user from being surprised and disturbed by
4244 unexpected movement of point or mark.
4245
4246 @menu
4247 * Point and mark:: A review of various locations.
4248 * Template for save-excursion::
4249 @end menu
4250
4251 @node Point and mark, Template for save-excursion, save-excursion, save-excursion
4252 @ifnottex
4253 @unnumberedsubsec Point and Mark
4254 @end ifnottex
4255
4256 Before discussing @code{save-excursion}, however, it may be useful
4257 first to review what point and mark are in GNU Emacs. @dfn{Point} is
4258 the current location of the cursor. Wherever the cursor
4259 is, that is point. More precisely, on terminals where the cursor
4260 appears to be on top of a character, point is immediately before the
4261 character. In Emacs Lisp, point is an integer. The first character in
4262 a buffer is number one, the second is number two, and so on. The
4263 function @code{point} returns the current position of the cursor as a
4264 number. Each buffer has its own value for point.
4265
4266 The @dfn{mark} is another position in the buffer; its value can be set
4267 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4268 a mark has been set, you can use the command @kbd{C-x C-x}
4269 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4270 and set the mark to be the previous position of point. In addition, if
4271 you set another mark, the position of the previous mark is saved in the
4272 mark ring. Many mark positions can be saved this way. You can jump the
4273 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4274 times.
4275
4276 The part of the buffer between point and mark is called @dfn{the
4277 region}. Numerous commands work on the region, including
4278 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4279 @code{print-region}.
4280
4281 The @code{save-excursion} special form saves the locations of point and
4282 mark and restores those positions after the code within the body of the
4283 special form is evaluated by the Lisp interpreter. Thus, if point were
4284 in the beginning of a piece of text and some code moved point to the end
4285 of the buffer, the @code{save-excursion} would put point back to where
4286 it was before, after the expressions in the body of the function were
4287 evaluated.
4288
4289 In Emacs, a function frequently moves point as part of its internal
4290 workings even though a user would not expect this. For example,
4291 @code{count-lines-region} moves point. To prevent the user from being
4292 bothered by jumps that are both unexpected and (from the user's point of
4293 view) unnecessary, @code{save-excursion} is often used to keep point and
4294 mark in the location expected by the user. The use of
4295 @code{save-excursion} is good housekeeping.
4296
4297 To make sure the house stays clean, @code{save-excursion} restores the
4298 values of point and mark even if something goes wrong in the code inside
4299 of it (or, to be more precise and to use the proper jargon, ``in case of
4300 abnormal exit''). This feature is very helpful.
4301
4302 In addition to recording the values of point and mark,
4303 @code{save-excursion} keeps track of the current buffer, and restores
4304 it, too. This means you can write code that will change the buffer and
4305 have @code{save-excursion} switch you back to the original buffer. This
4306 is how @code{save-excursion} is used in @code{append-to-buffer}.
4307 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4308
4309 @node Template for save-excursion, , Point and mark, save-excursion
4310 @comment node-name, next, previous, up
4311 @subsection Template for a @code{save-excursion} Expression
4312
4313 @need 800
4314 The template for code using @code{save-excursion} is simple:
4315
4316 @smallexample
4317 @group
4318 (save-excursion
4319 @var{body}@dots{})
4320 @end group
4321 @end smallexample
4322
4323 @noindent
4324 The body of the function is one or more expressions that will be
4325 evaluated in sequence by the Lisp interpreter. If there is more than
4326 one expression in the body, the value of the last one will be returned
4327 as the value of the @code{save-excursion} function. The other
4328 expressions in the body are evaluated only for their side effects; and
4329 @code{save-excursion} itself is used only for its side effect (which
4330 is restoring the positions of point and mark).
4331
4332 @need 1250
4333 In more detail, the template for a @code{save-excursion} expression
4334 looks like this:
4335
4336 @smallexample
4337 @group
4338 (save-excursion
4339 @var{first-expression-in-body}
4340 @var{second-expression-in-body}
4341 @var{third-expression-in-body}
4342 @dots{}
4343 @var{last-expression-in-body})
4344 @end group
4345 @end smallexample
4346
4347 @noindent
4348 An expression, of course, may be a symbol on its own or a list.
4349
4350 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4351 within the body of a @code{let} expression. It looks like this:
4352
4353 @smallexample
4354 @group
4355 (let @var{varlist}
4356 (save-excursion
4357 @var{body}@dots{}))
4358 @end group
4359 @end smallexample
4360
4361 @node Review, defun Exercises, save-excursion, Writing Defuns
4362 @comment node-name, next, previous, up
4363 @section Review
4364
4365 In the last few chapters we have introduced a fair number of functions
4366 and special forms. Here they are described in brief, along with a few
4367 similar functions that have not been mentioned yet.
4368
4369 @table @code
4370 @item eval-last-sexp
4371 Evaluate the last symbolic expression before the current location of
4372 point. The value is printed in the echo area unless the function is
4373 invoked with an argument; in that case, the output is printed in the
4374 current buffer. This command is normally bound to @kbd{C-x C-e}.
4375
4376 @item defun
4377 Define function. This special form has up to five parts: the name,
4378 a template for the arguments that will be passed to the function,
4379 documentation, an optional interactive declaration, and the body of the
4380 definition.
4381
4382 @need 1250
4383 For example:
4384
4385 @smallexample
4386 @group
4387 (defun back-to-indentation ()
4388 "Move point to first visible character on line."
4389 (interactive)
4390 (beginning-of-line 1)
4391 (skip-chars-forward " \t"))
4392 @end group
4393 @end smallexample
4394
4395 @item interactive
4396 Declare to the interpreter that the function can be used
4397 interactively. This special form may be followed by a string with one
4398 or more parts that pass the information to the arguments of the
4399 function, in sequence. These parts may also tell the interpreter to
4400 prompt for information. Parts of the string are separated by
4401 newlines, @samp{\n}.
4402
4403 Common code characters are:
4404
4405 @table @code
4406 @item b
4407 The name of an existing buffer.
4408
4409 @item f
4410 The name of an existing file.
4411
4412 @item p
4413 The numeric prefix argument. (Note that this `p' is lower case.)
4414
4415 @item r
4416 Point and the mark, as two numeric arguments, smallest first. This
4417 is the only code letter that specifies two successive arguments
4418 rather than one.
4419 @end table
4420
4421 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4422 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4423 code characters.
4424
4425 @item let
4426 Declare that a list of variables is for use within the body of the
4427 @code{let} and give them an initial value, either @code{nil} or a
4428 specified value; then evaluate the rest of the expressions in the body
4429 of the @code{let} and return the value of the last one. Inside the
4430 body of the @code{let}, the Lisp interpreter does not see the values of
4431 the variables of the same names that are bound outside of the
4432 @code{let}.
4433
4434 @need 1250
4435 For example,
4436
4437 @smallexample
4438 @group
4439 (let ((foo (buffer-name))
4440 (bar (buffer-size)))
4441 (message
4442 "This buffer is %s and has %d characters."
4443 foo bar))
4444 @end group
4445 @end smallexample
4446
4447 @item save-excursion
4448 Record the values of point and mark and the current buffer before
4449 evaluating the body of this special form. Restore the values of point
4450 and mark and buffer afterward.
4451
4452 @need 1250
4453 For example,
4454
4455 @smallexample
4456 @group
4457 (message "We are %d characters into this buffer."
4458 (- (point)
4459 (save-excursion
4460 (goto-char (point-min)) (point))))
4461 @end group
4462 @end smallexample
4463
4464 @item if
4465 Evaluate the first argument to the function; if it is true, evaluate
4466 the second argument; else evaluate the third argument, if there is one.
4467
4468 The @code{if} special form is called a @dfn{conditional}. There are
4469 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4470 commonly used.
4471
4472 @need 1250
4473 For example,
4474
4475 @smallexample
4476 @group
4477 (if (string-equal
4478 (number-to-string 21)
4479 (substring (emacs-version) 10 12))
4480 (message "This is version 21 Emacs")
4481 (message "This is not version 21 Emacs"))
4482 @end group
4483 @end smallexample
4484
4485 @item equal
4486 @itemx eq
4487 Test whether two objects are the same. @code{equal} uses one meaning
4488 of the word `same' and @code{eq} uses another: @code{equal} returns
4489 true if the two objects have a similar structure and contents, such as
4490 two copies of the same book. On the other hand, @code{eq}, returns
4491 true if both arguments are actually the same object.
4492 @findex equal
4493 @findex eq
4494
4495 @need 1250
4496 @item <
4497 @itemx >
4498 @itemx <=
4499 @itemx >=
4500 The @code{<} function tests whether its first argument is smaller than
4501 its second argument. A corresponding function, @code{>}, tests whether
4502 the first argument is greater than the second. Likewise, @code{<=}
4503 tests whether the first argument is less than or equal to the second and
4504 @code{>=} tests whether the first argument is greater than or equal to
4505 the second. In all cases, both arguments must be numbers or markers
4506 (markers indicate positions in buffers).
4507
4508 @item string<
4509 @itemx string-lessp
4510 @itemx string=
4511 @itemx string-equal
4512 The @code{string-lessp} function tests whether its first argument is
4513 smaller than the second argument. A shorter, alternative name for the
4514 same function (a @code{defalias}) is @code{string<}.
4515
4516 The arguments to @code{string-lessp} must be strings or symbols; the
4517 ordering is lexicographic, so case is significant. The print names of
4518 symbols are used instead of the symbols themselves.
4519
4520 @code{string-equal} provides the corresponding test for equality. Its
4521 shorter, alternative name is @code{string=}. There are no string test
4522 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4523
4524 @item message
4525 Print a message in the echo area. The first argument is a string that
4526 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4527 arguments that follow the string. The argument used by @samp{%s} must
4528 be a string or a symbol; the argument used by @samp{%d} must be a
4529 number. The argument used by @samp{%c} must be an ascii code number;
4530 it will be printed as the character with that @sc{ascii} code.
4531
4532 @item setq
4533 @itemx set
4534 The @code{setq} function sets the value of its first argument to the
4535 value of the second argument. The first argument is automatically
4536 quoted by @code{setq}. It does the same for succeeding pairs of
4537 arguments. Another function, @code{set}, takes only two arguments and
4538 evaluates both of them before setting the value returned by its first
4539 argument to the value returned by its second argument.
4540
4541 @item buffer-name
4542 Without an argument, return the name of the buffer, as a string.
4543
4544 @itemx buffer-file-name
4545 Without an argument, return the name of the file the buffer is
4546 visiting.
4547
4548 @item current-buffer
4549 Return the buffer in which Emacs is active; it may not be
4550 the buffer that is visible on the screen.
4551
4552 @item other-buffer
4553 Return the most recently selected buffer (other than the buffer passed
4554 to @code{other-buffer} as an argument and other than the current
4555 buffer).
4556
4557 @item switch-to-buffer
4558 Select a buffer for Emacs to be active in and display it in the current
4559 window so users can look at it. Usually bound to @kbd{C-x b}.
4560
4561 @item set-buffer
4562 Switch Emacs' attention to a buffer on which programs will run. Don't
4563 alter what the window is showing.
4564
4565 @item buffer-size
4566 Return the number of characters in the current buffer.
4567
4568 @item point
4569 Return the value of the current position of the cursor, as an
4570 integer counting the number of characters from the beginning of the
4571 buffer.
4572
4573 @item point-min
4574 Return the minimum permissible value of point in
4575 the current buffer. This is 1, unless narrowing is in effect.
4576
4577 @item point-max
4578 Return the value of the maximum permissible value of point in the
4579 current buffer. This is the end of the buffer, unless narrowing is in
4580 effect.
4581 @end table
4582
4583 @need 1500
4584 @node defun Exercises, , Review, Writing Defuns
4585 @section Exercises
4586
4587 @itemize @bullet
4588 @item
4589 Write a non-interactive function that doubles the value of its
4590 argument, a number. Make that function interactive.
4591
4592 @item
4593 Write a function that tests whether the current value of
4594 @code{fill-column} is greater than the argument passed to the function,
4595 and if so, prints an appropriate message.
4596 @end itemize
4597
4598 @node Buffer Walk Through, More Complex, Writing Defuns, Top
4599 @comment node-name, next, previous, up
4600 @chapter A Few Buffer--Related Functions
4601
4602 In this chapter we study in detail several of the functions used in GNU
4603 Emacs. This is called a ``walk-through''. These functions are used as
4604 examples of Lisp code, but are not imaginary examples; with the
4605 exception of the first, simplified function definition, these functions
4606 show the actual code used in GNU Emacs. You can learn a great deal from
4607 these definitions. The functions described here are all related to
4608 buffers. Later, we will study other functions.
4609
4610 @menu
4611 * Finding More:: How to find more information.
4612 * simplified-beginning-of-buffer:: Shows @code{goto-char},
4613 @code{point-min}, and @code{push-mark}.
4614 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4615 * append-to-buffer:: Uses @code{save-excursion} and
4616 @code{insert-buffer-substring}.
4617 * Buffer Related Review:: Review.
4618 * Buffer Exercises::
4619 @end menu
4620
4621 @node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4622 @section Finding More Information
4623
4624 @findex describe-function, @r{introduced}
4625 @cindex Find function documentation
4626 In this walk-through, I will describe each new function as we come to
4627 it, sometimes in detail and sometimes briefly. If you are interested,
4628 you can get the full documentation of any Emacs Lisp function at any
4629 time by typing @kbd{C-h f} and then the name of the function (and then
4630 @key{RET}). Similarly, you can get the full documentation for a
4631 variable by typing @kbd{C-h v} and then the name of the variable (and
4632 then @key{RET}).
4633
4634 @cindex Find source of function
4635 In versions 20 and higher, when a function is written in Emacs Lisp,
4636 @code{describe-function} will also tell you the location of the
4637 function definition. If you move point over the file name and press
4638 the @key{RET} key, which is this case means @code{help-follow} rather
4639 than `return' or `enter', Emacs will take you directly to the function
4640 definition.
4641
4642 More generally, if you want to see a function in its original source
4643 file, you can use the @code{find-tags} function to jump to it.
4644 @code{find-tags} works with a wide variety of languages, not just
4645 Lisp, and C, and it works with non-programming text as well. For
4646 example, @code{find-tags} will jump to the various nodes in the
4647 Texinfo source file of this document.
4648
4649 The @code{find-tags} function depends on `tags tables' that record
4650 the locations of the functions, variables, and other items to which
4651 @code{find-tags} jumps.
4652
4653 To use the @code{find-tags} command, type @kbd{M-.} (i.e., type the
4654 @key{META} key and the period key at the same time, or else type the
4655 @key{ESC} key and then type the period key), and then, at the prompt,
4656 type in the name of the function whose source code you want to see,
4657 such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4658 switch buffers and display the source code for the function on your
4659 screen. To switch back to your current buffer, type @kbd{C-x b
4660 @key{RET}}. (On some keyboards, the @key{META} key is labelled
4661 @key{ALT}.)
4662
4663 @c !!! 21.0.100 tags table location in this paragraph
4664 @cindex TAGS table, specifying
4665 @findex find-tags
4666 Depending on how the initial default values of your copy of Emacs are
4667 set, you may also need to specify the location of your `tags table',
4668 which is a file called @file{TAGS}. For example, if you are
4669 interested in Emacs sources, the tags table you will most likely want,
4670 if it has already been created for you, will be in a subdirectory of
4671 the @file{/usr/local/share/emacs/} directory; thus you would use the
4672 @code{M-x visit-tags-table} command and specify a pathname such as
4673 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
4674 @file{/usr/local/src/emacs/lisp/TAGS}. If the tags table has
4675 not already been created, you will have to create it yourself.
4676
4677 @need 1250
4678 To create a @file{TAGS} file in a specific directory, switch to that
4679 directory in Emacs using @kbd{M-x cd} command, or list the directory
4680 with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4681 @w{@code{etags *.el}} as the command to execute
4682
4683 @smallexample
4684 M-x compile RET etags *.el RET
4685 @end smallexample
4686
4687 For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4688
4689 After you become more familiar with Emacs Lisp, you will find that you will
4690 frequently use @code{find-tags} to navigate your way around source code;
4691 and you will create your own @file{TAGS} tables.
4692
4693 @cindex Library, as term for `file'
4694 Incidentally, the files that contain Lisp code are conventionally
4695 called @dfn{libraries}. The metaphor is derived from that of a
4696 specialized library, such as a law library or an engineering library,
4697 rather than a general library. Each library, or file, contains
4698 functions that relate to a particular topic or activity, such as
4699 @file{abbrev.el} for handling abbreviations and other typing
4700 shortcuts, and @file{help.el} for on-line help. (Sometimes several
4701 libraries provide code for a single activity, as the various
4702 @file{rmail@dots{}} files provide code for reading electronic mail.)
4703 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4704 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4705 by topic keywords.''
4706
4707 @node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4708 @comment node-name, next, previous, up
4709 @section A Simplified @code{beginning-of-buffer} Definition
4710 @findex simplified-beginning-of-buffer
4711
4712 The @code{beginning-of-buffer} command is a good function to start with
4713 since you are likely to be familiar with it and it is easy to
4714 understand. Used as an interactive command, @code{beginning-of-buffer}
4715 moves the cursor to the beginning of the buffer, leaving the mark at the
4716 previous position. It is generally bound to @kbd{M-<}.
4717
4718 In this section, we will discuss a shortened version of the function
4719 that shows how it is most frequently used. This shortened function
4720 works as written, but it does not contain the code for a complex option.
4721 In another section, we will describe the entire function.
4722 (@xref{beginning-of-buffer, , Complete Definition of
4723 @code{beginning-of-buffer}}.)
4724
4725 Before looking at the code, let's consider what the function
4726 definition has to contain: it must include an expression that makes
4727 the function interactive so it can be called by typing @kbd{M-x
4728 beginning-of-buffer} or by typing a keychord such as @kbd{C-<}; it
4729 must include code to leave a mark at the original position in the
4730 buffer; and it must include code to move the cursor to the beginning
4731 of the buffer.
4732
4733 @need 1250
4734 Here is the complete text of the shortened version of the function:
4735
4736 @smallexample
4737 @group
4738 (defun simplified-beginning-of-buffer ()
4739 "Move point to the beginning of the buffer;
4740 leave mark at previous position."
4741 (interactive)
4742 (push-mark)
4743 (goto-char (point-min)))
4744 @end group
4745 @end smallexample
4746
4747 Like all function definitions, this definition has five parts following
4748 the special form @code{defun}:
4749
4750 @enumerate
4751 @item
4752 The name: in this example, @code{simplified-beginning-of-buffer}.
4753
4754 @item
4755 A list of the arguments: in this example, an empty list, @code{()},
4756
4757 @item
4758 The documentation string.
4759
4760 @item
4761 The interactive expression.
4762
4763 @item
4764 The body.
4765 @end enumerate
4766
4767 @noindent
4768 In this function definition, the argument list is empty; this means that
4769 this function does not require any arguments. (When we look at the
4770 definition for the complete function, we will see that it may be passed
4771 an optional argument.)
4772
4773 The interactive expression tells Emacs that the function is intended to
4774 be used interactively. In this example, @code{interactive} does not have
4775 an argument because @code{simplified-beginning-of-buffer} does not
4776 require one.
4777
4778 @need 800
4779 The body of the function consists of the two lines:
4780
4781 @smallexample
4782 @group
4783 (push-mark)
4784 (goto-char (point-min))
4785 @end group
4786 @end smallexample
4787
4788 The first of these lines is the expression, @code{(push-mark)}. When
4789 this expression is evaluated by the Lisp interpreter, it sets a mark at
4790 the current position of the cursor, wherever that may be. The position
4791 of this mark is saved in the mark ring.
4792
4793 The next line is @code{(goto-char (point-min))}. This expression
4794 jumps the cursor to the minimum point in the buffer, that is, to the
4795 beginning of the buffer (or to the beginning of the accessible portion
4796 of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4797 Narrowing and Widening}.)
4798
4799 The @code{push-mark} command sets a mark at the place where the cursor
4800 was located before it was moved to the beginning of the buffer by the
4801 @code{(goto-char (point-min))} expression. Consequently, you can, if
4802 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4803
4804 That is all there is to the function definition!
4805
4806 @findex describe-function
4807 When you are reading code such as this and come upon an unfamiliar
4808 function, such as @code{goto-char}, you can find out what it does by
4809 using the @code{describe-function} command. To use this command, type
4810 @kbd{C-h f} and then type in the name of the function and press
4811 @key{RET}. The @code{describe-function} command will print the
4812 function's documentation string in a @file{*Help*} window. For
4813 example, the documentation for @code{goto-char} is:
4814
4815 @smallexample
4816 @group
4817 One arg, a number. Set point to that number.
4818 Beginning of buffer is position (point-min),
4819 end is (point-max).
4820 @end group
4821 @end smallexample
4822
4823 @noindent
4824 (The prompt for @code{describe-function} will offer you the symbol
4825 under or preceding the cursor, so you can save typing by positioning
4826 the cursor right over or after the function and then typing @kbd{C-h f
4827 @key{RET}}.)
4828
4829 The @code{end-of-buffer} function definition is written in the same way as
4830 the @code{beginning-of-buffer} definition except that the body of the
4831 function contains the expression @code{(goto-char (point-max))} in place
4832 of @code{(goto-char (point-min))}.
4833
4834 @node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4835 @comment node-name, next, previous, up
4836 @section The Definition of @code{mark-whole-buffer}
4837 @findex mark-whole-buffer
4838
4839 The @code{mark-whole-buffer} function is no harder to understand than the
4840 @code{simplified-beginning-of-buffer} function. In this case, however,
4841 we will look at the complete function, not a shortened version.
4842
4843 The @code{mark-whole-buffer} function is not as commonly used as the
4844 @code{beginning-of-buffer} function, but is useful nonetheless: it
4845 marks a whole buffer as a region by putting point at the beginning and
4846 a mark at the end of the buffer. It is generally bound to @kbd{C-x
4847 h}.
4848
4849
4850 @menu
4851 * mark-whole-buffer overview::
4852 * Body of mark-whole-buffer:: Only three lines of code.
4853 @end menu
4854
4855
4856 @node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4857 @ifnottex
4858 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4859 @end ifnottex
4860
4861 @need 1250
4862 In GNU Emacs 20, the code for the complete function looks like this:
4863
4864 @smallexample
4865 @group
4866 (defun mark-whole-buffer ()
4867 "Put point at beginning and mark at end of buffer."
4868 (interactive)
4869 (push-mark (point))
4870 (push-mark (point-max))
4871 (goto-char (point-min)))
4872 @end group
4873 @end smallexample
4874
4875 @need 1250
4876 Like all other functions, the @code{mark-whole-buffer} function fits
4877 into the template for a function definition. The template looks like
4878 this:
4879
4880 @smallexample
4881 @group
4882 (defun @var{name-of-function} (@var{argument-list})
4883 "@var{documentation}@dots{}"
4884 (@var{interactive-expression}@dots{})
4885 @var{body}@dots{})
4886 @end group
4887 @end smallexample
4888
4889 Here is how the function works: the name of the function is
4890 @code{mark-whole-buffer}; it is followed by an empty argument list,
4891 @samp{()}, which means that the function does not require arguments.
4892 The documentation comes next.
4893
4894 The next line is an @code{(interactive)} expression that tells Emacs
4895 that the function will be used interactively. These details are similar
4896 to the @code{simplified-beginning-of-buffer} function described in the
4897 previous section.
4898
4899 @node Body of mark-whole-buffer, , mark-whole-buffer overview, mark-whole-buffer
4900 @comment node-name, next, previous, up
4901 @subsection Body of @code{mark-whole-buffer}
4902
4903 The body of the @code{mark-whole-buffer} function consists of three
4904 lines of code:
4905
4906 @smallexample
4907 @group
4908 (push-mark (point))
4909 (push-mark (point-max))
4910 (goto-char (point-min))
4911 @end group
4912 @end smallexample
4913
4914 The first of these lines is the expression, @code{(push-mark (point))}.
4915
4916 This line does exactly the same job as the first line of the body of
4917 the @code{simplified-beginning-of-buffer} function, which is written
4918 @code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4919 at the current position of the cursor.
4920
4921 I don't know why the expression in @code{mark-whole-buffer} is written
4922 @code{(push-mark (point))} and the expression in
4923 @code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4924 whoever wrote the code did not know that the arguments for
4925 @code{push-mark} are optional and that if @code{push-mark} is not
4926 passed an argument, the function automatically sets mark at the
4927 location of point by default. Or perhaps the expression was written
4928 so as to parallel the structure of the next line. In any case, the
4929 line causes Emacs to determine the position of point and set a mark
4930 there.
4931
4932 The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4933 This expression sets a mark at the point in the buffer
4934 that has the highest number. This will be the end of the buffer (or,
4935 if the buffer is narrowed, the end of the accessible portion of the
4936 buffer. @xref{Narrowing & Widening, , Narrowing and Widening}, for
4937 more about narrowing.) After this mark has been set, the previous
4938 mark, the one set at point, is no longer set, but Emacs remembers its
4939 position, just as all other recent marks are always remembered. This
4940 means that you can, if you wish, go back to that position by typing
4941 @kbd{C-u C-@key{SPC}} twice.
4942
4943 (In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4944 complicated than shown here. The line reads
4945
4946 @smallexample
4947 (push-mark (point-max) nil t)
4948 @end smallexample
4949
4950 @noindent
4951 (The expression works nearly the same as before. It sets a mark at
4952 the highest numbered place in the buffer that it can. However, in
4953 this version, @code{push-mark} has two additional arguments The second
4954 argument to @code{push-mark} is @code{nil}. This tells the function
4955 it should @emph{not} display a message that says `Mark set' when it
4956 pushes the mark. The third argument is @code{t}. This tells
4957 @code{push-mark} to activate the mark when Transient Mark mode is
4958 turned on. Transient Mark mode highlights the currently active
4959 region. It is usually turned off.)
4960
4961 Finally, the last line of the function is @code{(goto-char
4962 (point-min)))}. This is written exactly the same way as it is written
4963 in @code{beginning-of-buffer}. The expression moves the cursor to
4964 the minimum point in the buffer, that is, to the beginning of the buffer
4965 (or to the beginning of the accessible portion of the buffer). As a
4966 result of this, point is placed at the beginning of the buffer and mark
4967 is set at the end of the buffer. The whole buffer is, therefore, the
4968 region.
4969
4970 @node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4971 @comment node-name, next, previous, up
4972 @section The Definition of @code{append-to-buffer}
4973 @findex append-to-buffer
4974
4975 The @code{append-to-buffer} command is very nearly as simple as the
4976 @code{mark-whole-buffer} command. What it does is copy the region (that
4977 is, the part of the buffer between point and mark) from the current
4978 buffer to a specified buffer.
4979
4980 @menu
4981 * append-to-buffer overview::
4982 * append interactive:: A two part interactive expression.
4983 * append-to-buffer body:: Incorporates a @code{let} expression.
4984 * append save-excursion:: How the @code{save-excursion} works.
4985 @end menu
4986
4987 @node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4988 @ifnottex
4989 @unnumberedsubsec An Overview of @code{append-to-buffer}
4990 @end ifnottex
4991
4992 @findex insert-buffer-substring
4993 The @code{append-to-buffer} command uses the
4994 @code{insert-buffer-substring} function to copy the region.
4995 @code{insert-buffer-substring} is described by its name: it takes a
4996 string of characters from part of a buffer, a ``substring'', and
4997 inserts them into another buffer. Most of @code{append-to-buffer} is
4998 concerned with setting up the conditions for
4999 @code{insert-buffer-substring} to work: the code must specify both the
5000 buffer to which the text will go and the region that will be copied.
5001 Here is the complete text of the function:
5002
5003 @smallexample
5004 @group
5005 (defun append-to-buffer (buffer start end)
5006 "Append to specified buffer the text of the region.
5007 It is inserted into that buffer before its point.
5008 @end group
5009
5010 @group
5011 When calling from a program, give three arguments:
5012 a buffer or the name of one, and two character numbers
5013 specifying the portion of the current buffer to be copied."
5014 (interactive "BAppend to buffer:@: \nr")
5015 (let ((oldbuf (current-buffer)))
5016 (save-excursion
5017 (set-buffer (get-buffer-create buffer))
5018 (insert-buffer-substring oldbuf start end))))
5019 @end group
5020 @end smallexample
5021
5022 The function can be understood by looking at it as a series of
5023 filled-in templates.
5024
5025 The outermost template is for the function definition. In this
5026 function, it looks like this (with several slots filled in):
5027
5028 @smallexample
5029 @group
5030 (defun append-to-buffer (buffer start end)
5031 "@var{documentation}@dots{}"
5032 (interactive "BAppend to buffer:@: \nr")
5033 @var{body}@dots{})
5034 @end group
5035 @end smallexample
5036
5037 The first line of the function includes its name and three arguments.
5038 The arguments are the @code{buffer} to which the text will be copied, and
5039 the @code{start} and @code{end} of the region in the current buffer that
5040 will be copied.
5041
5042 The next part of the function is the documentation, which is clear and
5043 complete.
5044
5045 @node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
5046 @comment node-name, next, previous, up
5047 @subsection The @code{append-to-buffer} Interactive Expression
5048
5049 Since the @code{append-to-buffer} function will be used interactively,
5050 the function must have an @code{interactive} expression. (For a
5051 review of @code{interactive}, see @ref{Interactive, , Making a
5052 Function Interactive}.) The expression reads as follows:
5053
5054 @smallexample
5055 (interactive "BAppend to buffer:@: \nr")
5056 @end smallexample
5057
5058 @noindent
5059 This expression has an argument inside of quotation marks and that
5060 argument has two parts, separated by @samp{\n}.
5061
5062 The first part is @samp{BAppend to buffer:@: }. Here, the @samp{B}
5063 tells Emacs to ask for the name of the buffer that will be passed to the
5064 function. Emacs will ask for the name by prompting the user in the
5065 minibuffer, using the string following the @samp{B}, which is the string
5066 @samp{Append to buffer:@: }. Emacs then binds the variable @code{buffer}
5067 in the function's argument list to the specified buffer.
5068
5069 The newline, @samp{\n}, separates the first part of the argument from
5070 the second part. It is followed by an @samp{r} that tells Emacs to bind
5071 the two arguments that follow the symbol @code{buffer} in the function's
5072 argument list (that is, @code{start} and @code{end}) to the values of
5073 point and mark.
5074
5075 @node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5076 @comment node-name, next, previous, up
5077 @subsection The Body of @code{append-to-buffer}
5078
5079 The body of the @code{append-to-buffer} function begins with @code{let}.
5080
5081 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5082 @code{let} expression is to create and give initial values to one or
5083 more variables that will only be used within the body of the
5084 @code{let}. This means that such a variable will not be confused with
5085 any variable of the same name outside the @code{let} expression.
5086
5087 We can see how the @code{let} expression fits into the function as a
5088 whole by showing a template for @code{append-to-buffer} with the
5089 @code{let} expression in outline:
5090
5091 @smallexample
5092 @group
5093 (defun append-to-buffer (buffer start end)
5094 "@var{documentation}@dots{}"
5095 (interactive "BAppend to buffer:@: \nr")
5096 (let ((@var{variable} @var{value}))
5097 @var{body}@dots{})
5098 @end group
5099 @end smallexample
5100
5101 The @code{let} expression has three elements:
5102
5103 @enumerate
5104 @item
5105 The symbol @code{let};
5106
5107 @item
5108 A varlist containing, in this case, a single two-element list,
5109 @code{(@var{variable} @var{value})};
5110
5111 @item
5112 The body of the @code{let} expression.
5113 @end enumerate
5114
5115 @need 800
5116 In the @code{append-to-buffer} function, the varlist looks like this:
5117
5118 @smallexample
5119 (oldbuf (current-buffer))
5120 @end smallexample
5121
5122 @noindent
5123 In this part of the @code{let} expression, the one variable,
5124 @code{oldbuf}, is bound to the value returned by the
5125 @code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5126 used to keep track of the buffer in which you are working and from
5127 which you will copy.
5128
5129 The element or elements of a varlist are surrounded by a set of
5130 parentheses so the Lisp interpreter can distinguish the varlist from
5131 the body of the @code{let}. As a consequence, the two-element list
5132 within the varlist is surrounded by a circumscribing set of parentheses.
5133 The line looks like this:
5134
5135 @smallexample
5136 @group
5137 (let ((oldbuf (current-buffer)))
5138 @dots{} )
5139 @end group
5140 @end smallexample
5141
5142 @noindent
5143 The two parentheses before @code{oldbuf} might surprise you if you did
5144 not realize that the first parenthesis before @code{oldbuf} marks the
5145 boundary of the varlist and the second parenthesis marks the beginning
5146 of the two-element list, @code{(oldbuf (current-buffer))}.
5147
5148 @node append save-excursion, , append-to-buffer body, append-to-buffer
5149 @comment node-name, next, previous, up
5150 @subsection @code{save-excursion} in @code{append-to-buffer}
5151
5152 The body of the @code{let} expression in @code{append-to-buffer}
5153 consists of a @code{save-excursion} expression.
5154
5155 The @code{save-excursion} function saves the locations of point and
5156 mark, and restores them to those positions after the expressions in the
5157 body of the @code{save-excursion} complete execution. In addition,
5158 @code{save-excursion} keeps track of the original buffer, and
5159 restores it. This is how @code{save-excursion} is used in
5160 @code{append-to-buffer}.
5161
5162 @need 1500
5163 @cindex Indentation for formatting
5164 @cindex Formatting convention
5165 Incidentally, it is worth noting here that a Lisp function is normally
5166 formatted so that everything that is enclosed in a multi-line spread is
5167 indented more to the right than the first symbol. In this function
5168 definition, the @code{let} is indented more than the @code{defun}, and
5169 the @code{save-excursion} is indented more than the @code{let}, like
5170 this:
5171
5172 @smallexample
5173 @group
5174 (defun @dots{}
5175 @dots{}
5176 @dots{}
5177 (let@dots{}
5178 (save-excursion
5179 @dots{}
5180 @end group
5181 @end smallexample
5182
5183 @need 1500
5184 @noindent
5185 This formatting convention makes it easy to see that the two lines in
5186 the body of the @code{save-excursion} are enclosed by the parentheses
5187 associated with @code{save-excursion}, just as the
5188 @code{save-excursion} itself is enclosed by the parentheses associated
5189 with the @code{let}:
5190
5191 @smallexample
5192 @group
5193 (let ((oldbuf (current-buffer)))
5194 (save-excursion
5195 (set-buffer (get-buffer-create buffer))
5196 (insert-buffer-substring oldbuf start end))))
5197 @end group
5198 @end smallexample
5199
5200 @need 1200
5201 The use of the @code{save-excursion} function can be viewed as a process
5202 of filling in the slots of a template:
5203
5204 @smallexample
5205 @group
5206 (save-excursion
5207 @var{first-expression-in-body}
5208 @var{second-expression-in-body}
5209 @dots{}
5210 @var{last-expression-in-body})
5211 @end group
5212 @end smallexample
5213
5214 @need 1200
5215 @noindent
5216 In this function, the body of the @code{save-excursion} contains only
5217 two expressions. The body looks like this:
5218
5219 @smallexample
5220 @group
5221 (set-buffer (get-buffer-create buffer))
5222 (insert-buffer-substring oldbuf start end)
5223 @end group
5224 @end smallexample
5225
5226 When the @code{append-to-buffer} function is evaluated, the two
5227 expressions in the body of the @code{save-excursion} are evaluated in
5228 sequence. The value of the last expression is returned as the value of
5229 the @code{save-excursion} function; the other expression is evaluated
5230 only for its side effects.
5231
5232 The first line in the body of the @code{save-excursion} uses the
5233 @code{set-buffer} function to change the current buffer to the one
5234 specified in the first argument to @code{append-to-buffer}. (Changing
5235 the buffer is the side effect; as we have said before, in Lisp, a side
5236 effect is often the primary thing we want.) The second line does the
5237 primary work of the function.
5238
5239 The @code{set-buffer} function changes Emacs' attention to the buffer to
5240 which the text will be copied and from which @code{save-excursion} will
5241 return.
5242
5243 @need 800
5244 The line looks like this:
5245
5246 @smallexample
5247 (set-buffer (get-buffer-create buffer))
5248 @end smallexample
5249
5250 The innermost expression of this list is @code{(get-buffer-create
5251 buffer)}. This expression uses the @code{get-buffer-create} function,
5252 which either gets the named buffer, or if it does not exist, creates one
5253 with the given name. This means you can use @code{append-to-buffer} to
5254 put text into a buffer that did not previously exist.
5255
5256 @code{get-buffer-create} also keeps @code{set-buffer} from getting an
5257 unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5258 were to specify a buffer that does not exist, Emacs would baulk.
5259 Since @code{get-buffer-create} will create a buffer if none exists,
5260 @code{set-buffer} is always provided with a buffer.
5261
5262 @need 1250
5263 The last line of @code{append-to-buffer} does the work of appending
5264 the text:
5265
5266 @smallexample
5267 (insert-buffer-substring oldbuf start end)
5268 @end smallexample
5269
5270 @noindent
5271 The @code{insert-buffer-substring} function copies a string @emph{from}
5272 the buffer specified as its first argument and inserts the string into
5273 the present buffer. In this case, the argument to
5274 @code{insert-buffer-substring} is the value of the variable created and
5275 bound by the @code{let}, namely the value of @code{oldbuf}, which was
5276 the current buffer when you gave the @code{append-to-buffer} command.
5277
5278 After @code{insert-buffer-substring} has done its work,
5279 @code{save-excursion} will restore the action to the original buffer and
5280 @code{append-to-buffer} will have done its job.
5281
5282 @need 800
5283 Written in skeletal form, the workings of the body look like this:
5284
5285 @smallexample
5286 @group
5287 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5288 (save-excursion ; @r{Keep track of buffer.}
5289 @var{change-buffer}
5290 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5291
5292 @var{change-back-to-original-buffer-when-finished}
5293 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5294
5295 @end group
5296 @end smallexample
5297
5298 In summary, @code{append-to-buffer} works as follows: it saves the value
5299 of the current buffer in the variable called @code{oldbuf}. It gets the
5300 new buffer, creating one if need be, and switches Emacs to it. Using
5301 the value of @code{oldbuf}, it inserts the region of text from the old
5302 buffer into the new buffer; and then using @code{save-excursion}, it
5303 brings you back to your original buffer.
5304
5305 In looking at @code{append-to-buffer}, you have explored a fairly
5306 complex function. It shows how to use @code{let} and
5307 @code{save-excursion}, and how to change to and come back from another
5308 buffer. Many function definitions use @code{let},
5309 @code{save-excursion}, and @code{set-buffer} this way.
5310
5311 @node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5312 @comment node-name, next, previous, up
5313 @section Review
5314
5315 Here is a brief summary of the various functions discussed in this chapter.
5316
5317 @table @code
5318 @item describe-function
5319 @itemx describe-variable
5320 Print the documentation for a function or variable.
5321 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5322
5323 @item find-tag
5324 Find the file containing the source for a function or variable and
5325 switch buffers to it, positioning point at the beginning of the item.
5326 Conventionally bound to @kbd{M-.} (that's a period following the
5327 @key{META} key).
5328
5329 @item save-excursion
5330 Save the location of point and mark and restore their values after the
5331 arguments to @code{save-excursion} have been evaluated. Also, remember
5332 the current buffer and return to it.
5333
5334 @item push-mark
5335 Set mark at a location and record the value of the previous mark on the
5336 mark ring. The mark is a location in the buffer that will keep its
5337 relative position even if text is added to or removed from the buffer.
5338
5339 @item goto-char
5340 Set point to the location specified by the value of the argument, which
5341 can be a number, a marker, or an expression that returns the number of
5342 a position, such as @code{(point-min)}.
5343
5344 @item insert-buffer-substring
5345 Copy a region of text from a buffer that is passed to the function as
5346 an argument and insert the region into the current buffer.
5347
5348 @item mark-whole-buffer
5349 Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5350
5351 @item set-buffer
5352 Switch the attention of Emacs to another buffer, but do not change the
5353 window being displayed. Used when the program rather than a human is
5354 to work on a different buffer.
5355
5356 @item get-buffer-create
5357 @itemx get-buffer
5358 Find a named buffer or create one if a buffer of that name does not
5359 exist. The @code{get-buffer} function returns @code{nil} if the named
5360 buffer does not exist.
5361 @end table
5362
5363 @need 1500
5364 @node Buffer Exercises, , Buffer Related Review, Buffer Walk Through
5365 @section Exercises
5366
5367 @itemize @bullet
5368 @item
5369 Write your own @code{simplified-end-of-buffer} function definition;
5370 then test it to see whether it works.
5371
5372 @item
5373 Use @code{if} and @code{get-buffer} to write a function that prints a
5374 message telling you whether a buffer exists.
5375
5376 @item
5377 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5378 function.
5379 @end itemize
5380
5381 @node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5382 @comment node-name, next, previous, up
5383 @chapter A Few More Complex Functions
5384
5385 In this chapter, we build on what we have learned in previous chapters
5386 by looking at more complex functions. The @code{copy-to-buffer}
5387 function illustrates use of two @code{save-excursion} expressions in
5388 one definition, while the @code{insert-buffer} function illustrates
5389 use of an asterisk in an @code{interactive} expression, use of
5390 @code{or}, and the important distinction between a name and the object
5391 to which the name refers.
5392
5393 @menu
5394 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5395 * insert-buffer:: Read-only, and with @code{or}.
5396 * beginning-of-buffer:: Shows @code{goto-char},
5397 @code{point-min}, and @code{push-mark}.
5398 * Second Buffer Related Review::
5399 * optional Exercise::
5400 @end menu
5401
5402 @node copy-to-buffer, insert-buffer, More Complex, More Complex
5403 @comment node-name, next, previous, up
5404 @section The Definition of @code{copy-to-buffer}
5405 @findex copy-to-buffer
5406
5407 After understanding how @code{append-to-buffer} works, it is easy to
5408 understand @code{copy-to-buffer}. This function copies text into a
5409 buffer, but instead of adding to the second buffer, it replaces the
5410 previous text in the second buffer. The code for the
5411 @code{copy-to-buffer} function is almost the same as the code for
5412 @code{append-to-buffer}, except that @code{erase-buffer} and a second
5413 @code{save-excursion} are used. (@xref{append-to-buffer, , The
5414 Definition of @code{append-to-buffer}}, for the description of
5415 @code{append-to-buffer}.)
5416
5417 @need 800
5418 The body of @code{copy-to-buffer} looks like this
5419
5420 @smallexample
5421 @group
5422 @dots{}
5423 (interactive "BCopy to buffer:@: \nr")
5424 (let ((oldbuf (current-buffer)))
5425 (save-excursion
5426 (set-buffer (get-buffer-create buffer))
5427 (erase-buffer)
5428 (save-excursion
5429 (insert-buffer-substring oldbuf start end)))))
5430 @end group
5431 @end smallexample
5432
5433 This code is similar to the code in @code{append-to-buffer}: it is
5434 only after changing to the buffer to which the text will be copied
5435 that the definition for this function diverges from the definition for
5436 @code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5437 buffer's former contents. (This is what is meant by `replacement'; to
5438 replace text, Emacs erases the previous text and then inserts new
5439 text.) After erasing the previous contents of the buffer,
5440 @code{save-excursion} is used for a second time and the new text is
5441 inserted.
5442
5443 Why is @code{save-excursion} used twice? Consider again what the
5444 function does.
5445
5446 @need 1250
5447 In outline, the body of @code{copy-to-buffer} looks like this:
5448
5449 @smallexample
5450 @group
5451 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5452 (save-excursion ; @r{First use of @code{save-excursion}.}
5453 @var{change-buffer}
5454 (erase-buffer)
5455 (save-excursion ; @r{Second use of @code{save-excursion}.}
5456 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5457 @end group
5458 @end smallexample
5459
5460 The first use of @code{save-excursion} returns Emacs to the buffer from
5461 which the text is being copied. That is clear, and is just like its use
5462 in @code{append-to-buffer}. Why the second use? The reason is that
5463 @code{insert-buffer-substring} always leaves point at the @emph{end} of
5464 the region being inserted. The second @code{save-excursion} causes
5465 Emacs to leave point at the beginning of the text being inserted. In
5466 most circumstances, users prefer to find point at the beginning of
5467 inserted text. (Of course, the @code{copy-to-buffer} function returns
5468 the user to the original buffer when done---but if the user @emph{then}
5469 switches to the copied-to buffer, point will go to the beginning of the
5470 text. Thus, this use of a second @code{save-excursion} is a little
5471 nicety.)
5472
5473 @node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5474 @comment node-name, next, previous, up
5475 @section The Definition of @code{insert-buffer}
5476 @findex insert-buffer
5477
5478 @code{insert-buffer} is yet another buffer-related function. This
5479 command copies another buffer @emph{into} the current buffer. It is the
5480 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5481 copy a region of text @emph{from} the current buffer to another buffer.
5482
5483 In addition, this code illustrates the use of @code{interactive} with a
5484 buffer that might be @dfn{read-only} and the important distinction
5485 between the name of an object and the object actually referred to.
5486
5487 @menu
5488 * insert-buffer code::
5489 * insert-buffer interactive:: When you can read, but not write.
5490 * insert-buffer body:: The body has an @code{or} and a @code{let}.
5491 * if & or:: Using an @code{if} instead of an @code{or}.
5492 * Insert or:: How the @code{or} expression works.
5493 * Insert let:: Two @code{save-excursion} expressions.
5494 @end menu
5495
5496 @node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5497 @ifnottex
5498 @unnumberedsubsec The Code for @code{insert-buffer}
5499 @end ifnottex
5500
5501 @need 800
5502 Here is the code:
5503
5504 @smallexample
5505 @group
5506 (defun insert-buffer (buffer)
5507 "Insert after point the contents of BUFFER.
5508 Puts mark after the inserted text.
5509 BUFFER may be a buffer or a buffer name."
5510 (interactive "*bInsert buffer:@: ")
5511 @end group
5512 @group
5513 (or (bufferp buffer)
5514 (setq buffer (get-buffer buffer)))
5515 (let (start end newmark)
5516 (save-excursion
5517 (save-excursion
5518 (set-buffer buffer)
5519 (setq start (point-min) end (point-max)))
5520 @end group
5521 @group
5522 (insert-buffer-substring buffer start end)
5523 (setq newmark (point)))
5524 (push-mark newmark)))
5525 @end group
5526 @end smallexample
5527
5528 @need 1200
5529 As with other function definitions, you can use a template to see an
5530 outline of the function:
5531
5532 @smallexample
5533 @group
5534 (defun insert-buffer (buffer)
5535 "@var{documentation}@dots{}"
5536 (interactive "*bInsert buffer:@: ")
5537 @var{body}@dots{})
5538 @end group
5539 @end smallexample
5540
5541 @node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5542 @comment node-name, next, previous, up
5543 @subsection The Interactive Expression in @code{insert-buffer}
5544 @findex interactive, @r{example use of}
5545
5546 In @code{insert-buffer}, the argument to the @code{interactive}
5547 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5548 buffer:@: }.
5549
5550 @menu
5551 * Read-only buffer:: When a buffer cannot be modified.
5552 * b for interactive:: An existing buffer or else its name.
5553 @end menu
5554
5555 @node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5556 @comment node-name, next, previous, up
5557 @unnumberedsubsubsec A Read-only Buffer
5558 @cindex Read-only buffer
5559 @cindex Asterisk for read-only buffer
5560 @findex * @r{for read-only buffer}
5561
5562 The asterisk is for the situation when the buffer is a read-only
5563 buffer---a buffer that cannot be modified. If @code{insert-buffer} is
5564 called on a buffer that is read-only, a message to this effect is
5565 printed in the echo area and the terminal may beep or blink at you;
5566 you will not be permitted to insert anything into current buffer. The
5567 asterisk does not need to be followed by a newline to separate it from
5568 the next argument.
5569
5570 @node b for interactive, , Read-only buffer, insert-buffer interactive
5571 @comment node-name, next, previous, up
5572 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5573
5574 The next argument in the interactive expression starts with a lower
5575 case @samp{b}. (This is different from the code for
5576 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5577 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5578 The lower-case @samp{b} tells the Lisp interpreter that the argument
5579 for @code{insert-buffer} should be an existing buffer or else its
5580 name. (The upper-case @samp{B} option provides for the possibility
5581 that the buffer does not exist.) Emacs will prompt you for the name
5582 of the buffer, offering you a default buffer, with name completion
5583 enabled. If the buffer does not exist, you receive a message that
5584 says ``No match''; your terminal may beep at you as well.
5585
5586 @node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5587 @comment node-name, next, previous, up
5588 @subsection The Body of the @code{insert-buffer} Function
5589
5590 The body of the @code{insert-buffer} function has two major parts: an
5591 @code{or} expression and a @code{let} expression. The purpose of the
5592 @code{or} expression is to ensure that the argument @code{buffer} is
5593 bound to a buffer and not just the name of a buffer. The body of the
5594 @code{let} expression contains the code which copies the other buffer
5595 into the current buffer.
5596
5597 @need 1250
5598 In outline, the two expressions fit into the @code{insert-buffer}
5599 function like this:
5600
5601 @smallexample
5602 @group
5603 (defun insert-buffer (buffer)
5604 "@var{documentation}@dots{}"
5605 (interactive "*bInsert buffer:@: ")
5606 (or @dots{}
5607 @dots{}
5608 @end group
5609 @group
5610 (let (@var{varlist})
5611 @var{body-of-}@code{let}@dots{} )
5612 @end group
5613 @end smallexample
5614
5615 To understand how the @code{or} expression ensures that the argument
5616 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5617 is first necessary to understand the @code{or} function.
5618
5619 Before doing this, let me rewrite this part of the function using
5620 @code{if} so that you can see what is done in a manner that will be familiar.
5621
5622 @node if & or, Insert or, insert-buffer body, insert-buffer
5623 @comment node-name, next, previous, up
5624 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5625
5626 The job to be done is to make sure the value of @code{buffer} is a
5627 buffer itself and not the name of a buffer. If the value is the name,
5628 then the buffer itself must be got.
5629
5630 You can imagine yourself at a conference where an usher is wandering
5631 around holding a list with your name on it and looking for you: the
5632 usher is ``bound'' to your name, not to you; but when the usher finds
5633 you and takes your arm, the usher becomes ``bound'' to you.
5634
5635 @need 800
5636 In Lisp, you might describe this situation like this:
5637
5638 @smallexample
5639 @group
5640 (if (not (holding-on-to-guest))
5641 (find-and-take-arm-of-guest))
5642 @end group
5643 @end smallexample
5644
5645 We want to do the same thing with a buffer---if we do not have the
5646 buffer itself, we want to get it.
5647
5648 @need 1200
5649 Using a predicate called @code{bufferp} that tells us whether we have a
5650 buffer (rather than its name), we can write the code like this:
5651
5652 @smallexample
5653 @group
5654 (if (not (bufferp buffer)) ; @r{if-part}
5655 (setq buffer (get-buffer buffer))) ; @r{then-part}
5656 @end group
5657 @end smallexample
5658
5659 @noindent
5660 Here, the true-or-false-test of the @code{if} expression is
5661 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5662 @w{@code{(setq buffer (get-buffer buffer))}}.
5663
5664 In the test, the function @code{bufferp} returns true if its argument is
5665 a buffer---but false if its argument is the name of the buffer. (The
5666 last character of the function name @code{bufferp} is the character
5667 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5668 indicates that the function is a predicate, which is a term that means
5669 that the function will determine whether some property is true or false.
5670 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5671 Argument}.)
5672
5673 @need 1200
5674 The function @code{not} precedes the expression @code{(bufferp buffer)},
5675 so the true-or-false-test looks like this:
5676
5677 @smallexample
5678 (not (bufferp buffer))
5679 @end smallexample
5680
5681 @noindent
5682 @code{not} is a function that returns true if its argument is false
5683 and false if its argument is true. So if @code{(bufferp buffer)}
5684 returns true, the @code{not} expression returns false and vice-versa:
5685 what is ``not true'' is false and what is ``not false'' is true.
5686
5687 Using this test, the @code{if} expression works as follows: when the
5688 value of the variable @code{buffer} is actually a buffer rather then
5689 its name, the true-or-false-test returns false and the @code{if}
5690 expression does not evaluate the then-part. This is fine, since we do
5691 not need to do anything to the variable @code{buffer} if it really is
5692 a buffer.
5693
5694 On the other hand, when the value of @code{buffer} is not a buffer
5695 itself, but the name of a buffer, the true-or-false-test returns true
5696 and the then-part of the expression is evaluated. In this case, the
5697 then-part is @code{(setq buffer (get-buffer buffer))}. This
5698 expression uses the @code{get-buffer} function to return an actual
5699 buffer itself, given its name. The @code{setq} then sets the variable
5700 @code{buffer} to the value of the buffer itself, replacing its previous
5701 value (which was the name of the buffer).
5702
5703 @node Insert or, Insert let, if & or, insert-buffer
5704 @comment node-name, next, previous, up
5705 @subsection The @code{or} in the Body
5706
5707 The purpose of the @code{or} expression in the @code{insert-buffer}
5708 function is to ensure that the argument @code{buffer} is bound to a
5709 buffer and not just to the name of a buffer. The previous section shows
5710 how the job could have been done using an @code{if} expression.
5711 However, the @code{insert-buffer} function actually uses @code{or}.
5712 To understand this, it is necessary to understand how @code{or} works.
5713
5714 @findex or
5715 An @code{or} function can have any number of arguments. It evaluates
5716 each argument in turn and returns the value of the first of its
5717 arguments that is not @code{nil}. Also, and this is a crucial feature
5718 of @code{or}, it does not evaluate any subsequent arguments after
5719 returning the first non-@code{nil} value.
5720
5721 @need 800
5722 The @code{or} expression looks like this:
5723
5724 @smallexample
5725 @group
5726 (or (bufferp buffer)
5727 (setq buffer (get-buffer buffer)))
5728 @end group
5729 @end smallexample
5730
5731 @noindent
5732 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5733 This expression returns true (a non-@code{nil} value) if the buffer is
5734 actually a buffer, and not just the name of a buffer. In the @code{or}
5735 expression, if this is the case, the @code{or} expression returns this
5736 true value and does not evaluate the next expression---and this is fine
5737 with us, since we do not want to do anything to the value of
5738 @code{buffer} if it really is a buffer.
5739
5740 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5741 which it will be if the value of @code{buffer} is the name of a buffer,
5742 the Lisp interpreter evaluates the next element of the @code{or}
5743 expression. This is the expression @code{(setq buffer (get-buffer
5744 buffer))}. This expression returns a non-@code{nil} value, which
5745 is the value to which it sets the variable @code{buffer}---and this
5746 value is a buffer itself, not the name of a buffer.
5747
5748 The result of all this is that the symbol @code{buffer} is always
5749 bound to a buffer itself rather than to the name of a buffer. All
5750 this is necessary because the @code{set-buffer} function in a
5751 following line only works with a buffer itself, not with the name to a
5752 buffer.
5753
5754 @need 1250
5755 Incidentally, using @code{or}, the situation with the usher would be
5756 written like this:
5757
5758 @smallexample
5759 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5760 @end smallexample
5761
5762 @node Insert let, , Insert or, insert-buffer
5763 @comment node-name, next, previous, up
5764 @subsection The @code{let} Expression in @code{insert-buffer}
5765
5766 After ensuring that the variable @code{buffer} refers to a buffer itself
5767 and not just to the name of a buffer, the @code{insert-buffer function}
5768 continues with a @code{let} expression. This specifies three local
5769 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5770 to the initial value @code{nil}. These variables are used inside the
5771 remainder of the @code{let} and temporarily hide any other occurrence of
5772 variables of the same name in Emacs until the end of the @code{let}.
5773
5774 @need 1200
5775 The body of the @code{let} contains two @code{save-excursion}
5776 expressions. First, we will look at the inner @code{save-excursion}
5777 expression in detail. The expression looks like this:
5778
5779 @smallexample
5780 @group
5781 (save-excursion
5782 (set-buffer buffer)
5783 (setq start (point-min) end (point-max)))
5784 @end group
5785 @end smallexample
5786
5787 @noindent
5788 The expression @code{(set-buffer buffer)} changes Emacs' attention
5789 from the current buffer to the one from which the text will copied.
5790 In that buffer, the variables @code{start} and @code{end} are set to
5791 the beginning and end of the buffer, using the commands
5792 @code{point-min} and @code{point-max}. Note that we have here an
5793 illustration of how @code{setq} is able to set two variables in the
5794 same expression. The first argument of @code{setq} is set to the
5795 value of its second, and its third argument is set to the value of its
5796 fourth.
5797
5798 After the body of the inner @code{save-excursion} is evaluated, the
5799 @code{save-excursion} restores the original buffer, but @code{start} and
5800 @code{end} remain set to the values of the beginning and end of the
5801 buffer from which the text will be copied.
5802
5803 @need 1250
5804 The outer @code{save-excursion} expression looks like this:
5805
5806 @smallexample
5807 @group
5808 (save-excursion
5809 (@var{inner-}@code{save-excursion}@var{-expression}
5810 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5811 (insert-buffer-substring buffer start end)
5812 (setq newmark (point)))
5813 @end group
5814 @end smallexample
5815
5816 @noindent
5817 The @code{insert-buffer-substring} function copies the text
5818 @emph{into} the current buffer @emph{from} the region indicated by
5819 @code{start} and @code{end} in @code{buffer}. Since the whole of the
5820 second buffer lies between @code{start} and @code{end}, the whole of
5821 the second buffer is copied into the buffer you are editing. Next,
5822 the value of point, which will be at the end of the inserted text, is
5823 recorded in the variable @code{newmark}.
5824
5825 After the body of the outer @code{save-excursion} is evaluated, point
5826 and mark are relocated to their original places.
5827
5828 However, it is convenient to locate a mark at the end of the newly
5829 inserted text and locate point at its beginning. The @code{newmark}
5830 variable records the end of the inserted text. In the last line of
5831 the @code{let} expression, the @code{(push-mark newmark)} expression
5832 function sets a mark to this location. (The previous location of the
5833 mark is still accessible; it is recorded on the mark ring and you can
5834 go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5835 located at the beginning of the inserted text, which is where it was
5836 before you called the insert function.
5837
5838 @need 1250
5839 The whole @code{let} expression looks like this:
5840
5841 @smallexample
5842 @group
5843 (let (start end newmark)
5844 (save-excursion
5845 (save-excursion
5846 (set-buffer buffer)
5847 (setq start (point-min) end (point-max)))
5848 (insert-buffer-substring buffer start end)
5849 (setq newmark (point)))
5850 (push-mark newmark))
5851 @end group
5852 @end smallexample
5853
5854 Like the @code{append-to-buffer} function, the @code{insert-buffer}
5855 function uses @code{let}, @code{save-excursion}, and
5856 @code{set-buffer}. In addition, the function illustrates one way to
5857 use @code{or}. All these functions are building blocks that we will
5858 find and use again and again.
5859
5860 @node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5861 @comment node-name, next, previous, up
5862 @section Complete Definition of @code{beginning-of-buffer}
5863 @findex beginning-of-buffer
5864
5865 The basic structure of the @code{beginning-of-buffer} function has
5866 already been discussed. (@xref{simplified-beginning-of-buffer, , A
5867 Simplified @code{beginning-of-buffer} Definition}.)
5868 This section describes the complex part of the definition.
5869
5870 As previously described, when invoked without an argument,
5871 @code{beginning-of-buffer} moves the cursor to the beginning of the
5872 buffer, leaving the mark at the previous position. However, when the
5873 command is invoked with a number between one and ten, the function
5874 considers that number to be a fraction of the length of the buffer,
5875 measured in tenths, and Emacs moves the cursor that fraction of the way
5876 from the beginning of the buffer. Thus, you can either call this
5877 function with the key command @kbd{M-<}, which will move the cursor to
5878 the beginning of the buffer, or with a key command such as @kbd{C-u 7
5879 M-<} which will move the cursor to a point 70% of the way through the
5880 buffer. If a number bigger than ten is used for the argument, it moves
5881 to the end of the buffer.
5882
5883 The @code{beginning-of-buffer} function can be called with or without an
5884 argument. The use of the argument is optional.
5885
5886 @menu
5887 * Optional Arguments::
5888 * beginning-of-buffer opt arg:: Example with optional argument.
5889 * beginning-of-buffer complete::
5890 @end menu
5891
5892 @node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5893 @subsection Optional Arguments
5894
5895 Unless told otherwise, Lisp expects that a function with an argument in
5896 its function definition will be called with a value for that argument.
5897 If that does not happen, you get an error and a message that says
5898 @samp{Wrong number of arguments}.
5899
5900 @cindex Optional arguments
5901 @cindex Keyword
5902 @findex optional
5903 However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5904 be used to tell the Lisp interpreter that an argument is optional.
5905 The keyword is @code{&optional}. (The @samp{&} in front of
5906 @samp{optional} is part of the keyword.) In a function definition, if
5907 an argument follows the keyword @code{&optional}, a value does not
5908 need to be passed to that argument when the function is called.
5909
5910 @need 1200
5911 The first line of the function definition of @code{beginning-of-buffer}
5912 therefore looks like this:
5913
5914 @smallexample
5915 (defun beginning-of-buffer (&optional arg)
5916 @end smallexample
5917
5918 @need 1250
5919 In outline, the whole function looks like this:
5920
5921 @smallexample
5922 @group
5923 (defun beginning-of-buffer (&optional arg)
5924 "@var{documentation}@dots{}"
5925 (interactive "P")
5926 (push-mark)
5927 (goto-char
5928 (@var{if-there-is-an-argument}
5929 @var{figure-out-where-to-go}
5930 @var{else-go-to}
5931 (point-min))))
5932 @end group
5933 @end smallexample
5934
5935 The function is similar to the @code{simplified-beginning-of-buffer}
5936 function except that the @code{interactive} expression has @code{"P"}
5937 as an argument and the @code{goto-char} function is followed by an
5938 if-then-else expression that figures out where to put the cursor if
5939 there is an argument.
5940
5941 The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5942 a prefix argument, if there is one, to the function. A prefix argument
5943 is made by typing the @key{META} key followed by a number, or by typing
5944 @kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5945 defaults to 4).
5946
5947 The true-or-false-test of the @code{if} expression is simple: it is
5948 simply the argument @code{arg}. If @code{arg} has a value that is not
5949 @code{nil}, which will be the case if @code{beginning-of-buffer} is
5950 called with an argument, then this true-or-false-test will return true
5951 and the then-part of the @code{if} expression will be evaluated. On the
5952 other hand, if @code{beginning-of-buffer} is not called with an
5953 argument, the value of @code{arg} will be @code{nil} and the else-part
5954 of the @code{if} expression will be evaluated. The else-part is simply
5955 @code{point-min}, and when this is the outcome, the whole
5956 @code{goto-char} expression is @code{(goto-char (point-min))}, which is
5957 how we saw the @code{beginning-of-buffer} function in its simplified
5958 form.
5959
5960 @node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5961 @subsection @code{beginning-of-buffer} with an Argument
5962
5963 When @code{beginning-of-buffer} is called with an argument, an
5964 expression is evaluated which calculates what value to pass to
5965 @code{goto-char}. This expression is rather complicated at first sight.
5966 It includes an inner @code{if} expression and much arithmetic. It looks
5967 like this:
5968
5969 @smallexample
5970 @group
5971 (if (> (buffer-size) 10000)
5972 ;; @r{Avoid overflow for large buffer sizes!}
5973 (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5974 (/
5975 (+ 10
5976 (*
5977 (buffer-size) (prefix-numeric-value arg))) 10))
5978 @end group
5979 @end smallexample
5980
5981 @menu
5982 * Disentangle beginning-of-buffer::
5983 * Large buffer case::
5984 * Small buffer case::
5985 @end menu
5986
5987 @node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5988 @ifnottex
5989 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5990 @end ifnottex
5991
5992 Like other complex-looking expressions, the conditional expression
5993 within @code{beginning-of-buffer} can be disentangled by looking at it
5994 as parts of a template, in this case, the template for an if-then-else
5995 expression. In skeletal form, the expression looks like this:
5996
5997 @smallexample
5998 @group
5999 (if (@var{buffer-is-large}
6000 @var{divide-buffer-size-by-10-and-multiply-by-arg}
6001 @var{else-use-alternate-calculation}
6002 @end group
6003 @end smallexample
6004
6005 The true-or-false-test of this inner @code{if} expression checks the
6006 size of the buffer. The reason for this is that the old Version 18
6007 Emacs used numbers that are no bigger than eight million or so
6008 and in the computation that followed, the programmer feared that Emacs
6009 might try to use over-large numbers if the buffer were large. The
6010 term `overflow', mentioned in the comment, means numbers that are over
6011 large. Version 21 Emacs uses larger numbers, but this code has not
6012 been touched, if only because people now look at buffers that are far,
6013 far larger than ever before.
6014
6015 There are two cases: if the buffer is large and if it is not.
6016
6017 @node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
6018 @comment node-name, next, previous, up
6019 @unnumberedsubsubsec What happens in a large buffer
6020
6021 In @code{beginning-of-buffer}, the inner @code{if} expression tests
6022 whether the size of the buffer is greater than 10,000 characters. To do
6023 this, it uses the @code{>} function and the @code{buffer-size} function.
6024
6025 @need 800
6026 The line looks like this:
6027
6028 @smallexample
6029 (if (> (buffer-size) 10000)
6030 @end smallexample
6031
6032 @need 1200
6033 @noindent
6034 When the buffer is large, the then-part of the @code{if} expression is
6035 evaluated. It reads like this (after formatting for easy reading):
6036
6037 @smallexample
6038 @group
6039 (*
6040 (prefix-numeric-value arg)
6041 (/ (buffer-size) 10))
6042 @end group
6043 @end smallexample
6044
6045 @noindent
6046 This expression is a multiplication, with two arguments to the function
6047 @code{*}.
6048
6049 The first argument is @code{(prefix-numeric-value arg)}. When
6050 @code{"P"} is used as the argument for @code{interactive}, the value
6051 passed to the function as its argument is passed a ``raw prefix
6052 argument'', and not a number. (It is a number in a list.) To perform
6053 the arithmetic, a conversion is necessary, and
6054 @code{prefix-numeric-value} does the job.
6055
6056 @findex / @r{(division)}
6057 @cindex Division
6058 The second argument is @code{(/ (buffer-size) 10)}. This expression
6059 divides the numeric value of the buffer by ten. This produces a number
6060 that tells how many characters make up one tenth of the buffer size.
6061 (In Lisp, @code{/} is used for division, just as @code{*} is
6062 used for multiplication.)
6063
6064 @need 1200
6065 In the multiplication expression as a whole, this amount is multiplied
6066 by the value of the prefix argument---the multiplication looks like this:
6067
6068 @smallexample
6069 @group
6070 (* @var{numeric-value-of-prefix-arg}
6071 @var{number-of-characters-in-one-tenth-of-the-buffer})
6072 @end group
6073 @end smallexample
6074
6075 @noindent
6076 If, for example, the prefix argument is @samp{7}, the one-tenth value
6077 will be multiplied by 7 to give a position 70% of the way through the
6078 buffer.
6079
6080 @need 1200
6081 The result of all this is that if the buffer is large, the
6082 @code{goto-char} expression reads like this:
6083
6084 @smallexample
6085 @group
6086 (goto-char (* (prefix-numeric-value arg)
6087 (/ (buffer-size) 10)))
6088 @end group
6089 @end smallexample
6090
6091 This puts the cursor where we want it.
6092
6093 @node Small buffer case, , Large buffer case, beginning-of-buffer opt arg
6094 @comment node-name, next, previous, up
6095 @unnumberedsubsubsec What happens in a small buffer
6096
6097 If the buffer contains fewer than 10,000 characters, a slightly
6098 different computation is performed. You might think this is not
6099 necessary, since the first computation could do the job. However, in
6100 a small buffer, the first method may not put the cursor on exactly the
6101 desired line; the second method does a better job.
6102
6103 @need 800
6104 The code looks like this:
6105
6106 @c Keep this on one line.
6107 @smallexample
6108 (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6109 @end smallexample
6110
6111 @need 1200
6112 @noindent
6113 This is code in which you figure out what happens by discovering how the
6114 functions are embedded in parentheses. It is easier to read if you
6115 reformat it with each expression indented more deeply than its
6116 enclosing expression:
6117
6118 @smallexample
6119 @group
6120 (/
6121 (+ 10
6122 (*
6123 (buffer-size)
6124 (prefix-numeric-value arg)))
6125 10))
6126 @end group
6127 @end smallexample
6128
6129 @need 1200
6130 @noindent
6131 Looking at parentheses, we see that the innermost operation is
6132 @code{(prefix-numeric-value arg)}, which converts the raw argument to a
6133 number. This number is multiplied by the buffer size in the following
6134 expression:
6135
6136 @smallexample
6137 (* (buffer-size) (prefix-numeric-value arg)
6138 @end smallexample
6139
6140 @noindent
6141 This multiplication creates a number that may be larger than the size of
6142 the buffer---seven times larger if the argument is 7, for example. Ten
6143 is then added to this number and finally the large number is divided by
6144 ten to provide a value that is one character larger than the percentage
6145 position in the buffer.
6146
6147 The number that results from all this is passed to @code{goto-char} and
6148 the cursor is moved to that point.
6149
6150 @node beginning-of-buffer complete, , beginning-of-buffer opt arg, beginning-of-buffer
6151 @comment node-name, next, previous, up
6152 @subsection The Complete @code{beginning-of-buffer}
6153
6154 @need 800
6155 Here is the complete text of the @code{beginning-of-buffer} function:
6156
6157 @smallexample
6158 @group
6159 (defun beginning-of-buffer (&optional arg)
6160 "Move point to the beginning of the buffer;
6161 leave mark at previous position.
6162 With arg N, put point N/10 of the way
6163 from the true beginning.
6164 Don't use this in Lisp programs!
6165 \(goto-char (point-min)) is faster
6166 and does not set the mark."
6167 (interactive "P")
6168 (push-mark)
6169 @end group
6170 @group
6171 (goto-char
6172 (if arg
6173 (if (> (buffer-size) 10000)
6174 ;; @r{Avoid overflow for large buffer sizes!}
6175 (* (prefix-numeric-value arg)
6176 (/ (buffer-size) 10))
6177 @end group
6178 @group
6179 (/ (+ 10 (* (buffer-size)
6180 (prefix-numeric-value arg)))
6181 10))
6182 (point-min)))
6183 (if arg (forward-line 1)))
6184 @end group
6185 @end smallexample
6186
6187 @noindent
6188 Except for two small points, the previous discussion shows how this
6189 function works. The first point deals with a detail in the
6190 documentation string, and the second point concerns the last line of
6191 the function.
6192
6193 @need 800
6194 In the documentation string, there is reference to an expression:
6195
6196 @smallexample
6197 \(goto-char (point-min))
6198 @end smallexample
6199
6200 @noindent
6201 A @samp{\} is used before the first parenthesis of this expression.
6202 This @samp{\} tells the Lisp interpreter that the expression should be
6203 printed as shown in the documentation rather than evaluated as a
6204 symbolic expression, which is what it looks like.
6205
6206 @need 1200
6207 Finally, the last line of the @code{beginning-of-buffer} command says to
6208 move point to the beginning of the next line if the command is
6209 invoked with an argument:
6210
6211 @smallexample
6212 (if arg (forward-line 1)))
6213 @end smallexample
6214
6215 @noindent
6216 This puts the cursor at the beginning of the first line after the
6217 appropriate tenths position in the buffer. This is a flourish that
6218 means that the cursor is always located @emph{at least} the requested
6219 tenths of the way through the buffer, which is a nicety that is,
6220 perhaps, not necessary, but which, if it did not occur, would be sure to
6221 draw complaints.
6222
6223 @node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6224 @comment node-name, next, previous, up
6225 @section Review
6226
6227 Here is a brief summary of some of the topics covered in this chapter.
6228
6229 @table @code
6230 @item or
6231 Evaluate each argument in sequence, and return the value of the first
6232 argument that is not @code{nil}; if none return a value that is not
6233 @code{nil}, return @code{nil}. In brief, return the first true value
6234 of the arguments; return a true value if one @emph{or} any of the
6235 other are true.
6236
6237 @item and
6238 Evaluate each argument in sequence, and if any are @code{nil}, return
6239 @code{nil}; if none are @code{nil}, return the value of the last
6240 argument. In brief, return a true value only if all the arguments are
6241 true; return a true value if one @emph{and} each of the others is
6242 true.
6243
6244 @item &optional
6245 A keyword used to indicate that an argument to a function definition
6246 is optional; this means that the function can be evaluated without the
6247 argument, if desired.
6248
6249 @item prefix-numeric-value
6250 Convert the `raw prefix argument' produced by @code{(interactive
6251 "P")} to a numeric value.
6252
6253 @item forward-line
6254 Move point forward to the beginning of the next line, or if the argument
6255 is greater than one, forward that many lines. If it can't move as far
6256 forward as it is supposed to, @code{forward-line} goes forward as far as
6257 it can and then returns a count of the number of additional lines it was
6258 supposed to move but couldn't.
6259
6260 @item erase-buffer
6261 Delete the entire contents of the current buffer.
6262
6263 @item bufferp
6264 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6265 @end table
6266
6267 @node optional Exercise, , Second Buffer Related Review, More Complex
6268 @section @code{optional} Argument Exercise
6269
6270 Write an interactive function with an optional argument that tests
6271 whether its argument, a number, is greater or less than the value of
6272 @code{fill-column}, and tells you which, in a message. However, if you
6273 do not pass an argument to the function, use 56 as a default value.
6274
6275 @node Narrowing & Widening, car cdr & cons, More Complex, Top
6276 @comment node-name, next, previous, up
6277 @chapter Narrowing and Widening
6278 @cindex Focusing attention (narrowing)
6279 @cindex Narrowing
6280 @cindex Widening
6281
6282 Narrowing is a feature of Emacs that makes it possible for you to focus
6283 on a specific part of a buffer, and work without accidentally changing
6284 other parts. Narrowing is normally disabled since it can confuse
6285 novices.
6286
6287 @menu
6288 * Narrowing advantages:: The advantages of narrowing
6289 * save-restriction:: The @code{save-restriction} special form.
6290 * what-line:: The number of the line that point is on.
6291 * narrow Exercise::
6292 @end menu
6293
6294 @node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6295 @ifnottex
6296 @unnumberedsec The Advantages of Narrowing
6297 @end ifnottex
6298
6299 With narrowing, the rest of a buffer is made invisible, as if it weren't
6300 there. This is an advantage if, for example, you want to replace a word
6301 in one part of a buffer but not in another: you narrow to the part you want
6302 and the replacement is carried out only in that section, not in the rest
6303 of the buffer. Searches will only work within a narrowed region, not
6304 outside of one, so if you are fixing a part of a document, you can keep
6305 yourself from accidentally finding parts you do not need to fix by
6306 narrowing just to the region you want.
6307 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6308
6309 However, narrowing does make the rest of the buffer invisible, which
6310 can scare people who inadvertently invoke narrowing and think they
6311 have deleted a part of their file. Moreover, the @code{undo} command
6312 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6313 (nor should it), so people can become quite desperate if they do not
6314 know that they can return the rest of a buffer to visibility with the
6315 @code{widen} command.
6316 (The key binding for @code{widen} is @kbd{C-x n w}.)
6317
6318 Narrowing is just as useful to the Lisp interpreter as to a human.
6319 Often, an Emacs Lisp function is designed to work on just part of a
6320 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6321 buffer that has been narrowed. The @code{what-line} function, for
6322 example, removes the narrowing from a buffer, if it has any narrowing
6323 and when it has finished its job, restores the narrowing to what it was.
6324 On the other hand, the @code{count-lines} function, which is called by
6325 @code{what-line}, uses narrowing to restrict itself to just that portion
6326 of the buffer in which it is interested and then restores the previous
6327 situation.
6328
6329 @node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6330 @comment node-name, next, previous, up
6331 @section The @code{save-restriction} Special Form
6332 @findex save-restriction
6333
6334 In Emacs Lisp, you can use the @code{save-restriction} special form to
6335 keep track of whatever narrowing is in effect, if any. When the Lisp
6336 interpreter meets with @code{save-restriction}, it executes the code
6337 in the body of the @code{save-restriction} expression, and then undoes
6338 any changes to narrowing that the code caused. If, for example, the
6339 buffer is narrowed and the code that follows @code{save-restriction}
6340 gets rid of the narrowing, @code{save-restriction} returns the buffer
6341 to its narrowed region afterwards. In the @code{what-line} command,
6342 any narrowing the buffer may have is undone by the @code{widen}
6343 command that immediately follows the @code{save-restriction} command.
6344 Any original narrowing is restored just before the completion of the
6345 function.
6346
6347 @need 1250
6348 The template for a @code{save-restriction} expression is simple:
6349
6350 @smallexample
6351 @group
6352 (save-restriction
6353 @var{body}@dots{} )
6354 @end group
6355 @end smallexample
6356
6357 @noindent
6358 The body of the @code{save-restriction} is one or more expressions that
6359 will be evaluated in sequence by the Lisp interpreter.
6360
6361 Finally, a point to note: when you use both @code{save-excursion} and
6362 @code{save-restriction}, one right after the other, you should use
6363 @code{save-excursion} outermost. If you write them in reverse order,
6364 you may fail to record narrowing in the buffer to which Emacs switches
6365 after calling @code{save-excursion}. Thus, when written together,
6366 @code{save-excursion} and @code{save-restriction} should be written
6367 like this:
6368
6369 @smallexample
6370 @group
6371 (save-excursion
6372 (save-restriction
6373 @var{body}@dots{}))
6374 @end group
6375 @end smallexample
6376
6377 In other circumstances, when not written together, the
6378 @code{save-excursion} and @code{save-restriction} special forms must
6379 be written in the order appropriate to the function.
6380
6381 @need 1250
6382 For example,
6383
6384 @smallexample
6385 @group
6386 (save-restriction
6387 (widen)
6388 (save-excursion
6389 @var{body}@dots{}))
6390 @end group
6391 @end smallexample
6392
6393 @node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6394 @comment node-name, next, previous, up
6395 @section @code{what-line}
6396 @findex what-line
6397 @cindex Widening, example of
6398
6399 The @code{what-line} command tells you the number of the line in which
6400 the cursor is located. The function illustrates the use of the
6401 @code{save-restriction} and @code{save-excursion} commands. Here is the
6402 text of the function in full:
6403
6404 @smallexample
6405 @group
6406 (defun what-line ()
6407 "Print the current line number (in the buffer) of point."
6408 (interactive)
6409 (save-restriction
6410 (widen)
6411 (save-excursion
6412 (beginning-of-line)
6413 (message "Line %d"
6414 (1+ (count-lines 1 (point)))))))
6415 @end group
6416 @end smallexample
6417
6418 The function has a documentation line and is interactive, as you would
6419 expect. The next two lines use the functions @code{save-restriction} and
6420 @code{widen}.
6421
6422 The @code{save-restriction} special form notes whatever narrowing is in
6423 effect, if any, in the current buffer and restores that narrowing after
6424 the code in the body of the @code{save-restriction} has been evaluated.
6425
6426 The @code{save-restriction} special form is followed by @code{widen}.
6427 This function undoes any narrowing the current buffer may have had
6428 when @code{what-line} was called. (The narrowing that was there is
6429 the narrowing that @code{save-restriction} remembers.) This widening
6430 makes it possible for the line counting commands to count from the
6431 beginning of the buffer. Otherwise, they would have been limited to
6432 counting within the accessible region. Any original narrowing is
6433 restored just before the completion of the function by the
6434 @code{save-restriction} special form.
6435
6436 The call to @code{widen} is followed by @code{save-excursion}, which
6437 saves the location of the cursor (i.e., of point) and of the mark, and
6438 restores them after the code in the body of the @code{save-excursion}
6439 uses the @code{beginning-of-line} function to move point.
6440
6441 (Note that the @code{(widen)} expression comes between the
6442 @code{save-restriction} and @code{save-excursion} special forms. When
6443 you write the two @code{save- @dots{}} expressions in sequence, write
6444 @code{save-excursion} outermost.)
6445
6446 @need 1200
6447 The last two lines of the @code{what-line} function are functions to
6448 count the number of lines in the buffer and then print the number in the
6449 echo area.
6450
6451 @smallexample
6452 @group
6453 (message "Line %d"
6454 (1+ (count-lines 1 (point)))))))
6455 @end group
6456 @end smallexample
6457
6458 The @code{message} function prints a one-line message at the bottom of the
6459 Emacs screen. The first argument is inside of quotation marks and is
6460 printed as a string of characters. However, it may contain @samp{%d},
6461 @samp{%s}, or @samp{%c} to print arguments that follow the string.
6462 @samp{%d} prints the argument as a decimal, so the message will say
6463 something such as @samp{Line 243}.
6464
6465 @need 1200
6466 The number that is printed in place of the @samp{%d} is computed by the
6467 last line of the function:
6468
6469 @smallexample
6470 (1+ (count-lines 1 (point)))
6471 @end smallexample
6472
6473 @noindent
6474 What this does is count the lines from the first position of the
6475 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6476 one to that number. (The @code{1+} function adds one to its
6477 argument.) We add one to it because line 2 has only one line before
6478 it, and @code{count-lines} counts only the lines @emph{before} the
6479 current line.
6480
6481 After @code{count-lines} has done its job, and the message has been
6482 printed in the echo area, the @code{save-excursion} restores point and
6483 mark to their original positions; and @code{save-restriction} restores
6484 the original narrowing, if any.
6485
6486 @node narrow Exercise, , what-line, Narrowing & Widening
6487 @section Exercise with Narrowing
6488
6489 Write a function that will display the first 60 characters of the
6490 current buffer, even if you have narrowed the buffer to its latter
6491 half so that the first line is inaccessible. Restore point, mark,
6492 and narrowing. For this exercise, you need to use
6493 @code{save-restriction}, @code{widen}, @code{goto-char},
6494 @code{point-min}, @code{buffer-substring}, @code{message}, and other
6495 functions, a whole potpourri.
6496
6497 @node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6498 @comment node-name, next, previous, up
6499 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6500 @findex car, @r{introduced}
6501 @findex cdr, @r{introduced}
6502
6503 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6504 functions. The @code{cons} function is used to construct lists, and
6505 the @code{car} and @code{cdr} functions are used to take them apart.
6506
6507 In the walk through of the @code{copy-region-as-kill} function, we
6508 will see @code{cons} as well as two variants on @code{cdr},
6509 namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6510
6511 @menu
6512 * Strange Names:: An historical aside: why the strange names?
6513 * car & cdr:: Functions for extracting part of a list.
6514 * cons:: Constructing a list.
6515 * nthcdr:: Calling @code{cdr} repeatedly.
6516 * nth::
6517 * setcar:: Changing the first element of a list.
6518 * setcdr:: Changing the rest of a list.
6519 * cons Exercise::
6520 @end menu
6521
6522 @node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6523 @ifnottex
6524 @unnumberedsec Strange Names
6525 @end ifnottex
6526
6527 The name of the @code{cons} function is not unreasonable: it is an
6528 abbreviation of the word `construct'. The origins of the names for
6529 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6530 is an acronym from the phrase `Contents of the Address part of the
6531 Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6532 the phrase `Contents of the Decrement part of the Register'. These
6533 phrases refer to specific pieces of hardware on the very early
6534 computer on which the original Lisp was developed. Besides being
6535 obsolete, the phrases have been completely irrelevant for more than 25
6536 years to anyone thinking about Lisp. Nonetheless, although a few
6537 brave scholars have begun to use more reasonable names for these
6538 functions, the old terms are still in use. In particular, since the
6539 terms are used in the Emacs Lisp source code, we will use them in this
6540 introduction.
6541
6542 @node car & cdr, cons, Strange Names, car cdr & cons
6543 @comment node-name, next, previous, up
6544 @section @code{car} and @code{cdr}
6545
6546 The @sc{car} of a list is, quite simply, the first item in the list.
6547 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6548 @code{rose}.
6549
6550 @need 1200
6551 If you are reading this in Info in GNU Emacs, you can see this by
6552 evaluating the following:
6553
6554 @smallexample
6555 (car '(rose violet daisy buttercup))
6556 @end smallexample
6557
6558 @noindent
6559 After evaluating the expression, @code{rose} will appear in the echo
6560 area.
6561
6562 Clearly, a more reasonable name for the @code{car} function would be
6563 @code{first} and this is often suggested.
6564
6565 @code{car} does not remove the first item from the list; it only reports
6566 what it is. After @code{car} has been applied to a list, the list is
6567 still the same as it was. In the jargon, @code{car} is
6568 `non-destructive'. This feature turns out to be important.
6569
6570 The @sc{cdr} of a list is the rest of the list, that is, the
6571 @code{cdr} function returns the part of the list that follows the
6572 first item. Thus, while the @sc{car} of the list @code{'(rose violet
6573 daisy buttercup)} is @code{rose}, the rest of the list, the value
6574 returned by the @code{cdr} function, is @code{(violet daisy
6575 buttercup)}.
6576
6577 @need 1250
6578 You can see this by evaluating the following in the usual way:
6579
6580 @smallexample
6581 (cdr '(rose violet daisy buttercup))
6582 @end smallexample
6583
6584 @noindent
6585 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6586 the echo area.
6587
6588 Like @code{car}, @code{cdr} does not remove any elements from the
6589 list---it just returns a report of what the second and subsequent
6590 elements are.
6591
6592 Incidentally, in the example, the list of flowers is quoted. If it were
6593 not, the Lisp interpreter would try to evaluate the list by calling
6594 @code{rose} as a function. In this example, we do not want to do that.
6595
6596 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6597
6598 (There is a lesson here: when you name new functions, consider very
6599 carefully what you are doing, since you may be stuck with the names
6600 for far longer than you expect. The reason this document perpetuates
6601 these names is that the Emacs Lisp source code uses them, and if I did
6602 not use them, you would have a hard time reading the code; but do,
6603 please, try to avoid using these terms yourself. The people who come
6604 after you will be grateful to you.)
6605
6606 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6607 such as the list @code{(pine fir oak maple)}, the element of the list
6608 returned by the function @code{car} is the symbol @code{pine} without
6609 any parentheses around it. @code{pine} is the first element in the
6610 list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6611 oak maple)}, as you can see by evaluating the following expressions in
6612 the usual way:
6613
6614 @smallexample
6615 @group
6616 (car '(pine fir oak maple))
6617
6618 (cdr '(pine fir oak maple))
6619 @end group
6620 @end smallexample
6621
6622 On the other hand, in a list of lists, the first element is itself a
6623 list. @code{car} returns this first element as a list. For example,
6624 the following list contains three sub-lists, a list of carnivores, a
6625 list of herbivores and a list of sea mammals:
6626
6627 @smallexample
6628 @group
6629 (car '((lion tiger cheetah)
6630 (gazelle antelope zebra)
6631 (whale dolphin seal)))
6632 @end group
6633 @end smallexample
6634
6635 @noindent
6636 In this example, the first element or @sc{car} of the list is the list of
6637 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6638 @code{((gazelle antelope zebra) (whale dolphin seal))}.
6639
6640 @smallexample
6641 @group
6642 (cdr '((lion tiger cheetah)
6643 (gazelle antelope zebra)
6644 (whale dolphin seal)))
6645 @end group
6646 @end smallexample
6647
6648 It is worth saying again that @code{car} and @code{cdr} are
6649 non-destructive---that is, they do not modify or change lists to which
6650 they are applied. This is very important for how they are used.
6651
6652 Also, in the first chapter, in the discussion about atoms, I said that
6653 in Lisp, ``certain kinds of atom, such as an array, can be separated
6654 into parts; but the mechanism for doing this is different from the
6655 mechanism for splitting a list. As far as Lisp is concerned, the
6656 atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
6657 @code{car} and @code{cdr} functions are used for splitting lists and
6658 are considered fundamental to Lisp. Since they cannot split or gain
6659 access to the parts of an array, an array is considered an atom.
6660 Conversely, the other fundamental function, @code{cons}, can put
6661 together or construct a list, but not an array. (Arrays are handled
6662 by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
6663 Emacs Lisp Reference Manual}.)
6664
6665 @node cons, nthcdr, car & cdr, car cdr & cons
6666 @comment node-name, next, previous, up
6667 @section @code{cons}
6668 @findex cons, @r{introduced}
6669
6670 The @code{cons} function constructs lists; it is the inverse of
6671 @code{car} and @code{cdr}. For example, @code{cons} can be used to make
6672 a four element list from the three element list, @code{(fir oak maple)}:
6673
6674 @smallexample
6675 (cons 'pine '(fir oak maple))
6676 @end smallexample
6677
6678 @need 800
6679 @noindent
6680 After evaluating this list, you will see
6681
6682 @smallexample
6683 (pine fir oak maple)
6684 @end smallexample
6685
6686 @noindent
6687 appear in the echo area. @code{cons} puts a new element at the
6688 beginning of a list; it attaches or pushes elements onto the list.
6689
6690 @menu
6691 * Build a list::
6692 * length:: How to find the length of a list.
6693 @end menu
6694
6695 @node Build a list, length, cons, cons
6696 @ifnottex
6697 @unnumberedsubsec Build a list
6698 @end ifnottex
6699
6700 @code{cons} must have a list to attach to.@footnote{Actually, you can
6701 @code{cons} an element to an atom to produce a dotted pair. Dotted
6702 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6703 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
6704 cannot start from absolutely nothing. If you are building a list, you
6705 need to provide at least an empty list at the beginning. Here is a
6706 series of @code{cons} expressions that build up a list of flowers. If
6707 you are reading this in Info in GNU Emacs, you can evaluate each of
6708 the expressions in the usual way; the value is printed in this text
6709 after @samp{@result{}}, which you may read as `evaluates to'.
6710
6711 @smallexample
6712 @group
6713 (cons 'buttercup ())
6714 @result{} (buttercup)
6715 @end group
6716
6717 @group
6718 (cons 'daisy '(buttercup))
6719 @result{} (daisy buttercup)
6720 @end group
6721
6722 @group
6723 (cons 'violet '(daisy buttercup))
6724 @result{} (violet daisy buttercup)
6725 @end group
6726
6727 @group
6728 (cons 'rose '(violet daisy buttercup))
6729 @result{} (rose violet daisy buttercup)
6730 @end group
6731 @end smallexample
6732
6733 @noindent
6734 In the first example, the empty list is shown as @code{()} and a list
6735 made up of @code{buttercup} followed by the empty list is constructed.
6736 As you can see, the empty list is not shown in the list that was
6737 constructed. All that you see is @code{(buttercup)}. The empty list is
6738 not counted as an element of a list because there is nothing in an empty
6739 list. Generally speaking, an empty list is invisible.
6740
6741 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6742 two element list by putting @code{daisy} in front of @code{buttercup};
6743 and the third example constructs a three element list by putting
6744 @code{violet} in front of @code{daisy} and @code{buttercup}.
6745
6746 @node length, , Build a list, cons
6747 @comment node-name, next, previous, up
6748 @subsection Find the Length of a List: @code{length}
6749 @findex length
6750
6751 You can find out how many elements there are in a list by using the Lisp
6752 function @code{length}, as in the following examples:
6753
6754 @smallexample
6755 @group
6756 (length '(buttercup))
6757 @result{} 1
6758 @end group
6759
6760 @group
6761 (length '(daisy buttercup))
6762 @result{} 2
6763 @end group
6764
6765 @group
6766 (length (cons 'violet '(daisy buttercup)))
6767 @result{} 3
6768 @end group
6769 @end smallexample
6770
6771 @noindent
6772 In the third example, the @code{cons} function is used to construct a
6773 three element list which is then passed to the @code{length} function as
6774 its argument.
6775
6776 @need 1200
6777 We can also use @code{length} to count the number of elements in an
6778 empty list:
6779
6780 @smallexample
6781 @group
6782 (length ())
6783 @result{} 0
6784 @end group
6785 @end smallexample
6786
6787 @noindent
6788 As you would expect, the number of elements in an empty list is zero.
6789
6790 An interesting experiment is to find out what happens if you try to find
6791 the length of no list at all; that is, if you try to call @code{length}
6792 without giving it an argument, not even an empty list:
6793
6794 @smallexample
6795 (length )
6796 @end smallexample
6797
6798 @need 800
6799 @noindent
6800 What you see, if you evaluate this, is the error message
6801
6802 @smallexample
6803 Wrong number of arguments: #<subr length>, 0
6804 @end smallexample
6805
6806 @noindent
6807 This means that the function receives the wrong number of
6808 arguments, zero, when it expects some other number of arguments. In
6809 this case, one argument is expected, the argument being a list whose
6810 length the function is measuring. (Note that @emph{one} list is
6811 @emph{one} argument, even if the list has many elements inside it.)
6812
6813 The part of the error message that says @samp{#<subr length>} is the
6814 name of the function. This is written with a special notation,
6815 @samp{#<subr}, that indicates that the function @code{length} is one
6816 of the primitive functions written in C rather than in Emacs Lisp.
6817 (@samp{subr} is an abbreviation for `subroutine'.) @xref{What Is a
6818 Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6819 Manual}, for more about subroutines.
6820
6821 @node nthcdr, nth, cons, car cdr & cons
6822 @comment node-name, next, previous, up
6823 @section @code{nthcdr}
6824 @findex nthcdr
6825
6826 The @code{nthcdr} function is associated with the @code{cdr} function.
6827 What it does is take the @sc{cdr} of a list repeatedly.
6828
6829 If you take the @sc{cdr} of the list @code{(pine fir
6830 oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
6831 repeat this on what was returned, you will be returned the list
6832 @code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
6833 list will just give you the original @sc{cdr} since the function does
6834 not change the list. You need to evaluate the @sc{cdr} of the
6835 @sc{cdr} and so on.) If you continue this, eventually you will be
6836 returned an empty list, which in this case, instead of being shown as
6837 @code{()} is shown as @code{nil}.
6838
6839 @need 1200
6840 For review, here is a series of repeated @sc{cdr}s, the text following
6841 the @samp{@result{}} shows what is returned.
6842
6843 @smallexample
6844 @group
6845 (cdr '(pine fir oak maple))
6846 @result{}(fir oak maple)
6847 @end group
6848
6849 @group
6850 (cdr '(fir oak maple))
6851 @result{} (oak maple)
6852 @end group
6853
6854 @group
6855 (cdr '(oak maple))
6856 @result{}(maple)
6857 @end group
6858
6859 @group
6860 (cdr '(maple))
6861 @result{} nil
6862 @end group
6863
6864 @group
6865 (cdr 'nil)
6866 @result{} nil
6867 @end group
6868
6869 @group
6870 (cdr ())
6871 @result{} nil
6872 @end group
6873 @end smallexample
6874
6875 @need 1200
6876 You can also do several @sc{cdr}s without printing the values in
6877 between, like this:
6878
6879 @smallexample
6880 @group
6881 (cdr (cdr '(pine fir oak maple)))
6882 @result{} (oak maple)
6883 @end group
6884 @end smallexample
6885
6886 @noindent
6887 In this example, the Lisp interpreter evaluates the innermost list first.
6888 The innermost list is quoted, so it just passes the list as it is to the
6889 innermost @code{cdr}. This @code{cdr} passes a list made up of the
6890 second and subsequent elements of the list to the outermost @code{cdr},
6891 which produces a list composed of the third and subsequent elements of
6892 the original list. In this example, the @code{cdr} function is repeated
6893 and returns a list that consists of the original list without its
6894 first two elements.
6895
6896 The @code{nthcdr} function does the same as repeating the call to
6897 @code{cdr}. In the following example, the argument 2 is passed to the
6898 function @code{nthcdr}, along with the list, and the value returned is
6899 the list without its first two items, which is exactly the same
6900 as repeating @code{cdr} twice on the list:
6901
6902 @smallexample
6903 @group
6904 (nthcdr 2 '(pine fir oak maple))
6905 @result{} (oak maple)
6906 @end group
6907 @end smallexample
6908
6909 @need 1200
6910 Using the original four element list, we can see what happens when
6911 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6912 and 5:
6913
6914 @smallexample
6915 @group
6916 ;; @r{Leave the list as it was.}
6917 (nthcdr 0 '(pine fir oak maple))
6918 @result{} (pine fir oak maple)
6919 @end group
6920
6921 @group
6922 ;; @r{Return a copy without the first element.}
6923 (nthcdr 1 '(pine fir oak maple))
6924 @result{} (fir oak maple)
6925 @end group
6926
6927 @group
6928 ;; @r{Return a copy of the list without three elements.}
6929 (nthcdr 3 '(pine fir oak maple))
6930 @result{} (maple)
6931 @end group
6932
6933 @group
6934 ;; @r{Return a copy lacking all four elements.}
6935 (nthcdr 4 '(pine fir oak maple))
6936 @result{} nil
6937 @end group
6938
6939 @group
6940 ;; @r{Return a copy lacking all elements.}
6941 (nthcdr 5 '(pine fir oak maple))
6942 @result{} nil
6943 @end group
6944 @end smallexample
6945
6946 @node nth, setcar, nthcdr, car cdr & cons
6947 @comment node-name, next, previous, up
6948 @section @code{nth}
6949 @findex nth
6950
6951 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6952 The @code{nth} function takes the @sc{car} of the result returned by
6953 @code{nthcdr}. It returns the Nth element of the list.
6954
6955 @need 1500
6956 Thus, if it were not defined in C for speed, the definition of
6957 @code{nth} would be:
6958
6959 @smallexample
6960 @group
6961 (defun nth (n list)
6962 "Returns the Nth element of LIST.
6963 N counts from zero. If LIST is not that long, nil is returned."
6964 (car (nthcdr n list)))
6965 @end group
6966 @end smallexample
6967
6968 @noindent
6969 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6970 but its definition was redone in C in the 1980s.)
6971
6972 The @code{nth} function returns a single element of a list.
6973 This can be very convenient.
6974
6975 Note that the elements are numbered from zero, not one. That is to
6976 say, the first element of a list, its @sc{car} is the zeroth element.
6977 This is called `zero-based' counting and often bothers people who
6978 are accustomed to the first element in a list being number one, which
6979 is `one-based'.
6980
6981 @need 1250
6982 For example:
6983
6984 @smallexample
6985 @group
6986 (nth 0 '("one" "two" "three"))
6987 @result{} "one"
6988
6989 (nth 1 '("one" "two" "three"))
6990 @result{} "two"
6991 @end group
6992 @end smallexample
6993
6994 It is worth mentioning that @code{nth}, like @code{nthcdr} and
6995 @code{cdr}, does not change the original list---the function is
6996 non-destructive. This is in sharp contrast to the @code{setcar} and
6997 @code{setcdr} functions.
6998
6999 @node setcar, setcdr, nth, car cdr & cons
7000 @comment node-name, next, previous, up
7001 @section @code{setcar}
7002 @findex setcar
7003
7004 As you might guess from their names, the @code{setcar} and @code{setcdr}
7005 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7006 They actually change the original list, unlike @code{car} and @code{cdr}
7007 which leave the original list as it was. One way to find out how this
7008 works is to experiment. We will start with the @code{setcar} function.
7009
7010 @need 1200
7011 First, we can make a list and then set the value of a variable to the
7012 list, using the @code{setq} function. Here is a list of animals:
7013
7014 @smallexample
7015 (setq animals '(antelope giraffe lion tiger))
7016 @end smallexample
7017
7018 @noindent
7019 If you are reading this in Info inside of GNU Emacs, you can evaluate
7020 this expression in the usual fashion, by positioning the cursor after
7021 the expression and typing @kbd{C-x C-e}. (I'm doing this right here as
7022 I write this. This is one of the advantages of having the interpreter
7023 built into the computing environment.)
7024
7025 @need 1200
7026 When we evaluate the variable @code{animals}, we see that it is bound to
7027 the list @code{(antelope giraffe lion tiger)}:
7028
7029 @smallexample
7030 @group
7031 animals
7032 @result{} (antelope giraffe lion tiger)
7033 @end group
7034 @end smallexample
7035
7036 @noindent
7037 Put another way, the variable @code{animals} points to the list
7038 @code{(antelope giraffe lion tiger)}.
7039
7040 Next, evaluate the function @code{setcar} while passing it two
7041 arguments, the variable @code{animals} and the quoted symbol
7042 @code{hippopotamus}; this is done by writing the three element list
7043 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7044 usual fashion:
7045
7046 @smallexample
7047 (setcar animals 'hippopotamus)
7048 @end smallexample
7049
7050 @need 1200
7051 @noindent
7052 After evaluating this expression, evaluate the variable @code{animals}
7053 again. You will see that the list of animals has changed:
7054
7055 @smallexample
7056 @group
7057 animals
7058 @result{} (hippopotamus giraffe lion tiger)
7059 @end group
7060 @end smallexample
7061
7062 @noindent
7063 The first element on the list, @code{antelope} is replaced by
7064 @code{hippopotamus}.
7065
7066 So we can see that @code{setcar} did not add a new element to the list
7067 as @code{cons} would have; it replaced @code{giraffe} with
7068 @code{hippopotamus}; it @emph{changed} the list.
7069
7070 @node setcdr, cons Exercise, setcar, car cdr & cons
7071 @comment node-name, next, previous, up
7072 @section @code{setcdr}
7073 @findex setcdr
7074
7075 The @code{setcdr} function is similar to the @code{setcar} function,
7076 except that the function replaces the second and subsequent elements of
7077 a list rather than the first element.
7078
7079 @need 1200
7080 To see how this works, set the value of the variable to a list of
7081 domesticated animals by evaluating the following expression:
7082
7083 @smallexample
7084 (setq domesticated-animals '(horse cow sheep goat))
7085 @end smallexample
7086
7087 @need 1200
7088 @noindent
7089 If you now evaluate the list, you will be returned the list
7090 @code{(horse cow sheep goat)}:
7091
7092 @smallexample
7093 @group
7094 domesticated-animals
7095 @result{} (horse cow sheep goat)
7096 @end group
7097 @end smallexample
7098
7099 @need 1200
7100 Next, evaluate @code{setcdr} with two arguments, the name of the
7101 variable which has a list as its value, and the list to which the
7102 @sc{cdr} of the first list will be set;
7103
7104 @smallexample
7105 (setcdr domesticated-animals '(cat dog))
7106 @end smallexample
7107
7108 @noindent
7109 If you evaluate this expression, the list @code{(cat dog)} will appear
7110 in the echo area. This is the value returned by the function. The
7111 result we are interested in is the ``side effect'', which we can see by
7112 evaluating the variable @code{domesticated-animals}:
7113
7114 @smallexample
7115 @group
7116 domesticated-animals
7117 @result{} (horse cat dog)
7118 @end group
7119 @end smallexample
7120
7121 @noindent
7122 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7123 @code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7124 @code{(cow sheep goat)} to @code{(cat dog)}.
7125
7126 @node cons Exercise, , setcdr, car cdr & cons
7127 @section Exercise
7128
7129 Construct a list of four birds by evaluating several expressions with
7130 @code{cons}. Find out what happens when you @code{cons} a list onto
7131 itself. Replace the first element of the list of four birds with a
7132 fish. Replace the rest of that list with a list of other fish.
7133 @node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7134 @comment node-name, next, previous, up
7135 @chapter Cutting and Storing Text
7136 @cindex Cutting and storing text
7137 @cindex Storing and cutting text
7138 @cindex Killing text
7139 @cindex Clipping text
7140 @cindex Erasing text
7141 @cindex Deleting text
7142
7143 Whenever you cut or clip text out of a buffer with a `kill' command in
7144 GNU Emacs, it is stored in a list and you can bring it back with a
7145 `yank' command.
7146
7147 (The use of the word `kill' in Emacs for processes which specifically
7148 @emph{do not} destroy the values of the entities is an unfortunate
7149 historical accident. A much more appropriate word would be `clip' since
7150 that is what the kill commands do; they clip text out of a buffer and
7151 put it into storage from which it can be brought back. I have often
7152 been tempted to replace globally all occurrences of `kill' in the Emacs
7153 sources with `clip' and all occurrences of `killed' with `clipped'.)
7154
7155 @menu
7156 * Storing Text:: Text is stored in a list.
7157 * zap-to-char:: Cutting out text up to a character.
7158 * kill-region:: Cutting text out of a region.
7159 * Digression into C:: Minor note on C programming language macros.
7160 * defvar:: How to give a variable an initial value.
7161 * copy-region-as-kill:: A definition for copying text.
7162 * cons & search-fwd Review::
7163 * search Exercises::
7164 @end menu
7165
7166 @node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7167 @ifnottex
7168 @unnumberedsec Storing Text in a List
7169 @end ifnottex
7170
7171 When text is cut out of a buffer, it is stored on a list. Successive
7172 pieces of text are stored on the list successively, so the list might
7173 look like this:
7174
7175 @smallexample
7176 ("a piece of text" "previous piece")
7177 @end smallexample
7178
7179 @need 1200
7180 @noindent
7181 The function @code{cons} can be used to add a piece of text to the list,
7182 like this:
7183
7184 @smallexample
7185 @group
7186 (cons "another piece"
7187 '("a piece of text" "previous piece"))
7188 @end group
7189 @end smallexample
7190
7191 @need 1200
7192 @noindent
7193 If you evaluate this expression, a list of three elements will appear in
7194 the echo area:
7195
7196 @smallexample
7197 ("another piece" "a piece of text" "previous piece")
7198 @end smallexample
7199
7200 With the @code{car} and @code{nthcdr} functions, you can retrieve
7201 whichever piece of text you want. For example, in the following code,
7202 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7203 and the @code{car} returns the first element of that remainder---the
7204 second element of the original list:
7205
7206 @smallexample
7207 @group
7208 (car (nthcdr 1 '("another piece"
7209 "a piece of text"
7210 "previous piece")))
7211 @result{} "a piece of text"
7212 @end group
7213 @end smallexample
7214
7215 The actual functions in Emacs are more complex than this, of course.
7216 The code for cutting and retrieving text has to be written so that
7217 Emacs can figure out which element in the list you want---the first,
7218 second, third, or whatever. In addition, when you get to the end of
7219 the list, Emacs should give you the first element of the list, rather
7220 than nothing at all.
7221
7222 The list that holds the pieces of text is called the @dfn{kill ring}.
7223 This chapter leads up to a description of the kill ring and how it is
7224 used by first tracing how the @code{zap-to-char} function works. This
7225 function uses (or `calls') a function that invokes a function that
7226 manipulates the kill ring. Thus, before reaching the mountains, we
7227 climb the foothills.
7228
7229 A subsequent chapter describes how text that is cut from the buffer is
7230 retrieved. @xref{Yanking, , Yanking Text Back}.
7231
7232 @node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7233 @comment node-name, next, previous, up
7234 @section @code{zap-to-char}
7235 @findex zap-to-char
7236
7237 The @code{zap-to-char} function barely changed between GNU Emacs
7238 version 19 and GNU Emacs version 21. However, @code{zap-to-char}
7239 calls another function, @code{kill-region}, which enjoyed a major rewrite
7240 on the way to version 21.
7241
7242 The @code{kill-region} function in Emacs 19 is complex, but does not
7243 use code that is important at this time. We will skip it.
7244
7245 The @code{kill-region} function in Emacs 21 is easier to read than the
7246 same function in Emacs 19 and introduces a very important concept,
7247 that of error handling. We will walk through the function.
7248
7249 But first, let us look at the interactive @code{zap-to-char} function.
7250
7251 @menu
7252 * Complete zap-to-char:: The complete implementation.
7253 * zap-to-char interactive:: A three part interactive expression.
7254 * zap-to-char body:: A short overview.
7255 * search-forward:: How to search for a string.
7256 * progn:: The @code{progn} special form.
7257 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7258 @end menu
7259
7260 @node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7261 @ifnottex
7262 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7263 @end ifnottex
7264
7265 The GNU Emacs version 19 and version 21 implementations of the
7266 @code{zap-to-char} function are nearly identical in form, and they
7267 work alike. The function removes the text in the region between the
7268 location of the cursor (i.e., of point) up to and including the next
7269 occurrence of a specified character. The text that @code{zap-to-char}
7270 removes is put in the kill ring; and it can be retrieved from the kill
7271 ring by typing @kbd{C-y} (@code{yank}). If the command is given an
7272 argument, it removes text through that number of occurrences. Thus,
7273 if the cursor were at the beginning of this sentence and the character
7274 were @samp{s}, @samp{Thus} would be removed. If the argument were
7275 two, @samp{Thus, if the curs} would be removed, up to and including
7276 the @samp{s} in @samp{cursor}.
7277
7278 If the specified character is not found, @code{zap-to-char} will say
7279 ``Search failed'', tell you the character you typed, and not remove
7280 any text.
7281
7282 In order to determine how much text to remove, @code{zap-to-char} uses
7283 a search function. Searches are used extensively in code that
7284 manipulates text, and we will focus attention on them as well as on the
7285 deletion command.
7286
7287 @need 800
7288 Here is the complete text of the version 19 implementation of the function:
7289
7290 @c v 19
7291 @smallexample
7292 @group
7293 (defun zap-to-char (arg char) ; version 19 implementation
7294 "Kill up to and including ARG'th occurrence of CHAR.
7295 Goes backward if ARG is negative; error if CHAR not found."
7296 (interactive "*p\ncZap to char: ")
7297 (kill-region (point)
7298 (progn
7299 (search-forward
7300 (char-to-string char) nil nil arg)
7301 (point))))
7302 @end group
7303 @end smallexample
7304
7305 @node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7306 @comment node-name, next, previous, up
7307 @subsection The @code{interactive} Expression
7308
7309 @need 800
7310 The interactive expression in the @code{zap-to-char} command looks like
7311 this:
7312
7313 @smallexample
7314 (interactive "*p\ncZap to char: ")
7315 @end smallexample
7316
7317 The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7318 three different things. First, and most simply, the asterisk, @samp{*},
7319 causes an error to be signalled if the buffer is read-only. This means that
7320 if you try @code{zap-to-char} in a read-only buffer you will not be able to
7321 remove text, and you will receive a message that says ``Buffer is
7322 read-only''; your terminal may beep at you as well.
7323
7324 The version 21 implementation does not have the asterisk, @samp{*}. The
7325 function works the same as in version 19: in both cases, it cannot
7326 remove text from a read-only buffer but the function does copy the
7327 text that would have been removed to the kill ring. Also, in both
7328 cases, you see an error message.
7329
7330 However, the version 19 implementation copies text from a read-only
7331 buffer only because of a mistake in the implementation of
7332 @code{interactive}. According to the documentation for
7333 @code{interactive}, the asterisk, @samp{*}, should prevent the
7334 @code{zap-to-char} function from doing anything at all when the buffer
7335 is read only. The function should not copy the text to the kill ring.
7336 It is a bug that it does.
7337
7338 In version 21, @code{interactive} is implemented correctly. So the
7339 asterisk, @samp{*}, had to be removed from the interactive
7340 specification. If you insert an @samp{*} and evaluate the function
7341 definition, then the next time you run the @code{zap-to-char} function
7342 on a read-only buffer, you will not copy any text.
7343
7344 That change aside, and a change to the documentation, the two versions
7345 of the @code{zap-to-char} function are identical.
7346
7347 Let us continue with the interactive specification.
7348
7349 The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7350 This part is separated from the next part by a newline, @samp{\n}.
7351 The @samp{p} means that the first argument to the function will be
7352 passed the value of a `processed prefix'. The prefix argument is
7353 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7354 the function is called interactively without a prefix, 1 is passed to
7355 this argument.
7356
7357 The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7358 }. In this part, the lower case @samp{c} indicates that
7359 @code{interactive} expects a prompt and that the argument will be a
7360 character. The prompt follows the @samp{c} and is the string @samp{Zap
7361 to char:@: } (with a space after the colon to make it look good).
7362
7363 What all this does is prepare the arguments to @code{zap-to-char} so they
7364 are of the right type, and give the user a prompt.
7365
7366 @node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7367 @comment node-name, next, previous, up
7368 @subsection The Body of @code{zap-to-char}
7369
7370 The body of the @code{zap-to-char} function contains the code that
7371 kills (that is, removes) the text in the region from the current
7372 position of the cursor up to and including the specified character.
7373 The first part of the code looks like this:
7374
7375 @smallexample
7376 (kill-region (point) @dots{}
7377 @end smallexample
7378
7379 @noindent
7380 @code{(point)} is the current position of the cursor.
7381
7382 The next part of the code is an expression using @code{progn}. The body
7383 of the @code{progn} consists of calls to @code{search-forward} and
7384 @code{point}.
7385
7386 It is easier to understand how @code{progn} works after learning about
7387 @code{search-forward}, so we will look at @code{search-forward} and
7388 then at @code{progn}.
7389
7390 @node search-forward, progn, zap-to-char body, zap-to-char
7391 @comment node-name, next, previous, up
7392 @subsection The @code{search-forward} Function
7393 @findex search-forward
7394
7395 The @code{search-forward} function is used to locate the
7396 zapped-for-character in @code{zap-to-char}. If the search is
7397 successful, @code{search-forward} leaves point immediately after the
7398 last character in the target string. (In @code{zap-to-char}, the
7399 target string is just one character long.) If the search is
7400 backwards, @code{search-forward} leaves point just before the first
7401 character in the target. Also, @code{search-forward} returns @code{t}
7402 for true. (Moving point is therefore a `side effect'.)
7403
7404 @need 1250
7405 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7406
7407 @smallexample
7408 (search-forward (char-to-string char) nil nil arg)
7409 @end smallexample
7410
7411 The @code{search-forward} function takes four arguments:
7412
7413 @enumerate
7414 @item
7415 The first argument is the target, what is searched for. This must be a
7416 string, such as @samp{"z"}.
7417
7418 As it happens, the argument passed to @code{zap-to-char} is a single
7419 character. Because of the way computers are built, the Lisp
7420 interpreter may treat a single character as being different from a
7421 string of characters. Inside the computer, a single character has a
7422 different electronic format than a string of one character. (A single
7423 character can often be recorded in the computer using exactly one
7424 byte; but a string may be longer, and the computer needs to be ready
7425 for this.) Since the @code{search-forward} function searches for a
7426 string, the character that the @code{zap-to-char} function receives as
7427 its argument must be converted inside the computer from one format to
7428 the other; otherwise the @code{search-forward} function will fail.
7429 The @code{char-to-string} function is used to make this conversion.
7430
7431 @item
7432 The second argument bounds the search; it is specified as a position in
7433 the buffer. In this case, the search can go to the end of the buffer,
7434 so no bound is set and the second argument is @code{nil}.
7435
7436 @item
7437 The third argument tells the function what it should do if the search
7438 fails---it can signal an error (and print a message) or it can return
7439 @code{nil}. A @code{nil} as the third argument causes the function to
7440 signal an error when the search fails.
7441
7442 @item
7443 The fourth argument to @code{search-forward} is the repeat count---how
7444 many occurrences of the string to look for. This argument is optional
7445 and if the function is called without a repeat count, this argument is
7446 passed the value 1. If this argument is negative, the search goes
7447 backwards.
7448 @end enumerate
7449
7450 @need 800
7451 In template form, a @code{search-forward} expression looks like this:
7452
7453 @smallexample
7454 @group
7455 (search-forward "@var{target-string}"
7456 @var{limit-of-search}
7457 @var{what-to-do-if-search-fails}
7458 @var{repeat-count})
7459 @end group
7460 @end smallexample
7461
7462 We will look at @code{progn} next.
7463
7464 @node progn, Summing up zap-to-char, search-forward, zap-to-char
7465 @comment node-name, next, previous, up
7466 @subsection The @code{progn} Special Form
7467 @findex progn
7468
7469 @code{progn} is a special form that causes each of its arguments to be
7470 evaluated in sequence and then returns the value of the last one. The
7471 preceding expressions are evaluated only for the side effects they
7472 perform. The values produced by them are discarded.
7473
7474 @need 800
7475 The template for a @code{progn} expression is very simple:
7476
7477 @smallexample
7478 @group
7479 (progn
7480 @var{body}@dots{})
7481 @end group
7482 @end smallexample
7483
7484 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7485 put point in exactly the right position; and return the location of
7486 point so that @code{kill-region} will know how far to kill to.
7487
7488 The first argument to the @code{progn} is @code{search-forward}. When
7489 @code{search-forward} finds the string, the function leaves point
7490 immediately after the last character in the target string. (In this
7491 case the target string is just one character long.) If the search is
7492 backwards, @code{search-forward} leaves point just before the first
7493 character in the target. The movement of point is a side effect.
7494
7495 The second and last argument to @code{progn} is the expression
7496 @code{(point)}. This expression returns the value of point, which in
7497 this case will be the location to which it has been moved by
7498 @code{search-forward}. This value is returned by the @code{progn}
7499 expression and is passed to @code{kill-region} as @code{kill-region}'s
7500 second argument.
7501
7502 @node Summing up zap-to-char, , progn, zap-to-char
7503 @comment node-name, next, previous, up
7504 @subsection Summing up @code{zap-to-char}
7505
7506 Now that we have seen how @code{search-forward} and @code{progn} work,
7507 we can see how the @code{zap-to-char} function works as a whole.
7508
7509 The first argument to @code{kill-region} is the position of the cursor
7510 when the @code{zap-to-char} command is given---the value of point at
7511 that time. Within the @code{progn}, the search function then moves
7512 point to just after the zapped-to-character and @code{point} returns the
7513 value of this location. The @code{kill-region} function puts together
7514 these two values of point, the first one as the beginning of the region
7515 and the second one as the end of the region, and removes the region.
7516
7517 The @code{progn} special form is necessary because the @code{kill-region}
7518 command takes two arguments; and it would fail if @code{search-forward}
7519 and @code{point} expressions were written in sequence as two
7520 additional arguments. The @code{progn} expression is a single argument
7521 to @code{kill-region} and returns the one value that @code{kill-region}
7522 needs for its second argument.
7523
7524 @node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7525 @comment node-name, next, previous, up
7526 @section @code{kill-region}
7527 @findex kill-region
7528
7529 The @code{zap-to-char} function uses the @code{kill-region} function.
7530 This function clips text from a region and copies that text to
7531 the kill ring, from which it may be retrieved.
7532
7533 The Emacs 21 version of that function uses @code{condition-case} and
7534 @code{copy-region-as-kill}, both of which we will explain.
7535 @code{condition-case} is an important special form.
7536
7537 In essence, the @code{kill-region} function calls
7538 @code{condition-case}, which takes three arguments. In this function,
7539 the first argument does nothing. The second argument contains the
7540 code that does the work when all goes well. The third argument
7541 contains the code that is called in the event of an error.
7542
7543 @menu
7544 * Complete kill-region:: The function definition.
7545 * condition-case:: Dealing with a problem.
7546 * delete-and-extract-region:: Doing the work.
7547 @end menu
7548
7549 @node Complete kill-region, condition-case, kill-region, kill-region
7550 @ifnottex
7551 @unnumberedsubsec The Complete @code{kill-region} Definition
7552 @end ifnottex
7553
7554 @need 1200
7555 We will go through the @code{condition-case} code in a moment. First,
7556 let us look at the complete definition of @code{kill-region}, with
7557 comments added:
7558
7559 @c v 21
7560 @smallexample
7561 @group
7562 (defun kill-region (beg end)
7563 "Kill between point and mark.
7564 The text is deleted but saved in the kill ring."
7565 (interactive "r")
7566 @end group
7567
7568 @group
7569 ;; 1. `condition-case' takes three arguments.
7570 ;; If the first argument is nil, as it is here,
7571 ;; information about the error signal is not
7572 ;; stored for use by another function.
7573 (condition-case nil
7574 @end group
7575
7576 @group
7577 ;; 2. The second argument to `condition-case'
7578 ;; tells the Lisp interpreter what to do when all goes well.
7579 @end group
7580
7581 @group
7582 ;; The `delete-and-extract-region' function usually does the
7583 ;; work. If the beginning and ending of the region are both
7584 ;; the same, then the variable `string' will be empty, or nil
7585 (let ((string (delete-and-extract-region beg end)))
7586 @end group
7587
7588 @group
7589 ;; `when' is an `if' clause that cannot take an `else-part'.
7590 ;; Emacs normally sets the value of `last-command' to the
7591 ;; previous command.
7592 @end group
7593 @group
7594 ;; `kill-append' concatenates the new string and the old.
7595 ;; `kill-new' inserts text into a new item in the kill ring.
7596 (when string
7597 (if (eq last-command 'kill-region)
7598 ;; if true, prepend string
7599 (kill-append string (< end beg))
7600 (kill-new string)))
7601 (setq this-command 'kill-region))
7602 @end group
7603
7604 @group
7605 ;; 3. The third argument to `condition-case' tells the interpreter
7606 ;; what to do with an error.
7607 @end group
7608 @group
7609 ;; The third argument has a conditions part and a body part.
7610 ;; If the conditions are met (in this case,
7611 ;; if text or buffer is read-only)
7612 ;; then the body is executed.
7613 @end group
7614 @group
7615 ((buffer-read-only text-read-only) ;; this is the if-part
7616 ;; then...
7617 (copy-region-as-kill beg end)
7618 @end group
7619 @group
7620 (if kill-read-only-ok ;; usually this variable is nil
7621 (message "Read only text copied to kill ring")
7622 ;; or else, signal an error if the buffer is read-only;
7623 (barf-if-buffer-read-only)
7624 ;; and, in any case, signal that the text is read-only.
7625 (signal 'text-read-only (list (current-buffer)))))))
7626 @end group
7627 @end smallexample
7628
7629 @node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7630 @comment node-name, next, previous, up
7631 @subsection @code{condition-case}
7632 @findex condition-case
7633
7634 As we have seen earlier (@pxref{Making Errors, , Generate an Error
7635 Message}), when the Emacs Lisp interpreter has trouble evaluating an
7636 expression, it provides you with help; in the jargon, this is called
7637 ``signaling an error''. Usually, the computer stops the program and
7638 shows you a message.
7639
7640 However, some programs undertake complicated actions. They should not
7641 simply stop on an error. In the @code{kill-region} function, the most
7642 likely error is that you will try to kill text that is read-only and
7643 cannot be removed. So the @code{kill-region} function contains code
7644 to handle this circumstance. This code, which makes up the body of
7645 the @code{kill-region} function, is inside of a @code{condition-case}
7646 special form.
7647
7648 @need 800
7649 The template for @code{condition-case} looks like this:
7650
7651 @smallexample
7652 @group
7653 (condition-case
7654 @var{var}
7655 @var{bodyform}
7656 @var{error-handler}@dots{})
7657 @end group
7658 @end smallexample
7659
7660 The second argument, @var{bodyform}, is straightforward. The
7661 @code{condition-case} special form causes the Lisp interpreter to
7662 evaluate the code in @var{bodyform}. If no error occurs, the special
7663 form returns the code's value and produces the side-effects, if any.
7664
7665 In short, the @var{bodyform} part of a @code{condition-case}
7666 expression determines what should happen when everything works
7667 correctly.
7668
7669 However, if an error occurs, among its other actions, the function
7670 generating the error signal will define one or more error condition
7671 names.
7672
7673 An error handler is the third argument to @code{condition case}.
7674 An error handler has two parts, a @var{condition-name} and a
7675 @var{body}. If the @var{condition-name} part of an error handler
7676 matches a condition name generated by an error, then the @var{body}
7677 part of the error handler is run.
7678
7679 As you will expect, the @var{condition-name} part of an error handler
7680 may be either a single condition name or a list of condition names.
7681
7682 Also, a complete @code{condition-case} expression may contain more
7683 than one error handler. When an error occurs, the first applicable
7684 handler is run.
7685
7686 Lastly, the first argument to the @code{condition-case} expression,
7687 the @var{var} argument, is sometimes bound to a variable that
7688 contains information about the error. However, if that argument is
7689 nil, as is the case in @code{kill-region}, that information is
7690 discarded.
7691
7692 @need 1200
7693 In brief, in the @code{kill-region} function, the code
7694 @code{condition-case} works like this:
7695
7696 @smallexample
7697 @group
7698 @var{If no errors}, @var{run only this code}
7699 @var{but}, @var{if errors}, @var{run this other code}.
7700 @end group
7701 @end smallexample
7702
7703 @node delete-and-extract-region, , condition-case, kill-region
7704 @comment node-name, next, previous, up
7705 @subsection @code{delete-and-extract-region}
7706 @findex delete-and-extract-region
7707
7708 A @code{condition-case} expression has two parts, a part that is
7709 evaluated in the expectation that all will go well, but which may
7710 generate an error; and a part that is evaluated when there is an
7711 error.
7712
7713 First, let us look at the code in @code{kill-region} that is run in
7714 the expectation that all goes well. This is the core of the function.
7715 The code looks like this:
7716
7717 @smallexample
7718 @group
7719 (let ((string (delete-and-extract-region beg end)))
7720 (when string
7721 (if (eq last-command 'kill-region)
7722 (kill-append string (< end beg))
7723 (kill-new string)))
7724 (setq this-command 'kill-region))
7725 @end group
7726 @end smallexample
7727
7728 It looks complicated because we have the new functions
7729 @code{delete-and-extract-region}, @code{kill-append}, and
7730 @code{kill-new} as well as the new variables,
7731 @code{last-command} and @code{this-command}.
7732
7733 The @code{delete-and-extract-region} function is straightforward. It
7734 is a built-in function that deletes the text in a region (a side
7735 effect) and also returns that text. This is the function that
7736 actually removes the text. (And if it cannot do that, it signals the
7737 error.)
7738
7739 In this @code{let} expression, the text that
7740 @code{delete-and-extract-region} returns is placed in the local
7741 variable called @samp{string}. This is the text that is removed from
7742 the buffer. (To be more precise, the variable is set to point to the
7743 address of the extracted text; to say it is `placed in' the variable
7744 is simply a shorthand.)
7745
7746 If the variable @samp{string} does point to text, that text is added
7747 to the kill ring. The variable will have a @code{nil} value if no
7748 text was removed.
7749
7750 The code uses @code{when} to determine whether the variable
7751 @samp{string} points to text. A @code{when} statement is simply a
7752 programmers' convenience. A @code{when} statement is an @code{if}
7753 statement without the possibility of an else clause. In your mind, you
7754 can replace @code{when} with @code{if} and understand what goes on.
7755 That is what the Lisp interpreter does.
7756
7757 @cindex Macro, lisp
7758 @cindex Lisp macro
7759 Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
7760 enables you to define new control constructs and other language
7761 features. It tells the interpreter how to compute another Lisp
7762 expression which will in turn compute the value. In this case, the
7763 `other expression' is an @code{if} expression. For more about Lisp
7764 macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7765 Manual}. The C programming language also provides macros. These are
7766 different, but also useful. We will briefly look at C macros in
7767 @ref{Digression into C, , @code{delete-and-extract-region}:
7768 Digressing into C}.
7769
7770 @need 1200
7771 If the string has content, then another conditional expression is
7772 executed. This is an @code{if} with both a then-part and an else-part.
7773
7774 @smallexample
7775 @group
7776 (if (eq last-command 'kill-region)
7777 (kill-append string (< end beg))
7778 (kill-new string)))
7779 @end group
7780 @end smallexample
7781
7782 The then-part is evaluated if the previous command was another call to
7783 @code{kill-region}; if not, the else-part is evaluated.
7784
7785 @code{last-command} is a variable that comes with Emacs that we have
7786 not seen before. Normally, whenever a function is executed, Emacs
7787 sets the value of @code{last-command} to the previous command.
7788
7789 @need 1200
7790 In this segment of the definition, the @code{if} expression checks
7791 whether the previous command was @code{kill-region}. If it was,
7792
7793 @smallexample
7794 (kill-append string (< end beg))
7795 @end smallexample
7796
7797 @noindent
7798 concatenates a copy of the newly clipped text to the just previously
7799 clipped text in the kill ring. (If the @w{@code{(< end beg))}}
7800 expression is true, @code{kill-append} prepends the string to the just
7801 previously clipped text. For a detailed discussion, see
7802 @ref{kill-append function, , The @code{kill-append} function}.)
7803
7804 If you then yank back the text, i.e., `paste' it, you get both
7805 pieces of text at once. That way, if you delete two words in a row,
7806 and then yank them back, you get both words, in their proper order,
7807 with one yank. (The @w{@code{(< end beg))}} expression makes sure the
7808 order is correct.)
7809
7810 On the other hand, if the previous command is not @code{kill-region},
7811 then the @code{kill-new} function is called, which adds the text to
7812 the kill ring as the latest item, and sets the
7813 @code{kill-ring-yank-pointer} variable to point to it.
7814
7815 @node Digression into C, defvar, kill-region, Cutting & Storing Text
7816 @comment node-name, next, previous, up
7817 @section @code{delete-and-extract-region}: Digressing into C
7818 @findex delete-and-extract-region
7819 @cindex C, a digression into
7820 @cindex Digression into C
7821
7822 The @code{zap-to-char} command uses the
7823 @code{delete-and-extract-region} function, which in turn uses two
7824 other functions, @code{copy-region-as-kill} and
7825 @code{del_range_1}. The @code{copy-region-as-kill} function will be
7826 described in a following section; it puts a copy of the region in the
7827 kill ring so it can be yanked back. (@xref{copy-region-as-kill, ,
7828 @code{copy-region-as-kill}}.)
7829
7830 The @code{delete-and-extract-region} function removes the contents of
7831 a region and you cannot get them back.
7832
7833 Unlike the other code discussed here, @code{delete-and-extract-region}
7834 is not written in Emacs Lisp; it is written in C and is one of the
7835 primitives of the GNU Emacs system. Since it is very simple, I will
7836 digress briefly from Lisp and describe it here.
7837
7838 @need 1500
7839 Like many of the other Emacs primitives,
7840 @code{delete-and-extract-region} is written as an instance of a C
7841 macro, a macro being a template for code. The complete macro looks
7842 like this:
7843
7844 @c /usr/local/src/emacs/src/editfns.c
7845 @smallexample
7846 @group
7847 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7848 Sdelete_and_extract_region, 2, 2, 0,
7849 "Delete the text between START and END and return it.")
7850 (start, end)
7851 Lisp_Object start, end;
7852 @{
7853 validate_region (&start, &end);
7854 return del_range_1 (XINT (start), XINT (end), 1, 1);
7855 @}
7856 @end group
7857 @end smallexample
7858
7859 Without going into the details of the macro writing process, let me
7860 point out that this macro starts with the word @code{DEFUN}. The word
7861 @code{DEFUN} was chosen since the code serves the same purpose as
7862 @code{defun} does in Lisp. The word @code{DEFUN} is followed by seven
7863 parts inside of parentheses:
7864
7865 @itemize @bullet
7866 @item
7867 The first part is the name given to the function in Lisp,
7868 @code{delete-and-extract-region}.
7869
7870 @item
7871 The second part is the name of the function in C,
7872 @code{Fdelete_and_extract_region}. By convention, it starts with
7873 @samp{F}. Since C does not use hyphens in names, underscores are used
7874 instead.
7875
7876 @item
7877 The third part is the name for the C constant structure that records
7878 information on this function for internal use. It is the name of the
7879 function in C but begins with an @samp{S} instead of an @samp{F}.
7880
7881 @item
7882 The fourth and fifth parts specify the minimum and maximum number of
7883 arguments the function can have. This function demands exactly 2
7884 arguments.
7885
7886 @item
7887 The sixth part is nearly like the argument that follows the
7888 @code{interactive} declaration in a function written in Lisp: a letter
7889 followed, perhaps, by a prompt. The only difference from the Lisp is
7890 when the macro is called with no arguments. Then you write a @code{0}
7891 (which is a `null string'), as in this macro.
7892
7893 If you were to specify arguments, you would place them between
7894 quotation marks. The C macro for @code{goto-char} includes
7895 @code{"NGoto char: "} in this position to indicate that the function
7896 expects a raw prefix, in this case, a numerical location in a buffer,
7897 and provides a prompt.
7898
7899 @item
7900 The seventh part is a documentation string, just like the one for a
7901 function written in Emacs Lisp, except that every newline must be
7902 written explicitly as @samp{\n} followed by a backslash and carriage
7903 return.
7904
7905 @need 1000
7906 Thus, the first two lines of documentation for @code{goto-char} are
7907 written like this:
7908
7909 @smallexample
7910 @group
7911 "Set point to POSITION, a number or marker.\n\
7912 Beginning of buffer is position (point-min), end is (point-max).
7913 @end group
7914 @end smallexample
7915 @end itemize
7916
7917 @need 1200
7918 In a C macro, the formal parameters come next, with a statement of
7919 what kind of object they are, followed by what might be called the `body'
7920 of the macro. For @code{delete-and-extract-region} the `body'
7921 consists of the following two lines:
7922
7923 @smallexample
7924 @group
7925 validate_region (&start, &end);
7926 return del_range_1 (XINT (start), XINT (end), 1, 1);
7927 @end group
7928 @end smallexample
7929
7930 The first function, @code{validate_region} checks whether the values
7931 passed as the beginning and end of the region are the proper type and
7932 are within range. The second function, @code{del_range_1}, actually
7933 deletes the text.
7934
7935 @code{del_range_1} is a complex function we will not look into. It
7936 updates the buffer and does other things.
7937
7938 However, it is worth looking at the two arguments passed to
7939 @code{del_range}. These are @w{@code{XINT (start)}} and @w{@code{XINT
7940 (end)}}.
7941
7942 As far as the C language is concerned, @code{start} and @code{end} are
7943 two integers that mark the beginning and end of the region to be
7944 deleted@footnote{More precisely, and requiring more expert knowledge
7945 to understand, the two integers are of type `Lisp_Object', which can
7946 also be a C union instead of an integer type.}.
7947
7948 In early versions of Emacs, these two numbers were thirty-two bits
7949 long, but the code is slowly being generalized to handle other
7950 lengths. Three of the available bits are used to specify the type of
7951 information and a fourth bit is used for handling the computer's
7952 memory; the remaining bits are used as `content'.
7953
7954 @samp{XINT} is a C macro that extracts the relevant number from the
7955 longer collection of bits; the four other bits are discarded.
7956
7957 @need 800
7958 The command in @code{delete-and-extract-region} looks like this:
7959
7960 @smallexample
7961 del_range_1 (XINT (start), XINT (end), 1, 1);
7962 @end smallexample
7963
7964 @noindent
7965 It deletes the region between the beginning position, @code{start},
7966 and the ending position, @code{end}.
7967
7968 From the point of view of the person writing Lisp, Emacs is all very
7969 simple; but hidden underneath is a great deal of complexity to make it
7970 all work.
7971
7972 @node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7973 @comment node-name, next, previous, up
7974 @section Initializing a Variable with @code{defvar}
7975 @findex defvar
7976 @cindex Initializing a variable
7977 @cindex Variable initialization
7978
7979 Unlike the @code{delete-and-extract-region} function, the
7980 @code{copy-region-as-kill} function is written in Emacs Lisp. Two
7981 functions within it, @code{kill-append} and @code{kill-new}, copy a
7982 region in a buffer and save it in a variable called the
7983 @code{kill-ring}. This section describes how the @code{kill-ring}
7984 variable is created and initialized using the @code{defvar} special
7985 form.
7986
7987 (Again we note that the term @code{kill-ring} is a misnomer. The text
7988 that is clipped out of the buffer can be brought back; it is not a ring
7989 of corpses, but a ring of resurrectable text.)
7990
7991 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7992 given an initial value by using the @code{defvar} special form. The
7993 name comes from ``define variable''.
7994
7995 The @code{defvar} special form is similar to @code{setq} in that it sets
7996 the value of a variable. It is unlike @code{setq} in two ways: first,
7997 it only sets the value of the variable if the variable does not already
7998 have a value. If the variable already has a value, @code{defvar} does
7999 not override the existing value. Second, @code{defvar} has a
8000 documentation string.
8001
8002 (Another special form, @code{defcustom}, is designed for variables
8003 that people customize. It has more features than @code{defvar}.
8004 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
8005
8006 @menu
8007 * See variable current value::
8008 * defvar and asterisk:: An old-time convention.
8009 @end menu
8010
8011 @node See variable current value, defvar and asterisk, defvar, defvar
8012 @ifnottex
8013 @unnumberedsubsec Seeing the Current Value of a Variable
8014 @end ifnottex
8015
8016 You can see the current value of a variable, any variable, by using
8017 the @code{describe-variable} function, which is usually invoked by
8018 typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
8019 (followed by @key{RET}) when prompted, you will see what is in your
8020 current kill ring---this may be quite a lot! Conversely, if you have
8021 been doing nothing this Emacs session except read this document, you
8022 may have nothing in it. Also, you will see the documentation for
8023 @code{kill-ring}:
8024
8025 @smallexample
8026 @group
8027 Documentation:
8028 List of killed text sequences.
8029 Since the kill ring is supposed to interact nicely with cut-and-paste
8030 facilities offered by window systems, use of this variable should
8031 @end group
8032 @group
8033 interact nicely with `interprogram-cut-function' and
8034 `interprogram-paste-function'. The functions `kill-new',
8035 `kill-append', and `current-kill' are supposed to implement this
8036 interaction; you may want to use them instead of manipulating the kill
8037 ring directly.
8038 @end group
8039 @end smallexample
8040
8041 @need 800
8042 The kill ring is defined by a @code{defvar} in the following way:
8043
8044 @smallexample
8045 @group
8046 (defvar kill-ring nil
8047 "List of killed text sequences.
8048 @dots{}")
8049 @end group
8050 @end smallexample
8051
8052 @noindent
8053 In this variable definition, the variable is given an initial value of
8054 @code{nil}, which makes sense, since if you have saved nothing, you want
8055 nothing back if you give a @code{yank} command. The documentation
8056 string is written just like the documentation string of a @code{defun}.
8057 As with the documentation string of the @code{defun}, the first line of
8058 the documentation should be a complete sentence, since some commands,
8059 like @code{apropos}, print only the first line of documentation.
8060 Succeeding lines should not be indented; otherwise they look odd when
8061 you use @kbd{C-h v} (@code{describe-variable}).
8062
8063 @node defvar and asterisk, , See variable current value, defvar
8064 @subsection @code{defvar} and an asterisk
8065 @findex defvar @r{for a user customizable variable}
8066 @findex defvar @r{with an asterisk}
8067
8068 In the past, Emacs used the @code{defvar} special form both for
8069 internal variables that you would not expect a user to change and for
8070 variables that you do expect a user to change. Although you can still
8071 use @code{defvar} for user customizable variables, please use
8072 @code{defcustom} instead, since that special form provides a path into
8073 the Customization commands. (@xref{defcustom, , Setting Variables
8074 with @code{defcustom}}.)
8075
8076 When you specified a variable using the @code{defvar} special form,
8077 you could distinguish a readily settable variable from others by
8078 typing an asterisk, @samp{*}, in the first column of its documentation
8079 string. For example:
8080
8081 @smallexample
8082 @group
8083 (defvar shell-command-default-error-buffer nil
8084 "*Buffer name for `shell-command' @dots{} error output.
8085 @dots{} ")
8086 @end group
8087 @end smallexample
8088
8089 @noindent
8090 This means that you could (and still can) use the @code{edit-options}
8091 command to change the value of
8092 @code{shell-command-default-error-buffer} temporarily.
8093
8094 @findex edit-options
8095 However, options set using @code{edit-options} are set only for the
8096 duration of your editing session. The new values are not saved
8097 between sessions. Each time Emacs starts, it reads the original
8098 value, unless you change the value within your @file{.emacs} file,
8099 either by setting it manually or by using @code{customize}.
8100 @xref{Emacs Initialization, , Your @file{.emacs} File}.
8101
8102 For me, the major use of the @code{edit-options} command is to suggest
8103 variables that I might want to set in my @file{.emacs} file. I urge
8104 you to look through the list. (@xref{Edit Options, , Editing Variable
8105 Values, emacs, The GNU Emacs Manual}.)
8106
8107 @node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8108 @comment node-name, next, previous, up
8109 @section @code{copy-region-as-kill}
8110 @findex copy-region-as-kill
8111 @findex nthcdr
8112
8113 The @code{copy-region-as-kill} function copies a region of text from a
8114 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8115 in the @code{kill-ring}.
8116
8117 If you call @code{copy-region-as-kill} immediately after a
8118 @code{kill-region} command, Emacs appends the newly copied text to the
8119 previously copied text. This means that if you yank back the text, you
8120 get it all, from both this and the previous operation. On the other
8121 hand, if some other command precedes the @code{copy-region-as-kill},
8122 the function copies the text into a separate entry in the kill ring.
8123
8124 @menu
8125 * Complete copy-region-as-kill:: The complete function definition.
8126 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8127 @end menu
8128
8129 @node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8130 @ifnottex
8131 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8132 @end ifnottex
8133
8134 @need 1200
8135 Here is the complete text of the version 21 @code{copy-region-as-kill}
8136 function:
8137
8138 @smallexample
8139 @group
8140 (defun copy-region-as-kill (beg end)
8141 "Save the region as if killed, but don't kill it.
8142 In Transient Mark mode, deactivate the mark.
8143 If `interprogram-cut-function' is non-nil, also save
8144 the text for a window system cut and paste."
8145 (interactive "r")
8146 @end group
8147 @group
8148 (if (eq last-command 'kill-region)
8149 (kill-append (buffer-substring beg end) (< end beg))
8150 (kill-new (buffer-substring beg end)))
8151 @end group
8152 @group
8153 (if transient-mark-mode
8154 (setq deactivate-mark t))
8155 nil)
8156 @end group
8157 @end smallexample
8158
8159 @need 800
8160 As usual, this function can be divided into its component parts:
8161
8162 @smallexample
8163 @group
8164 (defun copy-region-as-kill (@var{argument-list})
8165 "@var{documentation}@dots{}"
8166 (interactive "r")
8167 @var{body}@dots{})
8168 @end group
8169 @end smallexample
8170
8171 The arguments are @code{beg} and @code{end} and the function is
8172 interactive with @code{"r"}, so the two arguments must refer to the
8173 beginning and end of the region. If you have been reading though this
8174 document from the beginning, understanding these parts of a function is
8175 almost becoming routine.
8176
8177 The documentation is somewhat confusing unless you remember that the
8178 word `kill' has a meaning different from its usual meaning. The
8179 `Transient Mark' and @code{interprogram-cut-function} comments explain
8180 certain side-effects.
8181
8182 After you once set a mark, a buffer always contains a region. If you
8183 wish, you can use Transient Mark mode to highlight the region
8184 temporarily. (No one wants to highlight the region all the time, so
8185 Transient Mark mode highlights it only at appropriate times. Many
8186 people turn off Transient Mark mode, so the region is never
8187 highlighted.)
8188
8189 Also, a windowing system allows you to copy, cut, and paste among
8190 different programs. In the X windowing system, for example, the
8191 @code{interprogram-cut-function} function is @code{x-select-text},
8192 which works with the windowing system's equivalent of the Emacs kill
8193 ring.
8194
8195 The body of the @code{copy-region-as-kill} function starts with an
8196 @code{if} clause. What this clause does is distinguish between two
8197 different situations: whether or not this command is executed
8198 immediately after a previous @code{kill-region} command. In the first
8199 case, the new region is appended to the previously copied text.
8200 Otherwise, it is inserted into the beginning of the kill ring as a
8201 separate piece of text from the previous piece.
8202
8203 The last two lines of the function prevent the region from lighting up
8204 if Transient Mark mode is turned on.
8205
8206 The body of @code{copy-region-as-kill} merits discussion in detail.
8207
8208 @node copy-region-as-kill body, , Complete copy-region-as-kill, copy-region-as-kill
8209 @comment node-name, next, previous, up
8210 @subsection The Body of @code{copy-region-as-kill}
8211
8212 The @code{copy-region-as-kill} function works in much the same way as
8213 the @code{kill-region} function (@pxref{kill-region,
8214 ,@code{kill-region}}). Both are written so that two or more kills in
8215 a row combine their text into a single entry. If you yank back the
8216 text from the kill ring, you get it all in one piece. Moreover, kills
8217 that kill forward from the current position of the cursor are added to
8218 the end of the previously copied text and commands that copy text
8219 backwards add it to the beginning of the previously copied text. This
8220 way, the words in the text stay in the proper order.
8221
8222 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8223 use of the @code{last-command} variable that keeps track of the
8224 previous Emacs command.
8225
8226 @menu
8227 * last-command & this-command::
8228 * kill-append function::
8229 * kill-new function::
8230 @end menu
8231
8232 @node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8233 @ifnottex
8234 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8235 @end ifnottex
8236
8237 Normally, whenever a function is executed, Emacs sets the value of
8238 @code{this-command} to the function being executed (which in this case
8239 would be @code{copy-region-as-kill}). At the same time, Emacs sets
8240 the value of @code{last-command} to the previous value of
8241 @code{this-command}.
8242
8243 In the first part of the body of the @code{copy-region-as-kill}
8244 function, an @code{if} expression determines whether the value of
8245 @code{last-command} is @code{kill-region}. If so, the then-part of
8246 the @code{if} expression is evaluated; it uses the @code{kill-append}
8247 function to concatenate the text copied at this call to the function
8248 with the text already in the first element (the @sc{car}) of the kill
8249 ring. On the other hand, if the value of @code{last-command} is not
8250 @code{kill-region}, then the @code{copy-region-as-kill} function
8251 attaches a new element to the kill ring using the @code{kill-new}
8252 function.
8253
8254 @need 1250
8255 The @code{if} expression reads as follows; it uses @code{eq}, which is
8256 a function we have not yet seen:
8257
8258 @smallexample
8259 @group
8260 (if (eq last-command 'kill-region)
8261 ;; @r{then-part}
8262 (kill-append (buffer-substring beg end) (< end beg))
8263 ;; @r{else-part}
8264 (kill-new (buffer-substring beg end)))
8265 @end group
8266 @end smallexample
8267
8268 @findex eq @r{(example of use)}
8269 @noindent
8270 The @code{eq} function tests whether its first argument is the same Lisp
8271 object as its second argument. The @code{eq} function is similar to the
8272 @code{equal} function in that it is used to test for equality, but
8273 differs in that it determines whether two representations are actually
8274 the same object inside the computer, but with different names.
8275 @code{equal} determines whether the structure and contents of two
8276 expressions are the same.
8277
8278 If the previous command was @code{kill-region}, then the Emacs Lisp
8279 interpreter calls the @code{kill-append} function
8280
8281 @node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8282 @unnumberedsubsubsec The @code{kill-append} function
8283 @findex kill-append
8284
8285 @need 800
8286 The @code{kill-append} function looks like this:
8287
8288 @smallexample
8289 @group
8290 (defun kill-append (string before-p)
8291 "Append STRING to the end of the latest kill in the kill ring.
8292 If BEFORE-P is non-nil, prepend STRING to the kill.
8293 If `interprogram-cut-function' is set, pass the resulting kill to
8294 it."
8295 (kill-new (if before-p
8296 (concat string (car kill-ring))
8297 (concat (car kill-ring) string))
8298 t))
8299 @end group
8300 @end smallexample
8301
8302 @noindent
8303 The @code{kill-append} function is fairly straightforward. It uses
8304 the @code{kill-new} function, which we will discuss in more detail in
8305 a moment.
8306
8307 First, let us look at the conditional that is one of the two arguments
8308 to @code{kill-new}. It uses @code{concat} to concatenate the new text
8309 to the @sc{car} of the kill ring. Whether it prepends or appends the
8310 text depends on the results of an @code{if} expression:
8311
8312 @smallexample
8313 @group
8314 (if before-p ; @r{if-part}
8315 (concat string (car kill-ring)) ; @r{then-part}
8316 (concat (car kill-ring) string)) ; @r{else-part}
8317 @end group
8318 @end smallexample
8319
8320 @noindent
8321 If the region being killed is before the region that was killed in the
8322 last command, then it should be prepended before the material that was
8323 saved in the previous kill; and conversely, if the killed text follows
8324 what was just killed, it should be appended after the previous text.
8325 The @code{if} expression depends on the predicate @code{before-p} to
8326 decide whether the newly saved text should be put before or after the
8327 previously saved text.
8328
8329 The symbol @code{before-p} is the name of one of the arguments to
8330 @code{kill-append}. When the @code{kill-append} function is
8331 evaluated, it is bound to the value returned by evaluating the actual
8332 argument. In this case, this is the expression @code{(< end beg)}.
8333 This expression does not directly determine whether the killed text in
8334 this command is located before or after the kill text of the last
8335 command; what is does is determine whether the value of the variable
8336 @code{end} is less than the value of the variable @code{beg}. If it
8337 is, it means that the user is most likely heading towards the
8338 beginning of the buffer. Also, the result of evaluating the predicate
8339 expression, @code{(< end beg)}, will be true and the text will be
8340 prepended before the previous text. On the other hand, if the value of
8341 the variable @code{end} is greater than the value of the variable
8342 @code{beg}, the text will be appended after the previous text.
8343
8344 @need 800
8345 When the newly saved text will be prepended, then the string with the new
8346 text will be concatenated before the old text:
8347
8348 @smallexample
8349 (concat string (car kill-ring))
8350 @end smallexample
8351
8352 @need 1200
8353 @noindent
8354 But if the text will be appended, it will be concatenated
8355 after the old text:
8356
8357 @smallexample
8358 (concat (car kill-ring) string))
8359 @end smallexample
8360
8361 To understand how this works, we first need to review the
8362 @code{concat} function. The @code{concat} function links together or
8363 unites two strings of text. The result is a string. For example:
8364
8365 @smallexample
8366 @group
8367 (concat "abc" "def")
8368 @result{} "abcdef"
8369 @end group
8370
8371 @group
8372 (concat "new "
8373 (car '("first element" "second element")))
8374 @result{} "new first element"
8375
8376 (concat (car
8377 '("first element" "second element")) " modified")
8378 @result{} "first element modified"
8379 @end group
8380 @end smallexample
8381
8382 We can now make sense of @code{kill-append}: it modifies the contents
8383 of the kill ring. The kill ring is a list, each element of which is
8384 saved text. The @code{kill-append} function uses the @code{kill-new}
8385 function which in turn uses the @code{setcar} function.
8386
8387 @node kill-new function, , kill-append function, copy-region-as-kill body
8388 @unnumberedsubsubsec The @code{kill-new} function
8389 @findex kill-new
8390
8391 @need 1200
8392 The @code{kill-new} function looks like this:
8393
8394 @smallexample
8395 @group
8396 (defun kill-new (string &optional replace)
8397 "Make STRING the latest kill in the kill ring.
8398 Set the kill-ring-yank pointer to point to it.
8399 If `interprogram-cut-function' is non-nil, apply it to STRING.
8400 Optional second argument REPLACE non-nil means that STRING will replace
8401 the front of the kill ring, rather than being added to the list."
8402 @end group
8403 @group
8404 (and (fboundp 'menu-bar-update-yank-menu)
8405 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8406 @end group
8407 @group
8408 (if (and replace kill-ring)
8409 (setcar kill-ring string)
8410 (setq kill-ring (cons string kill-ring))
8411 (if (> (length kill-ring) kill-ring-max)
8412 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8413 @end group
8414 @group
8415 (setq kill-ring-yank-pointer kill-ring)
8416 (if interprogram-cut-function
8417 (funcall interprogram-cut-function string (not replace))))
8418 @end group
8419 @end smallexample
8420
8421 As usual, we can look at this function in parts.
8422
8423 @need 1200
8424 The first line of the documentation makes sense:
8425
8426 @smallexample
8427 Make STRING the latest kill in the kill ring.
8428 @end smallexample
8429
8430 @noindent
8431 Let's skip over the rest of the documentation for the moment.
8432
8433 Also, let's skip over the first two lines of code, those involving
8434 @code{menu-bar-update-yank-menu}. We will explain them below.
8435
8436 @need 1200
8437 The critical lines are these:
8438
8439 @smallexample
8440 @group
8441 (if (and replace kill-ring)
8442 ;; @r{then}
8443 (setcar kill-ring string)
8444 @end group
8445 @group
8446 ;; @r{else}
8447 (setq kill-ring (cons string kill-ring))
8448 (if (> (length kill-ring) kill-ring-max)
8449 ;; @r{avoid overly long kill ring}
8450 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8451 @end group
8452 @group
8453 (setq kill-ring-yank-pointer kill-ring)
8454 (if interprogram-cut-function
8455 (funcall interprogram-cut-function string (not replace))))
8456 @end group
8457 @end smallexample
8458
8459 The conditional test is @w{@code{(and replace kill-ring)}}.
8460 This will be true when two conditions are met: the kill ring has
8461 something in it, and the @code{replace} variable is true.
8462
8463 @need 1250
8464 The @code{kill-append} function sets @code{replace} to be true; then,
8465 when the kill ring has at least one item in it, the @code{setcar}
8466 expression is executed:
8467
8468 @smallexample
8469 (setcar kill-ring string)
8470 @end smallexample
8471
8472 The @code{setcar} function actually changes the first element of the
8473 @code{kill-ring} list to the value of @code{string}. It replaces the
8474 first element.
8475
8476 On the other hand, if the kill ring is empty, or replace is false, the
8477 else-part of the condition is executed:
8478
8479 @smallexample
8480 @group
8481 (setq kill-ring (cons string kill-ring))
8482 (if (> (length kill-ring) kill-ring-max)
8483 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8484 @end group
8485 @end smallexample
8486
8487 @noindent
8488 This expression first constructs a new version of the kill ring by
8489 prepending @code{string} to the existing kill ring as a new element.
8490 Then it executes a second @code{if} clause. This second @code{if}
8491 clause keeps the kill ring from growing too long.
8492
8493 Let's look at these two expressions in order.
8494
8495 The @code{setq} line of the else-part sets the new value of the kill
8496 ring to what results from adding the string being killed to the old kill
8497 ring.
8498
8499 @need 800
8500 We can see how this works with an example:
8501
8502 @smallexample
8503 (setq example-list '("here is a clause" "another clause"))
8504 @end smallexample
8505
8506 @need 1200
8507 @noindent
8508 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8509 @code{example-list} and see what it returns:
8510
8511 @smallexample
8512 @group
8513 example-list
8514 @result{} ("here is a clause" "another clause")
8515 @end group
8516 @end smallexample
8517
8518 @need 1200
8519 @noindent
8520 Now, we can add a new element on to this list by evaluating the
8521 following expression:
8522 @findex cons, @r{example}
8523
8524 @smallexample
8525 (setq example-list (cons "a third clause" example-list))
8526 @end smallexample
8527
8528 @need 800
8529 @noindent
8530 When we evaluate @code{example-list}, we find its value is:
8531
8532 @smallexample
8533 @group
8534 example-list
8535 @result{} ("a third clause" "here is a clause" "another clause")
8536 @end group
8537 @end smallexample
8538
8539 @noindent
8540 Thus, the third clause was added to the list by @code{cons}.
8541
8542 @need 1200
8543 This is exactly similar to what the @code{setq} and @code{cons} do in
8544 the function. Here is the line again:
8545
8546 @smallexample
8547 (setq kill-ring (cons string kill-ring))
8548 @end smallexample
8549
8550 @need 1200
8551 Now for the second part of the @code{if} clause. This expression
8552 keeps the kill ring from growing too long. It looks like this:
8553
8554 @smallexample
8555 @group
8556 (if (> (length kill-ring) kill-ring-max)
8557 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8558 @end group
8559 @end smallexample
8560
8561 The code checks whether the length of the kill ring is greater than
8562 the maximum permitted length. This is the value of
8563 @code{kill-ring-max} (which is 60, by default). If the length of the
8564 kill ring is too long, then this code sets the last element of the
8565 kill ring to @code{nil}. It does this by using two functions,
8566 @code{nthcdr} and @code{setcdr}.
8567
8568 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8569 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8570 @sc{car} of a list. In this case, however, @code{setcdr} will not be
8571 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8572 function is used to cause it to set the @sc{cdr} of the next to last
8573 element of the kill ring---this means that since the @sc{cdr} of the
8574 next to last element is the last element of the kill ring, it will set
8575 the last element of the kill ring.
8576
8577 @findex nthcdr, @r{example}
8578 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8579 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8580 @dots{} It does this @var{N} times and returns the results.
8581
8582 @findex setcdr, @r{example}
8583 Thus, if we had a four element list that was supposed to be three
8584 elements long, we could set the @sc{cdr} of the next to last element
8585 to @code{nil}, and thereby shorten the list.
8586
8587 You can see this by evaluating the following three expressions in turn.
8588 First set the value of @code{trees} to @code{(maple oak pine birch)},
8589 then set the @sc{cdr} of its second @sc{cdr} to @code{nil} and then
8590 find the value of @code{trees}:
8591
8592 @smallexample
8593 @group
8594 (setq trees '(maple oak pine birch))
8595 @result{} (maple oak pine birch)
8596 @end group
8597
8598 @group
8599 (setcdr (nthcdr 2 trees) nil)
8600 @result{} nil
8601
8602 trees
8603 @result{} (maple oak pine)
8604 @end group
8605 @end smallexample
8606
8607 @noindent
8608 (The value returned by the @code{setcdr} expression is @code{nil} since
8609 that is what the @sc{cdr} is set to.)
8610
8611 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8612 @sc{cdr} a number of times that is one less than the maximum permitted
8613 size of the kill ring and sets the @sc{cdr} of that element (which
8614 will be the rest of the elements in the kill ring) to @code{nil}.
8615 This prevents the kill ring from growing too long.
8616
8617 @need 800
8618 The next to last expression in the @code{kill-new} function is
8619
8620 @smallexample
8621 (setq kill-ring-yank-pointer kill-ring)
8622 @end smallexample
8623
8624 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8625 the @code{kill-ring}.
8626
8627 Even though the @code{kill-ring-yank-pointer} is called a
8628 @samp{pointer}, it is a variable just like the kill ring. However, the
8629 name has been chosen to help humans understand how the variable is used.
8630 The variable is used in functions such as @code{yank} and
8631 @code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8632
8633 @need 1200
8634 Now, to return to the first two lines in the body of the function:
8635
8636 @smallexample
8637 @group
8638 (and (fboundp 'menu-bar-update-yank-menu)
8639 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8640 @end group
8641 @end smallexample
8642
8643 @noindent
8644 This is an expression whose first element is the function @code{and}.
8645
8646 @findex and, @r{introduced}
8647 The @code{and} special form evaluates each of its arguments until one of
8648 the arguments returns a value of @code{nil}, in which case the
8649 @code{and} expression returns @code{nil}; however, if none of the
8650 arguments returns a value of @code{nil}, the value resulting from
8651 evaluating the last argument is returned. (Since such a value is not
8652 @code{nil}, it is considered true in Emacs Lisp.) In other words, an
8653 @code{and} expression returns a true value only if all its arguments
8654 are true.
8655 @findex and
8656
8657 In this case, the expression tests first to see whether
8658 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8659 calls it. The @code{fboundp} function returns true if the symbol it
8660 is testing has a function definition that `is not void'. If the
8661 symbol's function definition were void, we would receive an error
8662 message, as we did when we created errors intentionally (@pxref{Making
8663 Errors, , Generate an Error Message}).
8664
8665 @need 1200
8666 Essentially, the @code{and} is an @code{if} expression that reads like
8667 this:
8668
8669 @smallexample
8670 @group
8671 if @var{the-menu-bar-function-exists}
8672 then @var{execute-it}
8673 @end group
8674 @end smallexample
8675
8676 @code{menu-bar-update-yank-menu} is one of the functions that make it
8677 possible to use the `Select and Paste' menu in the Edit item of a menu
8678 bar; using a mouse, you can look at the various pieces of text you
8679 have saved and select one piece to paste.
8680
8681 Finally, the last expression in the @code{kill-new} function adds the
8682 newly copied string to whatever facility exists for copying and
8683 pasting among different programs running in a windowing system. In
8684 the X Windowing system, for example, the @code{x-select-text} function
8685 takes the string and stores it in memory operated by X. You can paste
8686 the string in another program, such as an Xterm.
8687
8688 @need 1200
8689 The expression looks like this:
8690
8691 @smallexample
8692 @group
8693 (if interprogram-cut-function
8694 (funcall interprogram-cut-function string (not replace))))
8695 @end group
8696 @end smallexample
8697
8698 If an @code{interprogram-cut-function} exists, then Emacs executes
8699 @code{funcall}, which in turn calls its first argument as a function
8700 and passes the remaining arguments to it. (Incidentally, as far as I
8701 can see, this @code{if} expression could be replaced by an @code{and}
8702 expression similar to the one in the first part of the function.)
8703
8704 We are not going to discuss windowing systems and other programs
8705 further, but merely note that this is a mechanism that enables GNU
8706 Emacs to work easily and well with other programs.
8707
8708 This code for placing text in the kill ring, either concatenated with
8709 an existing element or as a new element, leads us to the code for
8710 bringing back text that has been cut out of the buffer---the yank
8711 commands. However, before discussing the yank commands, it is better
8712 to learn how lists are implemented in a computer. This will make
8713 clear such mysteries as the use of the term `pointer'.
8714
8715 @node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8716 @comment node-name, next, previous, up
8717 @section Review
8718
8719 Here is a brief summary of some recently introduced functions.
8720
8721 @table @code
8722 @item car
8723 @itemx cdr
8724 @code{car} returns the first element of a list; @code{cdr} returns the
8725 second and subsequent elements of a list.
8726
8727 @need 1250
8728 For example:
8729
8730 @smallexample
8731 @group
8732 (car '(1 2 3 4 5 6 7))
8733 @result{} 1
8734 (cdr '(1 2 3 4 5 6 7))
8735 @result{} (2 3 4 5 6 7)
8736 @end group
8737 @end smallexample
8738
8739 @item cons
8740 @code{cons} constructs a list by prepending its first argument to its
8741 second argument.
8742
8743 @need 1250
8744 For example:
8745
8746 @smallexample
8747 @group
8748 (cons 1 '(2 3 4))
8749 @result{} (1 2 3 4)
8750 @end group
8751 @end smallexample
8752
8753 @item nthcdr
8754 Return the result of taking @sc{cdr} `n' times on a list.
8755 @iftex
8756 The
8757 @tex
8758 $n^{th}$
8759 @end tex
8760 @code{cdr}.
8761 @end iftex
8762 The `rest of the rest', as it were.
8763
8764 @need 1250
8765 For example:
8766
8767 @smallexample
8768 @group
8769 (nthcdr 3 '(1 2 3 4 5 6 7))
8770 @result{} (4 5 6 7)
8771 @end group
8772 @end smallexample
8773
8774 @item setcar
8775 @itemx setcdr
8776 @code{setcar} changes the first element of a list; @code{setcdr}
8777 changes the second and subsequent elements of a list.
8778
8779 @need 1250
8780 For example:
8781
8782 @smallexample
8783 @group
8784 (setq triple '(1 2 3))
8785
8786 (setcar triple '37)
8787
8788 triple
8789 @result{} (37 2 3)
8790
8791 (setcdr triple '("foo" "bar"))
8792
8793 triple
8794 @result{} (37 "foo" "bar")
8795 @end group
8796 @end smallexample
8797
8798 @item progn
8799 Evaluate each argument in sequence and then return the value of the
8800 last.
8801
8802 @need 1250
8803 For example:
8804
8805 @smallexample
8806 @group
8807 (progn 1 2 3 4)
8808 @result{} 4
8809 @end group
8810 @end smallexample
8811
8812 @item save-restriction
8813 Record whatever narrowing is in effect in the current buffer, if any,
8814 and restore that narrowing after evaluating the arguments.
8815
8816 @item search-forward
8817 Search for a string, and if the string is found, move point.
8818
8819 @need 1250
8820 @noindent
8821 Takes four arguments:
8822
8823 @enumerate
8824 @item
8825 The string to search for.
8826
8827 @item
8828 Optionally, the limit of the search.
8829
8830 @item
8831 Optionally, what to do if the search fails, return @code{nil} or an
8832 error message.
8833
8834 @item
8835 Optionally, how many times to repeat the search; if negative, the
8836 search goes backwards.
8837 @end enumerate
8838
8839 @item kill-region
8840 @itemx delete-region
8841 @itemx copy-region-as-kill
8842
8843 @code{kill-region} cuts the text between point and mark from the
8844 buffer and stores that text in the kill ring, so you can get it back
8845 by yanking.
8846
8847 @code{delete-and-extract-region} removes the text between point and
8848 mark from the buffer and throws it away. You cannot get it back.
8849
8850 @code{copy-region-as-kill} copies the text between point and mark into
8851 the kill ring, from which you can get it by yanking. The function
8852 does not cut or remove the text from the buffer.
8853 @end table
8854
8855 @need 1500
8856 @node search Exercises, , cons & search-fwd Review, Cutting & Storing Text
8857 @section Searching Exercises
8858
8859 @itemize @bullet
8860 @item
8861 Write an interactive function that searches for a string. If the
8862 search finds the string, leave point after it and display a message
8863 that says ``Found!''. (Do not use @code{search-forward} for the name
8864 of this function; if you do, you will overwrite the existing version of
8865 @code{search-forward} that comes with Emacs. Use a name such as
8866 @code{test-search} instead.)
8867
8868 @item
8869 Write a function that prints the third element of the kill ring in the
8870 echo area, if any; if the kill ring does not contain a third element,
8871 print an appropriate message.
8872 @end itemize
8873
8874 @node List Implementation, Yanking, Cutting & Storing Text, Top
8875 @comment node-name, next, previous, up
8876 @chapter How Lists are Implemented
8877 @cindex Lists in a computer
8878
8879 In Lisp, atoms are recorded in a straightforward fashion; if the
8880 implementation is not straightforward in practice, it is, nonetheless,
8881 straightforward in theory. The atom @samp{rose}, for example, is
8882 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8883 @samp{e}. A list, on the other hand, is kept differently. The mechanism
8884 is equally simple, but it takes a moment to get used to the idea. A
8885 list is kept using a series of pairs of pointers. In the series, the
8886 first pointer in each pair points to an atom or to another list, and the
8887 second pointer in each pair points to the next pair, or to the symbol
8888 @code{nil}, which marks the end of the list.
8889
8890 A pointer itself is quite simply the electronic address of what is
8891 pointed to. Hence, a list is kept as a series of electronic addresses.
8892
8893 @menu
8894 * Lists diagrammed::
8895 * Symbols as Chest:: Exploring a powerful metaphor.
8896 * List Exercise::
8897 @end menu
8898
8899 @node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8900 @ifnottex
8901 @unnumberedsec Lists diagrammed
8902 @end ifnottex
8903
8904 For example, the list @code{(rose violet buttercup)} has three elements,
8905 @samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
8906 electronic address of @samp{rose} is recorded in a segment of computer
8907 memory along with the address that gives the electronic address of where
8908 the atom @samp{violet} is located; and that address (the one that tells
8909 where @samp{violet} is located) is kept along with an address that tells
8910 where the address for the atom @samp{buttercup} is located.
8911
8912 @need 1200
8913 This sounds more complicated than it is and is easier seen in a diagram:
8914
8915 @c clear print-postscript-figures
8916 @c !!! cons-cell-diagram #1
8917 @ifnottex
8918 @smallexample
8919 @group
8920 ___ ___ ___ ___ ___ ___
8921 |___|___|--> |___|___|--> |___|___|--> nil
8922 | | |
8923 | | |
8924 --> rose --> violet --> buttercup
8925 @end group
8926 @end smallexample
8927 @end ifnottex
8928 @ifset print-postscript-figures
8929 @sp 1
8930 @tex
8931 @image{cons-1}
8932 %%%% old method of including an image
8933 % \input /usr/local/lib/tex/inputs/psfig.tex
8934 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8935 % \catcode`\@=0 %
8936 @end tex
8937 @sp 1
8938 @end ifset
8939 @ifclear print-postscript-figures
8940 @iftex
8941 @smallexample
8942 @group
8943 ___ ___ ___ ___ ___ ___
8944 |___|___|--> |___|___|--> |___|___|--> nil
8945 | | |
8946 | | |
8947 --> rose --> violet --> buttercup
8948 @end group
8949 @end smallexample
8950 @end iftex
8951 @end ifclear
8952
8953 @noindent
8954 In the diagram, each box represents a word of computer memory that
8955 holds a Lisp object, usually in the form of a memory address. The boxes,
8956 i.e.@: the addresses, are in pairs. Each arrow points to what the address
8957 is the address of, either an atom or another pair of addresses. The
8958 first box is the electronic address of @samp{rose} and the arrow points
8959 to @samp{rose}; the second box is the address of the next pair of boxes,
8960 the first part of which is the address of @samp{violet} and the second
8961 part of which is the address of the next pair. The very last box
8962 points to the symbol @code{nil}, which marks the end of the list.
8963
8964 @need 1200
8965 When a variable is set to a list with a function such as @code{setq},
8966 it stores the address of the first box in the variable. Thus,
8967 evaluation of the expression
8968
8969 @smallexample
8970 (setq bouquet '(rose violet buttercup))
8971 @end smallexample
8972
8973 @need 1250
8974 @noindent
8975 creates a situation like this:
8976
8977 @c cons-cell-diagram #2
8978 @ifnottex
8979 @smallexample
8980 @group
8981 bouquet
8982 |
8983 | ___ ___ ___ ___ ___ ___
8984 --> |___|___|--> |___|___|--> |___|___|--> nil
8985 | | |
8986 | | |
8987 --> rose --> violet --> buttercup
8988 @end group
8989 @end smallexample
8990 @end ifnottex
8991 @ifset print-postscript-figures
8992 @sp 1
8993 @tex
8994 @image{cons-2}
8995 %%%% old method of including an image
8996 % \input /usr/local/lib/tex/inputs/psfig.tex
8997 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
8998 % \catcode`\@=0 %
8999 @end tex
9000 @sp 1
9001 @end ifset
9002 @ifclear print-postscript-figures
9003 @iftex
9004 @smallexample
9005 @group
9006 bouquet
9007 |
9008 | ___ ___ ___ ___ ___ ___
9009 --> |___|___|--> |___|___|--> |___|___|--> nil
9010 | | |
9011 | | |
9012 --> rose --> violet --> buttercup
9013 @end group
9014 @end smallexample
9015 @end iftex
9016 @end ifclear
9017
9018 @noindent
9019 In this example, the symbol @code{bouquet} holds the address of the first
9020 pair of boxes.
9021
9022 @need 1200
9023 This same list can be illustrated in a different sort of box notation
9024 like this:
9025
9026 @c cons-cell-diagram #2a
9027 @ifnottex
9028 @smallexample
9029 @group
9030 bouquet
9031 |
9032 | -------------- --------------- ----------------
9033 | | car | cdr | | car | cdr | | car | cdr |
9034 -->| rose | o------->| violet | o------->| butter- | nil |
9035 | | | | | | | cup | |
9036 -------------- --------------- ----------------
9037 @end group
9038 @end smallexample
9039 @end ifnottex
9040 @ifset print-postscript-figures
9041 @sp 1
9042 @tex
9043 @image{cons-2a}
9044 %%%% old method of including an image
9045 % \input /usr/local/lib/tex/inputs/psfig.tex
9046 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9047 % \catcode`\@=0 %
9048 @end tex
9049 @sp 1
9050 @end ifset
9051 @ifclear print-postscript-figures
9052 @iftex
9053 @smallexample
9054 @group
9055 bouquet
9056 |
9057 | -------------- --------------- ----------------
9058 | | car | cdr | | car | cdr | | car | cdr |
9059 -->| rose | o------->| violet | o------->| butter- | nil |
9060 | | | | | | | cup | |
9061 -------------- --------------- ----------------
9062 @end group
9063 @end smallexample
9064 @end iftex
9065 @end ifclear
9066
9067 (Symbols consist of more than pairs of addresses, but the structure of
9068 a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9069 consists of a group of address-boxes, one of which is the address of
9070 the printed word @samp{bouquet}, a second of which is the address of a
9071 function definition attached to the symbol, if any, a third of which
9072 is the address of the first pair of address-boxes for the list
9073 @code{(rose violet buttercup)}, and so on. Here we are showing that
9074 the symbol's third address-box points to the first pair of
9075 address-boxes for the list.)
9076
9077 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9078 changed; the symbol simply has an address further down the list. (In
9079 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9080 evaluation of the following expression
9081
9082 @smallexample
9083 (setq flowers (cdr bouquet))
9084 @end smallexample
9085
9086 @need 800
9087 @noindent
9088 produces this:
9089
9090 @c cons-cell-diagram #3
9091 @ifnottex
9092 @sp 1
9093 @smallexample
9094 @group
9095 bouquet flowers
9096 | |
9097 | ___ ___ | ___ ___ ___ ___
9098 --> | | | --> | | | | | |
9099 |___|___|----> |___|___|--> |___|___|--> nil
9100 | | |
9101 | | |
9102 --> rose --> violet --> buttercup
9103 @end group
9104 @end smallexample
9105 @sp 1
9106 @end ifnottex
9107 @ifset print-postscript-figures
9108 @sp 1
9109 @tex
9110 @image{cons-3}
9111 %%%% old method of including an image
9112 % \input /usr/local/lib/tex/inputs/psfig.tex
9113 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9114 % \catcode`\@=0 %
9115 @end tex
9116 @sp 1
9117 @end ifset
9118 @ifclear print-postscript-figures
9119 @iftex
9120 @sp 1
9121 @smallexample
9122 @group
9123 bouquet flowers
9124 | |
9125 | ___ ___ | ___ ___ ___ ___
9126 --> | | | --> | | | | | |
9127 |___|___|----> |___|___|--> |___|___|--> nil
9128 | | |
9129 | | |
9130 --> rose --> violet --> buttercup
9131 @end group
9132 @end smallexample
9133 @sp 1
9134 @end iftex
9135 @end ifclear
9136
9137 @noindent
9138 The value of @code{flowers} is @code{(violet buttercup)}, which is
9139 to say, the symbol @code{flowers} holds the address of the pair of
9140 address-boxes, the first of which holds the address of @code{violet},
9141 and the second of which holds the address of @code{buttercup}.
9142
9143 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9144 pair}. @xref{List Type, , List Type , elisp, The GNU Emacs Lisp
9145 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9146 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9147 information about cons cells and dotted pairs.
9148
9149 @need 1200
9150 The function @code{cons} adds a new pair of addresses to the front of
9151 a series of addresses like that shown above. For example, evaluating
9152 the expression
9153
9154 @smallexample
9155 (setq bouquet (cons 'lily bouquet))
9156 @end smallexample
9157
9158 @need 1500
9159 @noindent
9160 produces:
9161
9162 @c cons-cell-diagram #4
9163 @ifnottex
9164 @sp 1
9165 @smallexample
9166 @group
9167 bouquet flowers
9168 | |
9169 | ___ ___ ___ ___ | ___ ___ ___ ___
9170 --> | | | | | | --> | | | | | |
9171 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9172 | | | |
9173 | | | |
9174 --> lily --> rose --> violet --> buttercup
9175 @end group
9176 @end smallexample
9177 @sp 1
9178 @end ifnottex
9179 @ifset print-postscript-figures
9180 @sp 1
9181 @tex
9182 @image{cons-4}
9183 %%%% old method of including an image
9184 % \input /usr/local/lib/tex/inputs/psfig.tex
9185 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9186 % \catcode`\@=0 %
9187 @end tex
9188 @sp 1
9189 @end ifset
9190 @ifclear print-postscript-figures
9191 @iftex
9192 @sp 1
9193 @smallexample
9194 @group
9195 bouquet flowers
9196 | |
9197 | ___ ___ ___ ___ | ___ ___ ___ ___
9198 --> | | | | | | --> | | | | | |
9199 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9200 | | | |
9201 | | | |
9202 --> lily --> rose --> violet --> buttercup
9203 @end group
9204 @end smallexample
9205 @sp 1
9206 @end iftex
9207 @end ifclear
9208
9209 @need 1200
9210 @noindent
9211 However, this does not change the value of the symbol
9212 @code{flowers}, as you can see by evaluating the following,
9213
9214 @smallexample
9215 (eq (cdr (cdr bouquet)) flowers)
9216 @end smallexample
9217
9218 @noindent
9219 which returns @code{t} for true.
9220
9221 Until it is reset, @code{flowers} still has the value
9222 @code{(violet buttercup)}; that is, it has the address of the cons
9223 cell whose first address is of @code{violet}. Also, this does not
9224 alter any of the pre-existing cons cells; they are all still there.
9225
9226 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9227 of the next cons cell in the series; to get the @sc{car} of a list,
9228 you get the address of the first element of the list; to @code{cons} a
9229 new element on a list, you add a new cons cell to the front of the list.
9230 That is all there is to it! The underlying structure of Lisp is
9231 brilliantly simple!
9232
9233 And what does the last address in a series of cons cells refer to? It
9234 is the address of the empty list, of @code{nil}.
9235
9236 In summary, when a Lisp variable is set to a value, it is provided with
9237 the address of the list to which the variable refers.
9238
9239 @node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9240 @section Symbols as a Chest of Drawers
9241 @cindex Symbols as a Chest of Drawers
9242 @cindex Chest of Drawers, metaphor for a symbol
9243 @cindex Drawers, Chest of, metaphor for a symbol
9244
9245 In an earlier section, I suggested that you might imagine a symbol as
9246 being a chest of drawers. The function definition is put in one
9247 drawer, the value in another, and so on. What is put in the drawer
9248 holding the value can be changed without affecting the contents of the
9249 drawer holding the function definition, and vice-versa.
9250
9251 Actually, what is put in each drawer is the address of the value or
9252 function definition. It is as if you found an old chest in the attic,
9253 and in one of its drawers you found a map giving you directions to
9254 where the buried treasure lies.
9255
9256 (In addition to its name, symbol definition, and variable value, a
9257 symbol has a `drawer' for a @dfn{property list} which can be used to
9258 record other information. Property lists are not discussed here; see
9259 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9260 Reference Manual}.)
9261
9262 @need 1500
9263 Here is a fanciful representation:
9264
9265 @c chest-of-drawers diagram
9266 @ifnottex
9267 @sp 1
9268 @smallexample
9269 @group
9270 Chest of Drawers Contents of Drawers
9271
9272 __ o0O0o __
9273 / \
9274 ---------------------
9275 | directions to | [map to]
9276 | symbol name | bouquet
9277 | |
9278 +---------------------+
9279 | directions to |
9280 | symbol definition | [none]
9281 | |
9282 +---------------------+
9283 | directions to | [map to]
9284 | variable value | (rose violet buttercup)
9285 | |
9286 +---------------------+
9287 | directions to |
9288 | property list | [not described here]
9289 | |
9290 +---------------------+
9291 |/ \|
9292 @end group
9293 @end smallexample
9294 @sp 1
9295 @end ifnottex
9296 @ifset print-postscript-figures
9297 @sp 1
9298 @tex
9299 @image{drawers}
9300 %%%% old method of including an image
9301 % \input /usr/local/lib/tex/inputs/psfig.tex
9302 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9303 % \catcode`\@=0 %
9304 @end tex
9305 @sp 1
9306 @end ifset
9307 @ifclear print-postscript-figures
9308 @iftex
9309 @sp 1
9310 @smallexample
9311 @group
9312 Chest of Drawers Contents of Drawers
9313
9314 __ o0O0o __
9315 / \
9316 ---------------------
9317 | directions to | [map to]
9318 | symbol name | bouquet
9319 | |
9320 +---------------------+
9321 | directions to |
9322 | symbol definition | [none]
9323 | |
9324 +---------------------+
9325 | directions to | [map to]
9326 | variable value | (rose violet buttercup)
9327 | |
9328 +---------------------+
9329 | directions to |
9330 | property list | [not described here]
9331 | |
9332 +---------------------+
9333 |/ \|
9334 @end group
9335 @end smallexample
9336 @sp 1
9337 @end iftex
9338 @end ifclear
9339
9340 @node List Exercise, , Symbols as Chest, List Implementation
9341 @section Exercise
9342
9343 Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
9344 more flowers on to this list and set this new list to
9345 @code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
9346 What does the @code{more-flowers} list now contain?
9347
9348 @node Yanking, Loops & Recursion, List Implementation, Top
9349 @comment node-name, next, previous, up
9350 @chapter Yanking Text Back
9351 @findex yank
9352 @findex rotate-yank-pointer
9353 @cindex Text retrieval
9354 @cindex Retrieving text
9355 @cindex Pasting text
9356
9357 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9358 you can bring it back with a `yank' command. The text that is cut out of
9359 the buffer is put in the kill ring and the yank commands insert the
9360 appropriate contents of the kill ring back into a buffer (not necessarily
9361 the original buffer).
9362
9363 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9364 the kill ring into the current buffer. If the @kbd{C-y} command is
9365 followed immediately by @kbd{M-y}, the first element is replaced by
9366 the second element. Successive @kbd{M-y} commands replace the second
9367 element with the third, fourth, or fifth element, and so on. When the
9368 last element in the kill ring is reached, it is replaced by the first
9369 element and the cycle is repeated. (Thus the kill ring is called a
9370 `ring' rather than just a `list'. However, the actual data structure
9371 that holds the text is a list.
9372 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9373 list is handled as a ring.)
9374
9375 @menu
9376 * Kill Ring Overview:: The kill ring is a list.
9377 * kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
9378 * yank nthcdr Exercises::
9379 @end menu
9380
9381 @node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9382 @comment node-name, next, previous, up
9383 @section Kill Ring Overview
9384 @cindex Kill ring overview
9385
9386 The kill ring is a list of textual strings. This is what it looks like:
9387
9388 @smallexample
9389 ("some text" "a different piece of text" "yet more text")
9390 @end smallexample
9391
9392 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9393 string of characters saying @samp{some text} would be inserted in this
9394 buffer where my cursor is located.
9395
9396 The @code{yank} command is also used for duplicating text by copying it.
9397 The copied text is not cut from the buffer, but a copy of it is put on the
9398 kill ring and is inserted by yanking it back.
9399
9400 Three functions are used for bringing text back from the kill ring:
9401 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9402 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9403 which is used by the two other functions.
9404
9405 These functions refer to the kill ring through a variable called the
9406 @code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
9407 @code{yank} and @code{yank-pop} functions is:
9408
9409 @smallexample
9410 (insert (car kill-ring-yank-pointer))
9411 @end smallexample
9412
9413 To begin to understand how @code{yank} and @code{yank-pop} work, it is
9414 first necessary to look at the @code{kill-ring-yank-pointer} variable
9415 and the @code{rotate-yank-pointer} function.
9416
9417 @node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9418 @comment node-name, next, previous, up
9419 @section The @code{kill-ring-yank-pointer} Variable
9420
9421 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9422 a variable. It points to something by being bound to the value of what
9423 it points to, like any other Lisp variable.
9424
9425 @need 1000
9426 Thus, if the value of the kill ring is:
9427
9428 @smallexample
9429 ("some text" "a different piece of text" "yet more text")
9430 @end smallexample
9431
9432 @need 1250
9433 @noindent
9434 and the @code{kill-ring-yank-pointer} points to the second clause, the
9435 value of @code{kill-ring-yank-pointer} is:
9436
9437 @smallexample
9438 ("a different piece of text" "yet more text")
9439 @end smallexample
9440
9441 As explained in the previous chapter (@pxref{List Implementation}), the
9442 computer does not keep two different copies of the text being pointed to
9443 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
9444 words ``a different piece of text'' and ``yet more text'' are not
9445 duplicated. Instead, the two Lisp variables point to the same pieces of
9446 text. Here is a diagram:
9447
9448 @c cons-cell-diagram #5
9449 @ifnottex
9450 @smallexample
9451 @group
9452 kill-ring kill-ring-yank-pointer
9453 | |
9454 | ___ ___ | ___ ___ ___ ___
9455 ---> | | | --> | | | | | |
9456 |___|___|----> |___|___|--> |___|___|--> nil
9457 | | |
9458 | | |
9459 | | --> "yet more text"
9460 | |
9461 | --> "a different piece of text
9462 |
9463 --> "some text"
9464 @end group
9465 @end smallexample
9466 @sp 1
9467 @end ifnottex
9468 @ifset print-postscript-figures
9469 @sp 1
9470 @tex
9471 @image{cons-5}
9472 %%%% old method of including an image
9473 % \input /usr/local/lib/tex/inputs/psfig.tex
9474 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9475 % \catcode`\@=0 %
9476 @end tex
9477 @sp 1
9478 @end ifset
9479 @ifclear print-postscript-figures
9480 @iftex
9481 @smallexample
9482 @group
9483 kill-ring kill-ring-yank-pointer
9484 | |
9485 | ___ ___ | ___ ___ ___ ___
9486 ---> | | | --> | | | | | |
9487 |___|___|----> |___|___|--> |___|___|--> nil
9488 | | |
9489 | | |
9490 | | --> "yet more text"
9491 | |
9492 | --> "a different piece of text
9493 |
9494 --> "some text"
9495 @end group
9496 @end smallexample
9497 @sp 1
9498 @end iftex
9499 @end ifclear
9500
9501 Both the variable @code{kill-ring} and the variable
9502 @code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
9503 usually described as if it were actually what it is composed of. The
9504 @code{kill-ring} is spoken of as if it were the list rather than that it
9505 points to the list. Conversely, the @code{kill-ring-yank-pointer} is
9506 spoken of as pointing to a list.
9507
9508 These two ways of talking about the same thing sound confusing at first but
9509 make sense on reflection. The kill ring is generally thought of as the
9510 complete structure of data that holds the information of what has recently
9511 been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
9512 on the other hand, serves to indicate---that is, to `point to'---that part
9513 of the kill ring of which the first element (the @sc{car}) will be
9514 inserted.
9515
9516 The @code{rotate-yank-pointer} function changes the element in the
9517 kill ring to which the @code{kill-ring-yank-pointer} points; when the
9518 pointer is set to point to the next element beyond the end of the kill
9519 ring, it automatically sets it to point to the first element of the
9520 kill ring. This is how the list is transformed into a ring. The
9521 @code{rotate-yank-pointer} function itself is not difficult, but
9522 contains many details. It and the much simpler @code{yank} and
9523 @code{yank-pop} functions are described in an appendix.
9524 @xref{Kill Ring, , Handling the Kill Ring}.
9525
9526 @need 1500
9527 @node yank nthcdr Exercises, , kill-ring-yank-pointer, Yanking
9528 @section Exercises with @code{yank} and @code{nthcdr}
9529
9530 @itemize @bullet
9531 @item
9532 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9533 your kill ring. Add several items to your kill ring; look at its
9534 value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
9535 around the kill ring. How many items were in your kill ring? Find
9536 the value of @code{kill-ring-max}. Was your kill ring full, or could
9537 you have kept more blocks of text within it?
9538
9539 @item
9540 Using @code{nthcdr} and @code{car}, construct a series of expressions
9541 to return the first, second, third, and fourth elements of a list.
9542 @end itemize
9543
9544 @node Loops & Recursion, Regexp Search, Yanking, Top
9545 @comment node-name, next, previous, up
9546 @chapter Loops and Recursion
9547 @cindex Loops and recursion
9548 @cindex Recursion and loops
9549 @cindex Repetition (loops)
9550
9551 Emacs Lisp has two primary ways to cause an expression, or a series of
9552 expressions, to be evaluated repeatedly: one uses a @code{while}
9553 loop, and the other uses @dfn{recursion}.
9554
9555 Repetition can be very valuable. For example, to move forward four
9556 sentences, you need only write a program that will move forward one
9557 sentence and then repeat the process four times. Since a computer does
9558 not get bored or tired, such repetitive action does not have the
9559 deleterious effects that excessive or the wrong kinds of repetition can
9560 have on humans.
9561
9562 People mostly write Emacs Lisp functions using @code{while} loops and
9563 their kin; but you can use recursion, which provides a very powerful
9564 way to think about and then to solve problems@footnote{You can write
9565 recursive functions to be frugal or wasteful of mental or computer
9566 resources; as it happens, methods that people find easy---that are
9567 frugal of `mental resources'---sometimes use considerable computer
9568 resources. Emacs was designed to run on machines that we now consider
9569 limited and its default settings are conservative. You may want to
9570 increase the values of @code{max-specpdl-size} and
9571 @code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
9572 15 and 30 times their default value.}.
9573
9574 @menu
9575 * while:: Causing a stretch of code to repeat.
9576 * dolist dotimes::
9577 * Recursion:: Causing a function to call itself.
9578 * Looping exercise::
9579 @end menu
9580
9581 @node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9582 @comment node-name, next, previous, up
9583 @section @code{while}
9584 @cindex Loops
9585 @findex while
9586
9587 The @code{while} special form tests whether the value returned by
9588 evaluating its first argument is true or false. This is similar to what
9589 the Lisp interpreter does with an @code{if}; what the interpreter does
9590 next, however, is different.
9591
9592 In a @code{while} expression, if the value returned by evaluating the
9593 first argument is false, the Lisp interpreter skips the rest of the
9594 expression (the @dfn{body} of the expression) and does not evaluate it.
9595 However, if the value is true, the Lisp interpreter evaluates the body
9596 of the expression and then again tests whether the first argument to
9597 @code{while} is true or false. If the value returned by evaluating the
9598 first argument is again true, the Lisp interpreter again evaluates the
9599 body of the expression.
9600
9601 @need 1200
9602 The template for a @code{while} expression looks like this:
9603
9604 @smallexample
9605 @group
9606 (while @var{true-or-false-test}
9607 @var{body}@dots{})
9608 @end group
9609 @end smallexample
9610
9611 @menu
9612 * Looping with while:: Repeat so long as test returns true.
9613 * Loop Example:: A @code{while} loop that uses a list.
9614 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
9615 * Incrementing Loop:: A loop with an incrementing counter.
9616 * Decrementing Loop:: A loop with a decrementing counter.
9617 @end menu
9618
9619 @node Looping with while, Loop Example, while, while
9620 @ifnottex
9621 @unnumberedsubsec Looping with @code{while}
9622 @end ifnottex
9623
9624 So long as the true-or-false-test of the @code{while} expression
9625 returns a true value when it is evaluated, the body is repeatedly
9626 evaluated. This process is called a loop since the Lisp interpreter
9627 repeats the same thing again and again, like an airplane doing a loop.
9628 When the result of evaluating the true-or-false-test is false, the
9629 Lisp interpreter does not evaluate the rest of the @code{while}
9630 expression and `exits the loop'.
9631
9632 Clearly, if the value returned by evaluating the first argument to
9633 @code{while} is always true, the body following will be evaluated
9634 again and again @dots{} and again @dots{} forever. Conversely, if the
9635 value returned is never true, the expressions in the body will never
9636 be evaluated. The craft of writing a @code{while} loop consists of
9637 choosing a mechanism such that the true-or-false-test returns true
9638 just the number of times that you want the subsequent expressions to
9639 be evaluated, and then have the test return false.
9640
9641 The value returned by evaluating a @code{while} is the value of the
9642 true-or-false-test. An interesting consequence of this is that a
9643 @code{while} loop that evaluates without error will return @code{nil}
9644 or false regardless of whether it has looped 1 or 100 times or none at
9645 all. A @code{while} expression that evaluates successfully never
9646 returns a true value! What this means is that @code{while} is always
9647 evaluated for its side effects, which is to say, the consequences of
9648 evaluating the expressions within the body of the @code{while} loop.
9649 This makes sense. It is not the mere act of looping that is desired,
9650 but the consequences of what happens when the expressions in the loop
9651 are repeatedly evaluated.
9652
9653 @node Loop Example, print-elements-of-list, Looping with while, while
9654 @comment node-name, next, previous, up
9655 @subsection A @code{while} Loop and a List
9656
9657 A common way to control a @code{while} loop is to test whether a list
9658 has any elements. If it does, the loop is repeated; but if it does not,
9659 the repetition is ended. Since this is an important technique, we will
9660 create a short example to illustrate it.
9661
9662 A simple way to test whether a list has elements is to evaluate the
9663 list: if it has no elements, it is an empty list and will return the
9664 empty list, @code{()}, which is a synonym for @code{nil} or false. On
9665 the other hand, a list with elements will return those elements when it
9666 is evaluated. Since Emacs Lisp considers as true any value that is not
9667 @code{nil}, a list that returns elements will test true in a
9668 @code{while} loop.
9669
9670 @need 1200
9671 For example, you can set the variable @code{empty-list} to @code{nil} by
9672 evaluating the following @code{setq} expression:
9673
9674 @smallexample
9675 (setq empty-list ())
9676 @end smallexample
9677
9678 @noindent
9679 After evaluating the @code{setq} expression, you can evaluate the
9680 variable @code{empty-list} in the usual way, by placing the cursor after
9681 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9682 echo area:
9683
9684 @smallexample
9685 empty-list
9686 @end smallexample
9687
9688 On the other hand, if you set a variable to be a list with elements, the
9689 list will appear when you evaluate the variable, as you can see by
9690 evaluating the following two expressions:
9691
9692 @smallexample
9693 @group
9694 (setq animals '(gazelle giraffe lion tiger))
9695
9696 animals
9697 @end group
9698 @end smallexample
9699
9700 Thus, to create a @code{while} loop that tests whether there are any
9701 items in the list @code{animals}, the first part of the loop will be
9702 written like this:
9703
9704 @smallexample
9705 @group
9706 (while animals
9707 @dots{}
9708 @end group
9709 @end smallexample
9710
9711 @noindent
9712 When the @code{while} tests its first argument, the variable
9713 @code{animals} is evaluated. It returns a list. So long as the list
9714 has elements, the @code{while} considers the results of the test to be
9715 true; but when the list is empty, it considers the results of the test
9716 to be false.
9717
9718 To prevent the @code{while} loop from running forever, some mechanism
9719 needs to be provided to empty the list eventually. An oft-used
9720 technique is to have one of the subsequent forms in the @code{while}
9721 expression set the value of the list to be the @sc{cdr} of the list.
9722 Each time the @code{cdr} function is evaluated, the list will be made
9723 shorter, until eventually only the empty list will be left. At this
9724 point, the test of the @code{while} loop will return false, and the
9725 arguments to the @code{while} will no longer be evaluated.
9726
9727 For example, the list of animals bound to the variable @code{animals}
9728 can be set to be the @sc{cdr} of the original list with the
9729 following expression:
9730
9731 @smallexample
9732 (setq animals (cdr animals))
9733 @end smallexample
9734
9735 @noindent
9736 If you have evaluated the previous expressions and then evaluate this
9737 expression, you will see @code{(giraffe lion tiger)} appear in the echo
9738 area. If you evaluate the expression again, @code{(lion tiger)} will
9739 appear in the echo area. If you evaluate it again and yet again,
9740 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
9741
9742 A template for a @code{while} loop that uses the @code{cdr} function
9743 repeatedly to cause the true-or-false-test eventually to test false
9744 looks like this:
9745
9746 @smallexample
9747 @group
9748 (while @var{test-whether-list-is-empty}
9749 @var{body}@dots{}
9750 @var{set-list-to-cdr-of-list})
9751 @end group
9752 @end smallexample
9753
9754 This test and use of @code{cdr} can be put together in a function that
9755 goes through a list and prints each element of the list on a line of its
9756 own.
9757
9758 @node print-elements-of-list, Incrementing Loop, Loop Example, while
9759 @subsection An Example: @code{print-elements-of-list}
9760 @findex print-elements-of-list
9761
9762 The @code{print-elements-of-list} function illustrates a @code{while}
9763 loop with a list.
9764
9765 @cindex @file{*scratch*} buffer
9766 The function requires several lines for its output. If you are
9767 reading this in Emacs 21 or a later version, you can evaluate the
9768 following expression inside of Info, as usual.
9769
9770 If you are using an earlier version of Emacs, you need to copy the
9771 necessary expressions to your @file{*scratch*} buffer and evaluate
9772 them there. This is because the echo area had only one line in the
9773 earlier versions.
9774
9775 You can copy the expressions by marking the beginning of the region
9776 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9777 the end of the region and then copying the region using @kbd{M-w}
9778 (@code{copy-region-as-kill}). In the @file{*scratch*} buffer, you can
9779 yank the expressions back by typing @kbd{C-y} (@code{yank}).
9780
9781 After you have copied the expressions to the @file{*scratch*} buffer,
9782 evaluate each expression in turn. Be sure to evaluate the last
9783 expression, @code{(print-elements-of-list animals)}, by typing
9784 @kbd{C-u C-x C-e}, that is, by giving an argument to
9785 @code{eval-last-sexp}. This will cause the result of the evaluation
9786 to be printed in the @file{*scratch*} buffer instead of being printed
9787 in the echo area. (Otherwise you will see something like this in your
9788 echo area: @code{^Jgiraffe^J^Jgazelle^J^Jlion^J^Jtiger^Jnil}, in which
9789 each @samp{^J} stands for a `newline'.)
9790
9791 @need 1500
9792 If you are using Emacs 21 or later, you can evaluate these expressions
9793 directly in the Info buffer, and the echo area will grow to show the
9794 results.
9795
9796 @smallexample
9797 @group
9798 (setq animals '(gazelle giraffe lion tiger))
9799
9800 (defun print-elements-of-list (list)
9801 "Print each element of LIST on a line of its own."
9802 (while list
9803 (print (car list))
9804 (setq list (cdr list))))
9805
9806 (print-elements-of-list animals)
9807 @end group
9808 @end smallexample
9809
9810 @need 1200
9811 @noindent
9812 When you evaluate the three expressions in sequence, you will see
9813 this:
9814
9815 @smallexample
9816 @group
9817 giraffe
9818
9819 gazelle
9820
9821 lion
9822
9823 tiger
9824 nil
9825 @end group
9826 @end smallexample
9827
9828 Each element of the list is printed on a line of its own (that is what
9829 the function @code{print} does) and then the value returned by the
9830 function is printed. Since the last expression in the function is the
9831 @code{while} loop, and since @code{while} loops always return
9832 @code{nil}, a @code{nil} is printed after the last element of the list.
9833
9834 @node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9835 @comment node-name, next, previous, up
9836 @subsection A Loop with an Incrementing Counter
9837
9838 A loop is not useful unless it stops when it ought. Besides
9839 controlling a loop with a list, a common way of stopping a loop is to
9840 write the first argument as a test that returns false when the correct
9841 number of repetitions are complete. This means that the loop must
9842 have a counter---an expression that counts how many times the loop
9843 repeats itself.
9844
9845 The test can be an expression such as @code{(< count desired-number)}
9846 which returns @code{t} for true if the value of @code{count} is less
9847 than the @code{desired-number} of repetitions and @code{nil} for false if
9848 the value of @code{count} is equal to or is greater than the
9849 @code{desired-number}. The expression that increments the count can be
9850 a simple @code{setq} such as @code{(setq count (1+ count))}, where
9851 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
9852 argument. (The expression @code{(1+ count)} has the same result as
9853 @code{(+ count 1)}, but is easier for a human to read.)
9854
9855 @need 1250
9856 The template for a @code{while} loop controlled by an incrementing
9857 counter looks like this:
9858
9859 @smallexample
9860 @group
9861 @var{set-count-to-initial-value}
9862 (while (< count desired-number) ; @r{true-or-false-test}
9863 @var{body}@dots{}
9864 (setq count (1+ count))) ; @r{incrementer}
9865 @end group
9866 @end smallexample
9867
9868 @noindent
9869 Note that you need to set the initial value of @code{count}; usually it
9870 is set to 1.
9871
9872 @menu
9873 * Incrementing Example:: Counting pebbles in a triangle.
9874 * Inc Example parts:: The parts of the function definition.
9875 * Inc Example altogether:: Putting the function definition together.
9876 @end menu
9877
9878 @node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9879 @unnumberedsubsubsec Example with incrementing counter
9880
9881 Suppose you are playing on the beach and decide to make a triangle of
9882 pebbles, putting one pebble in the first row, two in the second row,
9883 three in the third row and so on, like this:
9884
9885 @sp 1
9886 @c pebble diagram
9887 @ifnottex
9888 @smallexample
9889 @group
9890 *
9891 * *
9892 * * *
9893 * * * *
9894 @end group
9895 @end smallexample
9896 @end ifnottex
9897 @iftex
9898 @smallexample
9899 @group
9900 @bullet{}
9901 @bullet{} @bullet{}
9902 @bullet{} @bullet{} @bullet{}
9903 @bullet{} @bullet{} @bullet{} @bullet{}
9904 @end group
9905 @end smallexample
9906 @end iftex
9907 @sp 1
9908
9909 @noindent
9910 (About 2500 years ago, Pythagoras and others developed the beginnings of
9911 number theory by considering questions such as this.)
9912
9913 Suppose you want to know how many pebbles you will need to make a
9914 triangle with 7 rows?
9915
9916 Clearly, what you need to do is add up the numbers from 1 to 7. There
9917 are two ways to do this; start with the smallest number, one, and add up
9918 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9919 number and add the list going down: 7, 6, 5, 4 and so on. Because both
9920 mechanisms illustrate common ways of writing @code{while} loops, we will
9921 create two examples, one counting up and the other counting down. In
9922 this first example, we will start with 1 and add 2, 3, 4 and so on.
9923
9924 If you are just adding up a short list of numbers, the easiest way to do
9925 it is to add up all the numbers at once. However, if you do not know
9926 ahead of time how many numbers your list will have, or if you want to be
9927 prepared for a very long list, then you need to design your addition so
9928 that what you do is repeat a simple process many times instead of doing
9929 a more complex process once.
9930
9931 For example, instead of adding up all the pebbles all at once, what you
9932 can do is add the number of pebbles in the first row, 1, to the number
9933 in the second row, 2, and then add the total of those two rows to the
9934 third row, 3. Then you can add the number in the fourth row, 4, to the
9935 total of the first three rows; and so on.
9936
9937 The critical characteristic of the process is that each repetitive
9938 action is simple. In this case, at each step we add only two numbers,
9939 the number of pebbles in the row and the total already found. This
9940 process of adding two numbers is repeated again and again until the last
9941 row has been added to the total of all the preceding rows. In a more
9942 complex loop the repetitive action might not be so simple, but it will
9943 be simpler than doing everything all at once.
9944
9945 @node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9946 @unnumberedsubsubsec The parts of the function definition
9947
9948 The preceding analysis gives us the bones of our function definition:
9949 first, we will need a variable that we can call @code{total} that will
9950 be the total number of pebbles. This will be the value returned by
9951 the function.
9952
9953 Second, we know that the function will require an argument: this
9954 argument will be the total number of rows in the triangle. It can be
9955 called @code{number-of-rows}.
9956
9957 Finally, we need a variable to use as a counter. We could call this
9958 variable @code{counter}, but a better name is @code{row-number}.
9959 That is because what the counter does is count rows, and a program
9960 should be written to be as understandable as possible.
9961
9962 When the Lisp interpreter first starts evaluating the expressions in the
9963 function, the value of @code{total} should be set to zero, since we have
9964 not added anything to it. Then the function should add the number of
9965 pebbles in the first row to the total, and then add the number of
9966 pebbles in the second to the total, and then add the number of
9967 pebbles in the third row to the total, and so on, until there are no
9968 more rows left to add.
9969
9970 Both @code{total} and @code{row-number} are used only inside the
9971 function, so they can be declared as local variables with @code{let}
9972 and given initial values. Clearly, the initial value for @code{total}
9973 should be 0. The initial value of @code{row-number} should be 1,
9974 since we start with the first row. This means that the @code{let}
9975 statement will look like this:
9976
9977 @smallexample
9978 @group
9979 (let ((total 0)
9980 (row-number 1))
9981 @var{body}@dots{})
9982 @end group
9983 @end smallexample
9984
9985 After the internal variables are declared and bound to their initial
9986 values, we can begin the @code{while} loop. The expression that serves
9987 as the test should return a value of @code{t} for true so long as the
9988 @code{row-number} is less than or equal to the @code{number-of-rows}.
9989 (If the expression tests true only so long as the row number is less
9990 than the number of rows in the triangle, the last row will never be
9991 added to the total; hence the row number has to be either less than or
9992 equal to the number of rows.)
9993
9994 @need 1500
9995 @findex <= @r{(less than or equal)}
9996 Lisp provides the @code{<=} function that returns true if the value of
9997 its first argument is less than or equal to the value of its second
9998 argument and false otherwise. So the expression that the @code{while}
9999 will evaluate as its test should look like this:
10000
10001 @smallexample
10002 (<= row-number number-of-rows)
10003 @end smallexample
10004
10005 The total number of pebbles can be found by repeatedly adding the number
10006 of pebbles in a row to the total already found. Since the number of
10007 pebbles in the row is equal to the row number, the total can be found by
10008 adding the row number to the total. (Clearly, in a more complex
10009 situation, the number of pebbles in the row might be related to the row
10010 number in a more complicated way; if this were the case, the row number
10011 would be replaced by the appropriate expression.)
10012
10013 @smallexample
10014 (setq total (+ total row-number))
10015 @end smallexample
10016
10017 @noindent
10018 What this does is set the new value of @code{total} to be equal to the
10019 sum of adding the number of pebbles in the row to the previous total.
10020
10021 After setting the value of @code{total}, the conditions need to be
10022 established for the next repetition of the loop, if there is one. This
10023 is done by incrementing the value of the @code{row-number} variable,
10024 which serves as a counter. After the @code{row-number} variable has
10025 been incremented, the true-or-false-test at the beginning of the
10026 @code{while} loop tests whether its value is still less than or equal to
10027 the value of the @code{number-of-rows} and if it is, adds the new value
10028 of the @code{row-number} variable to the @code{total} of the previous
10029 repetition of the loop.
10030
10031 @need 1200
10032 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10033 @code{row-number} variable can be incremented with this expression:
10034
10035 @smallexample
10036 (setq row-number (1+ row-number))
10037 @end smallexample
10038
10039 @node Inc Example altogether, , Inc Example parts, Incrementing Loop
10040 @unnumberedsubsubsec Putting the function definition together
10041
10042 We have created the parts for the function definition; now we need to
10043 put them together.
10044
10045 @need 800
10046 First, the contents of the @code{while} expression:
10047
10048 @smallexample
10049 @group
10050 (while (<= row-number number-of-rows) ; @r{true-or-false-test}
10051 (setq total (+ total row-number))
10052 (setq row-number (1+ row-number))) ; @r{incrementer}
10053 @end group
10054 @end smallexample
10055
10056 Along with the @code{let} expression varlist, this very nearly
10057 completes the body of the function definition. However, it requires
10058 one final element, the need for which is somewhat subtle.
10059
10060 The final touch is to place the variable @code{total} on a line by
10061 itself after the @code{while} expression. Otherwise, the value returned
10062 by the whole function is the value of the last expression that is
10063 evaluated in the body of the @code{let}, and this is the value
10064 returned by the @code{while}, which is always @code{nil}.
10065
10066 This may not be evident at first sight. It almost looks as if the
10067 incrementing expression is the last expression of the whole function.
10068 But that expression is part of the body of the @code{while}; it is the
10069 last element of the list that starts with the symbol @code{while}.
10070 Moreover, the whole of the @code{while} loop is a list within the body
10071 of the @code{let}.
10072
10073 @need 1250
10074 In outline, the function will look like this:
10075
10076 @smallexample
10077 @group
10078 (defun @var{name-of-function} (@var{argument-list})
10079 "@var{documentation}@dots{}"
10080 (let (@var{varlist})
10081 (while (@var{true-or-false-test})
10082 @var{body-of-while}@dots{} )
10083 @dots{} ) ; @r{Need final expression here.}
10084 @end group
10085 @end smallexample
10086
10087 The result of evaluating the @code{let} is what is going to be returned
10088 by the @code{defun} since the @code{let} is not embedded within any
10089 containing list, except for the @code{defun} as a whole. However, if
10090 the @code{while} is the last element of the @code{let} expression, the
10091 function will always return @code{nil}. This is not what we want!
10092 Instead, what we want is the value of the variable @code{total}. This
10093 is returned by simply placing the symbol as the last element of the list
10094 starting with @code{let}. It gets evaluated after the preceding
10095 elements of the list are evaluated, which means it gets evaluated after
10096 it has been assigned the correct value for the total.
10097
10098 It may be easier to see this by printing the list starting with
10099 @code{let} all on one line. This format makes it evident that the
10100 @var{varlist} and @code{while} expressions are the second and third
10101 elements of the list starting with @code{let}, and the @code{total} is
10102 the last element:
10103
10104 @smallexample
10105 @group
10106 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10107 @end group
10108 @end smallexample
10109
10110 @need 1200
10111 Putting everything together, the @code{triangle} function definition
10112 looks like this:
10113
10114 @smallexample
10115 @group
10116 (defun triangle (number-of-rows) ; @r{Version with}
10117 ; @r{ incrementing counter.}
10118 "Add up the number of pebbles in a triangle.
10119 The first row has one pebble, the second row two pebbles,
10120 the third row three pebbles, and so on.
10121 The argument is NUMBER-OF-ROWS."
10122 @end group
10123 @group
10124 (let ((total 0)
10125 (row-number 1))
10126 (while (<= row-number number-of-rows)
10127 (setq total (+ total row-number))
10128 (setq row-number (1+ row-number)))
10129 total))
10130 @end group
10131 @end smallexample
10132
10133 @need 1200
10134 After you have installed @code{triangle} by evaluating the function, you
10135 can try it out. Here are two examples:
10136
10137 @smallexample
10138 @group
10139 (triangle 4)
10140
10141 (triangle 7)
10142 @end group
10143 @end smallexample
10144
10145 @noindent
10146 The sum of the first four numbers is 10 and the sum of the first seven
10147 numbers is 28.
10148
10149 @node Decrementing Loop, , Incrementing Loop, while
10150 @comment node-name, next, previous, up
10151 @subsection Loop with a Decrementing Counter
10152
10153 Another common way to write a @code{while} loop is to write the test
10154 so that it determines whether a counter is greater than zero. So long
10155 as the counter is greater than zero, the loop is repeated. But when
10156 the counter is equal to or less than zero, the loop is stopped. For
10157 this to work, the counter has to start out greater than zero and then
10158 be made smaller and smaller by a form that is evaluated
10159 repeatedly.
10160
10161 The test will be an expression such as @code{(> counter 0)} which
10162 returns @code{t} for true if the value of @code{counter} is greater
10163 than zero, and @code{nil} for false if the value of @code{counter} is
10164 equal to or less than zero. The expression that makes the number
10165 smaller and smaller can be a simple @code{setq} such as @code{(setq
10166 counter (1- counter))}, where @code{1-} is a built-in function in
10167 Emacs Lisp that subtracts 1 from its argument.
10168
10169 @need 1250
10170 The template for a decrementing @code{while} loop looks like this:
10171
10172 @smallexample
10173 @group
10174 (while (> counter 0) ; @r{true-or-false-test}
10175 @var{body}@dots{}
10176 (setq counter (1- counter))) ; @r{decrementer}
10177 @end group
10178 @end smallexample
10179
10180 @menu
10181 * Decrementing Example:: More pebbles on the beach.
10182 * Dec Example parts:: The parts of the function definition.
10183 * Dec Example altogether:: Putting the function definition together.
10184 @end menu
10185
10186 @node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10187 @unnumberedsubsubsec Example with decrementing counter
10188
10189 To illustrate a loop with a decrementing counter, we will rewrite the
10190 @code{triangle} function so the counter decreases to zero.
10191
10192 This is the reverse of the earlier version of the function. In this
10193 case, to find out how many pebbles are needed to make a triangle with
10194 3 rows, add the number of pebbles in the third row, 3, to the number
10195 in the preceding row, 2, and then add the total of those two rows to
10196 the row that precedes them, which is 1.
10197
10198 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10199 the number of pebbles in the seventh row, 7, to the number in the
10200 preceding row, which is 6, and then add the total of those two rows to
10201 the row that precedes them, which is 5, and so on. As in the previous
10202 example, each addition only involves adding two numbers, the total of
10203 the rows already added up and the number of pebbles in the row that is
10204 being added to the total. This process of adding two numbers is
10205 repeated again and again until there are no more pebbles to add.
10206
10207 We know how many pebbles to start with: the number of pebbles in the
10208 last row is equal to the number of rows. If the triangle has seven
10209 rows, the number of pebbles in the last row is 7. Likewise, we know how
10210 many pebbles are in the preceding row: it is one less than the number in
10211 the row.
10212
10213 @node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10214 @unnumberedsubsubsec The parts of the function definition
10215
10216 We start with three variables: the total number of rows in the
10217 triangle; the number of pebbles in a row; and the total number of
10218 pebbles, which is what we want to calculate. These variables can be
10219 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10220 @code{total}, respectively.
10221
10222 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10223 inside the function and are declared with @code{let}. The initial
10224 value of @code{total} should, of course, be zero. However, the
10225 initial value of @code{number-of-pebbles-in-row} should be equal to
10226 the number of rows in the triangle, since the addition will start with
10227 the longest row.
10228
10229 @need 1250
10230 This means that the beginning of the @code{let} expression will look
10231 like this:
10232
10233 @smallexample
10234 @group
10235 (let ((total 0)
10236 (number-of-pebbles-in-row number-of-rows))
10237 @var{body}@dots{})
10238 @end group
10239 @end smallexample
10240
10241 The total number of pebbles can be found by repeatedly adding the number
10242 of pebbles in a row to the total already found, that is, by repeatedly
10243 evaluating the following expression:
10244
10245 @smallexample
10246 (setq total (+ total number-of-pebbles-in-row))
10247 @end smallexample
10248
10249 @noindent
10250 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10251 the @code{number-of-pebbles-in-row} should be decremented by one, since
10252 the next time the loop repeats, the preceding row will be
10253 added to the total.
10254
10255 The number of pebbles in a preceding row is one less than the number of
10256 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10257 used to compute the number of pebbles in the preceding row. This can be
10258 done with the following expression:
10259
10260 @smallexample
10261 @group
10262 (setq number-of-pebbles-in-row
10263 (1- number-of-pebbles-in-row))
10264 @end group
10265 @end smallexample
10266
10267 Finally, we know that the @code{while} loop should stop making repeated
10268 additions when there are no pebbles in a row. So the test for
10269 the @code{while} loop is simply:
10270
10271 @smallexample
10272 (while (> number-of-pebbles-in-row 0)
10273 @end smallexample
10274
10275 @node Dec Example altogether, , Dec Example parts, Decrementing Loop
10276 @unnumberedsubsubsec Putting the function definition together
10277
10278 We can put these expressions together to create a function definition
10279 that works. However, on examination, we find that one of the local
10280 variables is unneeded!
10281
10282 @need 1250
10283 The function definition looks like this:
10284
10285 @smallexample
10286 @group
10287 ;;; @r{First subtractive version.}
10288 (defun triangle (number-of-rows)
10289 "Add up the number of pebbles in a triangle."
10290 (let ((total 0)
10291 (number-of-pebbles-in-row number-of-rows))
10292 (while (> number-of-pebbles-in-row 0)
10293 (setq total (+ total number-of-pebbles-in-row))
10294 (setq number-of-pebbles-in-row
10295 (1- number-of-pebbles-in-row)))
10296 total))
10297 @end group
10298 @end smallexample
10299
10300 As written, this function works.
10301
10302 However, we do not need @code{number-of-pebbles-in-row}.
10303
10304 @cindex Argument as local variable
10305 When the @code{triangle} function is evaluated, the symbol
10306 @code{number-of-rows} will be bound to a number, giving it an initial
10307 value. That number can be changed in the body of the function as if
10308 it were a local variable, without any fear that such a change will
10309 effect the value of the variable outside of the function. This is a
10310 very useful characteristic of Lisp; it means that the variable
10311 @code{number-of-rows} can be used anywhere in the function where
10312 @code{number-of-pebbles-in-row} is used.
10313
10314 @need 800
10315 Here is a second version of the function written a bit more cleanly:
10316
10317 @smallexample
10318 @group
10319 (defun triangle (number) ; @r{Second version.}
10320 "Return sum of numbers 1 through NUMBER inclusive."
10321 (let ((total 0))
10322 (while (> number 0)
10323 (setq total (+ total number))
10324 (setq number (1- number)))
10325 total))
10326 @end group
10327 @end smallexample
10328
10329 In brief, a properly written @code{while} loop will consist of three parts:
10330
10331 @enumerate
10332 @item
10333 A test that will return false after the loop has repeated itself the
10334 correct number of times.
10335
10336 @item
10337 An expression the evaluation of which will return the value desired
10338 after being repeatedly evaluated.
10339
10340 @item
10341 An expression to change the value passed to the true-or-false-test so
10342 that the test returns false after the loop has repeated itself the right
10343 number of times.
10344 @end enumerate
10345
10346 @node dolist dotimes, Recursion, while, Loops & Recursion
10347 @comment node-name, next, previous, up
10348 @section Save your time: @code{dolist} and @code{dotimes}
10349
10350 In addition to @code{while}, both @code{dolist} and @code{dotimes}
10351 provide for looping. Sometimes these are quicker to write than the
10352 equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
10353 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10354
10355 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10356 list': @code{dolist} automatically shortens the list each time it
10357 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10358 each shorter version of the list to the first of its arguments.
10359
10360 @code{dotimes} loops a specific number of time: you specify the number.
10361
10362 @menu
10363 * dolist::
10364 * dotimes::
10365 @end menu
10366
10367 @node dolist, dotimes, dolist dotimes, dolist dotimes
10368 @unnumberedsubsubsec The @code{dolist} Macro
10369 @findex dolist
10370
10371 Suppose, for example, you want to reverse a list, so that
10372 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10373
10374 @need 1250
10375 In practice, you would use the @code{reverse} function, like this:
10376
10377 @smallexample
10378 @group
10379 (setq animals '(gazelle giraffe lion tiger))
10380
10381 (reverse animals)
10382 @end group
10383 @end smallexample
10384
10385 @need 800
10386 @noindent
10387 Here is how you could reverse the list using a @code{while} loop:
10388
10389 @smallexample
10390 @group
10391 (setq animals '(gazelle giraffe lion tiger))
10392
10393 (defun reverse-list-with-while (list)
10394 "Using while, reverse the order of LIST."
10395 (let (value) ; make sure list starts empty
10396 (while list
10397 (setq value (cons (car list) value))
10398 (setq list (cdr list)))
10399 value))
10400
10401 (reverse-list-with-while animals)
10402 @end group
10403 @end smallexample
10404
10405 @need 800
10406 @noindent
10407 And here is how you could use the @code{dolist} macro:
10408
10409 @smallexample
10410 @group
10411 (setq animals '(gazelle giraffe lion tiger))
10412
10413 (defun reverse-list-with-dolist (list)
10414 "Using dolist, reverse the order of LIST."
10415 (let (value) ; make sure list starts empty
10416 (dolist (element list value)
10417 (setq value (cons element value)))))
10418
10419 (reverse-list-with-dolist animals)
10420 @end group
10421 @end smallexample
10422
10423 @need 1250
10424 @noindent
10425 In Info, you can place your cursor after the closing parenthesis of
10426 each expression and type @kbd{C-x C-e}; in each case, you should see
10427
10428 @smallexample
10429 (tiger lion giraffe gazelle)
10430 @end smallexample
10431
10432 @noindent
10433 in the echo area.
10434
10435 For this example, the existing @code{reverse} function is obviously best.
10436 The @code{while} loop is just like our first example (@pxref{Loop
10437 Example, , A @code{while} Loop and a List}). The @code{while} first
10438 checks whether the list has elements; if so, it constructs a new list
10439 by adding the first element of the list to the existing list (which in
10440 the first iteration of the loop is @code{nil}). Since the second
10441 element is prepended in front of the first element, and the third
10442 element is prepended in front of the second element, the list is reversed.
10443
10444 In the expression using a @code{while} loop,
10445 the @w{@code{(setq list (cdr list))}}
10446 expression shortens the list, so the @code{while} loop eventually
10447 stops. In addition, it provides the @code{cons} expression with a new
10448 first element by creating a new and shorter list at each repetition of
10449 the loop.
10450
10451 The @code{dolist} expression does very much the same as the
10452 @code{while} expression, except that the @code{dolist} macro does some
10453 of the work you have to do when writing a @code{while} expression.
10454
10455 Like a @code{while} loop, a @code{dolist} loops. What is different is
10456 that it automatically shortens the list each time it loops --- it
10457 `@sc{cdr}s down the list' on its own --- and it automatically binds
10458 the @sc{car} of each shorter version of the list to the first of its
10459 arguments.
10460
10461 In the example, the @sc{car} of each shorter version of the list is
10462 referred to using the symbol @samp{element}, the list itself is called
10463 @samp{list}, and the value returned is called @samp{value}. The
10464 remainder of the @code{dolist} expression is the body.
10465
10466 The @code{dolist} expression binds the @sc{car} of each shorter
10467 version of the list to @code{element} and then evaluates the body of
10468 the expression; and repeats the loop. The result is returned in
10469 @code{value}.
10470
10471 @node dotimes, , dolist, dolist dotimes
10472 @unnumberedsubsubsec The @code{dotimes} Macro
10473 @findex dotimes
10474
10475 The @code{dotimes} macro is similar to @code{dolist}, except that it
10476 loops a specific number of times.
10477
10478 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10479 and so forth each time around the loop, and the value of the third
10480 argument is returned. You need to provide the value of the second
10481 argument, which is how many times the macro loops.
10482
10483 @need 1250
10484 For example, the following binds the numbers from 0 up to, but not
10485 including, the number 3 to the first argument, @var{number}, and then
10486 constructs a list of the three numbers. (The first number is 0, the
10487 second number is 1, and the third number is 2; this makes a total of
10488 three numbers in all, starting with zero as the first number.)
10489
10490 @smallexample
10491 @group
10492 (let (value) ; otherwise a value is a void variable
10493 (dotimes (number 3 value)
10494 (setq value (cons number value))))
10495
10496 @result{} (2 1 0)
10497 @end group
10498 @end smallexample
10499
10500 @noindent
10501 @code{dotimes} returns @code{value}, so the way to use
10502 @code{dotimes} is to operate on some expression @var{number} number of
10503 times and then return the result, either as a list or an atom.
10504
10505 @need 1250
10506 Here is an example of a @code{defun} that uses @code{dotimes} to add
10507 up the number of pebbles in a triangle.
10508
10509 @smallexample
10510 @group
10511 (defun triangle-using-dotimes (number-of-rows)
10512 "Using dotimes, add up the number of pebbles in a triangle."
10513 (let ((total 0)) ; otherwise a total is a void variable
10514 (dotimes (number number-of-rows total)
10515 (setq total (+ total (1+ number))))))
10516
10517 (triangle-using-dotimes 4)
10518 @end group
10519 @end smallexample
10520
10521 @node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10522 @comment node-name, next, previous, up
10523 @section Recursion
10524 @cindex Recursion
10525
10526 A recursive function contains code that tells the Lisp interpreter to
10527 call a program that runs exactly like itself, but with slightly
10528 different arguments. The code runs exactly the same because it has
10529 the same name. However, even though it has the same name, it is not
10530 the same thread of execution. It is different. In the jargon, it is
10531 a different `instance'.
10532
10533 Eventually, if the program is written correctly, the `slightly
10534 different arguments' will become sufficiently different from the first
10535 arguments that the final instance will stop.
10536
10537 @menu
10538 * Building Robots:: Same model, different serial number ...
10539 * Recursive Definition Parts:: Walk until you stop ...
10540 * Recursion with list:: Using a list as the test whether to recurse.
10541 * Recursive triangle function::
10542 * Recursion with cond::
10543 * Recursive Patterns:: Often used templates.
10544 * No Deferment:: Don't store up work ...
10545 * No deferment solution::
10546 @end menu
10547
10548 @node Building Robots, Recursive Definition Parts, Recursion, Recursion
10549 @comment node-name, next, previous, up
10550 @subsection Building Robots: Extending the Metaphor
10551 @cindex Building robots
10552 @cindex Robots, building
10553
10554 It is sometimes helpful to think of a running program as a robot that
10555 does a job. In doing its job, a recursive function calls on a second
10556 robot to help it. The second robot is identical to the first in every
10557 way, except that the second robot helps the first and has been
10558 passed different arguments than the first.
10559
10560 In a recursive function, the second robot may call a third; and the
10561 third may call a fourth, and so on. Each of these is a different
10562 entity; but all are clones.
10563
10564 Since each robot has slightly different instructions---the arguments
10565 will differ from one robot to the next---the last robot should know
10566 when to stop.
10567
10568 Let's expand on the metaphor in which a computer program is a robot.
10569
10570 A function definition provides the blueprints for a robot. When you
10571 install a function definition, that is, when you evaluate a
10572 @code{defun} special form, you install the necessary equipment to
10573 build robots. It is as if you were in a factory, setting up an
10574 assembly line. Robots with the same name are built according to the
10575 same blueprints. So they have, as it were, the same `model number',
10576 but a different `serial number'.
10577
10578 We often say that a recursive function `calls itself'. What we mean
10579 is that the instructions in a recursive function cause the Lisp
10580 interpreter to run a different function that has the same name and
10581 does the same job as the first, but with different arguments.
10582
10583 It is important that the arguments differ from one instance to the
10584 next; otherwise, the process will never stop.
10585
10586 @node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10587 @comment node-name, next, previous, up
10588 @subsection The Parts of a Recursive Definition
10589 @cindex Parts of a Recursive Definition
10590 @cindex Recursive Definition Parts
10591
10592 A recursive function typically contains a conditional expression which
10593 has three parts:
10594
10595 @enumerate
10596 @item
10597 A true-or-false-test that determines whether the function is called
10598 again, here called the @dfn{do-again-test}.
10599
10600 @item
10601 The name of the function. When this name is called, a new instance of
10602 the function---a new robot, as it were---is created and told what to do.
10603
10604 @item
10605 An expression that returns a different value each time the function is
10606 called, here called the @dfn{next-step-expression}. Consequently, the
10607 argument (or arguments) passed to the new instance of the function
10608 will be different from that passed to the previous instance. This
10609 causes the conditional expression, the @dfn{do-again-test}, to test
10610 false after the correct number of repetitions.
10611 @end enumerate
10612
10613 Recursive functions can be much simpler than any other kind of
10614 function. Indeed, when people first start to use them, they often look
10615 so mysteriously simple as to be incomprehensible. Like riding a
10616 bicycle, reading a recursive function definition takes a certain knack
10617 which is hard at first but then seems simple.
10618
10619 @need 1200
10620 There are several different common recursive patterns. A very simple
10621 pattern looks like this:
10622
10623 @smallexample
10624 @group
10625 (defun @var{name-of-recursive-function} (@var{argument-list})
10626 "@var{documentation}@dots{}"
10627 (if @var{do-again-test}
10628 @var{body}@dots{}
10629 (@var{name-of-recursive-function}
10630 @var{next-step-expression})))
10631 @end group
10632 @end smallexample
10633
10634 Each time a recursive function is evaluated, a new instance of it is
10635 created and told what to do. The arguments tell the instance what to do.
10636
10637 An argument is bound to the value of the next-step-expression. Each
10638 instance runs with a different value of the next-step-expression.
10639
10640 The value in the next-step-expression is used in the do-again-test.
10641
10642 The value returned by the next-step-expression is passed to the new
10643 instance of the function, which evaluates it (or some
10644 transmogrification of it) to determine whether to continue or stop.
10645 The next-step-expression is designed so that the do-again-test returns
10646 false when the function should no longer be repeated.
10647
10648 The do-again-test is sometimes called the @dfn{stop condition},
10649 since it stops the repetitions when it tests false.
10650
10651 @node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10652 @comment node-name, next, previous, up
10653 @subsection Recursion with a List
10654
10655 The example of a @code{while} loop that printed the elements of a list
10656 of numbers can be written recursively. Here is the code, including
10657 an expression to set the value of the variable @code{animals} to a list.
10658
10659 If you are using Emacs 20 or before, this example must be copied to
10660 the @file{*scratch*} buffer and each expression must be evaluated
10661 there. Use @kbd{C-u C-x C-e} to evaluate the
10662 @code{(print-elements-recursively animals)} expression so that the
10663 results are printed in the buffer; otherwise the Lisp interpreter will
10664 try to squeeze the results into the one line of the echo area.
10665
10666 Also, place your cursor immediately after the last closing parenthesis
10667 of the @code{print-elements-recursively} function, before the comment.
10668 Otherwise, the Lisp interpreter will try to evaluate the comment.
10669
10670 If you are using Emacs 21 or later, you can evaluate this expression
10671 directly in Info.
10672
10673 @findex print-elements-recursively
10674 @smallexample
10675 @group
10676 (setq animals '(gazelle giraffe lion tiger))
10677
10678 (defun print-elements-recursively (list)
10679 "Print each element of LIST on a line of its own.
10680 Uses recursion."
10681 (if list ; @r{do-again-test}
10682 (progn
10683 (print (car list)) ; @r{body}
10684 (print-elements-recursively ; @r{recursive call}
10685 (cdr list))))) ; @r{next-step-expression}
10686
10687 (print-elements-recursively animals)
10688 @end group
10689 @end smallexample
10690
10691 The @code{print-elements-recursively} function first tests whether
10692 there is any content in the list; if there is, the function prints the
10693 first element of the list, the @sc{car} of the list. Then the
10694 function `invokes itself', but gives itself as its argument, not the
10695 whole list, but the second and subsequent elements of the list, the
10696 @sc{cdr} of the list.
10697
10698 Put another way, if the list is not empty, the function invokes
10699 another instance of code that is similar to the initial code, but is a
10700 different thread of execution, with different arguments than the first
10701 instance.
10702
10703 Put in yet another way, if the list is not empty, the first robot
10704 assemblies a second robot and tells it what to do; the second robot is
10705 a different individual from the first, but is the same model.
10706
10707 When the second evaluation occurs, the @code{if} expression is
10708 evaluated and if true, prints the first element of the list it
10709 receives as its argument (which is the second element of the original
10710 list). Then the function `calls itself' with the @sc{cdr} of the list
10711 it is invoked with, which (the second time around) is the @sc{cdr} of
10712 the @sc{cdr} of the original list.
10713
10714 Note that although we say that the function `calls itself', what we
10715 mean is that the Lisp interpreter assembles and instructs a new
10716 instance of the program. The new instance is a clone of the first,
10717 but is a separate individual.
10718
10719 Each time the function `invokes itself', it invokes itself on a
10720 shorter version of the original list. It creates a new instance that
10721 works on a shorter list.
10722
10723 Eventually, the function invokes itself on an empty list. It creates
10724 a new instance whose argument is @code{nil}. The conditional expression
10725 tests the value of @code{list}. Since the value of @code{list} is
10726 @code{nil}, the @code{if} expression tests false so the then-part is
10727 not evaluated. The function as a whole then returns @code{nil}.
10728
10729 @need 1200
10730 When you evaluate @code{(print-elements-recursively animals)} in the
10731 @file{*scratch*} buffer, you see this result:
10732
10733 @smallexample
10734 @group
10735 giraffe
10736
10737 gazelle
10738
10739 lion
10740
10741 tiger
10742 nil
10743 @end group
10744 @end smallexample
10745
10746 @node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10747 @comment node-name, next, previous, up
10748 @subsection Recursion in Place of a Counter
10749 @findex triangle-recursively
10750
10751 @need 1200
10752 The @code{triangle} function described in a previous section can also
10753 be written recursively. It looks like this:
10754
10755 @smallexample
10756 @group
10757 (defun triangle-recursively (number)
10758 "Return the sum of the numbers 1 through NUMBER inclusive.
10759 Uses recursion."
10760 (if (= number 1) ; @r{do-again-test}
10761 1 ; @r{then-part}
10762 (+ number ; @r{else-part}
10763 (triangle-recursively ; @r{recursive call}
10764 (1- number))))) ; @r{next-step-expression}
10765
10766 (triangle-recursively 7)
10767 @end group
10768 @end smallexample
10769
10770 @noindent
10771 You can install this function by evaluating it and then try it by
10772 evaluating @code{(triangle-recursively 7)}. (Remember to put your
10773 cursor immediately after the last parenthesis of the function
10774 definition, before the comment.) The function evaluates to 28.
10775
10776 To understand how this function works, let's consider what happens in the
10777 various cases when the function is passed 1, 2, 3, or 4 as the value of
10778 its argument.
10779
10780 @menu
10781 * Recursive Example arg of 1 or 2::
10782 * Recursive Example arg of 3 or 4::
10783 @end menu
10784
10785 @node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10786 @ifnottex
10787 @unnumberedsubsubsec An argument of 1 or 2
10788 @end ifnottex
10789
10790 First, what happens if the value of the argument is 1?
10791
10792 The function has an @code{if} expression after the documentation
10793 string. It tests whether the value of @code{number} is equal to 1; if
10794 so, Emacs evaluates the then-part of the @code{if} expression, which
10795 returns the number 1 as the value of the function. (A triangle with
10796 one row has one pebble in it.)
10797
10798 Suppose, however, that the value of the argument is 2. In this case,
10799 Emacs evaluates the else-part of the @code{if} expression.
10800
10801 @need 1200
10802 The else-part consists of an addition, the recursive call to
10803 @code{triangle-recursively} and a decrementing action; and it looks like
10804 this:
10805
10806 @smallexample
10807 (+ number (triangle-recursively (1- number)))
10808 @end smallexample
10809
10810 When Emacs evaluates this expression, the innermost expression is
10811 evaluated first; then the other parts in sequence. Here are the steps
10812 in detail:
10813
10814 @table @i
10815 @item Step 1 @w{ } Evaluate the innermost expression.
10816
10817 The innermost expression is @code{(1- number)} so Emacs decrements the
10818 value of @code{number} from 2 to 1.
10819
10820 @item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
10821
10822 The Lisp interpreter creates an individual instance of
10823 @code{triangle-recursively}. It does not matter that this function is
10824 contained within itself. Emacs passes the result Step 1 as the
10825 argument used by this instance of the @code{triangle-recursively}
10826 function
10827
10828 In this case, Emacs evaluates @code{triangle-recursively} with an
10829 argument of 1. This means that this evaluation of
10830 @code{triangle-recursively} returns 1.
10831
10832 @item Step 3 @w{ } Evaluate the value of @code{number}.
10833
10834 The variable @code{number} is the second element of the list that
10835 starts with @code{+}; its value is 2.
10836
10837 @item Step 4 @w{ } Evaluate the @code{+} expression.
10838
10839 The @code{+} expression receives two arguments, the first
10840 from the evaluation of @code{number} (Step 3) and the second from the
10841 evaluation of @code{triangle-recursively} (Step 2).
10842
10843 The result of the addition is the sum of 2 plus 1, and the number 3 is
10844 returned, which is correct. A triangle with two rows has three
10845 pebbles in it.
10846 @end table
10847
10848 @node Recursive Example arg of 3 or 4, , Recursive Example arg of 1 or 2, Recursive triangle function
10849 @unnumberedsubsubsec An argument of 3 or 4
10850
10851 Suppose that @code{triangle-recursively} is called with an argument of
10852 3.
10853
10854 @table @i
10855 @item Step 1 @w{ } Evaluate the do-again-test.
10856
10857 The @code{if} expression is evaluated first. This is the do-again
10858 test and returns false, so the else-part of the @code{if} expression
10859 is evaluated. (Note that in this example, the do-again-test causes
10860 the function to call itself when it tests false, not when it tests
10861 true.)
10862
10863 @item Step 2 @w{ } Evaluate the innermost expression of the else-part.
10864
10865 The innermost expression of the else-part is evaluated, which decrements
10866 3 to 2. This is the next-step-expression.
10867
10868 @item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
10869
10870 The number 2 is passed to the @code{triangle-recursively} function.
10871
10872 We know what happens when Emacs evaluates @code{triangle-recursively} with
10873 an argument of 2. After going through the sequence of actions described
10874 earlier, it returns a value of 3. So that is what will happen here.
10875
10876 @item Step 4 @w{ } Evaluate the addition.
10877
10878 3 will be passed as an argument to the addition and will be added to the
10879 number with which the function was called, which is 3.
10880 @end table
10881
10882 @noindent
10883 The value returned by the function as a whole will be 6.
10884
10885 Now that we know what will happen when @code{triangle-recursively} is
10886 called with an argument of 3, it is evident what will happen if it is
10887 called with an argument of 4:
10888
10889 @quotation
10890 @need 800
10891 In the recursive call, the evaluation of
10892
10893 @smallexample
10894 (triangle-recursively (1- 4))
10895 @end smallexample
10896
10897 @need 800
10898 @noindent
10899 will return the value of evaluating
10900
10901 @smallexample
10902 (triangle-recursively 3)
10903 @end smallexample
10904
10905 @noindent
10906 which is 6 and this value will be added to 4 by the addition in the
10907 third line.
10908 @end quotation
10909
10910 @noindent
10911 The value returned by the function as a whole will be 10.
10912
10913 Each time @code{triangle-recursively} is evaluated, it evaluates a
10914 version of itself---a different instance of itself---with a smaller
10915 argument, until the argument is small enough so that it does not
10916 evaluate itself.
10917
10918 Note that this particular design for a recursive function
10919 requires that operations be deferred.
10920
10921 Before @code{(triangle-recursively 7)} can calculate its answer, it
10922 must call @code{(triangle-recursively 6)}; and before
10923 @code{(triangle-recursively 6)} can calculate its answer, it must call
10924 @code{(triangle-recursively 5)}; and so on. That is to say, the
10925 calculation that @code{(triangle-recursively 7)} makes must be
10926 deferred until @code{(triangle-recursively 6)} makes its calculation;
10927 and @code{(triangle-recursively 6)} must defer until
10928 @code{(triangle-recursively 5)} completes; and so on.
10929
10930 If each of these instances of @code{triangle-recursively} are thought
10931 of as different robots, the first robot must wait for the second to
10932 complete its job, which must wait until the third completes, and so
10933 on.
10934
10935 There is a way around this kind of waiting, which we will discuss in
10936 @ref{No Deferment, , Recursion without Deferments}.
10937
10938 @node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10939 @comment node-name, next, previous, up
10940 @subsection Recursion Example Using @code{cond}
10941 @findex cond
10942
10943 The version of @code{triangle-recursively} described earlier is written
10944 with the @code{if} special form. It can also be written using another
10945 special form called @code{cond}. The name of the special form
10946 @code{cond} is an abbreviation of the word @samp{conditional}.
10947
10948 Although the @code{cond} special form is not used as often in the
10949 Emacs Lisp sources as @code{if}, it is used often enough to justify
10950 explaining it.
10951
10952 @need 800
10953 The template for a @code{cond} expression looks like this:
10954
10955 @smallexample
10956 @group
10957 (cond
10958 @var{body}@dots{})
10959 @end group
10960 @end smallexample
10961
10962 @noindent
10963 where the @var{body} is a series of lists.
10964
10965 @need 800
10966 Written out more fully, the template looks like this:
10967
10968 @smallexample
10969 @group
10970 (cond
10971 (@var{first-true-or-false-test} @var{first-consequent})
10972 (@var{second-true-or-false-test} @var{second-consequent})
10973 (@var{third-true-or-false-test} @var{third-consequent})
10974 @dots{})
10975 @end group
10976 @end smallexample
10977
10978 When the Lisp interpreter evaluates the @code{cond} expression, it
10979 evaluates the first element (the @sc{car} or true-or-false-test) of
10980 the first expression in a series of expressions within the body of the
10981 @code{cond}.
10982
10983 If the true-or-false-test returns @code{nil} the rest of that
10984 expression, the consequent, is skipped and the true-or-false-test of the
10985 next expression is evaluated. When an expression is found whose
10986 true-or-false-test returns a value that is not @code{nil}, the
10987 consequent of that expression is evaluated. The consequent can be one
10988 or more expressions. If the consequent consists of more than one
10989 expression, the expressions are evaluated in sequence and the value of
10990 the last one is returned. If the expression does not have a consequent,
10991 the value of the true-or-false-test is returned.
10992
10993 If none of the true-or-false-tests test true, the @code{cond} expression
10994 returns @code{nil}.
10995
10996 @need 1250
10997 Written using @code{cond}, the @code{triangle} function looks like this:
10998
10999 @smallexample
11000 @group
11001 (defun triangle-using-cond (number)
11002 (cond ((<= number 0) 0)
11003 ((= number 1) 1)
11004 ((> number 1)
11005 (+ number (triangle-using-cond (1- number))))))
11006 @end group
11007 @end smallexample
11008
11009 @noindent
11010 In this example, the @code{cond} returns 0 if the number is less than or
11011 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11012 number (triangle-using-cond (1- number)))} if the number is greater than
11013 1.
11014
11015 @node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11016 @comment node-name, next, previous, up
11017 @subsection Recursive Patterns
11018 @cindex Recursive Patterns
11019
11020 Here are three common recursive patterns. Each involves a list.
11021 Recursion does not need to involve lists, but Lisp is designed for lists
11022 and this provides a sense of its primal capabilities.
11023
11024 @menu
11025 * Every::
11026 * Accumulate::
11027 * Keep::
11028 @end menu
11029
11030 @node Every, Accumulate, Recursive Patterns, Recursive Patterns
11031 @comment node-name, next, previous, up
11032 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11033 @cindex Every, type of recursive pattern
11034 @cindex Recursive pattern: every
11035
11036 In the @code{every} recursive pattern, an action is performed on every
11037 element of a list.
11038
11039 @need 1500
11040 The basic pattern is:
11041
11042 @itemize @bullet
11043 @item
11044 If a list be empty, return @code{nil}.
11045 @item
11046 Else, act on the beginning of the list (the @sc{car} of the list)
11047 @itemize @minus
11048 @item
11049 through a recursive call by the function on the rest (the
11050 @sc{cdr}) of the list,
11051 @item
11052 and, optionally, combine the acted-on element, using @code{cons},
11053 with the results of acting on the rest.
11054 @end itemize
11055 @end itemize
11056
11057 @need 1500
11058 Here is example:
11059
11060 @smallexample
11061 @group
11062 (defun square-each (numbers-list)
11063 "Square each of a NUMBERS LIST, recursively."
11064 (if (not numbers-list) ; do-again-test
11065 nil
11066 (cons
11067 (* (car numbers-list) (car numbers-list))
11068 (square-each (cdr numbers-list))))) ; next-step-expression
11069 @end group
11070
11071 @group
11072 (square-each '(1 2 3))
11073 @result{} (1 4 9)
11074 @end group
11075 @end smallexample
11076
11077 @need 1200
11078 @noindent
11079 If @code{numbers-list} is empty, do nothing. But if it has content,
11080 construct a list combining the square of the first number in the list
11081 with the result of the recursive call.
11082
11083 (The example follows the pattern exactly: @code{nil} is returned if
11084 the numbers' list is empty. In practice, you would write the
11085 conditional so it carries out the action when the numbers' list is not
11086 empty.)
11087
11088 The @code{print-elements-recursively} function (@pxref{Recursion with
11089 list, , Recursion with a List}) is another example of an @code{every}
11090 pattern, except in this case, rather than bring the results together
11091 using @code{cons}, we print each element of output.
11092
11093 @need 1250
11094 The @code{print-elements-recursively} function looks like this:
11095
11096 @smallexample
11097 @group
11098 (setq animals '(gazelle giraffe lion tiger))
11099 @end group
11100
11101 @group
11102 (defun print-elements-recursively (list)
11103 "Print each element of LIST on a line of its own.
11104 Uses recursion."
11105 (if list ; @r{do-again-test}
11106 (progn
11107 (print (car list)) ; @r{body}
11108 (print-elements-recursively ; @r{recursive call}
11109 (cdr list))))) ; @r{next-step-expression}
11110
11111 (print-elements-recursively animals)
11112 @end group
11113 @end smallexample
11114
11115 @need 1500
11116 The pattern for @code{print-elements-recursively} is:
11117
11118 @itemize @bullet
11119 @item
11120 If the list be empty, do nothing.
11121 @item
11122 But if the list has at least one element,
11123 @itemize @minus
11124 @item
11125 act on the beginning of the list (the @sc{car} of the list),
11126 @item
11127 and make a recursive call on the rest (the @sc{cdr}) of the list.
11128 @end itemize
11129 @end itemize
11130
11131 @node Accumulate, Keep, Every, Recursive Patterns
11132 @comment node-name, next, previous, up
11133 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11134 @cindex Accumulate, type of recursive pattern
11135 @cindex Recursive pattern: accumulate
11136
11137 Another recursive pattern is called the @code{accumulate} pattern. In
11138 the @code{accumulate} recursive pattern, an action is performed on
11139 every element of a list and the result of that action is accumulated
11140 with the results of performing the action on the other elements.
11141
11142 This is very like the `every' pattern using @code{cons}, except that
11143 @code{cons} is not used, but some other combiner.
11144
11145 @need 1500
11146 The pattern is:
11147
11148 @itemize @bullet
11149 @item
11150 If a list be empty, return zero or some other constant.
11151 @item
11152 Else, act on the beginning of the list (the @sc{car} of the list),
11153 @itemize @minus
11154 @item
11155 and combine that acted-on element, using @code{+} or
11156 some other combining function, with
11157 @item
11158 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11159 @end itemize
11160 @end itemize
11161
11162 @need 1500
11163 Here is an example:
11164
11165 @smallexample
11166 @group
11167 (defun add-elements (numbers-list)
11168 "Add the elements of NUMBERS-LIST together."
11169 (if (not numbers-list)
11170 0
11171 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11172 @end group
11173
11174 @group
11175 (add-elements '(1 2 3 4))
11176 @result{} 10
11177 @end group
11178 @end smallexample
11179
11180 @xref{Files List, , Making a List of Files}, for an example of the
11181 accumulate pattern.
11182
11183 @node Keep, , Accumulate, Recursive Patterns
11184 @comment node-name, next, previous, up
11185 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11186 @cindex Keep, type of recursive pattern
11187 @cindex Recursive pattern: keep
11188
11189 A third recursive pattern is called the @code{keep} pattern.
11190 In the @code{keep} recursive pattern, each element of a list is tested;
11191 the element is acted on and the results are kept only if the element
11192 meets a criterion.
11193
11194 Again, this is very like the `every' pattern, except the element is
11195 skipped unless it meets a criterion.
11196
11197 @need 1500
11198 The pattern has three parts:
11199
11200 @itemize @bullet
11201 @item
11202 If a list be empty, return @code{nil}.
11203 @item
11204 Else, if the beginning of the list (the @sc{car} of the list) passes
11205 a test
11206 @itemize @minus
11207 @item
11208 act on that element and combine it, using @code{cons} with
11209 @item
11210 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11211 @end itemize
11212 @item
11213 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11214 the test
11215 @itemize @minus
11216 @item
11217 skip on that element,
11218 @item
11219 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11220 @end itemize
11221 @end itemize
11222
11223 @need 1500
11224 Here is an example that uses @code{cond}:
11225
11226 @smallexample
11227 @group
11228 (defun keep-three-letter-words (word-list)
11229 "Keep three letter words in WORD-LIST."
11230 (cond
11231 ;; First do-again-test: stop-condition
11232 ((not word-list) nil)
11233
11234 ;; Second do-again-test: when to act
11235 ((eq 3 (length (symbol-name (car word-list))))
11236 ;; combine acted-on element with recursive call on shorter list
11237 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11238
11239 ;; Third do-again-test: when to skip element;
11240 ;; recursively call shorter list with next-step expression
11241 (t (keep-three-letter-words (cdr word-list)))))
11242 @end group
11243
11244 @group
11245 (keep-three-letter-words '(one two three four five six))
11246 @result{} (one two six)
11247 @end group
11248 @end smallexample
11249
11250 It goes without saying that you need not use @code{nil} as the test for
11251 when to stop; and you can, of course, combine these patterns.
11252
11253 @node No Deferment, No deferment solution, Recursive Patterns, Recursion
11254 @subsection Recursion without Deferments
11255 @cindex Deferment in recursion
11256 @cindex Recursion without Deferments
11257
11258 Let's consider again what happens with the @code{triangle-recursively}
11259 function. We will find that the intermediate calculations are
11260 deferred until all can be done.
11261
11262 @need 800
11263 Here is the function definition:
11264
11265 @smallexample
11266 @group
11267 (defun triangle-recursively (number)
11268 "Return the sum of the numbers 1 through NUMBER inclusive.
11269 Uses recursion."
11270 (if (= number 1) ; @r{do-again-test}
11271 1 ; @r{then-part}
11272 (+ number ; @r{else-part}
11273 (triangle-recursively ; @r{recursive call}
11274 (1- number))))) ; @r{next-step-expression}
11275 @end group
11276 @end smallexample
11277
11278 What happens when we call this function with a argument of 7?
11279
11280 The first instance of the @code{triangle-recursively} function adds
11281 the number 7 to the value returned by a second instance of
11282 @code{triangle-recursively}, an instance that has been passed an
11283 argument of 6. That is to say, the first calculation is:
11284
11285 @smallexample
11286 (+ 7 (triangle-recursively 6)
11287 @end smallexample
11288
11289 @noindent
11290 The first instance of @code{triangle-recursively}---you may want to
11291 think of it as a little robot---cannot complete its job. It must hand
11292 off the calculation for @code{(triangle-recursively 6)} to a second
11293 instance of the program, to a second robot. This second individual is
11294 completely different from the first one; it is, in the jargon, a
11295 `different instantiation'. Or, put another way, it is a different
11296 robot. It is the same model as the first; it calculates triangle
11297 numbers recursively; but it has a different serial number.
11298
11299 And what does @code{(triangle-recursively 6)} return? It returns the
11300 number 6 added to the value returned by evaluating
11301 @code{triangle-recursively} with an argument of 5. Using the robot
11302 metaphor, it asks yet another robot to help it.
11303
11304 @need 800
11305 Now the total is:
11306
11307 @smallexample
11308 (+ 7 6 (triangle-recursively 5)
11309 @end smallexample
11310
11311 @need 800
11312 And what happens next?
11313
11314 @smallexample
11315 (+ 7 6 5 (triangle-recursively 4)
11316 @end smallexample
11317
11318 Each time @code{triangle-recursively} is called, except for the last
11319 time, it creates another instance of the program---another robot---and
11320 asks it to make a calculation.
11321
11322 @need 800
11323 Eventually, the full addition is set up and performed:
11324
11325 @smallexample
11326 (+ 7 6 5 4 3 2 1)
11327 @end smallexample
11328
11329 This design for the function defers the calculation of the first step
11330 until the second can be done, and defers that until the third can be
11331 done, and so on. Each deferment means the computer must remember what
11332 is being waited on. This is not a problem when there are only a few
11333 steps, as in this example. But it can be a problem when there are
11334 more steps.
11335
11336 @node No deferment solution, , No Deferment, Recursion
11337 @subsection No Deferment Solution
11338 @cindex No deferment solution
11339 @cindex Defermentless solution
11340 @cindex Solution without deferment
11341
11342 The solution to the problem of deferred operations is to write in a
11343 manner that does not defer operations@footnote{The phrase @dfn{tail
11344 recursive} is used to describe such a process, one that uses
11345 `constant space'.}. This requires
11346 writing to a different pattern, often one that involves writing two
11347 function definitions, an `initialization' function and a `helper'
11348 function.
11349
11350 The `initialization' function sets up the job; the `helper' function
11351 does the work.
11352
11353 @need 1200
11354 Here are the two function definitions for adding up numbers. They are
11355 so simple, I find them hard to understand.
11356
11357 @smallexample
11358 @group
11359 (defun triangle-initialization (number)
11360 "Return the sum of the numbers 1 through NUMBER inclusive.
11361 This is the `initialization' component of a two function
11362 duo that uses recursion."
11363 (triangle-recursive-helper 0 0 number))
11364 @end group
11365 @end smallexample
11366
11367 @smallexample
11368 @group
11369 (defun triangle-recursive-helper (sum counter number)
11370 "Return SUM, using COUNTER, through NUMBER inclusive.
11371 This is the `helper' component of a two function duo
11372 that uses recursion."
11373 (if (> counter number)
11374 sum
11375 (triangle-recursive-helper (+ sum counter) ; @r{sum}
11376 (1+ counter) ; @r{counter}
11377 number))) ; @r{number}
11378 @end group
11379 @end smallexample
11380
11381 @need 1250
11382 Install both function definitions by evaluating them, then call
11383 @code{triangle-initialization} with 2 rows:
11384
11385 @smallexample
11386 @group
11387 (triangle-initialization 2)
11388 @result{} 3
11389 @end group
11390 @end smallexample
11391
11392 The `initialization' function calls the first instance of the `helper'
11393 function with three arguments: zero, zero, and a number which is the
11394 number of rows in the triangle.
11395
11396 The first two arguments passed to the `helper' function are
11397 initialization values. These values are changed when
11398 @code{triangle-recursive-helper} invokes new instances.@footnote{The
11399 jargon is mildly confusing: @code{triangle-recursive-helper} uses a
11400 process that is iterative in a procedure that is recursive. The
11401 process is called iterative because the computer need only record the
11402 three values, @code{sum}, @code{counter}, and @code{number}; the
11403 procedure is recursive because the function `calls itself'. On the
11404 other hand, both the process and the procedure used by
11405 @code{triangle-recursively} are called recursive. The word
11406 `recursive' has different meanings in the two contexts.}
11407
11408 Let's see what happens when we have a triangle that has one row. (This
11409 triangle will have one pebble in it!)
11410
11411 @need 1200
11412 @code{triangle-initialization} will call its helper with
11413 the arguments @w{@code{0 0 1}}. That function will run the conditional
11414 test whether @code{(> counter number)}:
11415
11416 @smallexample
11417 (> 0 1)
11418 @end smallexample
11419
11420 @need 1200
11421 @noindent
11422 and find that the result is false, so it will invoke
11423 the then-part of the @code{if} clause:
11424
11425 @smallexample
11426 @group
11427 (triangle-recursive-helper
11428 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11429 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11430 number) ; @r{number stays the same}
11431 @end group
11432 @end smallexample
11433
11434 @need 800
11435 @noindent
11436 which will first compute:
11437
11438 @smallexample
11439 @group
11440 (triangle-recursive-helper (+ 0 0) ; @r{sum}
11441 (1+ 0) ; @r{counter}
11442 1) ; @r{number}
11443 @exdent which is:
11444
11445 (triangle-recursive-helper 0 1 1)
11446 @end group
11447 @end smallexample
11448
11449 Again, @code{(> counter number)} will be false, so again, the Lisp
11450 interpreter will evaluate @code{triangle-recursive-helper}, creating a
11451 new instance with new arguments.
11452
11453 @need 800
11454 This new instance will be;
11455
11456 @smallexample
11457 @group
11458 (triangle-recursive-helper
11459 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11460 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11461 number) ; @r{number stays the same}
11462
11463 @exdent which is:
11464
11465 (triangle-recursive-helper 1 2 1)
11466 @end group
11467 @end smallexample
11468
11469 In this case, the @code{(> counter number)} test will be true! So the
11470 instance will return the value of the sum, which will be 1, as
11471 expected.
11472
11473 Now, let's pass @code{triangle-initialization} an argument
11474 of 2, to find out how many pebbles there are in a triangle with two rows.
11475
11476 That function calls @code{(triangle-recursive-helper 0 0 2)}.
11477
11478 @need 800
11479 In stages, the instances called will be:
11480
11481 @smallexample
11482 @group
11483 @r{sum counter number}
11484 (triangle-recursive-helper 0 1 2)
11485
11486 (triangle-recursive-helper 1 2 2)
11487
11488 (triangle-recursive-helper 3 3 2)
11489 @end group
11490 @end smallexample
11491
11492 When the last instance is called, the @code{(> counter number)} test
11493 will be true, so the instance will return the value of @code{sum},
11494 which will be 3.
11495
11496 This kind of pattern helps when you are writing functions that can use
11497 many resources in a computer.
11498
11499 @need 1500
11500 @node Looping exercise, , Recursion, Loops & Recursion
11501 @section Looping Exercise
11502
11503 @itemize @bullet
11504 @item
11505 Write a function similar to @code{triangle} in which each row has a
11506 value which is the square of the row number. Use a @code{while} loop.
11507
11508 @item
11509 Write a function similar to @code{triangle} that multiplies instead of
11510 adds the values.
11511
11512 @item
11513 Rewrite these two functions recursively. Rewrite these functions
11514 using @code{cond}.
11515
11516 @c comma in printed title causes problem in Info cross reference
11517 @item
11518 Write a function for Texinfo mode that creates an index entry at the
11519 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
11520 (In a Texinfo file, @samp{@@dfn} marks a definition. For more
11521 information, see
11522 @ifinfo
11523 @ref{Indicating, , Indicating Definitions, texinfo}.)
11524 @end ifinfo
11525 @ifhtml
11526 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}.)
11527 @end ifhtml
11528 @iftex
11529 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
11530 Documentation Format}.)
11531 @end iftex
11532 @end itemize
11533
11534 @node Regexp Search, Counting Words, Loops & Recursion, Top
11535 @comment node-name, next, previous, up
11536 @chapter Regular Expression Searches
11537 @cindex Searches, illustrating
11538 @cindex Regular expression searches
11539 @cindex Patterns, searching for
11540 @cindex Motion by sentence and paragraph
11541 @cindex Sentences, movement by
11542 @cindex Paragraphs, movement by
11543
11544 Regular expression searches are used extensively in GNU Emacs. The
11545 two functions, @code{forward-sentence} and @code{forward-paragraph},
11546 illustrate these searches well. They use regular expressions to find
11547 where to move point. The phrase `regular expression' is often written
11548 as `regexp'.
11549
11550 Regular expression searches are described in @ref{Regexp Search, ,
11551 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11552 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11553 Manual}. In writing this chapter, I am presuming that you have at
11554 least a mild acquaintance with them. The major point to remember is
11555 that regular expressions permit you to search for patterns as well as
11556 for literal strings of characters. For example, the code in
11557 @code{forward-sentence} searches for the pattern of possible
11558 characters that could mark the end of a sentence, and moves point to
11559 that spot.
11560
11561 Before looking at the code for the @code{forward-sentence} function, it
11562 is worth considering what the pattern that marks the end of a sentence
11563 must be. The pattern is discussed in the next section; following that
11564 is a description of the regular expression search function,
11565 @code{re-search-forward}. The @code{forward-sentence} function
11566 is described in the section following. Finally, the
11567 @code{forward-paragraph} function is described in the last section of
11568 this chapter. @code{forward-paragraph} is a complex function that
11569 introduces several new features.
11570
11571 @menu
11572 * sentence-end:: The regular expression for @code{sentence-end}.
11573 * re-search-forward:: Very similar to @code{search-forward}.
11574 * forward-sentence:: A straightforward example of regexp search.
11575 * forward-paragraph:: A somewhat complex example.
11576 * etags:: How to create your own @file{TAGS} table.
11577 * Regexp Review::
11578 * re-search Exercises::
11579 @end menu
11580
11581 @node sentence-end, re-search-forward, Regexp Search, Regexp Search
11582 @comment node-name, next, previous, up
11583 @section The Regular Expression for @code{sentence-end}
11584 @findex sentence-end
11585
11586 The symbol @code{sentence-end} is bound to the pattern that marks the
11587 end of a sentence. What should this regular expression be?
11588
11589 Clearly, a sentence may be ended by a period, a question mark, or an
11590 exclamation mark. Indeed, only clauses that end with one of those three
11591 characters should be considered the end of a sentence. This means that
11592 the pattern should include the character set:
11593
11594 @smallexample
11595 [.?!]
11596 @end smallexample
11597
11598 However, we do not want @code{forward-sentence} merely to jump to a
11599 period, a question mark, or an exclamation mark, because such a character
11600 might be used in the middle of a sentence. A period, for example, is
11601 used after abbreviations. So other information is needed.
11602
11603 According to convention, you type two spaces after every sentence, but
11604 only one space after a period, a question mark, or an exclamation mark in
11605 the body of a sentence. So a period, a question mark, or an exclamation
11606 mark followed by two spaces is a good indicator of an end of sentence.
11607 However, in a file, the two spaces may instead be a tab or the end of a
11608 line. This means that the regular expression should include these three
11609 items as alternatives.
11610
11611 @need 800
11612 This group of alternatives will look like this:
11613
11614 @smallexample
11615 @group
11616 \\($\\| \\| \\)
11617 ^ ^^
11618 TAB SPC
11619 @end group
11620 @end smallexample
11621
11622 @noindent
11623 Here, @samp{$} indicates the end of the line, and I have pointed out
11624 where the tab and two spaces are inserted in the expression. Both are
11625 inserted by putting the actual characters into the expression.
11626
11627 Two backslashes, @samp{\\}, are required before the parentheses and
11628 vertical bars: the first backslash quotes the following backslash in
11629 Emacs; and the second indicates that the following character, the
11630 parenthesis or the vertical bar, is special.
11631
11632 @need 1000
11633 Also, a sentence may be followed by one or more carriage returns, like
11634 this:
11635
11636 @smallexample
11637 @group
11638 [
11639 ]*
11640 @end group
11641 @end smallexample
11642
11643 @noindent
11644 Like tabs and spaces, a carriage return is inserted into a regular
11645 expression by inserting it literally. The asterisk indicates that the
11646 @key{RET} is repeated zero or more times.
11647
11648 But a sentence end does not consist only of a period, a question mark or
11649 an exclamation mark followed by appropriate space: a closing quotation
11650 mark or a closing brace of some kind may precede the space. Indeed more
11651 than one such mark or brace may precede the space. These require a
11652 expression that looks like this:
11653
11654 @smallexample
11655 []\"')@}]*
11656 @end smallexample
11657
11658 In this expression, the first @samp{]} is the first character in the
11659 expression; the second character is @samp{"}, which is preceded by a
11660 @samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
11661 three characters are @samp{'}, @samp{)}, and @samp{@}}.
11662
11663 All this suggests what the regular expression pattern for matching the
11664 end of a sentence should be; and, indeed, if we evaluate
11665 @code{sentence-end} we find that it returns the following value:
11666
11667 @smallexample
11668 @group
11669 sentence-end
11670 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
11671 ]*"
11672 @end group
11673 @end smallexample
11674
11675 @ignore
11676
11677 @noindent
11678 (Note that here the @key{TAB}, two spaces, and @key{RET} are shown
11679 literally in the pattern.)
11680
11681 This regular expression can be decyphered as follows:
11682
11683 @table @code
11684 @item [.?!]
11685 The first part of the pattern is the three characters, a period, a question
11686 mark and an exclamation mark, within square brackets. The pattern must
11687 begin with one or other of these characters.
11688
11689 @item []\"')@}]*
11690 The second part of the pattern is the group of closing braces and
11691 quotation marks, which can appear zero or more times. These may follow
11692 the period, question mark or exclamation mark. In a regular expression,
11693 the backslash, @samp{\}, followed by the double quotation mark,
11694 @samp{"}, indicates the class of string-quote characters. Usually, the
11695 double quotation mark is the only character in this class. The
11696 asterisk, @samp{*}, indicates that the items in the previous group (the
11697 group surrounded by square brackets, @samp{[]}) may be repeated zero or
11698 more times.
11699
11700 @item \\($\\| \\| \\)
11701 The third part of the pattern is one or other of: either the end of a
11702 line, or two blank spaces, or a tab. The double back-slashes are used
11703 to prevent Emacs from reading the parentheses and vertical bars as part
11704 of the search pattern; the parentheses are used to mark the group and
11705 the vertical bars are used to indicated that the patterns to either side
11706 of them are alternatives. The dollar sign is used to indicate the end
11707 of a line and both the two spaces and the tab are each inserted as is to
11708 indicate what they are.
11709
11710 @item [@key{RET}]*
11711 Finally, the last part of the pattern indicates that the end of the line
11712 or the whitespace following the period, question mark or exclamation
11713 mark may, but need not, be followed by one or more carriage returns. In
11714 the pattern, the carriage return is inserted as an actual carriage
11715 return between square brackets but here it is shown as @key{RET}.
11716 @end table
11717
11718 @end ignore
11719
11720 @node re-search-forward, forward-sentence, sentence-end, Regexp Search
11721 @comment node-name, next, previous, up
11722 @section The @code{re-search-forward} Function
11723 @findex re-search-forward
11724
11725 The @code{re-search-forward} function is very like the
11726 @code{search-forward} function. (@xref{search-forward, , The
11727 @code{search-forward} Function}.)
11728
11729 @code{re-search-forward} searches for a regular expression. If the
11730 search is successful, it leaves point immediately after the last
11731 character in the target. If the search is backwards, it leaves point
11732 just before the first character in the target. You may tell
11733 @code{re-search-forward} to return @code{t} for true. (Moving point
11734 is therefore a `side effect'.)
11735
11736 Like @code{search-forward}, the @code{re-search-forward} function takes
11737 four arguments:
11738
11739 @enumerate
11740 @item
11741 The first argument is the regular expression that the function searches
11742 for. The regular expression will be a string between quotations marks.
11743
11744 @item
11745 The optional second argument limits how far the function will search; it is a
11746 bound, which is specified as a position in the buffer.
11747
11748 @item
11749 The optional third argument specifies how the function responds to
11750 failure: @code{nil} as the third argument causes the function to
11751 signal an error (and print a message) when the search fails; any other
11752 value causes it to return @code{nil} if the search fails and @code{t}
11753 if the search succeeds.
11754
11755 @item
11756 The optional fourth argument is the repeat count. A negative repeat
11757 count causes @code{re-search-forward} to search backwards.
11758 @end enumerate
11759
11760 @need 800
11761 The template for @code{re-search-forward} looks like this:
11762
11763 @smallexample
11764 @group
11765 (re-search-forward "@var{regular-expression}"
11766 @var{limit-of-search}
11767 @var{what-to-do-if-search-fails}
11768 @var{repeat-count})
11769 @end group
11770 @end smallexample
11771
11772 The second, third, and fourth arguments are optional. However, if you
11773 want to pass a value to either or both of the last two arguments, you
11774 must also pass a value to all the preceding arguments. Otherwise, the
11775 Lisp interpreter will mistake which argument you are passing the value
11776 to.
11777
11778 @need 1200
11779 In the @code{forward-sentence} function, the regular expression will be
11780 the value of the variable @code{sentence-end}, namely:
11781
11782 @smallexample
11783 @group
11784 "[.?!][]\"')@}]*\\($\\| \\| \\)[
11785 ]*"
11786 @end group
11787 @end smallexample
11788
11789 @noindent
11790 The limit of the search will be the end of the paragraph (since a
11791 sentence cannot go beyond a paragraph). If the search fails, the
11792 function will return @code{nil}; and the repeat count will be provided
11793 by the argument to the @code{forward-sentence} function.
11794
11795 @node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11796 @comment node-name, next, previous, up
11797 @section @code{forward-sentence}
11798 @findex forward-sentence
11799
11800 The command to move the cursor forward a sentence is a straightforward
11801 illustration of how to use regular expression searches in Emacs Lisp.
11802 Indeed, the function looks longer and more complicated than it is; this
11803 is because the function is designed to go backwards as well as forwards;
11804 and, optionally, over more than one sentence. The function is usually
11805 bound to the key command @kbd{M-e}.
11806
11807 @menu
11808 * Complete forward-sentence::
11809 * fwd-sentence while loops:: Two @code{while} loops.
11810 * fwd-sentence re-search:: A regular expression search.
11811 @end menu
11812
11813 @node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11814 @ifnottex
11815 @unnumberedsubsec Complete @code{forward-sentence} function definition
11816 @end ifnottex
11817
11818 @need 1250
11819 Here is the code for @code{forward-sentence}:
11820
11821 @smallexample
11822 @group
11823 (defun forward-sentence (&optional arg)
11824 "Move forward to next sentence-end. With argument, repeat.
11825 With negative argument, move backward repeatedly to sentence-beginning.
11826 Sentence ends are identified by the value of sentence-end
11827 treated as a regular expression. Also, every paragraph boundary
11828 terminates sentences as well."
11829 @end group
11830 @group
11831 (interactive "p")
11832 (or arg (setq arg 1))
11833 (while (< arg 0)
11834 (let ((par-beg
11835 (save-excursion (start-of-paragraph-text) (point))))
11836 (if (re-search-backward
11837 (concat sentence-end "[^ \t\n]") par-beg t)
11838 (goto-char (1- (match-end 0)))
11839 (goto-char par-beg)))
11840 (setq arg (1+ arg)))
11841 (while (> arg 0)
11842 (let ((par-end
11843 (save-excursion (end-of-paragraph-text) (point))))
11844 (if (re-search-forward sentence-end par-end t)
11845 (skip-chars-backward " \t\n")
11846 (goto-char par-end)))
11847 (setq arg (1- arg))))
11848 @end group
11849 @end smallexample
11850
11851 The function looks long at first sight and it is best to look at its
11852 skeleton first, and then its muscle. The way to see the skeleton is to
11853 look at the expressions that start in the left-most columns:
11854
11855 @smallexample
11856 @group
11857 (defun forward-sentence (&optional arg)
11858 "@var{documentation}@dots{}"
11859 (interactive "p")
11860 (or arg (setq arg 1))
11861 (while (< arg 0)
11862 @var{body-of-while-loop}
11863 (while (> arg 0)
11864 @var{body-of-while-loop}
11865 @end group
11866 @end smallexample
11867
11868 This looks much simpler! The function definition consists of
11869 documentation, an @code{interactive} expression, an @code{or}
11870 expression, and @code{while} loops.
11871
11872 Let's look at each of these parts in turn.
11873
11874 We note that the documentation is thorough and understandable.
11875
11876 The function has an @code{interactive "p"} declaration. This means
11877 that the processed prefix argument, if any, is passed to the
11878 function as its argument. (This will be a number.) If the function
11879 is not passed an argument (it is optional) then the argument
11880 @code{arg} will be bound to 1. When @code{forward-sentence} is called
11881 non-interactively without an argument, @code{arg} is bound to
11882 @code{nil}.
11883
11884 The @code{or} expression handles the prefix argument. What it does is
11885 either leave the value of @code{arg} as it is, but only if @code{arg}
11886 is bound to a value; or it sets the value of @code{arg} to 1, in the
11887 case when @code{arg} is bound to @code{nil}.
11888
11889 @node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11890 @unnumberedsubsec The @code{while} loops
11891
11892 Two @code{while} loops follow the @code{or} expression. The first
11893 @code{while} has a true-or-false-test that tests true if the prefix
11894 argument for @code{forward-sentence} is a negative number. This is for
11895 going backwards. The body of this loop is similar to the body of the
11896 second @code{while} clause, but it is not exactly the same. We will
11897 skip this @code{while} loop and concentrate on the second @code{while}
11898 loop.
11899
11900 @need 1500
11901 The second @code{while} loop is for moving point forward. Its skeleton
11902 looks like this:
11903
11904 @smallexample
11905 @group
11906 (while (> arg 0) ; @r{true-or-false-test}
11907 (let @var{varlist}
11908 (if (@var{true-or-false-test})
11909 @var{then-part}
11910 @var{else-part}
11911 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
11912 @end group
11913 @end smallexample
11914
11915 The @code{while} loop is of the decrementing kind.
11916 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
11917 has a true-or-false-test that tests true so long as the counter (in
11918 this case, the variable @code{arg}) is greater than zero; and it has a
11919 decrementer that subtracts 1 from the value of the counter every time
11920 the loop repeats.
11921
11922 If no prefix argument is given to @code{forward-sentence}, which is
11923 the most common way the command is used, this @code{while} loop will
11924 run once, since the value of @code{arg} will be 1.
11925
11926 The body of the @code{while} loop consists of a @code{let} expression,
11927 which creates and binds a local variable, and has, as its body, an
11928 @code{if} expression.
11929
11930 @need 1250
11931 The body of the @code{while} loop looks like this:
11932
11933 @smallexample
11934 @group
11935 (let ((par-end
11936 (save-excursion (end-of-paragraph-text) (point))))
11937 (if (re-search-forward sentence-end par-end t)
11938 (skip-chars-backward " \t\n")
11939 (goto-char par-end)))
11940 @end group
11941 @end smallexample
11942
11943 The @code{let} expression creates and binds the local variable
11944 @code{par-end}. As we shall see, this local variable is designed to
11945 provide a bound or limit to the regular expression search. If the
11946 search fails to find a proper sentence ending in the paragraph, it will
11947 stop on reaching the end of the paragraph.
11948
11949 But first, let us examine how @code{par-end} is bound to the value of
11950 the end of the paragraph. What happens is that the @code{let} sets the
11951 value of @code{par-end} to the value returned when the Lisp interpreter
11952 evaluates the expression
11953
11954 @smallexample
11955 @group
11956 (save-excursion (end-of-paragraph-text) (point))
11957 @end group
11958 @end smallexample
11959
11960 @noindent
11961 In this expression, @code{(end-of-paragraph-text)} moves point to the
11962 end of the paragraph, @code{(point)} returns the value of point, and then
11963 @code{save-excursion} restores point to its original position. Thus,
11964 the @code{let} binds @code{par-end} to the value returned by the
11965 @code{save-excursion} expression, which is the position of the end of
11966 the paragraph. (The @code{(end-of-paragraph-text)} function uses
11967 @code{forward-paragraph}, which we will discuss shortly.)
11968
11969 @need 1200
11970 Emacs next evaluates the body of the @code{let}, which is an @code{if}
11971 expression that looks like this:
11972
11973 @smallexample
11974 @group
11975 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
11976 (skip-chars-backward " \t\n") ; @r{then-part}
11977 (goto-char par-end))) ; @r{else-part}
11978 @end group
11979 @end smallexample
11980
11981 The @code{if} tests whether its first argument is true and if so,
11982 evaluates its then-part; otherwise, the Emacs Lisp interpreter
11983 evaluates the else-part. The true-or-false-test of the @code{if}
11984 expression is the regular expression search.
11985
11986 It may seem odd to have what looks like the `real work' of
11987 the @code{forward-sentence} function buried here, but this is a common
11988 way this kind of operation is carried out in Lisp.
11989
11990 @node fwd-sentence re-search, , fwd-sentence while loops, forward-sentence
11991 @unnumberedsubsec The regular expression search
11992
11993 The @code{re-search-forward} function searches for the end of the
11994 sentence, that is, for the pattern defined by the @code{sentence-end}
11995 regular expression. If the pattern is found---if the end of the sentence is
11996 found---then the @code{re-search-forward} function does two things:
11997
11998 @enumerate
11999 @item
12000 The @code{re-search-forward} function carries out a side effect, which
12001 is to move point to the end of the occurrence found.
12002
12003 @item
12004 The @code{re-search-forward} function returns a value of true. This is
12005 the value received by the @code{if}, and means that the search was
12006 successful.
12007 @end enumerate
12008
12009 @noindent
12010 The side effect, the movement of point, is completed before the
12011 @code{if} function is handed the value returned by the successful
12012 conclusion of the search.
12013
12014 When the @code{if} function receives the value of true from a successful
12015 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12016 which is the expression @code{(skip-chars-backward " \t\n")}. This
12017 expression moves backwards over any blank spaces, tabs or carriage
12018 returns until a printed character is found and then leaves point after
12019 the character. Since point has already been moved to the end of the
12020 pattern that marks the end of the sentence, this action leaves point
12021 right after the closing printed character of the sentence, which is
12022 usually a period.
12023
12024 On the other hand, if the @code{re-search-forward} function fails to
12025 find a pattern marking the end of the sentence, the function returns
12026 false. The false then causes the @code{if} to evaluate its third
12027 argument, which is @code{(goto-char par-end)}: it moves point to the
12028 end of the paragraph.
12029
12030 Regular expression searches are exceptionally useful and the pattern
12031 illustrated by @code{re-search-forward}, in which the search is the
12032 test of an @code{if} expression, is handy. You will see or write code
12033 incorporating this pattern often.
12034
12035 @node forward-paragraph, etags, forward-sentence, Regexp Search
12036 @comment node-name, next, previous, up
12037 @section @code{forward-paragraph}: a Goldmine of Functions
12038 @findex forward-paragraph
12039
12040 The @code{forward-paragraph} function moves point forward to the end
12041 of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12042 number of functions that are important in themselves, including
12043 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12044
12045 The function definition for @code{forward-paragraph} is considerably
12046 longer than the function definition for @code{forward-sentence}
12047 because it works with a paragraph, each line of which may begin with a
12048 fill prefix.
12049
12050 A fill prefix consists of a string of characters that are repeated at
12051 the beginning of each line. For example, in Lisp code, it is a
12052 convention to start each line of a paragraph-long comment with
12053 @samp{;;; }. In Text mode, four blank spaces make up another common
12054 fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
12055 emacs, The GNU Emacs Manual}, for more information about fill
12056 prefixes.)
12057
12058 The existence of a fill prefix means that in addition to being able to
12059 find the end of a paragraph whose lines begin on the left-most
12060 column, the @code{forward-paragraph} function must be able to find the
12061 end of a paragraph when all or many of the lines in the buffer begin
12062 with the fill prefix.
12063
12064 Moreover, it is sometimes practical to ignore a fill prefix that
12065 exists, especially when blank lines separate paragraphs.
12066 This is an added complication.
12067
12068 @menu
12069 * forward-paragraph in brief:: Key parts of the function definition.
12070 * fwd-para let:: The @code{let*} expression.
12071 * fwd-para while:: The forward motion @code{while} loop.
12072 * fwd-para between paragraphs:: Movement between paragraphs.
12073 * fwd-para within paragraph:: Movement within paragraphs.
12074 * fwd-para no fill prefix:: When there is no fill prefix.
12075 * fwd-para with fill prefix:: When there is a fill prefix.
12076 * fwd-para summary:: Summary of @code{forward-paragraph} code.
12077 @end menu
12078
12079 @node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12080 @ifnottex
12081 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
12082 @end ifnottex
12083
12084 Rather than print all of the @code{forward-paragraph} function, we
12085 will only print parts of it. Read without preparation, the function
12086 can be daunting!
12087
12088 @need 800
12089 In outline, the function looks like this:
12090
12091 @smallexample
12092 @group
12093 (defun forward-paragraph (&optional arg)
12094 "@var{documentation}@dots{}"
12095 (interactive "p")
12096 (or arg (setq arg 1))
12097 (let*
12098 @var{varlist}
12099 (while (< arg 0) ; @r{backward-moving-code}
12100 @dots{}
12101 (setq arg (1+ arg)))
12102 (while (> arg 0) ; @r{forward-moving-code}
12103 @dots{}
12104 (setq arg (1- arg)))))
12105 @end group
12106 @end smallexample
12107
12108 The first parts of the function are routine: the function's argument
12109 list consists of one optional argument. Documentation follows.
12110
12111 The lower case @samp{p} in the @code{interactive} declaration means
12112 that the processed prefix argument, if any, is passed to the function.
12113 This will be a number, and is the repeat count of how many paragraphs
12114 point will move. The @code{or} expression in the next line handles
12115 the common case when no argument is passed to the function, which occurs
12116 if the function is called from other code rather than interactively.
12117 This case was described earlier. (@xref{forward-sentence, The
12118 @code{forward-sentence} function}.) Now we reach the end of the
12119 familiar part of this function.
12120
12121 @node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12122 @unnumberedsubsec The @code{let*} expression
12123
12124 The next line of the @code{forward-paragraph} function begins a
12125 @code{let*} expression. This is a different kind of expression than
12126 we have seen so far. The symbol is @code{let*} not @code{let}.
12127
12128 The @code{let*} special form is like @code{let} except that Emacs sets
12129 each variable in sequence, one after another, and variables in the
12130 latter part of the varlist can make use of the values to which Emacs
12131 set variables in the earlier part of the varlist.
12132
12133 In the @code{let*} expression in this function, Emacs binds two
12134 variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12135 The value to which @code{paragraph-separate} is bound depends on the
12136 value of @code{fill-prefix-regexp}.
12137
12138 @need 1200
12139 Let's look at each in turn. The symbol @code{fill-prefix-regexp} is
12140 set to the value returned by evaluating the following list:
12141
12142 @smallexample
12143 @group
12144 (and fill-prefix
12145 (not (equal fill-prefix ""))
12146 (not paragraph-ignore-fill-prefix)
12147 (regexp-quote fill-prefix))
12148 @end group
12149 @end smallexample
12150
12151 @noindent
12152 This is an expression whose first element is the @code{and} special form.
12153
12154 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12155 function}), the @code{and} special form evaluates each of its
12156 arguments until one of the arguments returns a value of @code{nil}, in
12157 which case the @code{and} expression returns @code{nil}; however, if
12158 none of the arguments returns a value of @code{nil}, the value
12159 resulting from evaluating the last argument is returned. (Since such
12160 a value is not @code{nil}, it is considered true in Lisp.) In other
12161 words, an @code{and} expression returns a true value only if all its
12162 arguments are true.
12163 @findex and
12164
12165 In this case, the variable @code{fill-prefix-regexp} is bound to a
12166 non-@code{nil} value only if the following four expressions produce a
12167 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12168 @code{fill-prefix-regexp} is bound to @code{nil}.
12169
12170 @table @code
12171 @item fill-prefix
12172 When this variable is evaluated, the value of the fill prefix, if any,
12173 is returned. If there is no fill prefix, this variable returns
12174 @code{nil}.
12175
12176 @item (not (equal fill-prefix "")
12177 This expression checks whether an existing fill prefix is an empty
12178 string, that is, a string with no characters in it. An empty string is
12179 not a useful fill prefix.
12180
12181 @item (not paragraph-ignore-fill-prefix)
12182 This expression returns @code{nil} if the variable
12183 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12184 true value such as @code{t}.
12185
12186 @item (regexp-quote fill-prefix)
12187 This is the last argument to the @code{and} special form. If all the
12188 arguments to the @code{and} are true, the value resulting from
12189 evaluating this expression will be returned by the @code{and} expression
12190 and bound to the variable @code{fill-prefix-regexp},
12191 @end table
12192
12193 @findex regexp-quote
12194 @noindent
12195 The result of evaluating this @code{and} expression successfully is that
12196 @code{fill-prefix-regexp} will be bound to the value of
12197 @code{fill-prefix} as modified by the @code{regexp-quote} function.
12198 What @code{regexp-quote} does is read a string and return a regular
12199 expression that will exactly match the string and match nothing else.
12200 This means that @code{fill-prefix-regexp} will be set to a value that
12201 will exactly match the fill prefix if the fill prefix exists.
12202 Otherwise, the variable will be set to @code{nil}.
12203
12204 The second local variable in the @code{let*} expression is
12205 @code{paragraph-separate}. It is bound to the value returned by
12206 evaluating the expression:
12207
12208 @smallexample
12209 @group
12210 (if fill-prefix-regexp
12211 (concat paragraph-separate
12212 "\\|^" fill-prefix-regexp "[ \t]*$")
12213 paragraph-separate)))
12214 @end group
12215 @end smallexample
12216
12217 This expression shows why @code{let*} rather than @code{let} was used.
12218 The true-or-false-test for the @code{if} depends on whether the variable
12219 @code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12220
12221 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12222 the else-part of the @code{if} expression and binds
12223 @code{paragraph-separate} to its local value.
12224 (@code{paragraph-separate} is a regular expression that matches what
12225 separates paragraphs.)
12226
12227 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12228 the then-part of the @code{if} expression and binds
12229 @code{paragraph-separate} to a regular expression that includes the
12230 @code{fill-prefix-regexp} as part of the pattern.
12231
12232 Specifically, @code{paragraph-separate} is set to the original value
12233 of the paragraph separate regular expression concatenated with an
12234 alternative expression that consists of the @code{fill-prefix-regexp}
12235 followed by a blank line. The @samp{^} indicates that the
12236 @code{fill-prefix-regexp} must begin a line, and the optional
12237 whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12238 The @samp{\\|} defines this portion of the regexp as an alternative to
12239 @code{paragraph-separate}.
12240
12241 Now we get into the body of the @code{let*}. The first part of the body
12242 of the @code{let*} deals with the case when the function is given a
12243 negative argument and is therefore moving backwards. We will skip this
12244 section.
12245
12246 @node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12247 @unnumberedsubsec The forward motion @code{while} loop
12248
12249 The second part of the body of the @code{let*} deals with forward
12250 motion. It is a @code{while} loop that repeats itself so long as the
12251 value of @code{arg} is greater than zero. In the most common use of
12252 the function, the value of the argument is 1, so the body of the
12253 @code{while} loop is evaluated exactly once, and the cursor moves
12254 forward one paragraph.
12255
12256 This part handles three situations: when point is between paragraphs,
12257 when point is within a paragraph and there is a fill prefix, and
12258 when point is within a paragraph and there is no fill prefix.
12259
12260 @need 800
12261 The @code{while} loop looks like this:
12262
12263 @smallexample
12264 @group
12265 (while (> arg 0)
12266 (beginning-of-line)
12267
12268 ;; @r{between paragraphs}
12269 (while (prog1 (and (not (eobp))
12270 (looking-at paragraph-separate))
12271 (forward-line 1)))
12272 @end group
12273
12274 @group
12275 ;; @r{within paragraphs, with a fill prefix}
12276 (if fill-prefix-regexp
12277 ;; @r{There is a fill prefix; it overrides paragraph-start.}
12278 (while (and (not (eobp))
12279 (not (looking-at paragraph-separate))
12280 (looking-at fill-prefix-regexp))
12281 (forward-line 1))
12282 @end group
12283
12284 @group
12285 ;; @r{within paragraphs, no fill prefix}
12286 (if (re-search-forward paragraph-start nil t)
12287 (goto-char (match-beginning 0))
12288 (goto-char (point-max))))
12289
12290 (setq arg (1- arg)))
12291 @end group
12292 @end smallexample
12293
12294 We can see immediately that this is a decrementing counter @code{while}
12295 loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12296
12297 @need 800
12298 The body of the loop consists of three expressions:
12299
12300 @smallexample
12301 @group
12302 ;; @r{between paragraphs}
12303 (beginning-of-line)
12304 (while
12305 @var{body-of-while})
12306 @end group
12307
12308 @group
12309 ;; @r{within paragraphs, with fill prefix}
12310 (if @var{true-or-false-test}
12311 @var{then-part}
12312 @end group
12313
12314 @group
12315 ;; @r{within paragraphs, no fill prefix}
12316 @var{else-part}
12317 @end group
12318 @end smallexample
12319
12320 @noindent
12321 When the Emacs Lisp interpreter evaluates the body of the
12322 @code{while} loop, the first thing it does is evaluate the
12323 @code{(beginning-of-line)} expression and move point to the beginning
12324 of the line. Then there is an inner @code{while} loop. This
12325 @code{while} loop is designed to move the cursor out of the blank
12326 space between paragraphs, if it should happen to be there. Finally,
12327 there is an @code{if} expression that actually moves point to the end
12328 of the paragraph.
12329
12330 @node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12331 @unnumberedsubsec Between paragraphs
12332
12333 First, let us look at the inner @code{while} loop. This loop handles
12334 the case when point is between paragraphs; it uses three functions
12335 that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12336 @findex prog1
12337 @findex eobp
12338 @findex looking-at
12339
12340 @itemize @bullet
12341 @item
12342 @code{prog1} is similar to the @code{progn} special form,
12343 except that @code{prog1} evaluates its arguments in sequence and then
12344 returns the value of its first argument as the value of the whole
12345 expression. (@code{progn} returns the value of its last argument as the
12346 value of the expression.) The second and subsequent arguments to
12347 @code{prog1} are evaluated only for their side effects.
12348
12349 @item
12350 @code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12351 function that returns true if point is at the end of the buffer.
12352
12353 @item
12354 @code{looking-at} is a function that returns true if the text following
12355 point matches the regular expression passed @code{looking-at} as its
12356 argument.
12357 @end itemize
12358
12359 @need 800
12360 The @code{while} loop we are studying looks like this:
12361
12362 @smallexample
12363 @group
12364 (while (prog1 (and (not (eobp))
12365 (looking-at paragraph-separate))
12366 (forward-line 1)))
12367 @end group
12368 @end smallexample
12369
12370 @need 1200
12371 @noindent
12372 This is a @code{while} loop with no body! The true-or-false-test of the
12373 loop is the expression:
12374
12375 @smallexample
12376 @group
12377 (prog1 (and (not (eobp))
12378 (looking-at paragraph-separate))
12379 (forward-line 1))
12380 @end group
12381 @end smallexample
12382
12383 @noindent
12384 The first argument to the @code{prog1} is the @code{and} expression. It
12385 has within in it a test of whether point is at the end of the buffer and
12386 also a test of whether the pattern following point matches the regular
12387 expression for separating paragraphs.
12388
12389 If the cursor is not at the end of the buffer and if the characters
12390 following the cursor mark the separation between two paragraphs, then
12391 the @code{and} expression is true. After evaluating the @code{and}
12392 expression, the Lisp interpreter evaluates the second argument to
12393 @code{prog1}, which is @code{forward-line}. This moves point forward
12394 one line. The value returned by the @code{prog1} however, is the
12395 value of its first argument, so the @code{while} loop continues so
12396 long as point is not at the end of the buffer and is between
12397 paragraphs. When, finally, point is moved to a paragraph, the
12398 @code{and} expression tests false. Note however, that the
12399 @code{forward-line} command is carried out anyhow. This means that
12400 when point is moved from between paragraphs to a paragraph, it is left
12401 at the beginning of the second line of the paragraph.
12402
12403 @node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12404 @unnumberedsubsec Within paragraphs
12405
12406 The next expression in the outer @code{while} loop is an @code{if}
12407 expression. The Lisp interpreter evaluates the then-part of the
12408 @code{if} when the @code{fill-prefix-regexp} variable has a value other
12409 than @code{nil}, and it evaluates the else-part when the value of
12410 @code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12411 fill prefix.
12412
12413 @node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12414 @unnumberedsubsec No fill prefix
12415
12416 It is simplest to look at the code for the case when there is no fill
12417 prefix first. This code consists of yet another inner @code{if}
12418 expression, and reads as follows:
12419
12420 @smallexample
12421 @group
12422 (if (re-search-forward paragraph-start nil t)
12423 (goto-char (match-beginning 0))
12424 (goto-char (point-max)))
12425 @end group
12426 @end smallexample
12427
12428 @noindent
12429 This expression actually does the work that most people think of as
12430 the primary purpose of the @code{forward-paragraph} command: it causes
12431 a regular expression search to occur that searches forward to the
12432 start of the next paragraph and if it is found, moves point there; but
12433 if the start of another paragraph if not found, it moves point to the
12434 end of the accessible region of the buffer.
12435
12436 The only unfamiliar part of this is the use of @code{match-beginning}.
12437 This is another function that is new to us. The
12438 @code{match-beginning} function returns a number specifying the
12439 location of the start of the text that was matched by the last regular
12440 expression search.
12441
12442 The @code{match-beginning} function is used here because of a
12443 characteristic of a forward search: a successful forward search,
12444 regardless of whether it is a plain search or a regular expression
12445 search, will move point to the end of the text that is found. In this
12446 case, a successful search will move point to the end of the pattern for
12447 @code{paragraph-start}, which will be the beginning of the next
12448 paragraph rather than the end of the current one.
12449
12450 However, we want to put point at the end of the current paragraph, not at
12451 the beginning of the next one. The two positions may be different,
12452 because there may be several blank lines between paragraphs.
12453
12454 @findex match-beginning
12455 When given an argument of 0, @code{match-beginning} returns the position
12456 that is the start of the text that the most recent regular
12457 expression search matched. In this case, the most recent regular
12458 expression search is the one looking for @code{paragraph-start}, so
12459 @code{match-beginning} returns the beginning position of the pattern,
12460 rather than the end of the pattern. The beginning position is the end
12461 of the paragraph.
12462
12463 (Incidentally, when passed a positive number as an argument, the
12464 @code{match-beginning} function will place point at that parenthesized
12465 expression in the last regular expression. It is a useful function.)
12466
12467 @node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12468 @unnumberedsubsec With a fill prefix
12469
12470 The inner @code{if} expression just discussed is the else-part of an enclosing
12471 @code{if} expression which tests whether there is a fill prefix. If
12472 there is a fill prefix, the then-part of this @code{if} is evaluated.
12473 It looks like this:
12474
12475 @smallexample
12476 @group
12477 (while (and (not (eobp))
12478 (not (looking-at paragraph-separate))
12479 (looking-at fill-prefix-regexp))
12480 (forward-line 1))
12481 @end group
12482 @end smallexample
12483
12484 @noindent
12485 What this expression does is move point forward line by line so long
12486 as three conditions are true:
12487
12488 @enumerate
12489 @item
12490 Point is not at the end of the buffer.
12491
12492 @item
12493 The text following point does not separate paragraphs.
12494
12495 @item
12496 The pattern following point is the fill prefix regular expression.
12497 @end enumerate
12498
12499 The last condition may be puzzling, until you remember that point was
12500 moved to the beginning of the line early in the @code{forward-paragraph}
12501 function. This means that if the text has a fill prefix, the
12502 @code{looking-at} function will see it.
12503
12504 @node fwd-para summary, , fwd-para with fill prefix, forward-paragraph
12505 @unnumberedsubsec Summary
12506
12507 In summary, when moving forward, the @code{forward-paragraph} function
12508 does the following:
12509
12510 @itemize @bullet
12511 @item
12512 Move point to the beginning of the line.
12513
12514 @item
12515 Skip over lines between paragraphs.
12516
12517 @item
12518 Check whether there is a fill prefix, and if there is:
12519
12520 @itemize ---
12521
12522 @item
12523 Go forward line by line so long as the line is not a paragraph
12524 separating line.
12525 @end itemize
12526
12527 @item
12528 But if there is no fill prefix,
12529
12530 @itemize ---
12531
12532 @item
12533 Search for the next paragraph start pattern.
12534
12535 @item
12536 Go to the beginning of the paragraph start pattern, which will be the
12537 end of the previous paragraph.
12538
12539 @item
12540 Or else go to the end of the accessible portion of the buffer.
12541 @end itemize
12542 @end itemize
12543
12544 @need 1200
12545 For review, here is the code we have just been discussing, formatted
12546 for clarity:
12547
12548 @smallexample
12549 @group
12550 (interactive "p")
12551 (or arg (setq arg 1))
12552 (let* (
12553 (fill-prefix-regexp
12554 (and fill-prefix (not (equal fill-prefix ""))
12555 (not paragraph-ignore-fill-prefix)
12556 (regexp-quote fill-prefix)))
12557 @end group
12558
12559 @group
12560 (paragraph-separate
12561 (if fill-prefix-regexp
12562 (concat paragraph-separate
12563 "\\|^"
12564 fill-prefix-regexp
12565 "[ \t]*$")
12566 paragraph-separate)))
12567
12568 @var{omitted-backward-moving-code} @dots{}
12569 @end group
12570
12571 @group
12572 (while (> arg 0) ; @r{forward-moving-code}
12573 (beginning-of-line)
12574
12575 (while (prog1 (and (not (eobp))
12576 (looking-at paragraph-separate))
12577 (forward-line 1)))
12578 @end group
12579
12580 @group
12581 (if fill-prefix-regexp
12582 (while (and (not (eobp)) ; @r{then-part}
12583 (not (looking-at paragraph-separate))
12584 (looking-at fill-prefix-regexp))
12585 (forward-line 1))
12586 @end group
12587 @group
12588 ; @r{else-part: the inner-if}
12589 (if (re-search-forward paragraph-start nil t)
12590 (goto-char (match-beginning 0))
12591 (goto-char (point-max))))
12592
12593 (setq arg (1- arg))))) ; @r{decrementer}
12594 @end group
12595 @end smallexample
12596
12597 The full definition for the @code{forward-paragraph} function not only
12598 includes this code for going forwards, but also code for going backwards.
12599
12600 If you are reading this inside of GNU Emacs and you want to see the
12601 whole function, you can type @kbd{C-h f} (@code{describe-function})
12602 and the name of the function. This gives you the function
12603 documentation and the name of the library containing the function's
12604 source. Place point over the name of the library and press the RET
12605 key; you will be taken directly to the source. (Be sure to install
12606 your sources! Without them, you are like a person who tries to drive
12607 a car with his eyes shut!)
12608
12609 @c !!! again, 21.0.100 tags table location in this paragraph
12610 Or -- a good habit to get into -- you can type @kbd{M-.}
12611 (@code{find-tag}) and the name of the function when prompted for it.
12612 This will take you directly to the source. If the @code{find-tag}
12613 function first asks you for the name of a @file{TAGS} table, give it
12614 the name of the @file{TAGS} file such as
12615 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS}. (The exact path to your
12616 @file{TAGS} file depends on how your copy of Emacs was installed.)
12617
12618 You can also create your own @file{TAGS} file for directories that
12619 lack one.
12620 @ifnottex
12621 @xref{etags, , Create Your Own @file{TAGS} File}.
12622 @end ifnottex
12623
12624 @node etags, Regexp Review, forward-paragraph, Regexp Search
12625 @section Create Your Own @file{TAGS} File
12626 @findex etags
12627 @cindex @file{TAGS} file, create own
12628
12629 The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12630 source for a function, variable, node, or other source. The function
12631 depends on tags tables to tell it where to go.
12632
12633 You often need to build and install tags tables yourself. They are
12634 not built automatically. A tags table is called a @file{TAGS} file;
12635 the name is in upper case letters.
12636
12637 You can create a @file{TAGS} file by calling the @code{etags} program
12638 that comes as a part of the Emacs distribution. Usually, @code{etags}
12639 is compiled and installed when Emacs is built. (@code{etags} is not
12640 an Emacs Lisp function or a part of Emacs; it is a C program.)
12641
12642 @need 1250
12643 To create a @file{TAGS} file, first switch to the directory in which
12644 you want to create the file. In Emacs you can do this with the
12645 @kbd{M-x cd} command, or by visiting a file in the directory, or by
12646 listing the directory with @kbd{C-x d} (@code{dired}). Then run the
12647 compile command, with @w{@code{etags *.el}} as the command to execute
12648
12649 @smallexample
12650 M-x compile RET etags *.el RET
12651 @end smallexample
12652
12653 @noindent
12654 to create a @file{TAGS} file.
12655
12656 For example, if you have a large number of files in your
12657 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12658 of which I load 12---you can create a @file{TAGS} file for the Emacs
12659 Lisp files in that directory.
12660
12661 @need 1250
12662 The @code{etags} program takes all the
12663 usual shell `wildcards'. For example, if you have two directories for
12664 which you want a single @file{TAGS file}, type
12665 @w{@code{etags *.el ../elisp/*.el}},
12666 where @file{../elisp/} is the second directory:
12667
12668 @smallexample
12669 M-x compile RET etags *.el ../elisp/*.el RET
12670 @end smallexample
12671
12672 @need 1250
12673 Type
12674
12675 @smallexample
12676 M-x compile RET etags --help RET
12677 @end smallexample
12678
12679 @noindent
12680 to see a list of the options accepted by @code{etags} as well as a
12681 list of supported languages.
12682
12683 The @code{etags} program handles more than 20 languages, including
12684 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12685 Pascal, Perl, Python, Texinfo, makefiles, and most assemblers. The
12686 program has no switches for specifying the language; it recognizes the
12687 language in an input file according to its file name and contents.
12688
12689 @file{etags} is very helpful when you are writing code yourself and
12690 want to refer back to functions you have already written. Just run
12691 @code{etags} again at intervals as you write new functions, so they
12692 become part of the @file{TAGS} file.
12693
12694 If you think an appropriate @file{TAGS} file already exists for what
12695 you want, but do not know where it is, you can use the @code{locate}
12696 program to attempt to find it.
12697
12698 Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12699 full path names of all your @file{TAGS} files. On my system, this
12700 command lists 34 @file{TAGS} files. On the other hand, a `plain
12701 vanilla' system I recently installed did not contain any @file{TAGS}
12702 files.
12703
12704 If the tags table you want has been created, you can use the @code{M-x
12705 visit-tags-table} command to specify it. Otherwise, you will need to
12706 create the tag table yourself and then use @code{M-x
12707 visit-tags-table}.
12708
12709 @subsubheading Building Tags in the Emacs sources
12710 @cindex Building Tags in the Emacs sources
12711 @cindex Tags in the Emacs sources
12712 @findex make tags
12713
12714 The GNU Emacs sources come with a @file{Makefile} that contains a
12715 sophisticated @code{etags} command that creates, collects, and merges
12716 tags tables from all over the Emacs sources and puts the information
12717 into one @file{TAGS} file in the @file{src/} directory below the top
12718 level of your Emacs source directory.
12719
12720 @need 1250
12721 To build this @file{TAGS} file, go to the top level of your Emacs
12722 source directory and run the compile command @code{make tags}:
12723
12724 @smallexample
12725 M-x compile RET make tags RET
12726 @end smallexample
12727
12728 @noindent
12729 (The @code{make tags} command works well with the GNU Emacs sources,
12730 as well as with some other source packages.)
12731
12732 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12733 Manual}.
12734
12735 @node Regexp Review, re-search Exercises, etags, Regexp Search
12736 @comment node-name, next, previous, up
12737 @section Review
12738
12739 Here is a brief summary of some recently introduced functions.
12740
12741 @table @code
12742 @item while
12743 Repeatedly evaluate the body of the expression so long as the first
12744 element of the body tests true. Then return @code{nil}. (The
12745 expression is evaluated only for its side effects.)
12746
12747 @need 1250
12748 For example:
12749
12750 @smallexample
12751 @group
12752 (let ((foo 2))
12753 (while (> foo 0)
12754 (insert (format "foo is %d.\n" foo))
12755 (setq foo (1- foo))))
12756
12757 @result{} foo is 2.
12758 foo is 1.
12759 nil
12760 @end group
12761 @end smallexample
12762 @noindent
12763 (The @code{insert} function inserts its arguments at point; the
12764 @code{format} function returns a string formatted from its arguments
12765 the way @code{message} formats its arguments; @code{\n} produces a new
12766 line.)
12767
12768 @item re-search-forward
12769 Search for a pattern, and if the pattern is found, move point to rest
12770 just after it.
12771
12772 @noindent
12773 Takes four arguments, like @code{search-forward}:
12774
12775 @enumerate
12776 @item
12777 A regular expression that specifies the pattern to search for.
12778
12779 @item
12780 Optionally, the limit of the search.
12781
12782 @item
12783 Optionally, what to do if the search fails, return @code{nil} or an
12784 error message.
12785
12786 @item
12787 Optionally, how many times to repeat the search; if negative, the
12788 search goes backwards.
12789 @end enumerate
12790
12791 @item let*
12792 Bind some variables locally to particular values,
12793 and then evaluate the remaining arguments, returning the value of the
12794 last one. While binding the local variables, use the local values of
12795 variables bound earlier, if any.
12796
12797 @need 1250
12798 For example:
12799
12800 @smallexample
12801 @group
12802 (let* ((foo 7)
12803 (bar (* 3 foo)))
12804 (message "`bar' is %d." bar))
12805 @result{} `bar' is 21.
12806 @end group
12807 @end smallexample
12808
12809 @item match-beginning
12810 Return the position of the start of the text found by the last regular
12811 expression search.
12812
12813 @item looking-at
12814 Return @code{t} for true if the text after point matches the argument,
12815 which should be a regular expression.
12816
12817 @item eobp
12818 Return @code{t} for true if point is at the end of the accessible part
12819 of a buffer. The end of the accessible part is the end of the buffer
12820 if the buffer is not narrowed; it is the end of the narrowed part if
12821 the buffer is narrowed.
12822
12823 @item prog1
12824 Evaluate each argument in sequence and then return the value of the
12825 @emph{first}.
12826
12827 @need 1250
12828 For example:
12829
12830 @smallexample
12831 @group
12832 (prog1 1 2 3 4)
12833 @result{} 1
12834 @end group
12835 @end smallexample
12836 @end table
12837
12838 @need 1500
12839 @node re-search Exercises, , Regexp Review, Regexp Search
12840 @section Exercises with @code{re-search-forward}
12841
12842 @itemize @bullet
12843 @item
12844 Write a function to search for a regular expression that matches two
12845 or more blank lines in sequence.
12846
12847 @item
12848 Write a function to search for duplicated words, such as `the the'.
12849 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12850 Manual}, for information on how to write a regexp (a regular
12851 expression) to match a string that is composed of two identical
12852 halves. You can devise several regexps; some are better than others.
12853 The function I use is described in an appendix, along with several
12854 regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
12855 @end itemize
12856
12857 @node Counting Words, Words in a defun, Regexp Search, Top
12858 @chapter Counting: Repetition and Regexps
12859 @cindex Repetition for word counting
12860 @cindex Regular expressions for word counting
12861
12862 Repetition and regular expression searches are powerful tools that you
12863 often use when you write code in Emacs Lisp. This chapter illustrates
12864 the use of regular expression searches through the construction of
12865 word count commands using @code{while} loops and recursion.
12866
12867 @menu
12868 * Why Count Words::
12869 * count-words-region:: Use a regexp, but find a problem.
12870 * recursive-count-words:: Start with case of no words in region.
12871 * Counting Exercise::
12872 @end menu
12873
12874 @node Why Count Words, count-words-region, Counting Words, Counting Words
12875 @ifnottex
12876 @unnumberedsec Counting words
12877 @end ifnottex
12878
12879 The standard Emacs distribution contains a function for counting the
12880 number of lines within a region. However, there is no corresponding
12881 function for counting words.
12882
12883 Certain types of writing ask you to count words. Thus, if you write
12884 an essay, you may be limited to 800 words; if you write a novel, you
12885 may discipline yourself to write 1000 words a day. It seems odd to me
12886 that Emacs lacks a word count command. Perhaps people use Emacs
12887 mostly for code or types of documentation that do not require word
12888 counts; or perhaps they restrict themselves to the operating system
12889 word count command, @code{wc}. Alternatively, people may follow
12890 the publishers' convention and compute a word count by dividing the
12891 number of characters in a document by five. In any event, here are
12892 commands to count words.
12893
12894 @node count-words-region, recursive-count-words, Why Count Words, Counting Words
12895 @comment node-name, next, previous, up
12896 @section The @code{count-words-region} Function
12897 @findex count-words-region
12898
12899 A word count command could count words in a line, paragraph, region,
12900 or buffer. What should the command cover? You could design the
12901 command to count the number of words in a complete buffer. However,
12902 the Emacs tradition encourages flexibility---you may want to count
12903 words in just a section, rather than all of a buffer. So it makes
12904 more sense to design the command to count the number of words in a
12905 region. Once you have a @code{count-words-region} command, you can,
12906 if you wish, count words in a whole buffer by marking it with @kbd{C-x
12907 h} (@code{mark-whole-buffer}).
12908
12909 Clearly, counting words is a repetitive act: starting from the
12910 beginning of the region, you count the first word, then the second
12911 word, then the third word, and so on, until you reach the end of the
12912 region. This means that word counting is ideally suited to recursion
12913 or to a @code{while} loop.
12914
12915 @menu
12916 * Design count-words-region:: The definition using a @code{while} loop.
12917 * Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
12918 @end menu
12919
12920 @node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12921 @ifnottex
12922 @unnumberedsubsec Designing @code{count-words-region}
12923 @end ifnottex
12924
12925 First, we will implement the word count command with a @code{while}
12926 loop, then with recursion. The command will, of course, be
12927 interactive.
12928
12929 @need 800
12930 The template for an interactive function definition is, as always:
12931
12932 @smallexample
12933 @group
12934 (defun @var{name-of-function} (@var{argument-list})
12935 "@var{documentation}@dots{}"
12936 (@var{interactive-expression}@dots{})
12937 @var{body}@dots{})
12938 @end group
12939 @end smallexample
12940
12941 What we need to do is fill in the slots.
12942
12943 The name of the function should be self-explanatory and similar to the
12944 existing @code{count-lines-region} name. This makes the name easier
12945 to remember. @code{count-words-region} is a good choice.
12946
12947 The function counts words within a region. This means that the
12948 argument list must contain symbols that are bound to the two
12949 positions, the beginning and end of the region. These two positions
12950 can be called @samp{beginning} and @samp{end} respectively. The first
12951 line of the documentation should be a single sentence, since that is
12952 all that is printed as documentation by a command such as
12953 @code{apropos}. The interactive expression will be of the form
12954 @samp{(interactive "r")}, since that will cause Emacs to pass the
12955 beginning and end of the region to the function's argument list. All
12956 this is routine.
12957
12958 The body of the function needs to be written to do three tasks:
12959 first, to set up conditions under which the @code{while} loop can
12960 count words, second, to run the @code{while} loop, and third, to send
12961 a message to the user.
12962
12963 When a user calls @code{count-words-region}, point may be at the
12964 beginning or the end of the region. However, the counting process
12965 must start at the beginning of the region. This means we will want
12966 to put point there if it is not already there. Executing
12967 @code{(goto-char beginning)} ensures this. Of course, we will want to
12968 return point to its expected position when the function finishes its
12969 work. For this reason, the body must be enclosed in a
12970 @code{save-excursion} expression.
12971
12972 The central part of the body of the function consists of a
12973 @code{while} loop in which one expression jumps point forward word by
12974 word, and another expression counts those jumps. The true-or-false-test
12975 of the @code{while} loop should test true so long as point should jump
12976 forward, and false when point is at the end of the region.
12977
12978 We could use @code{(forward-word 1)} as the expression for moving point
12979 forward word by word, but it is easier to see what Emacs identifies as a
12980 `word' if we use a regular expression search.
12981
12982 A regular expression search that finds the pattern for which it is
12983 searching leaves point after the last character matched. This means
12984 that a succession of successful word searches will move point forward
12985 word by word.
12986
12987 As a practical matter, we want the regular expression search to jump
12988 over whitespace and punctuation between words as well as over the
12989 words themselves. A regexp that refuses to jump over interword
12990 whitespace would never jump more than one word! This means that
12991 the regexp should include the whitespace and punctuation that follows
12992 a word, if any, as well as the word itself. (A word may end a buffer
12993 and not have any following whitespace or punctuation, so that part of
12994 the regexp must be optional.)
12995
12996 Thus, what we want for the regexp is a pattern defining one or more
12997 word constituent characters followed, optionally, by one or more
12998 characters that are not word constituents. The regular expression for
12999 this is:
13000
13001 @smallexample
13002 \w+\W*
13003 @end smallexample
13004
13005 @noindent
13006 The buffer's syntax table determines which characters are and are not
13007 word constituents. (@xref{Syntax, , What Constitutes a Word or
13008 Symbol?}, for more about syntax. Also, see @ref{Syntax, Syntax, The
13009 Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
13010 Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13011
13012 @need 800
13013 The search expression looks like this:
13014
13015 @smallexample
13016 (re-search-forward "\\w+\\W*")
13017 @end smallexample
13018
13019 @noindent
13020 (Note that paired backslashes precede the @samp{w} and @samp{W}. A
13021 single backslash has special meaning to the Emacs Lisp interpreter. It
13022 indicates that the following character is interpreted differently than
13023 usual. For example, the two characters, @samp{\n}, stand for
13024 @samp{newline}, rather than for a backslash followed by @samp{n}. Two
13025 backslashes in a row stand for an ordinary, `unspecial' backslash.)
13026
13027 We need a counter to count how many words there are; this variable
13028 must first be set to 0 and then incremented each time Emacs goes
13029 around the @code{while} loop. The incrementing expression is simply:
13030
13031 @smallexample
13032 (setq count (1+ count))
13033 @end smallexample
13034
13035 Finally, we want to tell the user how many words there are in the
13036 region. The @code{message} function is intended for presenting this
13037 kind of information to the user. The message has to be phrased so
13038 that it reads properly regardless of how many words there are in the
13039 region: we don't want to say that ``there are 1 words in the region''.
13040 The conflict between singular and plural is ungrammatical. We can
13041 solve this problem by using a conditional expression that evaluates
13042 different messages depending on the number of words in the region.
13043 There are three possibilities: no words in the region, one word in the
13044 region, and more than one word. This means that the @code{cond}
13045 special form is appropriate.
13046
13047 @need 1500
13048 All this leads to the following function definition:
13049
13050 @smallexample
13051 @group
13052 ;;; @r{First version; has bugs!}
13053 (defun count-words-region (beginning end)
13054 "Print number of words in the region.
13055 Words are defined as at least one word-constituent
13056 character followed by at least one character that
13057 is not a word-constituent. The buffer's syntax
13058 table determines which characters these are."
13059 (interactive "r")
13060 (message "Counting words in region ... ")
13061 @end group
13062
13063 @group
13064 ;;; @r{1. Set up appropriate conditions.}
13065 (save-excursion
13066 (goto-char beginning)
13067 (let ((count 0))
13068 @end group
13069
13070 @group
13071 ;;; @r{2. Run the} while @r{loop.}
13072 (while (< (point) end)
13073 (re-search-forward "\\w+\\W*")
13074 (setq count (1+ count)))
13075 @end group
13076
13077 @group
13078 ;;; @r{3. Send a message to the user.}
13079 (cond ((zerop count)
13080 (message
13081 "The region does NOT have any words."))
13082 ((= 1 count)
13083 (message
13084 "The region has 1 word."))
13085 (t
13086 (message
13087 "The region has %d words." count))))))
13088 @end group
13089 @end smallexample
13090
13091 @noindent
13092 As written, the function works, but not in all circumstances.
13093
13094 @node Whitespace Bug, , Design count-words-region, count-words-region
13095 @comment node-name, next, previous, up
13096 @subsection The Whitespace Bug in @code{count-words-region}
13097
13098 The @code{count-words-region} command described in the preceding
13099 section has two bugs, or rather, one bug with two manifestations.
13100 First, if you mark a region containing only whitespace in the middle
13101 of some text, the @code{count-words-region} command tells you that the
13102 region contains one word! Second, if you mark a region containing
13103 only whitespace at the end of the buffer or the accessible portion of
13104 a narrowed buffer, the command displays an error message that looks
13105 like this:
13106
13107 @smallexample
13108 Search failed: "\\w+\\W*"
13109 @end smallexample
13110
13111 If you are reading this in Info in GNU Emacs, you can test for these
13112 bugs yourself.
13113
13114 First, evaluate the function in the usual manner to install it.
13115 @ifinfo
13116 Here is a copy of the definition. Place your cursor after the closing
13117 parenthesis and type @kbd{C-x C-e} to install it.
13118
13119 @smallexample
13120 @group
13121 ;; @r{First version; has bugs!}
13122 (defun count-words-region (beginning end)
13123 "Print number of words in the region.
13124 Words are defined as at least one word-constituent character followed
13125 by at least one character that is not a word-constituent. The buffer's
13126 syntax table determines which characters these are."
13127 @end group
13128 @group
13129 (interactive "r")
13130 (message "Counting words in region ... ")
13131 @end group
13132
13133 @group
13134 ;;; @r{1. Set up appropriate conditions.}
13135 (save-excursion
13136 (goto-char beginning)
13137 (let ((count 0))
13138 @end group
13139
13140 @group
13141 ;;; @r{2. Run the} while @r{loop.}
13142 (while (< (point) end)
13143 (re-search-forward "\\w+\\W*")
13144 (setq count (1+ count)))
13145 @end group
13146
13147 @group
13148 ;;; @r{3. Send a message to the user.}
13149 (cond ((zerop count)
13150 (message "The region does NOT have any words."))
13151 ((= 1 count) (message "The region has 1 word."))
13152 (t (message "The region has %d words." count))))))
13153 @end group
13154 @end smallexample
13155 @end ifinfo
13156
13157 @need 1000
13158 If you wish, you can also install this keybinding by evaluating it:
13159
13160 @smallexample
13161 (global-set-key "\C-c=" 'count-words-region)
13162 @end smallexample
13163
13164 To conduct the first test, set mark and point to the beginning and end
13165 of the following line and then type @kbd{C-c =} (or @kbd{M-x
13166 count-words-region} if you have not bound @kbd{C-c =}):
13167
13168 @smallexample
13169 one two three
13170 @end smallexample
13171
13172 @noindent
13173 Emacs will tell you, correctly, that the region has three words.
13174
13175 Repeat the test, but place mark at the beginning of the line and place
13176 point just @emph{before} the word @samp{one}. Again type the command
13177 @kbd{C-c =} (or @kbd{M-x count-words-region}). Emacs should tell you
13178 that the region has no words, since it is composed only of the
13179 whitespace at the beginning of the line. But instead Emacs tells you
13180 that the region has one word!
13181
13182 For the third test, copy the sample line to the end of the
13183 @file{*scratch*} buffer and then type several spaces at the end of the
13184 line. Place mark right after the word @samp{three} and point at the
13185 end of line. (The end of the line will be the end of the buffer.)
13186 Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13187 Again, Emacs should tell you that the region has no words, since it is
13188 composed only of the whitespace at the end of the line. Instead,
13189 Emacs displays an error message saying @samp{Search failed}.
13190
13191 The two bugs stem from the same problem.
13192
13193 Consider the first manifestation of the bug, in which the command
13194 tells you that the whitespace at the beginning of the line contains
13195 one word. What happens is this: The @code{M-x count-words-region}
13196 command moves point to the beginning of the region. The @code{while}
13197 tests whether the value of point is smaller than the value of
13198 @code{end}, which it is. Consequently, the regular expression search
13199 looks for and finds the first word. It leaves point after the word.
13200 @code{count} is set to one. The @code{while} loop repeats; but this
13201 time the value of point is larger than the value of @code{end}, the
13202 loop is exited; and the function displays a message saying the number
13203 of words in the region is one. In brief, the regular expression
13204 search looks for and finds the word even though it is outside
13205 the marked region.
13206
13207 In the second manifestation of the bug, the region is whitespace at
13208 the end of the buffer. Emacs says @samp{Search failed}. What happens
13209 is that the true-or-false-test in the @code{while} loop tests true, so
13210 the search expression is executed. But since there are no more words
13211 in the buffer, the search fails.
13212
13213 In both manifestations of the bug, the search extends or attempts to
13214 extend outside of the region.
13215
13216 The solution is to limit the search to the region---this is a fairly
13217 simple action, but as you may have come to expect, it is not quite as
13218 simple as you might think.
13219
13220 As we have seen, the @code{re-search-forward} function takes a search
13221 pattern as its first argument. But in addition to this first,
13222 mandatory argument, it accepts three optional arguments. The optional
13223 second argument bounds the search. The optional third argument, if
13224 @code{t}, causes the function to return @code{nil} rather than signal
13225 an error if the search fails. The optional fourth argument is a
13226 repeat count. (In Emacs, you can see a function's documentation by
13227 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13228
13229 In the @code{count-words-region} definition, the value of the end of
13230 the region is held by the variable @code{end} which is passed as an
13231 argument to the function. Thus, we can add @code{end} as an argument
13232 to the regular expression search expression:
13233
13234 @smallexample
13235 (re-search-forward "\\w+\\W*" end)
13236 @end smallexample
13237
13238 However, if you make only this change to the @code{count-words-region}
13239 definition and then test the new version of the definition on a
13240 stretch of whitespace, you will receive an error message saying
13241 @samp{Search failed}.
13242
13243 What happens is this: the search is limited to the region, and fails
13244 as you expect because there are no word-constituent characters in the
13245 region. Since it fails, we receive an error message. But we do not
13246 want to receive an error message in this case; we want to receive the
13247 message that "The region does NOT have any words."
13248
13249 The solution to this problem is to provide @code{re-search-forward}
13250 with a third argument of @code{t}, which causes the function to return
13251 @code{nil} rather than signal an error if the search fails.
13252
13253 However, if you make this change and try it, you will see the message
13254 ``Counting words in region ... '' and @dots{} you will keep on seeing
13255 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13256
13257 Here is what happens: the search is limited to the region, as before,
13258 and it fails because there are no word-constituent characters in the
13259 region, as expected. Consequently, the @code{re-search-forward}
13260 expression returns @code{nil}. It does nothing else. In particular,
13261 it does not move point, which it does as a side effect if it finds the
13262 search target. After the @code{re-search-forward} expression returns
13263 @code{nil}, the next expression in the @code{while} loop is evaluated.
13264 This expression increments the count. Then the loop repeats. The
13265 true-or-false-test tests true because the value of point is still less
13266 than the value of end, since the @code{re-search-forward} expression
13267 did not move point. @dots{} and the cycle repeats @dots{}
13268
13269 The @code{count-words-region} definition requires yet another
13270 modification, to cause the true-or-false-test of the @code{while} loop
13271 to test false if the search fails. Put another way, there are two
13272 conditions that must be satisfied in the true-or-false-test before the
13273 word count variable is incremented: point must still be within the
13274 region and the search expression must have found a word to count.
13275
13276 Since both the first condition and the second condition must be true
13277 together, the two expressions, the region test and the search
13278 expression, can be joined with an @code{and} special form and embedded in
13279 the @code{while} loop as the true-or-false-test, like this:
13280
13281 @smallexample
13282 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13283 @end smallexample
13284
13285 @c colon in printed section title causes problem in Info cross reference
13286 @c also trouble with an overfull hbox
13287 @iftex
13288 @noindent
13289 (For information about @code{and}, see
13290 @ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13291 Functions}.)
13292 @end iftex
13293 @ifinfo
13294 @noindent
13295 (@xref{forward-paragraph}, for information about @code{and}.)
13296 @end ifinfo
13297
13298 The @code{re-search-forward} expression returns @code{t} if the search
13299 succeeds and as a side effect moves point. Consequently, as words are
13300 found, point is moved through the region. When the search
13301 expression fails to find another word, or when point reaches the end
13302 of the region, the true-or-false-test tests false, the @code{while}
13303 loop exists, and the @code{count-words-region} function displays one
13304 or other of its messages.
13305
13306 After incorporating these final changes, the @code{count-words-region}
13307 works without bugs (or at least, without bugs that I have found!).
13308 Here is what it looks like:
13309
13310 @smallexample
13311 @group
13312 ;;; @r{Final version:} @code{while}
13313 (defun count-words-region (beginning end)
13314 "Print number of words in the region."
13315 (interactive "r")
13316 (message "Counting words in region ... ")
13317 @end group
13318
13319 @group
13320 ;;; @r{1. Set up appropriate conditions.}
13321 (save-excursion
13322 (let ((count 0))
13323 (goto-char beginning)
13324 @end group
13325
13326 @group
13327 ;;; @r{2. Run the} while @r{loop.}
13328 (while (and (< (point) end)
13329 (re-search-forward "\\w+\\W*" end t))
13330 (setq count (1+ count)))
13331 @end group
13332
13333 @group
13334 ;;; @r{3. Send a message to the user.}
13335 (cond ((zerop count)
13336 (message
13337 "The region does NOT have any words."))
13338 ((= 1 count)
13339 (message
13340 "The region has 1 word."))
13341 (t
13342 (message
13343 "The region has %d words." count))))))
13344 @end group
13345 @end smallexample
13346
13347 @node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13348 @comment node-name, next, previous, up
13349 @section Count Words Recursively
13350 @cindex Count words recursively
13351 @cindex Recursively counting words
13352 @cindex Words, counted recursively
13353
13354 You can write the function for counting words recursively as well as
13355 with a @code{while} loop. Let's see how this is done.
13356
13357 First, we need to recognize that the @code{count-words-region}
13358 function has three jobs: it sets up the appropriate conditions for
13359 counting to occur; it counts the words in the region; and it sends a
13360 message to the user telling how many words there are.
13361
13362 If we write a single recursive function to do everything, we will
13363 receive a message for every recursive call. If the region contains 13
13364 words, we will receive thirteen messages, one right after the other.
13365 We don't want this! Instead, we must write two functions to do the
13366 job, one of which (the recursive function) will be used inside of the
13367 other. One function will set up the conditions and display the
13368 message; the other will return the word count.
13369
13370 Let us start with the function that causes the message to be displayed.
13371 We can continue to call this @code{count-words-region}.
13372
13373 This is the function that the user will call. It will be interactive.
13374 Indeed, it will be similar to our previous versions of this
13375 function, except that it will call @code{recursive-count-words} to
13376 determine how many words are in the region.
13377
13378 @need 1250
13379 We can readily construct a template for this function, based on our
13380 previous versions:
13381
13382 @smallexample
13383 @group
13384 ;; @r{Recursive version; uses regular expression search}
13385 (defun count-words-region (beginning end)
13386 "@var{documentation}@dots{}"
13387 (@var{interactive-expression}@dots{})
13388 @end group
13389 @group
13390
13391 ;;; @r{1. Set up appropriate conditions.}
13392 (@var{explanatory message})
13393 (@var{set-up functions}@dots{}
13394 @end group
13395 @group
13396
13397 ;;; @r{2. Count the words.}
13398 @var{recursive call}
13399 @end group
13400 @group
13401
13402 ;;; @r{3. Send a message to the user.}
13403 @var{message providing word count}))
13404 @end group
13405 @end smallexample
13406
13407 The definition looks straightforward, except that somehow the count
13408 returned by the recursive call must be passed to the message
13409 displaying the word count. A little thought suggests that this can be
13410 done by making use of a @code{let} expression: we can bind a variable
13411 in the varlist of a @code{let} expression to the number of words in
13412 the region, as returned by the recursive call; and then the
13413 @code{cond} expression, using binding, can display the value to the
13414 user.
13415
13416 Often, one thinks of the binding within a @code{let} expression as
13417 somehow secondary to the `primary' work of a function. But in this
13418 case, what you might consider the `primary' job of the function,
13419 counting words, is done within the @code{let} expression.
13420
13421 @need 1250
13422 Using @code{let}, the function definition looks like this:
13423
13424 @smallexample
13425 @group
13426 (defun count-words-region (beginning end)
13427 "Print number of words in the region."
13428 (interactive "r")
13429 @end group
13430
13431 @group
13432 ;;; @r{1. Set up appropriate conditions.}
13433 (message "Counting words in region ... ")
13434 (save-excursion
13435 (goto-char beginning)
13436 @end group
13437
13438 @group
13439 ;;; @r{2. Count the words.}
13440 (let ((count (recursive-count-words end)))
13441 @end group
13442
13443 @group
13444 ;;; @r{3. Send a message to the user.}
13445 (cond ((zerop count)
13446 (message
13447 "The region does NOT have any words."))
13448 ((= 1 count)
13449 (message
13450 "The region has 1 word."))
13451 (t
13452 (message
13453 "The region has %d words." count))))))
13454 @end group
13455 @end smallexample
13456
13457 Next, we need to write the recursive counting function.
13458
13459 A recursive function has at least three parts: the `do-again-test', the
13460 `next-step-expression', and the recursive call.
13461
13462 The do-again-test determines whether the function will or will not be
13463 called again. Since we are counting words in a region and can use a
13464 function that moves point forward for every word, the do-again-test
13465 can check whether point is still within the region. The do-again-test
13466 should find the value of point and determine whether point is before,
13467 at, or after the value of the end of the region. We can use the
13468 @code{point} function to locate point. Clearly, we must pass the
13469 value of the end of the region to the recursive counting function as an
13470 argument.
13471
13472 In addition, the do-again-test should also test whether the search finds a
13473 word. If it does not, the function should not call itself again.
13474
13475 The next-step-expression changes a value so that when the recursive
13476 function is supposed to stop calling itself, it stops. More
13477 precisely, the next-step-expression changes a value so that at the
13478 right time, the do-again-test stops the recursive function from
13479 calling itself again. In this case, the next-step-expression can be
13480 the expression that moves point forward, word by word.
13481
13482 The third part of a recursive function is the recursive call.
13483
13484 Somewhere, also, we also need a part that does the `work' of the
13485 function, a part that does the counting. A vital part!
13486
13487 @need 1250
13488 But already, we have an outline of the recursive counting function:
13489
13490 @smallexample
13491 @group
13492 (defun recursive-count-words (region-end)
13493 "@var{documentation}@dots{}"
13494 @var{do-again-test}
13495 @var{next-step-expression}
13496 @var{recursive call})
13497 @end group
13498 @end smallexample
13499
13500 Now we need to fill in the slots. Let's start with the simplest cases
13501 first: if point is at or beyond the end of the region, there cannot
13502 be any words in the region, so the function should return zero.
13503 Likewise, if the search fails, there are no words to count, so the
13504 function should return zero.
13505
13506 On the other hand, if point is within the region and the search
13507 succeeds, the function should call itself again.
13508
13509 @need 800
13510 Thus, the do-again-test should look like this:
13511
13512 @smallexample
13513 @group
13514 (and (< (point) region-end)
13515 (re-search-forward "\\w+\\W*" region-end t))
13516 @end group
13517 @end smallexample
13518
13519 Note that the search expression is part of the do-again-test---the
13520 function returns @code{t} if its search succeeds and @code{nil} if it
13521 fails. (@xref{Whitespace Bug, , The Whitespace Bug in
13522 @code{count-words-region}}, for an explanation of how
13523 @code{re-search-forward} works.)
13524
13525 The do-again-test is the true-or-false test of an @code{if} clause.
13526 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13527 clause should call the function again; but if it fails, the else-part
13528 should return zero since either point is outside the region or the
13529 search failed because there were no words to find.
13530
13531 But before considering the recursive call, we need to consider the
13532 next-step-expression. What is it? Interestingly, it is the search
13533 part of the do-again-test.
13534
13535 In addition to returning @code{t} or @code{nil} for the
13536 do-again-test, @code{re-search-forward} moves point forward as a side
13537 effect of a successful search. This is the action that changes the
13538 value of point so that the recursive function stops calling itself
13539 when point completes its movement through the region. Consequently,
13540 the @code{re-search-forward} expression is the next-step-expression.
13541
13542 @need 1200
13543 In outline, then, the body of the @code{recursive-count-words}
13544 function looks like this:
13545
13546 @smallexample
13547 @group
13548 (if @var{do-again-test-and-next-step-combined}
13549 ;; @r{then}
13550 @var{recursive-call-returning-count}
13551 ;; @r{else}
13552 @var{return-zero})
13553 @end group
13554 @end smallexample
13555
13556 How to incorporate the mechanism that counts?
13557
13558 If you are not used to writing recursive functions, a question like
13559 this can be troublesome. But it can and should be approached
13560 systematically.
13561
13562 We know that the counting mechanism should be associated in some way
13563 with the recursive call. Indeed, since the next-step-expression moves
13564 point forward by one word, and since a recursive call is made for
13565 each word, the counting mechanism must be an expression that adds one
13566 to the value returned by a call to @code{recursive-count-words}.
13567
13568 Consider several cases:
13569
13570 @itemize @bullet
13571 @item
13572 If there are two words in the region, the function should return
13573 a value resulting from adding one to the value returned when it counts
13574 the first word, plus the number returned when it counts the remaining
13575 words in the region, which in this case is one.
13576
13577 @item
13578 If there is one word in the region, the function should return
13579 a value resulting from adding one to the value returned when it counts
13580 that word, plus the number returned when it counts the remaining
13581 words in the region, which in this case is zero.
13582
13583 @item
13584 If there are no words in the region, the function should return zero.
13585 @end itemize
13586
13587 From the sketch we can see that the else-part of the @code{if} returns
13588 zero for the case of no words. This means that the then-part of the
13589 @code{if} must return a value resulting from adding one to the value
13590 returned from a count of the remaining words.
13591
13592 @need 1200
13593 The expression will look like this, where @code{1+} is a function that
13594 adds one to its argument.
13595
13596 @smallexample
13597 (1+ (recursive-count-words region-end))
13598 @end smallexample
13599
13600 @need 1200
13601 The whole @code{recursive-count-words} function will then look like
13602 this:
13603
13604 @smallexample
13605 @group
13606 (defun recursive-count-words (region-end)
13607 "@var{documentation}@dots{}"
13608
13609 ;;; @r{1. do-again-test}
13610 (if (and (< (point) region-end)
13611 (re-search-forward "\\w+\\W*" region-end t))
13612 @end group
13613
13614 @group
13615 ;;; @r{2. then-part: the recursive call}
13616 (1+ (recursive-count-words region-end))
13617
13618 ;;; @r{3. else-part}
13619 0))
13620 @end group
13621 @end smallexample
13622
13623 @need 1250
13624 Let's examine how this works:
13625
13626 If there are no words in the region, the else part of the @code{if}
13627 expression is evaluated and consequently the function returns zero.
13628
13629 If there is one word in the region, the value of point is less than
13630 the value of @code{region-end} and the search succeeds. In this case,
13631 the true-or-false-test of the @code{if} expression tests true, and the
13632 then-part of the @code{if} expression is evaluated. The counting
13633 expression is evaluated. This expression returns a value (which will
13634 be the value returned by the whole function) that is the sum of one
13635 added to the value returned by a recursive call.
13636
13637 Meanwhile, the next-step-expression has caused point to jump over the
13638 first (and in this case only) word in the region. This means that
13639 when @code{(recursive-count-words region-end)} is evaluated a second
13640 time, as a result of the recursive call, the value of point will be
13641 equal to or greater than the value of region end. So this time,
13642 @code{recursive-count-words} will return zero. The zero will be added
13643 to one, and the original evaluation of @code{recursive-count-words}
13644 will return one plus zero, which is one, which is the correct amount.
13645
13646 Clearly, if there are two words in the region, the first call to
13647 @code{recursive-count-words} returns one added to the value returned
13648 by calling @code{recursive-count-words} on a region containing the
13649 remaining word---that is, it adds one to one, producing two, which is
13650 the correct amount.
13651
13652 Similarly, if there are three words in the region, the first call to
13653 @code{recursive-count-words} returns one added to the value returned
13654 by calling @code{recursive-count-words} on a region containing the
13655 remaining two words---and so on and so on.
13656
13657 @need 1250
13658 @noindent
13659 With full documentation the two functions look like this:
13660
13661 @need 1250
13662 @noindent
13663 The recursive function:
13664
13665 @findex recursive-count-words
13666 @smallexample
13667 @group
13668 (defun recursive-count-words (region-end)
13669 "Number of words between point and REGION-END."
13670 @end group
13671
13672 @group
13673 ;;; @r{1. do-again-test}
13674 (if (and (< (point) region-end)
13675 (re-search-forward "\\w+\\W*" region-end t))
13676 @end group
13677
13678 @group
13679 ;;; @r{2. then-part: the recursive call}
13680 (1+ (recursive-count-words region-end))
13681
13682 ;;; @r{3. else-part}
13683 0))
13684 @end group
13685 @end smallexample
13686
13687 @need 800
13688 @noindent
13689 The wrapper:
13690
13691 @smallexample
13692 @group
13693 ;;; @r{Recursive version}
13694 (defun count-words-region (beginning end)
13695 "Print number of words in the region.
13696 @end group
13697
13698 @group
13699 Words are defined as at least one word-constituent
13700 character followed by at least one character that is
13701 not a word-constituent. The buffer's syntax table
13702 determines which characters these are."
13703 @end group
13704 @group
13705 (interactive "r")
13706 (message "Counting words in region ... ")
13707 (save-excursion
13708 (goto-char beginning)
13709 (let ((count (recursive-count-words end)))
13710 @end group
13711 @group
13712 (cond ((zerop count)
13713 (message
13714 "The region does NOT have any words."))
13715 @end group
13716 @group
13717 ((= 1 count)
13718 (message "The region has 1 word."))
13719 (t
13720 (message
13721 "The region has %d words." count))))))
13722 @end group
13723 @end smallexample
13724
13725 @node Counting Exercise, , recursive-count-words, Counting Words
13726 @section Exercise: Counting Punctuation
13727
13728 Using a @code{while} loop, write a function to count the number of
13729 punctuation marks in a region---period, comma, semicolon, colon,
13730 exclamation mark, and question mark. Do the same using recursion.
13731
13732 @node Words in a defun, Readying a Graph, Counting Words, Top
13733 @chapter Counting Words in a @code{defun}
13734 @cindex Counting words in a @code{defun}
13735 @cindex Word counting in a @code{defun}
13736
13737 Our next project is to count the number of words in a function
13738 definition. Clearly, this can be done using some variant of
13739 @code{count-word-region}. @xref{Counting Words, , Counting Words:
13740 Repetition and Regexps}. If we are just going to count the words in
13741 one definition, it is easy enough to mark the definition with the
13742 @kbd{C-M-h} (@code{mark-defun}) command, and then call
13743 @code{count-word-region}.
13744
13745 However, I am more ambitious: I want to count the words and symbols in
13746 every definition in the Emacs sources and then print a graph that
13747 shows how many functions there are of each length: how many contain 40
13748 to 49 words or symbols, how many contain 50 to 59 words or symbols,
13749 and so on. I have often been curious how long a typical function is,
13750 and this will tell.
13751
13752 @menu
13753 * Divide and Conquer::
13754 * Words and Symbols:: What to count?
13755 * Syntax:: What constitutes a word or symbol?
13756 * count-words-in-defun:: Very like @code{count-words}.
13757 * Several defuns:: Counting several defuns in a file.
13758 * Find a File:: Do you want to look at a file?
13759 * lengths-list-file:: A list of the lengths of many definitions.
13760 * Several files:: Counting in definitions in different files.
13761 * Several files recursively:: Recursively counting in different files.
13762 * Prepare the data:: Prepare the data for display in a graph.
13763 @end menu
13764
13765 @node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13766 @ifnottex
13767 @unnumberedsec Divide and Conquer
13768 @end ifnottex
13769
13770 Described in one phrase, the histogram project is daunting; but
13771 divided into numerous small steps, each of which we can take one at a
13772 time, the project becomes less fearsome. Let us consider what the
13773 steps must be:
13774
13775 @itemize @bullet
13776 @item
13777 First, write a function to count the words in one definition. This
13778 includes the problem of handling symbols as well as words.
13779
13780 @item
13781 Second, write a function to list the numbers of words in each function
13782 in a file. This function can use the @code{count-words-in-defun}
13783 function.
13784
13785 @item
13786 Third, write a function to list the numbers of words in each function
13787 in each of several files. This entails automatically finding the
13788 various files, switching to them, and counting the words in the
13789 definitions within them.
13790
13791 @item
13792 Fourth, write a function to convert the list of numbers that we
13793 created in step three to a form that will be suitable for printing as
13794 a graph.
13795
13796 @item
13797 Fifth, write a function to print the results as a graph.
13798 @end itemize
13799
13800 This is quite a project! But if we take each step slowly, it will not
13801 be difficult.
13802
13803 @node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13804 @section What to Count?
13805 @cindex Words and symbols in defun
13806
13807 When we first start thinking about how to count the words in a
13808 function definition, the first question is (or ought to be) what are
13809 we going to count? When we speak of `words' with respect to a Lisp
13810 function definition, we are actually speaking, in large part, of
13811 `symbols'. For example, the following @code{multiply-by-seven}
13812 function contains the five symbols @code{defun},
13813 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
13814 addition, in the documentation string, it contains the four words
13815 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
13816 symbol @samp{number} is repeated, so the definition contains a total
13817 of ten words and symbols.
13818
13819 @smallexample
13820 @group
13821 (defun multiply-by-seven (number)
13822 "Multiply NUMBER by seven."
13823 (* 7 number))
13824 @end group
13825 @end smallexample
13826
13827 @noindent
13828 However, if we mark the @code{multiply-by-seven} definition with
13829 @kbd{C-M-h} (@code{mark-defun}), and then call
13830 @code{count-words-region} on it, we will find that
13831 @code{count-words-region} claims the definition has eleven words, not
13832 ten! Something is wrong!
13833
13834 The problem is twofold: @code{count-words-region} does not count the
13835 @samp{*} as a word, and it counts the single symbol,
13836 @code{multiply-by-seven}, as containing three words. The hyphens are
13837 treated as if they were interword spaces rather than intraword
13838 connectors: @samp{multiply-by-seven} is counted as if it were written
13839 @samp{multiply by seven}.
13840
13841 The cause of this confusion is the regular expression search within
13842 the @code{count-words-region} definition that moves point forward word
13843 by word. In the canonical version of @code{count-words-region}, the
13844 regexp is:
13845
13846 @smallexample
13847 "\\w+\\W*"
13848 @end smallexample
13849
13850 @noindent
13851 This regular expression is a pattern defining one or more word
13852 constituent characters possibly followed by one or more characters
13853 that are not word constituents. What is meant by `word constituent
13854 characters' brings us to the issue of syntax, which is worth a section
13855 of its own.
13856
13857 @node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13858 @section What Constitutes a Word or Symbol?
13859 @cindex Syntax categories and tables
13860
13861 Emacs treats different characters as belonging to different
13862 @dfn{syntax categories}. For example, the regular expression,
13863 @samp{\\w+}, is a pattern specifying one or more @emph{word
13864 constituent} characters. Word constituent characters are members of
13865 one syntax category. Other syntax categories include the class of
13866 punctuation characters, such as the period and the comma, and the
13867 class of whitespace characters, such as the blank space and the tab
13868 character. (For more information, see @ref{Syntax, Syntax, The Syntax
13869 Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13870 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13871
13872 Syntax tables specify which characters belong to which categories.
13873 Usually, a hyphen is not specified as a `word constituent character'.
13874 Instead, it is specified as being in the `class of characters that are
13875 part of symbol names but not words.' This means that the
13876 @code{count-words-region} function treats it in the same way it treats
13877 an interword white space, which is why @code{count-words-region}
13878 counts @samp{multiply-by-seven} as three words.
13879
13880 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13881 one symbol: modify the syntax table or modify the regular expression.
13882
13883 We could redefine a hyphen as a word constituent character by
13884 modifying the syntax table that Emacs keeps for each mode. This
13885 action would serve our purpose, except that a hyphen is merely the
13886 most common character within symbols that is not typically a word
13887 constituent character; there are others, too.
13888
13889 Alternatively, we can redefine the regular expression used in the
13890 @code{count-words} definition so as to include symbols. This
13891 procedure has the merit of clarity, but the task is a little tricky.
13892
13893 @need 1200
13894 The first part is simple enough: the pattern must match ``at least one
13895 character that is a word or symbol constituent''. Thus:
13896
13897 @smallexample
13898 "\\(\\w\\|\\s_\\)+"
13899 @end smallexample
13900
13901 @noindent
13902 The @samp{\\(} is the first part of the grouping construct that
13903 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13904 by the @samp{\\|}. The @samp{\\w} matches any word-constituent
13905 character and the @samp{\\s_} matches any character that is part of a
13906 symbol name but not a word-constituent character. The @samp{+}
13907 following the group indicates that the word or symbol constituent
13908 characters must be matched at least once.
13909
13910 However, the second part of the regexp is more difficult to design.
13911 What we want is to follow the first part with ``optionally one or more
13912 characters that are not constituents of a word or symbol''. At first,
13913 I thought I could define this with the following:
13914
13915 @smallexample
13916 "\\(\\W\\|\\S_\\)*"
13917 @end smallexample
13918
13919 @noindent
13920 The upper case @samp{W} and @samp{S} match characters that are
13921 @emph{not} word or symbol constituents. Unfortunately, this
13922 expression matches any character that is either not a word constituent
13923 or not a symbol constituent. This matches any character!
13924
13925 I then noticed that every word or symbol in my test region was
13926 followed by white space (blank space, tab, or newline). So I tried
13927 placing a pattern to match one or more blank spaces after the pattern
13928 for one or more word or symbol constituents. This failed, too. Words
13929 and symbols are often separated by whitespace, but in actual code
13930 parentheses may follow symbols and punctuation may follow words. So
13931 finally, I designed a pattern in which the word or symbol constituents
13932 are followed optionally by characters that are not white space and
13933 then followed optionally by white space.
13934
13935 @need 800
13936 Here is the full regular expression:
13937
13938 @smallexample
13939 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13940 @end smallexample
13941
13942 @node count-words-in-defun, Several defuns, Syntax, Words in a defun
13943 @section The @code{count-words-in-defun} Function
13944 @cindex Counting words in a @code{defun}
13945
13946 We have seen that there are several ways to write a
13947 @code{count-word-region} function. To write a
13948 @code{count-words-in-defun}, we need merely adapt one of these
13949 versions.
13950
13951 The version that uses a @code{while} loop is easy to understand, so I
13952 am going to adapt that. Because @code{count-words-in-defun} will be
13953 part of a more complex program, it need not be interactive and it need
13954 not display a message but just return the count. These considerations
13955 simplify the definition a little.
13956
13957 On the other hand, @code{count-words-in-defun} will be used within a
13958 buffer that contains function definitions. Consequently, it is
13959 reasonable to ask that the function determine whether it is called
13960 when point is within a function definition, and if it is, to return
13961 the count for that definition. This adds complexity to the
13962 definition, but saves us from needing to pass arguments to the
13963 function.
13964
13965 @need 1250
13966 These considerations lead us to prepare the following template:
13967
13968 @smallexample
13969 @group
13970 (defun count-words-in-defun ()
13971 "@var{documentation}@dots{}"
13972 (@var{set up}@dots{}
13973 (@var{while loop}@dots{})
13974 @var{return count})
13975 @end group
13976 @end smallexample
13977
13978 @noindent
13979 As usual, our job is to fill in the slots.
13980
13981 First, the set up.
13982
13983 We are presuming that this function will be called within a buffer
13984 containing function definitions. Point will either be within a
13985 function definition or not. For @code{count-words-in-defun} to work,
13986 point must move to the beginning of the definition, a counter must
13987 start at zero, and the counting loop must stop when point reaches the
13988 end of the definition.
13989
13990 The @code{beginning-of-defun} function searches backwards for an
13991 opening delimiter such as a @samp{(} at the beginning of a line, and
13992 moves point to that position, or else to the limit of the search. In
13993 practice, this means that @code{beginning-of-defun} moves point to the
13994 beginning of an enclosing or preceding function definition, or else to
13995 the beginning of the buffer. We can use @code{beginning-of-defun} to
13996 place point where we wish to start.
13997
13998 The @code{while} loop requires a counter to keep track of the words or
13999 symbols being counted. A @code{let} expression can be used to create
14000 a local variable for this purpose, and bind it to an initial value of zero.
14001
14002 The @code{end-of-defun} function works like @code{beginning-of-defun}
14003 except that it moves point to the end of the definition.
14004 @code{end-of-defun} can be used as part of an expression that
14005 determines the position of the end of the definition.
14006
14007 The set up for @code{count-words-in-defun} takes shape rapidly: first
14008 we move point to the beginning of the definition, then we create a
14009 local variable to hold the count, and finally, we record the position
14010 of the end of the definition so the @code{while} loop will know when to stop
14011 looping.
14012
14013 @need 1250
14014 The code looks like this:
14015
14016 @smallexample
14017 @group
14018 (beginning-of-defun)
14019 (let ((count 0)
14020 (end (save-excursion (end-of-defun) (point))))
14021 @end group
14022 @end smallexample
14023
14024 @noindent
14025 The code is simple. The only slight complication is likely to concern
14026 @code{end}: it is bound to the position of the end of the definition
14027 by a @code{save-excursion} expression that returns the value of point
14028 after @code{end-of-defun} temporarily moves it to the end of the
14029 definition.
14030
14031 The second part of the @code{count-words-in-defun}, after the set up,
14032 is the @code{while} loop.
14033
14034 The loop must contain an expression that jumps point forward word by
14035 word and symbol by symbol, and another expression that counts the
14036 jumps. The true-or-false-test for the @code{while} loop should test
14037 true so long as point should jump forward, and false when point is at
14038 the end of the definition. We have already redefined the regular
14039 expression for this (@pxref{Syntax}), so the loop is straightforward:
14040
14041 @smallexample
14042 @group
14043 (while (and (< (point) end)
14044 (re-search-forward
14045 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14046 (setq count (1+ count)))
14047 @end group
14048 @end smallexample
14049
14050 The third part of the function definition returns the count of words
14051 and symbols. This part is the last expression within the body of the
14052 @code{let} expression, and can be, very simply, the local variable
14053 @code{count}, which when evaluated returns the count.
14054
14055 @need 1250
14056 Put together, the @code{count-words-in-defun} definition looks like this:
14057
14058 @findex count-words-in-defun
14059 @smallexample
14060 @group
14061 (defun count-words-in-defun ()
14062 "Return the number of words and symbols in a defun."
14063 (beginning-of-defun)
14064 (let ((count 0)
14065 (end (save-excursion (end-of-defun) (point))))
14066 @end group
14067 @group
14068 (while
14069 (and (< (point) end)
14070 (re-search-forward
14071 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14072 end t))
14073 (setq count (1+ count)))
14074 count))
14075 @end group
14076 @end smallexample
14077
14078 How to test this? The function is not interactive, but it is easy to
14079 put a wrapper around the function to make it interactive; we can use
14080 almost the same code as for the recursive version of
14081 @code{count-words-region}:
14082
14083 @smallexample
14084 @group
14085 ;;; @r{Interactive version.}
14086 (defun count-words-defun ()
14087 "Number of words and symbols in a function definition."
14088 (interactive)
14089 (message
14090 "Counting words and symbols in function definition ... ")
14091 @end group
14092 @group
14093 (let ((count (count-words-in-defun)))
14094 (cond
14095 ((zerop count)
14096 (message
14097 "The definition does NOT have any words or symbols."))
14098 @end group
14099 @group
14100 ((= 1 count)
14101 (message
14102 "The definition has 1 word or symbol."))
14103 (t
14104 (message
14105 "The definition has %d words or symbols." count)))))
14106 @end group
14107 @end smallexample
14108
14109 @need 800
14110 @noindent
14111 Let's re-use @kbd{C-c =} as a convenient keybinding:
14112
14113 @smallexample
14114 (global-set-key "\C-c=" 'count-words-defun)
14115 @end smallexample
14116
14117 Now we can try out @code{count-words-defun}: install both
14118 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14119 keybinding, and then place the cursor within the following definition:
14120
14121 @smallexample
14122 @group
14123 (defun multiply-by-seven (number)
14124 "Multiply NUMBER by seven."
14125 (* 7 number))
14126 @result{} 10
14127 @end group
14128 @end smallexample
14129
14130 @noindent
14131 Success! The definition has 10 words and symbols.
14132
14133 The next problem is to count the numbers of words and symbols in
14134 several definitions within a single file.
14135
14136 @node Several defuns, Find a File, count-words-in-defun, Words in a defun
14137 @section Count Several @code{defuns} Within a File
14138
14139 A file such as @file{simple.el} may have 80 or more function
14140 definitions within it. Our long term goal is to collect statistics on
14141 many files, but as a first step, our immediate goal is to collect
14142 statistics on one file.
14143
14144 The information will be a series of numbers, each number being the
14145 length of a function definition. We can store the numbers in a list.
14146
14147 We know that we will want to incorporate the information regarding one
14148 file with information about many other files; this means that the
14149 function for counting definition lengths within one file need only
14150 return the list of lengths. It need not and should not display any
14151 messages.
14152
14153 The word count commands contain one expression to jump point forward
14154 word by word and another expression to count the jumps. The function
14155 to return the lengths of definitions can be designed to work the same
14156 way, with one expression to jump point forward definition by
14157 definition and another expression to construct the lengths' list.
14158
14159 This statement of the problem makes it elementary to write the
14160 function definition. Clearly, we will start the count at the
14161 beginning of the file, so the first command will be @code{(goto-char
14162 (point-min))}. Next, we start the @code{while} loop; and the
14163 true-or-false test of the loop can be a regular expression search for
14164 the next function definition---so long as the search succeeds, point
14165 is moved forward and then the body of the loop is evaluated. The body
14166 needs an expression that constructs the lengths' list. @code{cons},
14167 the list construction command, can be used to create the list. That
14168 is almost all there is to it.
14169
14170 @need 800
14171 Here is what this fragment of code looks like:
14172
14173 @smallexample
14174 @group
14175 (goto-char (point-min))
14176 (while (re-search-forward "^(defun" nil t)
14177 (setq lengths-list
14178 (cons (count-words-in-defun) lengths-list)))
14179 @end group
14180 @end smallexample
14181
14182 What we have left out is the mechanism for finding the file that
14183 contains the function definitions.
14184
14185 In previous examples, we either used this, the Info file, or we
14186 switched back and forth to some other buffer, such as the
14187 @file{*scratch*} buffer.
14188
14189 Finding a file is a new process that we have not yet discussed.
14190
14191 @node Find a File, lengths-list-file, Several defuns, Words in a defun
14192 @comment node-name, next, previous, up
14193 @section Find a File
14194 @cindex Find a File
14195
14196 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14197 command. This command is almost, but not quite right for the lengths
14198 problem.
14199
14200 @need 1200
14201 Let's look at the source for @code{find-file} (you can use the
14202 @code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14203 find the source of a function):
14204
14205 @smallexample
14206 @group
14207 (defun find-file (filename)
14208 "Edit file FILENAME.
14209 Switch to a buffer visiting file FILENAME,
14210 creating one if none already exists."
14211 (interactive "FFind file: ")
14212 (switch-to-buffer (find-file-noselect filename)))
14213 @end group
14214 @end smallexample
14215
14216 The definition possesses short but complete documentation and an
14217 interactive specification that prompts you for a file name when you
14218 use the command interactively. The body of the definition contains
14219 two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14220
14221 According to its documentation as shown by @kbd{C-h f} (the
14222 @code{describe-function} command), the @code{find-file-noselect}
14223 function reads the named file into a buffer and returns the buffer.
14224 However, the buffer is not selected. Emacs does not switch its
14225 attention (or yours if you are using @code{find-file-noselect}) to the
14226 named buffer. That is what @code{switch-to-buffer} does: it switches
14227 the buffer to which Emacs attention is directed; and it switches the
14228 buffer displayed in the window to the new buffer. We have discussed
14229 buffer switching elsewhere. (@xref{Switching Buffers}.)
14230
14231 In this histogram project, we do not need to display each file on the
14232 screen as the program determines the length of each definition within
14233 it. Instead of employing @code{switch-to-buffer}, we can work with
14234 @code{set-buffer}, which redirects the attention of the computer
14235 program to a different buffer but does not redisplay it on the screen.
14236 So instead of calling on @code{find-file} to do the job, we must write
14237 our own expression.
14238
14239 The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
14240
14241 @node lengths-list-file, Several files, Find a File, Words in a defun
14242 @section @code{lengths-list-file} in Detail
14243
14244 The core of the @code{lengths-list-file} function is a @code{while}
14245 loop containing a function to move point forward `defun by defun' and
14246 a function to count the number of words and symbols in each defun.
14247 This core must be surrounded by functions that do various other tasks,
14248 including finding the file, and ensuring that point starts out at the
14249 beginning of the file. The function definition looks like this:
14250 @findex lengths-list-file
14251
14252 @smallexample
14253 @group
14254 (defun lengths-list-file (filename)
14255 "Return list of definitions' lengths within FILE.
14256 The returned list is a list of numbers.
14257 Each number is the number of words or
14258 symbols in one function definition."
14259 @end group
14260 @group
14261 (message "Working on `%s' ... " filename)
14262 (save-excursion
14263 (let ((buffer (find-file-noselect filename))
14264 (lengths-list))
14265 (set-buffer buffer)
14266 (setq buffer-read-only t)
14267 (widen)
14268 (goto-char (point-min))
14269 (while (re-search-forward "^(defun" nil t)
14270 (setq lengths-list
14271 (cons (count-words-in-defun) lengths-list)))
14272 (kill-buffer buffer)
14273 lengths-list)))
14274 @end group
14275 @end smallexample
14276
14277 @noindent
14278 The function is passed one argument, the name of the file on which it
14279 will work. It has four lines of documentation, but no interactive
14280 specification. Since people worry that a computer is broken if they
14281 don't see anything going on, the first line of the body is a
14282 message.
14283
14284 The next line contains a @code{save-excursion} that returns Emacs'
14285 attention to the current buffer when the function completes. This is
14286 useful in case you embed this function in another function that
14287 presumes point is restored to the original buffer.
14288
14289 In the varlist of the @code{let} expression, Emacs finds the file and
14290 binds the local variable @code{buffer} to the buffer containing the
14291 file. At the same time, Emacs creates @code{lengths-list} as a local
14292 variable.
14293
14294 Next, Emacs switches its attention to the buffer.
14295
14296 In the following line, Emacs makes the buffer read-only. Ideally,
14297 this line is not necessary. None of the functions for counting words
14298 and symbols in a function definition should change the buffer.
14299 Besides, the buffer is not going to be saved, even if it were changed.
14300 This line is entirely the consequence of great, perhaps excessive,
14301 caution. The reason for the caution is that this function and those
14302 it calls work on the sources for Emacs and it is very inconvenient if
14303 they are inadvertently modified. It goes without saying that I did
14304 not realize a need for this line until an experiment went awry and
14305 started to modify my Emacs source files @dots{}
14306
14307 Next comes a call to widen the buffer if it is narrowed. This
14308 function is usually not needed---Emacs creates a fresh buffer if none
14309 already exists; but if a buffer visiting the file already exists Emacs
14310 returns that one. In this case, the buffer may be narrowed and must
14311 be widened. If we wanted to be fully `user-friendly', we would
14312 arrange to save the restriction and the location of point, but we
14313 won't.
14314
14315 The @code{(goto-char (point-min))} expression moves point to the
14316 beginning of the buffer.
14317
14318 Then comes a @code{while} loop in which the `work' of the function is
14319 carried out. In the loop, Emacs determines the length of each
14320 definition and constructs a lengths' list containing the information.
14321
14322 Emacs kills the buffer after working through it. This is to save
14323 space inside of Emacs. My version of Emacs 19 contained over 300
14324 source files of interest; Emacs 21 contains over 800 source files.
14325 Another function will apply @code{lengths-list-file} to each of the
14326 files.
14327
14328 Finally, the last expression within the @code{let} expression is the
14329 @code{lengths-list} variable; its value is returned as the value of
14330 the whole function.
14331
14332 You can try this function by installing it in the usual fashion. Then
14333 place your cursor after the following expression and type @kbd{C-x
14334 C-e} (@code{eval-last-sexp}).
14335
14336 @c !!! 21.0.100 lisp sources location here
14337 @smallexample
14338 (lengths-list-file
14339 "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14340 @end smallexample
14341
14342 @c was: (lengths-list-file "../lisp/debug.el")
14343 @c !!! as of 21, Info file is in
14344 @c /usr/share/info/emacs-lisp-intro.info.gz
14345 @c but debug.el is in /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14346
14347 @noindent
14348 (You may need to change the pathname of the file; the one here worked
14349 with GNU Emacs version 21.0.100. To change the expression, copy it to
14350 the @file{*scratch*} buffer and edit it.
14351
14352 @need 1200
14353 @noindent
14354 (Also, to see the full length of the list, rather than a truncated
14355 version, you may have to evaluate the following:
14356
14357 @smallexample
14358 (custom-set-variables '(eval-expression-print-length nil))
14359 @end smallexample
14360
14361 @noindent
14362 (@xref{defcustom, , Setting Variables with @code{defcustom}}.
14363 Then evaluate the @code{lengths-list-file} expression.)
14364
14365 @need 1200
14366 The lengths' list for @file{debug.el} takes less than a second to
14367 produce and looks like this:
14368
14369 @smallexample
14370 (77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14371 @end smallexample
14372
14373 @need 1500
14374 (Using my old machine, the version 19 lengths' list for @file{debug.el}
14375 took seven seconds to produce and looked like this:
14376
14377 @smallexample
14378 (75 41 80 62 20 45 44 68 45 12 34 235)
14379 @end smallexample
14380
14381 (The newer version of @file{debug.el} contains more defuns than the
14382 earlier one; and my new machine is much faster than the old one.)
14383
14384 Note that the length of the last definition in the file is first in
14385 the list.
14386
14387 @node Several files, Several files recursively, lengths-list-file, Words in a defun
14388 @section Count Words in @code{defuns} in Different Files
14389
14390 In the previous section, we created a function that returns a list of
14391 the lengths of each definition in a file. Now, we want to define a
14392 function to return a master list of the lengths of the definitions in
14393 a list of files.
14394
14395 Working on each of a list of files is a repetitious act, so we can use
14396 either a @code{while} loop or recursion.
14397
14398 @menu
14399 * lengths-list-many-files:: Return a list of the lengths of defuns.
14400 * append:: Attach one list to another.
14401 @end menu
14402
14403 @node lengths-list-many-files, append, Several files, Several files
14404 @ifnottex
14405 @unnumberedsubsec Determine the lengths of @code{defuns}
14406 @end ifnottex
14407
14408 The design using a @code{while} loop is routine. The argument passed
14409 the function is a list of files. As we saw earlier (@pxref{Loop
14410 Example}), you can write a @code{while} loop so that the body of the
14411 loop is evaluated if such a list contains elements, but to exit the
14412 loop if the list is empty. For this design to work, the body of the
14413 loop must contain an expression that shortens the list each time the
14414 body is evaluated, so that eventually the list is empty. The usual
14415 technique is to set the value of the list to the value of the @sc{cdr}
14416 of the list each time the body is evaluated.
14417
14418 @need 800
14419 The template looks like this:
14420
14421 @smallexample
14422 @group
14423 (while @var{test-whether-list-is-empty}
14424 @var{body}@dots{}
14425 @var{set-list-to-cdr-of-list})
14426 @end group
14427 @end smallexample
14428
14429 Also, we remember that a @code{while} loop returns @code{nil} (the
14430 result of evaluating the true-or-false-test), not the result of any
14431 evaluation within its body. (The evaluations within the body of the
14432 loop are done for their side effects.) However, the expression that
14433 sets the lengths' list is part of the body---and that is the value
14434 that we want returned by the function as a whole. To do this, we
14435 enclose the @code{while} loop within a @code{let} expression, and
14436 arrange that the last element of the @code{let} expression contains
14437 the value of the lengths' list. (@xref{Incrementing Example, , Loop
14438 Example with an Incrementing Counter}.)
14439
14440 @findex lengths-list-many-files
14441 @need 1250
14442 These considerations lead us directly to the function itself:
14443
14444 @smallexample
14445 @group
14446 ;;; @r{Use @code{while} loop.}
14447 (defun lengths-list-many-files (list-of-files)
14448 "Return list of lengths of defuns in LIST-OF-FILES."
14449 @end group
14450 @group
14451 (let (lengths-list)
14452
14453 ;;; @r{true-or-false-test}
14454 (while list-of-files
14455 (setq lengths-list
14456 (append
14457 lengths-list
14458
14459 ;;; @r{Generate a lengths' list.}
14460 (lengths-list-file
14461 (expand-file-name (car list-of-files)))))
14462 @end group
14463
14464 @group
14465 ;;; @r{Make files' list shorter.}
14466 (setq list-of-files (cdr list-of-files)))
14467
14468 ;;; @r{Return final value of lengths' list.}
14469 lengths-list))
14470 @end group
14471 @end smallexample
14472
14473 @code{expand-file-name} is a built-in function that converts a file
14474 name to the absolute, long, path name form of the directory in which
14475 the function is called.
14476
14477 @c !!! 21.0.100 lisp sources location here
14478 @need 1500
14479 Thus, if @code{expand-file-name} is called on @code{debug.el} when
14480 Emacs is visiting the
14481 @file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14482
14483 @smallexample
14484 debug.el
14485 @end smallexample
14486
14487 @need 800
14488 @noindent
14489 becomes
14490
14491 @c !!! 21.0.100 lisp sources location here
14492 @smallexample
14493 /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14494 @end smallexample
14495
14496 The only other new element of this function definition is the as yet
14497 unstudied function @code{append}, which merits a short section for
14498 itself.
14499
14500 @node append, , lengths-list-many-files, Several files
14501 @subsection The @code{append} Function
14502
14503 @need 800
14504 The @code{append} function attaches one list to another. Thus,
14505
14506 @smallexample
14507 (append '(1 2 3 4) '(5 6 7 8))
14508 @end smallexample
14509
14510 @need 800
14511 @noindent
14512 produces the list
14513
14514 @smallexample
14515 (1 2 3 4 5 6 7 8)
14516 @end smallexample
14517
14518 This is exactly how we want to attach two lengths' lists produced by
14519 @code{lengths-list-file} to each other. The results contrast with
14520 @code{cons},
14521
14522 @smallexample
14523 (cons '(1 2 3 4) '(5 6 7 8))
14524 @end smallexample
14525
14526 @need 1250
14527 @noindent
14528 which constructs a new list in which the first argument to @code{cons}
14529 becomes the first element of the new list:
14530
14531 @smallexample
14532 ((1 2 3 4) 5 6 7 8)
14533 @end smallexample
14534
14535 @node Several files recursively, Prepare the data, Several files, Words in a defun
14536 @section Recursively Count Words in Different Files
14537
14538 Besides a @code{while} loop, you can work on each of a list of files
14539 with recursion. A recursive version of @code{lengths-list-many-files}
14540 is short and simple.
14541
14542 The recursive function has the usual parts: the `do-again-test', the
14543 `next-step-expression', and the recursive call. The `do-again-test'
14544 determines whether the function should call itself again, which it
14545 will do if the @code{list-of-files} contains any remaining elements;
14546 the `next-step-expression' resets the @code{list-of-files} to the
14547 @sc{cdr} of itself, so eventually the list will be empty; and the
14548 recursive call calls itself on the shorter list. The complete
14549 function is shorter than this description!
14550 @findex recursive-lengths-list-many-files
14551
14552 @smallexample
14553 @group
14554 (defun recursive-lengths-list-many-files (list-of-files)
14555 "Return list of lengths of each defun in LIST-OF-FILES."
14556 (if list-of-files ; @r{do-again-test}
14557 (append
14558 (lengths-list-file
14559 (expand-file-name (car list-of-files)))
14560 (recursive-lengths-list-many-files
14561 (cdr list-of-files)))))
14562 @end group
14563 @end smallexample
14564
14565 @noindent
14566 In a sentence, the function returns the lengths' list for the first of
14567 the @code{list-of-files} appended to the result of calling itself on
14568 the rest of the @code{list-of-files}.
14569
14570 Here is a test of @code{recursive-lengths-list-many-files}, along with
14571 the results of running @code{lengths-list-file} on each of the files
14572 individually.
14573
14574 Install @code{recursive-lengths-list-many-files} and
14575 @code{lengths-list-file}, if necessary, and then evaluate the
14576 following expressions. You may need to change the files' pathnames;
14577 those here work when this Info file and the Emacs sources are located
14578 in their customary places. To change the expressions, copy them to
14579 the @file{*scratch*} buffer, edit them, and then evaluate them.
14580
14581 The results are shown after the @samp{@result{}}. (These results are
14582 for files from Emacs Version 21.0.100; files from other versions of
14583 Emacs may produce different results.)
14584
14585 @c !!! 21.0.100 lisp sources location here
14586 @smallexample
14587 @group
14588 (cd "/usr/local/share/emacs/21.0.100/")
14589
14590 (lengths-list-file "./lisp/macros.el")
14591 @result{} (273 263 456 90)
14592 @end group
14593
14594 @group
14595 (lengths-list-file "./lisp/mail/mailalias.el")
14596 @result{} (38 32 26 77 174 180 321 198 324)
14597 @end group
14598
14599 @group
14600 (lengths-list-file "./lisp/makesum.el")
14601 @result{} (85 181)
14602 @end group
14603
14604 @group
14605 (recursive-lengths-list-many-files
14606 '("./lisp/macros.el"
14607 "./lisp/mail/mailalias.el"
14608 "./lisp/makesum.el"))
14609 @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14610 @end group
14611 @end smallexample
14612
14613 The @code{recursive-lengths-list-many-files} function produces the
14614 output we want.
14615
14616 The next step is to prepare the data in the list for display in a graph.
14617
14618 @node Prepare the data, , Several files recursively, Words in a defun
14619 @section Prepare the Data for Display in a Graph
14620
14621 The @code{recursive-lengths-list-many-files} function returns a list
14622 of numbers. Each number records the length of a function definition.
14623 What we need to do now is transform this data into a list of numbers
14624 suitable for generating a graph. The new list will tell how many
14625 functions definitions contain less than 10 words and
14626 symbols, how many contain between 10 and 19 words and symbols, how
14627 many contain between 20 and 29 words and symbols, and so on.
14628
14629 In brief, we need to go through the lengths' list produced by the
14630 @code{recursive-lengths-list-many-files} function and count the number
14631 of defuns within each range of lengths, and produce a list of those
14632 numbers.
14633
14634 Based on what we have done before, we can readily foresee that it
14635 should not be too hard to write a function that `@sc{cdr}s' down the
14636 lengths' list, looks at each element, determines which length range it
14637 is in, and increments a counter for that range.
14638
14639 However, before beginning to write such a function, we should consider
14640 the advantages of sorting the lengths' list first, so the numbers are
14641 ordered from smallest to largest. First, sorting will make it easier
14642 to count the numbers in each range, since two adjacent numbers will
14643 either be in the same length range or in adjacent ranges. Second, by
14644 inspecting a sorted list, we can discover the highest and lowest
14645 number, and thereby determine the largest and smallest length range
14646 that we will need.
14647
14648 @menu
14649 * Sorting:: Sorting lists.
14650 * Files List:: Making a list of files.
14651 * Counting function definitions::
14652 @end menu
14653
14654 @node Sorting, Files List, Prepare the data, Prepare the data
14655 @subsection Sorting Lists
14656 @findex sort
14657
14658 Emacs contains a function to sort lists, called (as you might guess)
14659 @code{sort}. The @code{sort} function takes two arguments, the list
14660 to be sorted, and a predicate that determines whether the first of
14661 two list elements is ``less'' than the second.
14662
14663 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14664 Type Object as an Argument}), a predicate is a function that
14665 determines whether some property is true or false. The @code{sort}
14666 function will reorder a list according to whatever property the
14667 predicate uses; this means that @code{sort} can be used to sort
14668 non-numeric lists by non-numeric criteria---it can, for example,
14669 alphabetize a list.
14670
14671 @need 1250
14672 The @code{<} function is used when sorting a numeric list. For example,
14673
14674 @smallexample
14675 (sort '(4 8 21 17 33 7 21 7) '<)
14676 @end smallexample
14677
14678 @need 800
14679 @noindent
14680 produces this:
14681
14682 @smallexample
14683 (4 7 7 8 17 21 21 33)
14684 @end smallexample
14685
14686 @noindent
14687 (Note that in this example, both the arguments are quoted so that the
14688 symbols are not evaluated before being passed to @code{sort} as
14689 arguments.)
14690
14691 Sorting the list returned by the
14692 @code{recursive-lengths-list-many-files} function is straightforward;
14693 it uses the @code{<} function:
14694
14695 @smallexample
14696 @group
14697 (sort
14698 (recursive-lengths-list-many-files
14699 '("../lisp/macros.el"
14700 "../lisp/mailalias.el"
14701 "../lisp/makesum.el"))
14702 '<
14703 @end group
14704 @end smallexample
14705
14706 @need 800
14707 @noindent
14708 which produces:
14709
14710 @smallexample
14711 (85 86 116 122 154 176 179 265)
14712 @end smallexample
14713
14714 @noindent
14715 (Note that in this example, the first argument to @code{sort} is not
14716 quoted, since the expression must be evaluated so as to produce the
14717 list that is passed to @code{sort}.)
14718
14719 @node Files List, Counting function definitions, Sorting, Prepare the data
14720 @subsection Making a List of Files
14721
14722 The @code{recursive-lengths-list-many-files} function requires a list
14723 of files as its argument. For our test examples, we constructed such
14724 a list by hand; but the Emacs Lisp source directory is too large for
14725 us to do for that. Instead, we will write a function to do the job
14726 for us. In this function, we will use both a @code{while} loop and a
14727 recursive call.
14728
14729 @findex directory-files
14730 We did not have to write a function like this for older versions of
14731 GNU Emacs, since they placed all the @samp{.el} files in one
14732 directory. Instead, we were able to use the @code{directory-files}
14733 function, which lists the names of files that match a specified
14734 pattern within a single directory.
14735
14736 However, recent versions of Emacs place Emacs Lisp files in
14737 sub-directories of the top level @file{lisp} directory. This
14738 re-arrangement eases navigation. For example, all the mail related
14739 files are in a @file{lisp} sub-directory called @file{mail}. But at
14740 the same time, this arrangement forces us to create a file listing
14741 function that descends into the sub-directories.
14742
14743 @findex files-in-below-directory
14744 We can create this function, called @code{files-in-below-directory},
14745 using familiar functions such as @code{car}, @code{nthcdr}, and
14746 @code{substring} in conjunction with an existing function called
14747 @code{directory-files-and-attributes}. This latter function not only
14748 lists all the filenames in a directory, including the names
14749 of sub-directories, but also their attributes.
14750
14751 To restate our goal: to create a function that will enable us
14752 to feed filenames to @code{recursive-lengths-list-many-files}
14753 as a list that looks like this (but with more elements):
14754
14755 @smallexample
14756 @group
14757 ("../lisp/macros.el"
14758 "../lisp/mail/rmail.el"
14759 "../lisp/makesum.el")
14760 @end group
14761 @end smallexample
14762
14763 The @code{directory-files-and-attributes} function returns a list of
14764 lists. Each of the lists within the main list consists of 13
14765 elements. The first element is a string that contains the name of the
14766 file -- which, in GNU/Linux, may be a `directory file', that is to
14767 say, a file with the special attributes of a directory. The second
14768 element of the list is @code{t} for a directory, a string
14769 for symbolic link (the string is the name linked to), or @code{nil}.
14770
14771 For example, the first @samp{.el} file in the @file{lisp/} directory
14772 is @file{abbrev.el}. Its name is
14773 @file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14774 directory or a symbolic link.
14775
14776 @need 1000
14777 This is how @code{directory-files-and-attributes} lists that file and
14778 its attributes:
14779
14780 @smallexample
14781 @group
14782 ("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14783 nil
14784 1
14785 1000
14786 100
14787 @end group
14788 @group
14789 (15019 32380)
14790 (14883 48041)
14791 (15214 49336)
14792 11583
14793 "-rw-rw-r--"
14794 @end group
14795 @group
14796 t
14797 341385
14798 776)
14799 @end group
14800 @end smallexample
14801
14802 @need 1200
14803 On the other hand, @file{mail/} is a directory within the @file{lisp/}
14804 directory. The beginning of its listing looks like this:
14805
14806 @smallexample
14807 @group
14808 ("/usr/local/share/emacs/21.0.100/lisp/mail"
14809 t
14810 @dots{}
14811 )
14812 @end group
14813 @end smallexample
14814
14815 (Look at the documentation of @code{file-attributes} to learn about
14816 the different attributes. Bear in mind that the
14817 @code{file-attributes} function does not list the filename, so its
14818 first element is @code{directory-files-and-attributes}'s second
14819 element.)
14820
14821 We will want our new function, @code{files-in-below-directory}, to
14822 list the @samp{.el} files in the directory it is told to check, and in
14823 any directories below that directory.
14824
14825 This gives us a hint on how to construct
14826 @code{files-in-below-directory}: within a directory, the function
14827 should add @samp{.el} filenames to a list; and if, within a directory,
14828 the function comes upon a sub-directory, it should go into that
14829 sub-directory and repeat its actions.
14830
14831 However, we should note that every directory contains a name that
14832 refers to itself, called @file{.}, (``dot'') and a name that refers to
14833 its parent directory, called @file{..} (``double dot''). (In
14834 @file{/}, the root directory, @file{..} refers to itself, since
14835 @file{/} has no parent.) Clearly, we do not want our
14836 @code{files-in-below-directory} function to enter those directories,
14837 since they always lead us, directly or indirectly, to the current
14838 directory.
14839
14840 Consequently, our @code{files-in-below-directory} function must do
14841 several tasks:
14842
14843 @itemize @bullet
14844 @item
14845 Check to see whether it is looking at a filename that ends in
14846 @samp{.el}; and if so, add its name to a list.
14847
14848 @item
14849 Check to see whether it is looking at a filename that is the name of a
14850 directory; and if so,
14851
14852 @itemize @minus
14853 @item
14854 Check to see whether it is looking at @file{.} or @file{..}; and if
14855 so skip it.
14856
14857 @item
14858 Or else, go into that directory and repeat the process.
14859 @end itemize
14860 @end itemize
14861
14862 Let's write a function definition to do these tasks. We will use a
14863 @code{while} loop to move from one filename to another within a
14864 directory, checking what needs to be done; and we will use a recursive
14865 call to repeat the actions on each sub-directory. The recursive
14866 pattern is `accumulate'
14867 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14868 using @code{append} as the combiner.
14869
14870 @ignore
14871 (directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14872 (shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14873 @end ignore
14874
14875 @c /usr/local/share/emacs/21.0.100/lisp/
14876
14877 @need 800
14878 Here is the function:
14879
14880 @smallexample
14881 @group
14882 (defun files-in-below-directory (directory)
14883 "List the .el files in DIRECTORY and in its sub-directories."
14884 ;; Although the function will be used non-interactively,
14885 ;; it will be easier to test if we make it interactive.
14886 ;; The directory will have a name such as
14887 ;; "/usr/local/share/emacs/21.0.100/lisp/"
14888 (interactive "DDirectory name: ")
14889 @end group
14890 @group
14891 (let (el-files-list
14892 (current-directory-list
14893 (directory-files-and-attributes directory t)))
14894 ;; while we are in the current directory
14895 (while current-directory-list
14896 @end group
14897 @group
14898 (cond
14899 ;; check to see whether filename ends in `.el'
14900 ;; and if so, append its name to a list.
14901 ((equal ".el" (substring (car (car current-directory-list)) -3))
14902 (setq el-files-list
14903 (cons (car (car current-directory-list)) el-files-list)))
14904 @end group
14905 @group
14906 ;; check whether filename is that of a directory
14907 ((eq t (car (cdr (car current-directory-list))))
14908 ;; decide whether to skip or recurse
14909 (if
14910 (equal (or "." "..")
14911 (substring (car (car current-directory-list)) -1))
14912 ;; then do nothing if filename is that of
14913 ;; current directory or parent
14914 ()
14915 @end group
14916 @group
14917 ;; else descend into the directory and repeat the process
14918 (setq el-files-list
14919 (append
14920 (files-in-below-directory
14921 (car (car current-directory-list)))
14922 el-files-list)))))
14923 ;; move to the next filename in the list; this also
14924 ;; shortens the list so the while loop eventually comes to an end
14925 (setq current-directory-list (cdr current-directory-list)))
14926 ;; return the filenames
14927 el-files-list))
14928 @end group
14929 @end smallexample
14930
14931 @c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14932
14933 The @code{files-in-below-directory} @code{directory-files} function
14934 takes one argument, the name of a directory.
14935
14936 @need 1250
14937 Thus, on my system,
14938
14939 @c !!! 21.0.100 lisp sources location here
14940 @smallexample
14941 @group
14942 (length
14943 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14944 @end group
14945 @end smallexample
14946
14947 @noindent
14948 tells me that my version 21.0.100 Lisp sources directory contains 754
14949 @samp{.el} files.
14950
14951 @code{files-in-below-directory} returns a list in reverse alphabetical
14952 order. An expression to sort the list in alphabetical order looks
14953 like this:
14954
14955 @smallexample
14956 @group
14957 (sort
14958 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14959 'string-lessp)
14960 @end group
14961 @end smallexample
14962
14963 @ignore
14964 (defun test ()
14965 "Test how long it takes to find lengths of all elisp defuns."
14966 (insert "\n" (current-time-string) "\n")
14967 (sit-for 0)
14968 (sort
14969 (recursive-lengths-list-many-files
14970 '("../lisp/macros.el"
14971 "../lisp/mailalias.el"
14972 "../lisp/makesum.el"))
14973 '<)
14974 (insert (format "%s" (current-time-string))))
14975
14976 @end ignore
14977
14978 @node Counting function definitions, , Files List, Prepare the data
14979 @subsection Counting function definitions
14980
14981 Our immediate goal is to generate a list that tells us how many
14982 function definitions contain fewer than 10 words and symbols, how many
14983 contain between 10 and 19 words and symbols, how many contain between
14984 20 and 29 words and symbols, and so on.
14985
14986 With a sorted list of numbers, this is easy: count how many elements
14987 of the list are smaller than 10, then, after moving past the numbers
14988 just counted, count how many are smaller than 20, then, after moving
14989 past the numbers just counted, count how many are smaller than 30, and
14990 so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
14991 larger than the top of that range. We can call the list of such
14992 numbers the @code{top-of-ranges} list.
14993
14994 @need 1200
14995 If we wished, we could generate this list automatically, but it is
14996 simpler to write a list manually. Here it is:
14997 @vindex top-of-ranges
14998
14999 @smallexample
15000 @group
15001 (defvar top-of-ranges
15002 '(10 20 30 40 50
15003 60 70 80 90 100
15004 110 120 130 140 150
15005 160 170 180 190 200
15006 210 220 230 240 250
15007 260 270 280 290 300)
15008 "List specifying ranges for `defuns-per-range'.")
15009 @end group
15010 @end smallexample
15011
15012 To change the ranges, we edit this list.
15013
15014 Next, we need to write the function that creates the list of the
15015 number of definitions within each range. Clearly, this function must
15016 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15017 as arguments.
15018
15019 The @code{defuns-per-range} function must do two things again and
15020 again: it must count the number of definitions within a range
15021 specified by the current top-of-range value; and it must shift to the
15022 next higher value in the @code{top-of-ranges} list after counting the
15023 number of definitions in the current range. Since each of these
15024 actions is repetitive, we can use @code{while} loops for the job.
15025 One loop counts the number of definitions in the range defined by the
15026 current top-of-range value, and the other loop selects each of the
15027 top-of-range values in turn.
15028
15029 Several entries of the @code{sorted-lengths} list are counted for each
15030 range; this means that the loop for the @code{sorted-lengths} list
15031 will be inside the loop for the @code{top-of-ranges} list, like a
15032 small gear inside a big gear.
15033
15034 The inner loop counts the number of definitions within the range. It
15035 is a simple counting loop of the type we have seen before.
15036 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15037 The true-or-false test of the loop tests whether the value from the
15038 @code{sorted-lengths} list is smaller than the current value of the
15039 top of the range. If it is, the function increments the counter and
15040 tests the next value from the @code{sorted-lengths} list.
15041
15042 @need 1250
15043 The inner loop looks like this:
15044
15045 @smallexample
15046 @group
15047 (while @var{length-element-smaller-than-top-of-range}
15048 (setq number-within-range (1+ number-within-range))
15049 (setq sorted-lengths (cdr sorted-lengths)))
15050 @end group
15051 @end smallexample
15052
15053 The outer loop must start with the lowest value of the
15054 @code{top-of-ranges} list, and then be set to each of the succeeding
15055 higher values in turn. This can be done with a loop like this:
15056
15057 @smallexample
15058 @group
15059 (while top-of-ranges
15060 @var{body-of-loop}@dots{}
15061 (setq top-of-ranges (cdr top-of-ranges)))
15062 @end group
15063 @end smallexample
15064
15065 @need 1200
15066 Put together, the two loops look like this:
15067
15068 @smallexample
15069 @group
15070 (while top-of-ranges
15071
15072 ;; @r{Count the number of elements within the current range.}
15073 (while @var{length-element-smaller-than-top-of-range}
15074 (setq number-within-range (1+ number-within-range))
15075 (setq sorted-lengths (cdr sorted-lengths)))
15076
15077 ;; @r{Move to next range.}
15078 (setq top-of-ranges (cdr top-of-ranges)))
15079 @end group
15080 @end smallexample
15081
15082 In addition, in each circuit of the outer loop, Emacs should record
15083 the number of definitions within that range (the value of
15084 @code{number-within-range}) in a list. We can use @code{cons} for
15085 this purpose. (@xref{cons, , @code{cons}}.)
15086
15087 The @code{cons} function works fine, except that the list it
15088 constructs will contain the number of definitions for the highest
15089 range at its beginning and the number of definitions for the lowest
15090 range at its end. This is because @code{cons} attaches new elements
15091 of the list to the beginning of the list, and since the two loops are
15092 working their way through the lengths' list from the lower end first,
15093 the @code{defuns-per-range-list} will end up largest number first.
15094 But we will want to print our graph with smallest values first and the
15095 larger later. The solution is to reverse the order of the
15096 @code{defuns-per-range-list}. We can do this using the
15097 @code{nreverse} function, which reverses the order of a list.
15098 @findex nreverse
15099
15100 @need 800
15101 For example,
15102
15103 @smallexample
15104 (nreverse '(1 2 3 4))
15105 @end smallexample
15106
15107 @need 800
15108 @noindent
15109 produces:
15110
15111 @smallexample
15112 (4 3 2 1)
15113 @end smallexample
15114
15115 Note that the @code{nreverse} function is ``destructive''---that is,
15116 it changes the list to which it is applied; this contrasts with the
15117 @code{car} and @code{cdr} functions, which are non-destructive. In
15118 this case, we do not want the original @code{defuns-per-range-list},
15119 so it does not matter that it is destroyed. (The @code{reverse}
15120 function provides a reversed copy of a list, leaving the original list
15121 as is.)
15122 @findex reverse
15123
15124 @need 1250
15125 Put all together, the @code{defuns-per-range} looks like this:
15126
15127 @smallexample
15128 @group
15129 (defun defuns-per-range (sorted-lengths top-of-ranges)
15130 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15131 (let ((top-of-range (car top-of-ranges))
15132 (number-within-range 0)
15133 defuns-per-range-list)
15134 @end group
15135
15136 @group
15137 ;; @r{Outer loop.}
15138 (while top-of-ranges
15139 @end group
15140
15141 @group
15142 ;; @r{Inner loop.}
15143 (while (and
15144 ;; @r{Need number for numeric test.}
15145 (car sorted-lengths)
15146 (< (car sorted-lengths) top-of-range))
15147 @end group
15148
15149 @group
15150 ;; @r{Count number of definitions within current range.}
15151 (setq number-within-range (1+ number-within-range))
15152 (setq sorted-lengths (cdr sorted-lengths)))
15153
15154 ;; @r{Exit inner loop but remain within outer loop.}
15155 @end group
15156
15157 @group
15158 (setq defuns-per-range-list
15159 (cons number-within-range defuns-per-range-list))
15160 (setq number-within-range 0) ; @r{Reset count to zero.}
15161 @end group
15162
15163 @group
15164 ;; @r{Move to next range.}
15165 (setq top-of-ranges (cdr top-of-ranges))
15166 ;; @r{Specify next top of range value.}
15167 (setq top-of-range (car top-of-ranges)))
15168 @end group
15169
15170 @group
15171 ;; @r{Exit outer loop and count the number of defuns larger than}
15172 ;; @r{ the largest top-of-range value.}
15173 (setq defuns-per-range-list
15174 (cons
15175 (length sorted-lengths)
15176 defuns-per-range-list))
15177 @end group
15178
15179 @group
15180 ;; @r{Return a list of the number of definitions within each range,}
15181 ;; @r{ smallest to largest.}
15182 (nreverse defuns-per-range-list)))
15183 @end group
15184 @end smallexample
15185
15186 @need 1200
15187 @noindent
15188 The function is straightforward except for one subtle feature. The
15189 true-or-false test of the inner loop looks like this:
15190
15191 @smallexample
15192 @group
15193 (and (car sorted-lengths)
15194 (< (car sorted-lengths) top-of-range))
15195 @end group
15196 @end smallexample
15197
15198 @need 800
15199 @noindent
15200 instead of like this:
15201
15202 @smallexample
15203 (< (car sorted-lengths) top-of-range)
15204 @end smallexample
15205
15206 The purpose of the test is to determine whether the first item in the
15207 @code{sorted-lengths} list is less than the value of the top of the
15208 range.
15209
15210 The simple version of the test works fine unless the
15211 @code{sorted-lengths} list has a @code{nil} value. In that case, the
15212 @code{(car sorted-lengths)} expression function returns
15213 @code{nil}. The @code{<} function cannot compare a number to
15214 @code{nil}, which is an empty list, so Emacs signals an error and
15215 stops the function from attempting to continue to execute.
15216
15217 The @code{sorted-lengths} list always becomes @code{nil} when the
15218 counter reaches the end of the list. This means that any attempt to
15219 use the @code{defuns-per-range} function with the simple version of
15220 the test will fail.
15221
15222 We solve the problem by using the @code{(car sorted-lengths)}
15223 expression in conjunction with the @code{and} expression. The
15224 @code{(car sorted-lengths)} expression returns a non-@code{nil}
15225 value so long as the list has at least one number within it, but
15226 returns @code{nil} if the list is empty. The @code{and} expression
15227 first evaluates the @code{(car sorted-lengths)} expression, and
15228 if it is @code{nil}, returns false @emph{without} evaluating the
15229 @code{<} expression. But if the @code{(car sorted-lengths)}
15230 expression returns a non-@code{nil} value, the @code{and} expression
15231 evaluates the @code{<} expression, and returns that value as the value
15232 of the @code{and} expression.
15233
15234 @c colon in printed section title causes problem in Info cross reference
15235 This way, we avoid an error.
15236 @iftex
15237 @xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15238 Functions}, for more information about @code{and}.
15239 @end iftex
15240 @ifinfo
15241 @xref{forward-paragraph}, for more information about @code{and}.
15242 @end ifinfo
15243
15244 Here is a short test of the @code{defuns-per-range} function. First,
15245 evaluate the expression that binds (a shortened)
15246 @code{top-of-ranges} list to the list of values, then evaluate the
15247 expression for binding the @code{sorted-lengths} list, and then
15248 evaluate the @code{defuns-per-range} function.
15249
15250 @smallexample
15251 @group
15252 ;; @r{(Shorter list than we will use later.)}
15253 (setq top-of-ranges
15254 '(110 120 130 140 150
15255 160 170 180 190 200))
15256
15257 (setq sorted-lengths
15258 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15259
15260 (defuns-per-range sorted-lengths top-of-ranges)
15261 @end group
15262 @end smallexample
15263
15264 @need 800
15265 @noindent
15266 The list returned looks like this:
15267
15268 @smallexample
15269 (2 2 2 0 0 1 0 2 0 0 4)
15270 @end smallexample
15271
15272 @noindent
15273 Indeed, there are two elements of the @code{sorted-lengths} list
15274 smaller than 110, two elements between 110 and 119, two elements
15275 between 120 and 129, and so on. There are four elements with a value
15276 of 200 or larger.
15277
15278 @c The next step is to turn this numbers' list into a graph.
15279
15280 @node Readying a Graph, Emacs Initialization, Words in a defun, Top
15281 @chapter Readying a Graph
15282 @cindex Readying a graph
15283 @cindex Graph prototype
15284 @cindex Prototype graph
15285 @cindex Body of graph
15286
15287 Our goal is to construct a graph showing the numbers of function
15288 definitions of various lengths in the Emacs lisp sources.
15289
15290 As a practical matter, if you were creating a graph, you would
15291 probably use a program such as @code{gnuplot} to do the job.
15292 (@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
15293 however, we create one from scratch, and in the process we will
15294 re-acquaint ourselves with some of what we learned before and learn
15295 more.
15296
15297 In this chapter, we will first write a simple graph printing function.
15298 This first definition will be a @dfn{prototype}, a rapidly written
15299 function that enables us to reconnoiter this unknown graph-making
15300 territory. We will discover dragons, or find that they are myth.
15301 After scouting the terrain, we will feel more confident and enhance
15302 the function to label the axes automatically.
15303
15304 @menu
15305 * Columns of a graph::
15306 * graph-body-print:: How to print the body of a graph.
15307 * recursive-graph-body-print::
15308 * Printed Axes::
15309 * Line Graph Exercise::
15310 @end menu
15311
15312 @node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15313 @ifnottex
15314 @unnumberedsec Printing the Columns of a Graph
15315 @end ifnottex
15316
15317 Since Emacs is designed to be flexible and work with all kinds of
15318 terminals, including character-only terminals, the graph will need to
15319 be made from one of the `typewriter' symbols. An asterisk will do; as
15320 we enhance the graph-printing function, we can make the choice of
15321 symbol a user option.
15322
15323 We can call this function @code{graph-body-print}; it will take a
15324 @code{numbers-list} as its only argument. At this stage, we will not
15325 label the graph, but only print its body.
15326
15327 The @code{graph-body-print} function inserts a vertical column of
15328 asterisks for each element in the @code{numbers-list}. The height of
15329 each line is determined by the value of that element of the
15330 @code{numbers-list}.
15331
15332 Inserting columns is a repetitive act; that means that this function can
15333 be written either with a @code{while} loop or recursively.
15334
15335 Our first challenge is to discover how to print a column of asterisks.
15336 Usually, in Emacs, we print characters onto a screen horizontally,
15337 line by line, by typing. We have two routes we can follow: write our
15338 own column-insertion function or discover whether one exists in Emacs.
15339
15340 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15341 command. This command is like the @kbd{C-h a} (command-apropos)
15342 command, except that the latter finds only those functions that are
15343 commands. The @kbd{M-x apropos} command lists all symbols that match
15344 a regular expression, including functions that are not interactive.
15345 @findex apropos
15346
15347 What we want to look for is some command that prints or inserts
15348 columns. Very likely, the name of the function will contain either
15349 the word `print' or the word `insert' or the word `column'.
15350 Therefore, we can simply type @kbd{M-x apropos RET
15351 print\|insert\|column RET} and look at the result. On my system, this
15352 command takes quite some time, and then produces a list of 79
15353 functions and variables. Scanning down the list, the only function
15354 that looks as if it might do the job is @code{insert-rectangle}.
15355
15356 @need 1200
15357 Indeed, this is the function we want; its documentation says:
15358
15359 @smallexample
15360 @group
15361 insert-rectangle:
15362 Insert text of RECTANGLE with upper left corner at point.
15363 RECTANGLE's first line is inserted at point,
15364 its second line is inserted at a point vertically under point, etc.
15365 RECTANGLE should be a list of strings.
15366 @end group
15367 @end smallexample
15368
15369 We can run a quick test, to make sure it does what we expect of it.
15370
15371 Here is the result of placing the cursor after the
15372 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15373 (@code{eval-last-sexp}). The function inserts the strings
15374 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15375 point. Also the function returns @code{nil}.
15376
15377 @smallexample
15378 @group
15379 (insert-rectangle '("first" "second" "third"))first
15380 second
15381 third
15382 nil
15383 @end group
15384 @end smallexample
15385
15386 @noindent
15387 Of course, we won't be inserting the text of the
15388 @code{insert-rectangle} expression itself into the buffer in which we
15389 are making the graph, but will call the function from our program. We
15390 shall, however, have to make sure that point is in the buffer at the
15391 place where the @code{insert-rectangle} function will insert its
15392 column of strings.
15393
15394 If you are reading this in Info, you can see how this works by
15395 switching to another buffer, such as the @file{*scratch*} buffer,
15396 placing point somewhere in the buffer, typing @kbd{M-:},
15397 typing the @code{insert-rectangle} expression into the minibuffer at
15398 the prompt, and then typing @key{RET}. This causes Emacs to evaluate
15399 the expression in the minibuffer, but to use as the value of point the
15400 position of point in the @file{*scratch*} buffer. (@kbd{M-:}
15401 is the keybinding for @code{eval-expression}.)
15402
15403 We find when we do this that point ends up at the end of the last
15404 inserted line---that is to say, this function moves point as a
15405 side-effect. If we were to repeat the command, with point at this
15406 position, the next insertion would be below and to the right of the
15407 previous insertion. We don't want this! If we are going to make a
15408 bar graph, the columns need to be beside each other.
15409
15410 So we discover that each cycle of the column-inserting @code{while}
15411 loop must reposition point to the place we want it, and that place
15412 will be at the top, not the bottom, of the column. Moreover, we
15413 remember that when we print a graph, we do not expect all the columns
15414 to be the same height. This means that the top of each column may be
15415 at a different height from the previous one. We cannot simply
15416 reposition point to the same line each time, but moved over to the
15417 right---or perhaps we can@dots{}
15418
15419 We are planning to make the columns of the bar graph out of asterisks.
15420 The number of asterisks in the column is the number specified by the
15421 current element of the @code{numbers-list}. We need to construct a
15422 list of asterisks of the right length for each call to
15423 @code{insert-rectangle}. If this list consists solely of the requisite
15424 number of asterisks, then we will have position point the right number
15425 of lines above the base for the graph to print correctly. This could
15426 be difficult.
15427
15428 Alternatively, if we can figure out some way to pass
15429 @code{insert-rectangle} a list of the same length each time, then we
15430 can place point on the same line each time, but move it over one
15431 column to the right for each new column. If we do this, however, some
15432 of the entries in the list passed to @code{insert-rectangle} must be
15433 blanks rather than asterisks. For example, if the maximum height of
15434 the graph is 5, but the height of the column is 3, then
15435 @code{insert-rectangle} requires an argument that looks like this:
15436
15437 @smallexample
15438 (" " " " "*" "*" "*")
15439 @end smallexample
15440
15441 This last proposal is not so difficult, so long as we can determine
15442 the column height. There are two ways for us to specify the column
15443 height: we can arbitrarily state what it will be, which would work
15444 fine for graphs of that height; or we can search through the list of
15445 numbers and use the maximum height of the list as the maximum height
15446 of the graph. If the latter operation were difficult, then the former
15447 procedure would be easiest, but there is a function built into Emacs
15448 that determines the maximum of its arguments. We can use that
15449 function. The function is called @code{max} and it returns the
15450 largest of all its arguments, which must be numbers. Thus, for
15451 example,
15452
15453 @smallexample
15454 (max 3 4 6 5 7 3)
15455 @end smallexample
15456
15457 @noindent
15458 returns 7. (A corresponding function called @code{min} returns the
15459 smallest of all its arguments.)
15460 @findex max
15461 @findex min
15462
15463 However, we cannot simply call @code{max} on the @code{numbers-list};
15464 the @code{max} function expects numbers as its argument, not a list of
15465 numbers. Thus, the following expression,
15466
15467 @smallexample
15468 (max '(3 4 6 5 7 3))
15469 @end smallexample
15470
15471 @need 800
15472 @noindent
15473 produces the following error message;
15474
15475 @smallexample
15476 Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
15477 @end smallexample
15478
15479 @findex apply
15480 We need a function that passes a list of arguments to a function.
15481 This function is @code{apply}. This function `applies' its first
15482 argument (a function) to its remaining arguments, the last of which
15483 may be a list.
15484
15485 @need 1250
15486 For example,
15487
15488 @smallexample
15489 (apply 'max 3 4 7 3 '(4 8 5))
15490 @end smallexample
15491
15492 @noindent
15493 returns 8.
15494
15495 (Incidentally, I don't know how you would learn of this function
15496 without a book such as this. It is possible to discover other
15497 functions, like @code{search-forward} or @code{insert-rectangle}, by
15498 guessing at a part of their names and then using @code{apropos}. Even
15499 though its base in metaphor is clear---`apply' its first argument to
15500 the rest---I doubt a novice would come up with that particular word
15501 when using @code{apropos} or other aid. Of course, I could be wrong;
15502 after all, the function was first named by someone who had to invent
15503 it.)
15504
15505 The second and subsequent arguments to @code{apply} are optional, so
15506 we can use @code{apply} to call a function and pass the elements of a
15507 list to it, like this, which also returns 8:
15508
15509 @smallexample
15510 (apply 'max '(4 8 5))
15511 @end smallexample
15512
15513 This latter way is how we will use @code{apply}. The
15514 @code{recursive-lengths-list-many-files} function returns a numbers'
15515 list to which we can apply @code{max} (we could also apply @code{max} to
15516 the sorted numbers' list; it does not matter whether the list is
15517 sorted or not.)
15518
15519 @need 800
15520 Hence, the operation for finding the maximum height of the graph is this:
15521
15522 @smallexample
15523 (setq max-graph-height (apply 'max numbers-list))
15524 @end smallexample
15525
15526 Now we can return to the question of how to create a list of strings
15527 for a column of the graph. Told the maximum height of the graph
15528 and the number of asterisks that should appear in the column, the
15529 function should return a list of strings for the
15530 @code{insert-rectangle} command to insert.
15531
15532 Each column is made up of asterisks or blanks. Since the function is
15533 passed the value of the height of the column and the number of
15534 asterisks in the column, the number of blanks can be found by
15535 subtracting the number of asterisks from the height of the column.
15536 Given the number of blanks and the number of asterisks, two
15537 @code{while} loops can be used to construct the list:
15538
15539 @smallexample
15540 @group
15541 ;;; @r{First version.}
15542 (defun column-of-graph (max-graph-height actual-height)
15543 "Return list of strings that is one column of a graph."
15544 (let ((insert-list nil)
15545 (number-of-top-blanks
15546 (- max-graph-height actual-height)))
15547 @end group
15548
15549 @group
15550 ;; @r{Fill in asterisks.}
15551 (while (> actual-height 0)
15552 (setq insert-list (cons "*" insert-list))
15553 (setq actual-height (1- actual-height)))
15554 @end group
15555
15556 @group
15557 ;; @r{Fill in blanks.}
15558 (while (> number-of-top-blanks 0)
15559 (setq insert-list (cons " " insert-list))
15560 (setq number-of-top-blanks
15561 (1- number-of-top-blanks)))
15562 @end group
15563
15564 @group
15565 ;; @r{Return whole list.}
15566 insert-list))
15567 @end group
15568 @end smallexample
15569
15570 If you install this function and then evaluate the following
15571 expression you will see that it returns the list as desired:
15572
15573 @smallexample
15574 (column-of-graph 5 3)
15575 @end smallexample
15576
15577 @need 800
15578 @noindent
15579 returns
15580
15581 @smallexample
15582 (" " " " "*" "*" "*")
15583 @end smallexample
15584
15585 As written, @code{column-of-graph} contains a major flaw: the symbols
15586 used for the blank and for the marked entries in the column are
15587 `hard-coded' as a space and asterisk. This is fine for a prototype,
15588 but you, or another user, may wish to use other symbols. For example,
15589 in testing the graph function, you many want to use a period in place
15590 of the space, to make sure the point is being repositioned properly
15591 each time the @code{insert-rectangle} function is called; or you might
15592 want to substitute a @samp{+} sign or other symbol for the asterisk.
15593 You might even want to make a graph-column that is more than one
15594 display column wide. The program should be more flexible. The way to
15595 do that is to replace the blank and the asterisk with two variables
15596 that we can call @code{graph-blank} and @code{graph-symbol} and define
15597 those variables separately.
15598
15599 Also, the documentation is not well written. These considerations
15600 lead us to the second version of the function:
15601
15602 @smallexample
15603 @group
15604 (defvar graph-symbol "*"
15605 "String used as symbol in graph, usually an asterisk.")
15606 @end group
15607
15608 @group
15609 (defvar graph-blank " "
15610 "String used as blank in graph, usually a blank space.
15611 graph-blank must be the same number of columns wide
15612 as graph-symbol.")
15613 @end group
15614 @end smallexample
15615
15616 @noindent
15617 (For an explanation of @code{defvar}, see
15618 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
15619
15620 @smallexample
15621 @group
15622 ;;; @r{Second version.}
15623 (defun column-of-graph (max-graph-height actual-height)
15624 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15625
15626 @end group
15627 @group
15628 The graph-symbols are contiguous entries at the end
15629 of the list.
15630 The list will be inserted as one column of a graph.
15631 The strings are either graph-blank or graph-symbol."
15632 @end group
15633
15634 @group
15635 (let ((insert-list nil)
15636 (number-of-top-blanks
15637 (- max-graph-height actual-height)))
15638 @end group
15639
15640 @group
15641 ;; @r{Fill in @code{graph-symbols}.}
15642 (while (> actual-height 0)
15643 (setq insert-list (cons graph-symbol insert-list))
15644 (setq actual-height (1- actual-height)))
15645 @end group
15646
15647 @group
15648 ;; @r{Fill in @code{graph-blanks}.}
15649 (while (> number-of-top-blanks 0)
15650 (setq insert-list (cons graph-blank insert-list))
15651 (setq number-of-top-blanks
15652 (1- number-of-top-blanks)))
15653
15654 ;; @r{Return whole list.}
15655 insert-list))
15656 @end group
15657 @end smallexample
15658
15659 If we wished, we could rewrite @code{column-of-graph} a third time to
15660 provide optionally for a line graph as well as for a bar graph. This
15661 would not be hard to do. One way to think of a line graph is that it
15662 is no more than a bar graph in which the part of each bar that is
15663 below the top is blank. To construct a column for a line graph, the
15664 function first constructs a list of blanks that is one shorter than
15665 the value, then it uses @code{cons} to attach a graph symbol to the
15666 list; then it uses @code{cons} again to attach the `top blanks' to
15667 the list.
15668
15669 It is easy to see how to write such a function, but since we don't
15670 need it, we will not do it. But the job could be done, and if it were
15671 done, it would be done with @code{column-of-graph}. Even more
15672 important, it is worth noting that few changes would have to be made
15673 anywhere else. The enhancement, if we ever wish to make it, is
15674 simple.
15675
15676 Now, finally, we come to our first actual graph printing function.
15677 This prints the body of a graph, not the labels for the vertical and
15678 horizontal axes, so we can call this @code{graph-body-print}.
15679
15680 @node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15681 @section The @code{graph-body-print} Function
15682 @findex graph-body-print
15683
15684 After our preparation in the preceding section, the
15685 @code{graph-body-print} function is straightforward. The function
15686 will print column after column of asterisks and blanks, using the
15687 elements of a numbers' list to specify the number of asterisks in each
15688 column. This is a repetitive act, which means we can use a
15689 decrementing @code{while} loop or recursive function for the job. In
15690 this section, we will write the definition using a @code{while} loop.
15691
15692 The @code{column-of-graph} function requires the height of the graph
15693 as an argument, so we should determine and record that as a local variable.
15694
15695 This leads us to the following template for the @code{while} loop
15696 version of this function:
15697
15698 @smallexample
15699 @group
15700 (defun graph-body-print (numbers-list)
15701 "@var{documentation}@dots{}"
15702 (let ((height @dots{}
15703 @dots{}))
15704 @end group
15705
15706 @group
15707 (while numbers-list
15708 @var{insert-columns-and-reposition-point}
15709 (setq numbers-list (cdr numbers-list)))))
15710 @end group
15711 @end smallexample
15712
15713 @noindent
15714 We need to fill in the slots of the template.
15715
15716 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15717 determine the height of the graph.
15718
15719 The @code{while} loop will cycle through the @code{numbers-list} one
15720 element at a time. As it is shortened by the @code{(setq numbers-list
15721 (cdr numbers-list))} expression, the @sc{car} of each instance of the
15722 list is the value of the argument for @code{column-of-graph}.
15723
15724 At each cycle of the @code{while} loop, the @code{insert-rectangle}
15725 function inserts the list returned by @code{column-of-graph}. Since
15726 the @code{insert-rectangle} function moves point to the lower right of
15727 the inserted rectangle, we need to save the location of point at the
15728 time the rectangle is inserted, move back to that position after the
15729 rectangle is inserted, and then move horizontally to the next place
15730 from which @code{insert-rectangle} is called.
15731
15732 If the inserted columns are one character wide, as they will be if
15733 single blanks and asterisks are used, the repositioning command is
15734 simply @code{(forward-char 1)}; however, the width of a column may be
15735 greater than one. This means that the repositioning command should be
15736 written @code{(forward-char symbol-width)}. The @code{symbol-width}
15737 itself is the length of a @code{graph-blank} and can be found using
15738 the expression @code{(length graph-blank)}. The best place to bind
15739 the @code{symbol-width} variable to the value of the width of graph
15740 column is in the varlist of the @code{let} expression.
15741
15742 @need 1250
15743 These considerations lead to the following function definition:
15744
15745 @smallexample
15746 @group
15747 (defun graph-body-print (numbers-list)
15748 "Print a bar graph of the NUMBERS-LIST.
15749 The numbers-list consists of the Y-axis values."
15750
15751 (let ((height (apply 'max numbers-list))
15752 (symbol-width (length graph-blank))
15753 from-position)
15754 @end group
15755
15756 @group
15757 (while numbers-list
15758 (setq from-position (point))
15759 (insert-rectangle
15760 (column-of-graph height (car numbers-list)))
15761 (goto-char from-position)
15762 (forward-char symbol-width)
15763 @end group
15764 @group
15765 ;; @r{Draw graph column by column.}
15766 (sit-for 0)
15767 (setq numbers-list (cdr numbers-list)))
15768 @end group
15769 @group
15770 ;; @r{Place point for X axis labels.}
15771 (forward-line height)
15772 (insert "\n")
15773 ))
15774 @end group
15775 @end smallexample
15776
15777 @noindent
15778 The one unexpected expression in this function is the
15779 @w{@code{(sit-for 0)}} expression in the @code{while} loop. This
15780 expression makes the graph printing operation more interesting to
15781 watch than it would be otherwise. The expression causes Emacs to
15782 `sit' or do nothing for a zero length of time and then redraw the
15783 screen. Placed here, it causes Emacs to redraw the screen column by
15784 column. Without it, Emacs would not redraw the screen until the
15785 function exits.
15786
15787 We can test @code{graph-body-print} with a short list of numbers.
15788
15789 @enumerate
15790 @item
15791 Install @code{graph-symbol}, @code{graph-blank},
15792 @code{column-of-graph}, which are in
15793 @iftex
15794 @ref{Readying a Graph, , Readying a Graph},
15795 @end iftex
15796 @ifinfo
15797 @ref{Columns of a graph},
15798 @end ifinfo
15799 and @code{graph-body-print}.
15800
15801 @need 800
15802 @item
15803 Copy the following expression:
15804
15805 @smallexample
15806 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15807 @end smallexample
15808
15809 @item
15810 Switch to the @file{*scratch*} buffer and place the cursor where you
15811 want the graph to start.
15812
15813 @item
15814 Type @kbd{M-:} (@code{eval-expression}).
15815
15816 @item
15817 Yank the @code{graph-body-print} expression into the minibuffer
15818 with @kbd{C-y} (@code{yank)}.
15819
15820 @item
15821 Press @key{RET} to evaluate the @code{graph-body-print} expression.
15822 @end enumerate
15823
15824 @need 800
15825 Emacs will print a graph like this:
15826
15827 @smallexample
15828 @group
15829 *
15830 * **
15831 * ****
15832 *** ****
15833 ********* *
15834 ************
15835 *************
15836 @end group
15837 @end smallexample
15838
15839 @node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15840 @section The @code{recursive-graph-body-print} Function
15841 @findex recursive-graph-body-print
15842
15843 The @code{graph-body-print} function may also be written recursively.
15844 The recursive solution is divided into two parts: an outside `wrapper'
15845 that uses a @code{let} expression to determine the values of several
15846 variables that need only be found once, such as the maximum height of
15847 the graph, and an inside function that is called recursively to print
15848 the graph.
15849
15850 @need 1250
15851 The `wrapper' is uncomplicated:
15852
15853 @smallexample
15854 @group
15855 (defun recursive-graph-body-print (numbers-list)
15856 "Print a bar graph of the NUMBERS-LIST.
15857 The numbers-list consists of the Y-axis values."
15858 (let ((height (apply 'max numbers-list))
15859 (symbol-width (length graph-blank))
15860 from-position)
15861 (recursive-graph-body-print-internal
15862 numbers-list
15863 height
15864 symbol-width)))
15865 @end group
15866 @end smallexample
15867
15868 The recursive function is a little more difficult. It has four parts:
15869 the `do-again-test', the printing code, the recursive call, and the
15870 `next-step-expression'. The `do-again-test' is an @code{if}
15871 expression that determines whether the @code{numbers-list} contains
15872 any remaining elements; if it does, the function prints one column of
15873 the graph using the printing code and calls itself again. The
15874 function calls itself again according to the value produced by the
15875 `next-step-expression' which causes the call to act on a shorter
15876 version of the @code{numbers-list}.
15877
15878 @smallexample
15879 @group
15880 (defun recursive-graph-body-print-internal
15881 (numbers-list height symbol-width)
15882 "Print a bar graph.
15883 Used within recursive-graph-body-print function."
15884 @end group
15885
15886 @group
15887 (if numbers-list
15888 (progn
15889 (setq from-position (point))
15890 (insert-rectangle
15891 (column-of-graph height (car numbers-list)))
15892 @end group
15893 @group
15894 (goto-char from-position)
15895 (forward-char symbol-width)
15896 (sit-for 0) ; @r{Draw graph column by column.}
15897 (recursive-graph-body-print-internal
15898 (cdr numbers-list) height symbol-width))))
15899 @end group
15900 @end smallexample
15901
15902 @need 1250
15903 After installation, this expression can be tested; here is a sample:
15904
15905 @smallexample
15906 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15907 @end smallexample
15908
15909 @need 800
15910 Here is what @code{recursive-graph-body-print} produces:
15911
15912 @smallexample
15913 @group
15914 *
15915 ** *
15916 **** *
15917 **** ***
15918 * *********
15919 ************
15920 *************
15921 @end group
15922 @end smallexample
15923
15924 Either of these two functions, @code{graph-body-print} or
15925 @code{recursive-graph-body-print}, create the body of a graph.
15926
15927 @node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15928 @section Need for Printed Axes
15929
15930 A graph needs printed axes, so you can orient yourself. For a do-once
15931 project, it may be reasonable to draw the axes by hand using Emacs'
15932 Picture mode; but a graph drawing function may be used more than once.
15933
15934 For this reason, I have written enhancements to the basic
15935 @code{print-graph-body} function that automatically print labels for
15936 the horizontal and vertical axes. Since the label printing functions
15937 do not contain much new material, I have placed their description in
15938 an appendix. @xref{Full Graph, , A Graph with Labelled Axes}.
15939
15940 @node Line Graph Exercise, , Printed Axes, Readying a Graph
15941 @section Exercise
15942
15943 Write a line graph version of the graph printing functions.
15944
15945 @node Emacs Initialization, Debugging, Readying a Graph, Top
15946 @chapter Your @file{.emacs} File
15947 @cindex @file{.emacs} file
15948 @cindex Customizing your @file{.emacs} file
15949 @cindex Initialization file
15950
15951 ``You don't have to like Emacs to like it'' -- this seemingly
15952 paradoxical statement is the secret of GNU Emacs. The plain, `out of
15953 the box' Emacs is a generic tool. Most people who use it, customize
15954 it to suit themselves.
15955
15956 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15957 expressions in Emacs Lisp you can change or extend Emacs.
15958
15959 @menu
15960 * Default Configuration::
15961 * Site-wide Init:: You can write site-wide init files.
15962 * defcustom:: Emacs will write code for you.
15963 * Beginning a .emacs File:: How to write a @code{.emacs file}.
15964 * Text and Auto-fill:: Automatically wrap lines.
15965 * Mail Aliases:: Use abbreviations for email addresses.
15966 * Indent Tabs Mode:: Don't use tabs with @TeX{}
15967 * Keybindings:: Create some personal keybindings.
15968 * Keymaps:: More about key binding.
15969 * Loading Files:: Load (i.e., evaluate) files automatically.
15970 * Autoload:: Make functions available.
15971 * Simple Extension:: Define a function; bind it to a key.
15972 * X11 Colors:: Colors in version 19 in X.
15973 * Miscellaneous::
15974 * Mode Line:: How to customize your mode line.
15975 @end menu
15976
15977 @node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15978 @ifnottex
15979 @unnumberedsec Emacs' Default Configuration
15980 @end ifnottex
15981
15982 There are those who appreciate Emacs' default configuration. After
15983 all, Emacs starts you in C mode when you edit a C file, starts you in
15984 Fortran mode when you edit a Fortran file, and starts you in
15985 Fundamental mode when you edit an unadorned file. This all makes
15986 sense, if you do not know who is going to use Emacs. Who knows what a
15987 person hopes to do with an unadorned file? Fundamental mode is the
15988 right default for such a file, just as C mode is the right default for
15989 editing C code. But when you do know who is going to use Emacs---you,
15990 yourself---then it makes sense to customize Emacs.
15991
15992 For example, I seldom want Fundamental mode when I edit an
15993 otherwise undistinguished file; I want Text mode. This is why I
15994 customize Emacs: so it suits me.
15995
15996 You can customize and extend Emacs by writing or adapting a
15997 @file{~/.emacs} file. This is your personal initialization file; its
15998 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
15999 may also add @file{.el} to @file{~/.emacs} and call it a
16000 @file{~/.emacs.el} file. In the past, you were forbidden to type the
16001 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16002 you may. The new format is consistent with the Emacs Lisp file
16003 naming conventions; the old format saves typing.}
16004
16005 A @file{~/.emacs} file contains Emacs Lisp code. You can write this
16006 code yourself; or you can use Emacs' @code{customize} feature to write
16007 the code for you. You can combine your own expressions and
16008 auto-written Customize expressions in your @file{.emacs} file.
16009
16010 (I myself prefer to write my own expressions, except for those,
16011 particularly fonts, that I find easier to manipulate using the
16012 @code{customize} command. I combine the two methods.)
16013
16014 Most of this chapter is about writing expressions yourself. It
16015 describes a simple @file{.emacs} file; for more information, see
16016 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16017 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16018 Manual}.
16019
16020 @node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16021 @section Site-wide Initialization Files
16022
16023 @cindex @file{default.el} init file
16024 @cindex @file{site-init.el} init file
16025 @cindex @file{site-load.el} init file
16026 In addition to your personal initialization file, Emacs automatically
16027 loads various site-wide initialization files, if they exist. These
16028 have the same form as your @file{.emacs} file, but are loaded by
16029 everyone.
16030
16031 Two site-wide initialization files, @file{site-load.el} and
16032 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16033 `dumped' version of Emacs is created, as is most common. (Dumped
16034 copies of Emacs load more quickly. However, once a file is loaded and
16035 dumped, a change to it does not lead to a change in Emacs unless you
16036 load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16037 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16038 @file{INSTALL} file.)
16039
16040 Three other site-wide initialization files are loaded automatically
16041 each time you start Emacs, if they exist. These are
16042 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16043 file, and @file{default.el}, and the terminal type file, which are both
16044 loaded @emph{after} your @file{.emacs} file.
16045
16046 Settings and definitions in your @file{.emacs} file will overwrite
16047 conflicting settings and definitions in a @file{site-start.el} file,
16048 if it exists; but the settings and definitions in a @file{default.el}
16049 or terminal type file will overwrite those in your @file{.emacs} file.
16050 (You can prevent interference from a terminal type file by setting
16051 @code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16052 Simple Extension}.)
16053
16054 @c Rewritten to avoid overfull hbox.
16055 The @file{INSTALL} file that comes in the distribution contains
16056 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16057
16058 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16059 control loading. These files are in the @file{lisp} directory of the
16060 Emacs distribution and are worth perusing.
16061
16062 The @file{loaddefs.el} file contains a good many suggestions as to
16063 what to put into your own @file{.emacs} file, or into a site-wide
16064 initialization file.
16065
16066 @node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16067 @section Specifying Variables using @code{defcustom}
16068 @findex defcustom
16069
16070 You can specify variables using @code{defcustom} so that you and
16071 others can then can use Emacs' @code{customize} feature to set their
16072 values. (You cannot use @code{customize} to write function
16073 definitions; but you can write @code{defuns} in your @file{.emacs}
16074 file. Indeed, you can write any Lisp expression in your @file{.emacs}
16075 file.)
16076
16077 The @code{customize} feature depends on the @code{defcustom} special
16078 form. Although you can use @code{defvar} or @code{setq} for variables
16079 that users set, the @code{defcustom} special form is designed for the
16080 job.
16081
16082 You can use your knowledge of @code{defvar} for writing the
16083 first three arguments for @code{defcustom}. The first argument to
16084 @code{defcustom} is the name of the variable. The second argument is
16085 the variable's initial value, if any; and this value is set only if
16086 the value has not already been set. The third argument is the
16087 documentation.
16088
16089 The fourth and subsequent arguments to @code{defcustom} specify types
16090 and options; these are not featured in @code{defvar}. (These
16091 arguments are optional.)
16092
16093 Each of these arguments consists of a keyword followed by a value.
16094 Each keyword starts with the character @code{:}.
16095
16096 @need 1250
16097 For example, the customizable user option variable
16098 @code{text-mode-hook} looks like this:
16099
16100 @smallexample
16101 @group
16102 (defcustom text-mode-hook nil
16103 "Normal hook run when entering Text mode and many related modes."
16104 :type 'hook
16105 :options '(turn-on-auto-fill flyspell-mode)
16106 :group 'data)
16107 @end group
16108 @end smallexample
16109
16110 @noindent
16111 The name of the variable is @code{text-mode-hook}; it has no default
16112 value; and its documentation string tells you what it does.
16113
16114 The @code{:type} keyword tells Emacs what kind of data
16115 @code{text-mode-hook} should be set to and how to display the value in
16116 a Customization buffer.
16117
16118 The @code{:options} keyword specifies a suggested list of values for
16119 the variable. Currently, you can use @code{:options} only for a hook.
16120 The list is only a suggestion; it is not exclusive; a person who sets
16121 the variable may set it to other values; the list shown following the
16122 @code{:options} keyword is intended to offer convenient choices to a
16123 user.
16124
16125 Finally, the @code{:group} keyword tells the Emacs Customization
16126 command in which group the variable is located. This tells where to
16127 find it.
16128
16129 For more information, see @ref{Customization, , Writing Customization
16130 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16131
16132 Consider @code{text-mode-hook} as an example.
16133
16134 There are two ways to customize this variable. You can use the
16135 customization command or write the appropriate expressions yourself.
16136
16137 @need 800
16138 Using the customization command, you can type:
16139
16140 @smallexample
16141 M-x customize
16142 @end smallexample
16143
16144 @noindent
16145 and find that the group for editing files of data is called `data'.
16146 Enter that group. Text Mode Hook is the first member. You can click
16147 on its various options to set the values. After you click on the
16148 button to
16149
16150 @smallexample
16151 Save for Future Sessions
16152 @end smallexample
16153
16154 @noindent
16155 Emacs will write an expression into your @file{.emacs} file.
16156 It will look like this:
16157
16158 @smallexample
16159 @group
16160 (custom-set-variables
16161 ;; custom-set-variables was added by Custom --
16162 ;; don't edit or cut/paste it!
16163 ;; Your init file should contain only one such instance.
16164 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16165 @end group
16166 @end smallexample
16167
16168 @noindent
16169 (The @code{text-mode-hook-identify} function tells
16170 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16171
16172 In spite of the warning, you certainly may edit, cut, and paste the
16173 expression! I do all time. The purpose of the warning is to scare
16174 those who do not know what they are doing, so they do not
16175 inadvertently generate an error.
16176
16177 The @code{custom-set-variables} works somewhat differently than a
16178 @code{setq}. While I have never learned the differences, I do modify
16179 the @code{custom-set-variables} expressions in my @file{.emacs} file
16180 by hand: I make the changes in what appears to me to be a reasonable
16181 manner and have not had any problems. Others prefer to use the
16182 Customization command and let Emacs do the work for them.
16183
16184 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16185 This function sets the various font faces. Over time, I have set a
16186 considerable number of faces. Some of the time, I re-set them using
16187 @code{customize}; other times, I simply edit the
16188 @code{custom-set-faces} expression in my @file{.emacs} file itself.
16189
16190 The second way to customize your @code{text-mode-hook} is to set it
16191 yourself in your @file{.emacs} file using code that has nothing to do
16192 with the @code{custom-set-@dots{}} functions.
16193
16194 @need 800
16195 When you do this, and later use @code{customize}, you will see a
16196 message that says
16197
16198 @smallexample
16199 this option has been changed outside the customize buffer.
16200 @end smallexample
16201
16202 @need 800
16203 This message is only a warning. If you click on the button to
16204
16205 @smallexample
16206 Save for Future Sessions
16207 @end smallexample
16208
16209 @noindent
16210 Emacs will write a @code{custom-set-@dots{}} expression near the end
16211 of your @file{.emacs} file that will be evaluated after your
16212 hand-written expression. It will, therefore, overrule your
16213 hand-written expression. No harm will be done. When you do this,
16214 however, be careful to remember which expression is active; if you
16215 forget, you may confuse yourself.
16216
16217 So long as you remember where the values are set, you will have no
16218 trouble. In any event, the values are always set in your
16219 initialization file, which is usually called @file{.emacs}.
16220
16221 I myself use @code{customize} for hardly anything. Mostly, I write
16222 expressions myself.
16223
16224 @node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16225 @section Beginning a @file{.emacs} File
16226 @cindex @file{.emacs} file, beginning of
16227
16228 When you start Emacs, it loads your @file{.emacs} file unless you tell
16229 it not to by specifying @samp{-q} on the command line. (The
16230 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16231
16232 A @file{.emacs} file contains Lisp expressions. Often, these are no
16233 more than expressions to set values; sometimes they are function
16234 definitions.
16235
16236 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16237 Manual}, for a short description of initialization files.
16238
16239 This chapter goes over some of the same ground, but is a walk among
16240 extracts from a complete, long-used @file{.emacs} file---my own.
16241
16242 The first part of the file consists of comments: reminders to myself.
16243 By now, of course, I remember these things, but when I started, I did
16244 not.
16245
16246 @smallexample
16247 @group
16248 ;;;; Bob's .emacs file
16249 ; Robert J. Chassell
16250 ; 26 September 1985
16251 @end group
16252 @end smallexample
16253
16254 @noindent
16255 Look at that date! I started this file a long time ago. I have been
16256 adding to it ever since.
16257
16258 @smallexample
16259 @group
16260 ; Each section in this file is introduced by a
16261 ; line beginning with four semicolons; and each
16262 ; entry is introduced by a line beginning with
16263 ; three semicolons.
16264 @end group
16265 @end smallexample
16266
16267 @noindent
16268 This describes the usual conventions for comments in Emacs Lisp.
16269 Everything on a line that follows a semicolon is a comment. Two,
16270 three, and four semicolons are used as section and subsection
16271 markers. (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16272 Manual}, for more about comments.)
16273
16274 @smallexample
16275 @group
16276 ;;;; The Help Key
16277 ; Control-h is the help key;
16278 ; after typing control-h, type a letter to
16279 ; indicate the subject about which you want help.
16280 ; For an explanation of the help facility,
16281 ; type control-h two times in a row.
16282 @end group
16283 @end smallexample
16284
16285 @noindent
16286 Just remember: type @kbd{C-h} two times for help.
16287
16288 @smallexample
16289 @group
16290 ; To find out about any mode, type control-h m
16291 ; while in that mode. For example, to find out
16292 ; about mail mode, enter mail mode and then type
16293 ; control-h m.
16294 @end group
16295 @end smallexample
16296
16297 @noindent
16298 `Mode help', as I call this, is very helpful. Usually, it tells you
16299 all you need to know.
16300
16301 Of course, you don't need to include comments like these in your
16302 @file{.emacs} file. I included them in mine because I kept forgetting
16303 about Mode help or the conventions for comments---but I was able to
16304 remember to look here to remind myself.
16305
16306 @node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16307 @section Text and Auto Fill Mode
16308
16309 Now we come to the part that `turns on' Text mode and
16310 Auto Fill mode.
16311
16312 @smallexample
16313 @group
16314 ;;; Text mode and Auto Fill mode
16315 ; The next three lines put Emacs into Text mode
16316 ; and Auto Fill mode, and are for writers who
16317 ; want to start writing prose rather than code.
16318
16319 (setq default-major-mode 'text-mode)
16320 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16321 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16322 @end group
16323 @end smallexample
16324
16325 Here is the first part of this @file{.emacs} file that does something
16326 besides remind a forgetful human!
16327
16328 The first of the two lines in parentheses tells Emacs to turn on Text
16329 mode when you find a file, @emph{unless} that file should go into some
16330 other mode, such as C mode.
16331
16332 @cindex Per-buffer, local variables list
16333 @cindex Local variables list, per-buffer,
16334 @cindex Automatic mode selection
16335 @cindex Mode selection, automatic
16336 When Emacs reads a file, it looks at the extension to the file name,
16337 if any. (The extension is the part that comes after a @samp{.}.) If
16338 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16339 on C mode. Also, Emacs looks at first nonblank line of the file; if
16340 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
16341 possesses a list of extensions and specifications that it uses
16342 automatically. In addition, Emacs looks near the last page for a
16343 per-buffer, ``local variables list'', if any.
16344
16345 @ifinfo
16346 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16347 Emacs Manual}.
16348
16349 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16350 Manual}.
16351 @end ifinfo
16352 @iftex
16353 See sections ``How Major Modes are Chosen'' and ``Local Variables in
16354 Files'' in @cite{The GNU Emacs Manual}.
16355 @end iftex
16356
16357 Now, back to the @file{.emacs} file.
16358
16359 @need 800
16360 Here is the line again; how does it work?
16361
16362 @cindex Text Mode turned on
16363 @smallexample
16364 (setq default-major-mode 'text-mode)
16365 @end smallexample
16366
16367 @noindent
16368 This line is a short, but complete Emacs Lisp expression.
16369
16370 We are already familiar with @code{setq}. It sets the following variable,
16371 @code{default-major-mode}, to the subsequent value, which is
16372 @code{text-mode}. The single quote mark before @code{text-mode} tells
16373 Emacs to deal directly with the @code{text-mode} variable, not with
16374 whatever it might stand for. @xref{set & setq, , Setting the Value of
16375 a Variable}, for a reminder of how @code{setq} works. The main point
16376 is that there is no difference between the procedure you use to set
16377 a value in your @file{.emacs} file and the procedure you use anywhere
16378 else in Emacs.
16379
16380 @need 800
16381 Here are the next two lines:
16382
16383 @cindex Auto Fill mode turned on
16384 @findex add-hook
16385 @smallexample
16386 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16387 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16388 @end smallexample
16389
16390 @noindent
16391 In these two lines, the @code{add-hook} command first adds
16392 @code{text-mode-hook-identify} to the variable called
16393 @code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16394 variable.
16395
16396 @code{turn-on-auto-fill} is the name of a program, that, you guessed
16397 it!, turns on Auto Fill mode. @code{text-mode-hook-identify} is a
16398 function that tells @code{toggle-text-mode-auto-fill} which buffers
16399 are in Text mode.
16400
16401 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16402 onto Text mode. So every time Emacs turns on Text mode, Emacs also
16403 turns on Auto Fill mode.
16404
16405 In brief, the first line causes Emacs to enter Text mode when you edit
16406 a file, unless the file name extension, first non-blank line, or local
16407 variables tell Emacs otherwise.
16408
16409 Text mode among other actions, sets the syntax table to work
16410 conveniently for writers. In Text mode, Emacs considers an apostrophe
16411 as part of a word like a letter; but Emacs does not consider a period
16412 or a space as part of a word. Thus, @kbd{M-f} moves you over
16413 @samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
16414 the @samp{t} of @samp{it's}.
16415
16416 The second and third lines causes Emacs to turn on Auto Fill mode when
16417 it turns on Text mode. In Auto Fill mode, Emacs automatically breaks
16418 a line that is too wide and brings the excessively wide part of the
16419 line down to the next line. Emacs breaks lines between words, not
16420 within them.
16421
16422 When Auto Fill mode is turned off, lines continue to the right as you
16423 type them. Depending on how you set the value of
16424 @code{truncate-lines}, the words you type either disappear off the
16425 right side of the screen, or else are shown, in a rather ugly and
16426 unreadable manner, as a continuation line on the screen.
16427
16428 @need 1250
16429 In addition, in this part of my @file{.emacs} file, I tell the Emacs
16430 fill commands to insert two spaces after a colon:
16431
16432 @smallexample
16433 (setq colon-double-space t)
16434 @end smallexample
16435
16436 @node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16437 @section Mail Aliases
16438
16439 Here is a @code{setq} that `turns on' mail aliases, along with more
16440 reminders.
16441
16442 @smallexample
16443 @group
16444 ;;; Mail mode
16445 ; To enter mail mode, type `C-x m'
16446 ; To enter RMAIL (for reading mail),
16447 ; type `M-x rmail'
16448
16449 (setq mail-aliases t)
16450 @end group
16451 @end smallexample
16452
16453 @cindex Mail aliases
16454 @noindent
16455 This @code{setq} command sets the value of the variable
16456 @code{mail-aliases} to @code{t}. Since @code{t} means true, the line
16457 says, in effect, ``Yes, use mail aliases.''
16458
16459 Mail aliases are convenient short names for long email addresses or
16460 for lists of email addresses. The file where you keep your `aliases'
16461 is @file{~/.mailrc}. You write an alias like this:
16462
16463 @smallexample
16464 alias geo george@@foobar.wiz.edu
16465 @end smallexample
16466
16467 @noindent
16468 When you write a message to George, address it to @samp{geo}; the
16469 mailer will automatically expand @samp{geo} to the full address.
16470
16471 @node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16472 @section Indent Tabs Mode
16473 @cindex Tabs, preventing
16474 @findex indent-tabs-mode
16475
16476 By default, Emacs inserts tabs in place of multiple spaces when it
16477 formats a region. (For example, you might indent many lines of text
16478 all at once with the @code{indent-region} command.) Tabs look fine on
16479 a terminal or with ordinary printing, but they produce badly indented
16480 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16481
16482 @need 1250
16483 The following turns off Indent Tabs mode:
16484
16485 @smallexample
16486 @group
16487 ;;; Prevent Extraneous Tabs
16488 (setq-default indent-tabs-mode nil)
16489 @end group
16490 @end smallexample
16491
16492 Note that this line uses @code{setq-default} rather than the
16493 @code{setq} command that we have seen before. The @code{setq-default}
16494 command sets values only in buffers that do not have their own local
16495 values for the variable.
16496
16497 @ifinfo
16498 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16499
16500 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16501 Manual}.
16502 @end ifinfo
16503 @iftex
16504 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16505 Files'' in @cite{The GNU Emacs Manual}.
16506 @end iftex
16507
16508 @node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16509 @section Some Keybindings
16510
16511 Now for some personal keybindings:
16512
16513 @smallexample
16514 @group
16515 ;;; Compare windows
16516 (global-set-key "\C-cw" 'compare-windows)
16517 @end group
16518 @end smallexample
16519
16520 @findex compare-windows
16521 @code{compare-windows} is a nifty command that compares the text in
16522 your current window with text in the next window. It makes the
16523 comparison by starting at point in each window, moving over text in
16524 each window as far as they match. I use this command all the time.
16525
16526 This also shows how to set a key globally, for all modes.
16527
16528 @cindex Setting a key globally
16529 @cindex Global set key
16530 @cindex Key setting globally
16531 @findex global-set-key
16532 The command is @code{global-set-key}. It is followed by the
16533 keybinding. In a @file{.emacs} file, the keybinding is written as
16534 shown: @code{\C-c} stands for `control-c', which means `press the
16535 control key and the @kbd{c} key at the same time'. The @code{w} means
16536 `press the @kbd{w} key'. The keybinding is surrounded by double
16537 quotation marks. In documentation, you would write this as @kbd{C-c
16538 w}. (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16539 than a @key{CTL} key, you would write @code{\M-c}. @xref{Init
16540 Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16541 Manual}, for details.)
16542
16543 The command invoked by the keys is @code{compare-windows}. Note that
16544 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
16545 would first try to evaluate the symbol to determine its value.
16546
16547 These three things, the double quotation marks, the backslash before
16548 the @samp{C}, and the single quote mark are necessary parts of
16549 keybinding that I tend to forget. Fortunately, I have come to
16550 remember that I should look at my existing @file{.emacs} file, and
16551 adapt what is there.
16552
16553 As for the keybinding itself: @kbd{C-c w}. This combines the prefix
16554 key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
16555 set of keys, @kbd{C-c} followed by a single character, is strictly
16556 reserved for individuals' own use. (I call these `own' keys, since
16557 these are for my own use.) You should always be able to create such a
16558 keybinding for your own use without stomping on someone else's
16559 keybinding. If you ever write an extension to Emacs, please avoid
16560 taking any of these keys for public use. Create a key like @kbd{C-c
16561 C-w} instead. Otherwise, we will run out of `own' keys.
16562
16563 @need 1250
16564 Here is another keybinding, with a comment:
16565
16566 @smallexample
16567 @group
16568 ;;; Keybinding for `occur'
16569 ; I use occur a lot, so let's bind it to a key:
16570 (global-set-key "\C-co" 'occur)
16571 @end group
16572 @end smallexample
16573
16574 @findex occur
16575 The @code{occur} command shows all the lines in the current buffer
16576 that contain a match for a regular expression. Matching lines are
16577 shown in a buffer called @file{*Occur*}. That buffer serves as a menu
16578 to jump to occurrences.
16579
16580 @findex global-unset-key
16581 @cindex Unbinding key
16582 @cindex Key unbinding
16583 @need 1250
16584 Here is how to unbind a key, so it does not
16585 work:
16586
16587 @smallexample
16588 @group
16589 ;;; Unbind `C-x f'
16590 (global-unset-key "\C-xf")
16591 @end group
16592 @end smallexample
16593
16594 There is a reason for this unbinding: I found I inadvertently typed
16595 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
16596 file, as I intended, I accidentally set the width for filled text,
16597 almost always to a width I did not want. Since I hardly ever reset my
16598 default width, I simply unbound the key.
16599
16600 @findex list-buffers, @r{rebound}
16601 @findex buffer-menu, @r{bound to key}
16602 @need 1250
16603 The following rebinds an existing key:
16604
16605 @smallexample
16606 @group
16607 ;;; Rebind `C-x C-b' for `buffer-menu'
16608 (global-set-key "\C-x\C-b" 'buffer-menu)
16609 @end group
16610 @end smallexample
16611
16612 By default, @kbd{C-x C-b} runs the
16613 @code{list-buffers} command. This command lists
16614 your buffers in @emph{another} window. Since I
16615 almost always want to do something in that
16616 window, I prefer the @code{buffer-menu}
16617 command, which not only lists the buffers,
16618 but moves point into that window.
16619
16620 @node Keymaps, Loading Files, Keybindings, Emacs Initialization
16621 @section Keymaps
16622 @cindex Keymaps
16623 @cindex Rebinding keys
16624
16625 Emacs uses @dfn{keymaps} to record which keys call which commands.
16626 When you use @code{global-set-key} to set the keybinding for a single
16627 command in all parts of Emacs, you are specifying the keybinding in
16628 @code{current-global-map}.
16629
16630 Specific modes, such as C mode or Text mode, have their own keymaps;
16631 the mode-specific keymaps override the global map that is shared by
16632 all buffers.
16633
16634 The @code{global-set-key} function binds, or rebinds, the global
16635 keymap. For example, the following binds the key @kbd{C-x C-b} to the
16636 function @code{buffer-menu}:
16637
16638 @smallexample
16639 (global-set-key "\C-x\C-b" 'buffer-menu)
16640 @end smallexample
16641
16642 Mode-specific keymaps are bound using the @code{define-key} function,
16643 which takes a specific keymap as an argument, as well as the key and
16644 the command. For example, my @file{.emacs} file contains the
16645 following expression to bind the @code{texinfo-insert-@@group} command
16646 to @kbd{C-c C-c g}:
16647
16648 @smallexample
16649 @group
16650 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16651 @end group
16652 @end smallexample
16653
16654 @noindent
16655 The @code{texinfo-insert-@@group} function itself is a little extension
16656 to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
16657 use this command all the time and prefer to type the three strokes
16658 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16659 (@samp{@@group} and its matching @samp{@@end group} are commands that
16660 keep all enclosed text together on one page; many multi-line examples
16661 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16662
16663 @need 1250
16664 Here is the @code{texinfo-insert-@@group} function definition:
16665
16666 @smallexample
16667 @group
16668 (defun texinfo-insert-@@group ()
16669 "Insert the string @@group in a Texinfo buffer."
16670 (interactive)
16671 (beginning-of-line)
16672 (insert "@@group\n"))
16673 @end group
16674 @end smallexample
16675
16676 (Of course, I could have used Abbrev mode to save typing, rather than
16677 write a function to insert a word; but I prefer key strokes consistent
16678 with other Texinfo mode key bindings.)
16679
16680 You will see numerous @code{define-key} expressions in
16681 @file{loaddefs.el} as well as in the various mode libraries, such as
16682 @file{cc-mode.el} and @file{lisp-mode.el}.
16683
16684 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16685 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16686 Reference Manual}, for more information about keymaps.
16687
16688 @node Loading Files, Autoload, Keymaps, Emacs Initialization
16689 @section Loading Files
16690 @cindex Loading files
16691 @c findex load
16692
16693 Many people in the GNU Emacs community have written extensions to
16694 Emacs. As time goes by, these extensions are often included in new
16695 releases. For example, the Calendar and Diary packages are now part
16696 of the standard GNU Emacs.
16697
16698 (Calc, which I consider a vital part of Emacs, would be part of the
16699 standard distribution except that it was so large it was packaged
16700 separately and no one has changed that.)
16701
16702 You can use a @code{load} command to evaluate a complete file and
16703 thereby install all the functions and variables in the file into Emacs.
16704 For example:
16705
16706 @c (auto-compression-mode t)
16707
16708 @smallexample
16709 (load "~/emacs/slowsplit")
16710 @end smallexample
16711
16712 This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16713 exists, the faster, byte compiled @file{slowsplit.elc} file from the
16714 @file{emacs} sub-directory of your home directory. The file contains
16715 the function @code{split-window-quietly}, which John Robinson wrote in
16716 1989.
16717
16718 The @code{split-window-quietly} function splits a window with the
16719 minimum of redisplay. I installed it in 1989 because it worked well
16720 with the slow 1200 baud terminals I was then using. Nowadays, I only
16721 occasionally come across such a slow connection, but I continue to use
16722 the function because I like the way it leaves the bottom half of a
16723 buffer in the lower of the new windows and the top half in the upper
16724 window.
16725
16726 @need 1250
16727 To replace the key binding for the default
16728 @code{split-window-vertically}, you must also unset that key and bind
16729 the keys to @code{split-window-quietly}, like this:
16730
16731 @smallexample
16732 @group
16733 (global-unset-key "\C-x2")
16734 (global-set-key "\C-x2" 'split-window-quietly)
16735 @end group
16736 @end smallexample
16737
16738 @vindex load-path
16739 If you load many extensions, as I do, then instead of specifying the
16740 exact location of the extension file, as shown above, you can specify
16741 that directory as part of Emacs' @code{load-path}. Then, when Emacs
16742 loads a file, it will search that directory as well as its default
16743 list of directories. (The default list is specified in @file{paths.h}
16744 when Emacs is built.)
16745
16746 @need 1250
16747 The following command adds your @file{~/emacs} directory to the
16748 existing load path:
16749
16750 @smallexample
16751 @group
16752 ;;; Emacs Load Path
16753 (setq load-path (cons "~/emacs" load-path))
16754 @end group
16755 @end smallexample
16756
16757 Incidentally, @code{load-library} is an interactive interface to the
16758 @code{load} function. The complete function looks like this:
16759
16760 @findex load-library
16761 @smallexample
16762 @group
16763 (defun load-library (library)
16764 "Load the library named LIBRARY.
16765 This is an interface to the function `load'."
16766 (interactive "sLoad library: ")
16767 (load library))
16768 @end group
16769 @end smallexample
16770
16771 The name of the function, @code{load-library}, comes from the use of
16772 `library' as a conventional synonym for `file'. The source for the
16773 @code{load-library} command is in the @file{files.el} library.
16774
16775 Another interactive command that does a slightly different job is
16776 @code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
16777 Emacs, emacs, The GNU Emacs Manual}, for information on the
16778 distinction between @code{load-library} and this command.
16779
16780 @node Autoload, Simple Extension, Loading Files, Emacs Initialization
16781 @section Autoloading
16782 @findex autoload
16783
16784 Instead of installing a function by loading the file that contains it,
16785 or by evaluating the function definition, you can make the function
16786 available but not actually install it until it is first called. This
16787 is called @dfn{autoloading}.
16788
16789 When you execute an autoloaded function, Emacs automatically evaluates
16790 the file that contains the definition, and then calls the function.
16791
16792 Emacs starts quicker with autoloaded functions, since their libraries
16793 are not loaded right away; but you need to wait a moment when you
16794 first use such a function, while its containing file is evaluated.
16795
16796 Rarely used functions are frequently autoloaded. The
16797 @file{loaddefs.el} library contains hundreds of autoloaded functions,
16798 from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
16799 come to use a `rare' function frequently. When you do, you should
16800 load that function's file with a @code{load} expression in your
16801 @file{.emacs} file.
16802
16803 In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16804 that contain functions that would otherwise be autoloaded. (Actually,
16805 it would have been better to include these files in my `dumped' Emacs
16806 when I built it, but I forgot. @xref{Building Emacs, , Building
16807 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16808 file for more about dumping.)
16809
16810 You may also want to include autoloaded expressions in your @file{.emacs}
16811 file. @code{autoload} is a built-in function that takes up to five
16812 arguments, the final three of which are optional. The first argument
16813 is the name of the function to be autoloaded; the second is the name
16814 of the file to be loaded. The third argument is documentation for the
16815 function, and the fourth tells whether the function can be called
16816 interactively. The fifth argument tells what type of
16817 object---@code{autoload} can handle a keymap or macro as well as a
16818 function (the default is a function).
16819
16820 @need 800
16821 Here is a typical example:
16822
16823 @smallexample
16824 @group
16825 (autoload 'html-helper-mode
16826 "html-helper-mode" "Edit HTML documents" t)
16827 @end group
16828 @end smallexample
16829
16830 @noindent
16831 (@code{html-helper-mode} is an alternative to @code{html-mode}, which
16832 is a standard part of the distribution).
16833
16834 @noindent
16835 This expression autoloads the @code{html-helper-mode} function. It
16836 takes it from the @file{html-helper-mode.el} file (or from the byte
16837 compiled file @file{html-helper-mode.elc}, if it exists.) The file
16838 must be located in a directory specified by @code{load-path}. The
16839 documentation says that this is a mode to help you edit documents
16840 written in the HyperText Markup Language. You can call this mode
16841 interactively by typing @kbd{M-x html-helper-mode}. (You need to
16842 duplicate the function's regular documentation in the autoload
16843 expression because the regular function is not yet loaded, so its
16844 documentation is not available.)
16845
16846 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16847 Manual}, for more information.
16848
16849 @node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16850 @section A Simple Extension: @code{line-to-top-of-window}
16851 @findex line-to-top-of-window
16852 @cindex Simple extension in @file{.emacs} file
16853
16854 Here is a simple extension to Emacs that moves the line point is on to
16855 the top of the window. I use this all the time, to make text easier
16856 to read.
16857
16858 You can put the following code into a separate file and then load it
16859 from your @file{.emacs} file, or you can include it within your
16860 @file{.emacs} file.
16861
16862 @need 1250
16863 Here is the definition:
16864
16865 @smallexample
16866 @group
16867 ;;; Line to top of window;
16868 ;;; replace three keystroke sequence C-u 0 C-l
16869 (defun line-to-top-of-window ()
16870 "Move the line point is on to top of window."
16871 (interactive)
16872 (recenter 0))
16873 @end group
16874 @end smallexample
16875
16876 @need 1250
16877 Now for the keybinding.
16878
16879 Nowadays, function keys as well as mouse button events and
16880 non-@sc{ascii} characters are written within square brackets, without
16881 quotation marks. (In Emacs version 18 and before, you had to write
16882 different function key bindings for each different make of terminal.)
16883
16884 I bind @code{line-to-top-of-window} to my @key{F6} function key like
16885 this:
16886
16887 @smallexample
16888 (global-set-key [f6] 'line-to-top-of-window)
16889 @end smallexample
16890
16891 For more information, see @ref{Init Rebinding, , Rebinding Keys in
16892 Your Init File, emacs, The GNU Emacs Manual}.
16893
16894 @cindex Conditional 'twixt two versions of Emacs
16895 @cindex Version of Emacs, choosing
16896 @cindex Emacs version, choosing
16897 If you run two versions of GNU Emacs, such as versions 20 and 21, and
16898 use one @file{.emacs} file, you can select which code to evaluate with
16899 the following conditional:
16900
16901 @smallexample
16902 @group
16903 (cond
16904 ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16905 ;; evaluate version 20 code
16906 ( @dots{} ))
16907 ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16908 ;; evaluate version 21 code
16909 ( @dots{} )))
16910 @end group
16911 @end smallexample
16912
16913 For example, in contrast to version 20, version 21 blinks its cursor
16914 by default. I hate such blinking, as well as some other features in
16915 version 21, so I placed the following in my @file{.emacs}
16916 file@footnote{When I start instances of Emacs that do not load my
16917 @file{.emacs} file or any site file, I also turn off blinking:
16918
16919 @smallexample
16920 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16921 @end smallexample
16922 }:
16923
16924 @smallexample
16925 @group
16926 (if (string-equal "21" (substring (emacs-version) 10 12))
16927 (progn
16928 (blink-cursor-mode 0)
16929 ;; Insert newline when you press `C-n' (next-line)
16930 ;; at the end of the buffer
16931 (setq next-line-add-newlines t)
16932 @end group
16933 @group
16934 ;; Turn on image viewing
16935 (auto-image-file-mode t)
16936 @end group
16937 @group
16938 ;; Turn on menu bar (this bar has text)
16939 ;; (Use numeric argument to turn on)
16940 (menu-bar-mode 1)
16941 @end group
16942 @group
16943 ;; Turn off tool bar (this bar has icons)
16944 ;; (Use numeric argument to turn on)
16945 (tool-bar-mode nil)
16946 @end group
16947 @group
16948 ;; Turn off tooltip mode for tool bar
16949 ;; (This mode causes icon explanations to pop up)
16950 ;; (Use numeric argument to turn on)
16951 (tooltip-mode nil)
16952 ;; If tooltips turned on, make tips appear promptly
16953 (setq tooltip-delay 0.1) ; default is one second
16954 ))
16955 @end group
16956 @end smallexample
16957
16958 @noindent
16959 (You will note that instead of typing @code{(number-to-string 21)}, I
16960 decided to save typing and wrote `21' as a string, @code{"21"}, rather
16961 than convert it from an integer to a string. In this instance, this
16962 expression is better than the longer, but more general
16963 @code{(number-to-string 21)}. However, if you do not know ahead of
16964 time what type of information will be returned, then the
16965 @code{number-to-string} function will be needed.)
16966
16967 @node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16968 @section X11 Colors
16969
16970 You can specify colors when you use Emacs with the MIT X Windowing
16971 system.
16972
16973 I dislike the default colors and specify my own.
16974
16975 @need 1250
16976 Here are the expressions in my @file{.emacs}
16977 file that set values:
16978
16979 @smallexample
16980 @group
16981 ;; Set cursor color
16982 (set-cursor-color "white")
16983
16984 ;; Set mouse color
16985 (set-mouse-color "white")
16986
16987 ;; Set foreground and background
16988 (set-foreground-color "white")
16989 (set-background-color "darkblue")
16990 @end group
16991
16992 @group
16993 ;;; Set highlighting colors for isearch and drag
16994 (set-face-foreground 'highlight "white")
16995 (set-face-background 'highlight "blue")
16996 @end group
16997
16998 @group
16999 (set-face-foreground 'region "cyan")
17000 (set-face-background 'region "blue")
17001 @end group
17002
17003 @group
17004 (set-face-foreground 'secondary-selection "skyblue")
17005 (set-face-background 'secondary-selection "darkblue")
17006 @end group
17007
17008 @group
17009 ;; Set calendar highlighting colors
17010 (setq calendar-load-hook
17011 '(lambda ()
17012 (set-face-foreground 'diary-face "skyblue")
17013 (set-face-background 'holiday-face "slate blue")
17014 (set-face-foreground 'holiday-face "white")))
17015 @end group
17016 @end smallexample
17017
17018 The various shades of blue soothe my eye and prevent me from seeing
17019 the screen flicker.
17020
17021 Alternatively, I could have set my specifications in various X
17022 initialization files. For example, I could set the foreground,
17023 background, cursor, and pointer (i.e., mouse) colors in my
17024 @file{~/.Xresources} file like this:
17025
17026 @smallexample
17027 @group
17028 Emacs*foreground: white
17029 Emacs*background: darkblue
17030 Emacs*cursorColor: white
17031 Emacs*pointerColor: white
17032 @end group
17033 @end smallexample
17034
17035 In any event, since it is not part of Emacs, I set the root color of
17036 my X window in my @file{~/.xinitrc} file, like this@footnote{I
17037 occasionally run more modern window managers, such as Sawfish with
17038 GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17039 image rather than a plain color.}:
17040
17041 @smallexample
17042 @group
17043 # I use TWM for window manager.
17044 xsetroot -solid Navy -fg white &
17045 @end group
17046 @end smallexample
17047
17048 @node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17049 @section Miscellaneous Settings for a @file{.emacs} File
17050
17051 Here are a few miscellaneous settings:
17052 @sp 1
17053
17054 @itemize @minus
17055 @item
17056 Set the shape and color of the mouse cursor:
17057 @smallexample
17058 @group
17059 ; Cursor shapes are defined in
17060 ; `/usr/include/X11/cursorfont.h';
17061 ; for example, the `target' cursor is number 128;
17062 ; the `top_left_arrow' cursor is number 132.
17063 @end group
17064
17065 @group
17066 (let ((mpointer (x-get-resource "*mpointer"
17067 "*emacs*mpointer")))
17068 ;; If you have not set your mouse pointer
17069 ;; then set it, otherwise leave as is:
17070 (if (eq mpointer nil)
17071 (setq mpointer "132")) ; top_left_arrow
17072 @end group
17073 @group
17074 (setq x-pointer-shape (string-to-int mpointer))
17075 (set-mouse-color "white"))
17076 @end group
17077 @end smallexample
17078 @end itemize
17079
17080 @node Mode Line, , Miscellaneous, Emacs Initialization
17081 @section A Modified Mode Line
17082 @vindex default-mode-line-format
17083 @cindex Mode line format
17084
17085 Finally, a feature I really like: a modified mode line.
17086
17087 When I work over a network, I forget which machine I am using. Also,
17088 I tend to I lose track of where I am, and which line point is on.
17089
17090 So I reset my mode line to look like this:
17091
17092 @smallexample
17093 -:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
17094 @end smallexample
17095
17096 I am visiting a file called @file{foo.texi}, on my machine
17097 @file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
17098 Texinfo mode, and am at the top of the buffer.
17099
17100 @need 1200
17101 My @file{.emacs} file has a section that looks like this:
17102
17103 @smallexample
17104 @group
17105 ;; Set a Mode Line that tells me which machine, which directory,
17106 ;; and which line I am on, plus the other customary information.
17107 (setq default-mode-line-format
17108 (quote
17109 (#("-" 0 1
17110 (help-echo
17111 "mouse-1: select window, mouse-2: delete others ..."))
17112 mode-line-mule-info
17113 mode-line-modified
17114 mode-line-frame-identification
17115 " "
17116 @end group
17117 @group
17118 mode-line-buffer-identification
17119 " "
17120 (:eval (substring
17121 (system-name) 0 (string-match "\\..+" (system-name))))
17122 ":"
17123 default-directory
17124 #(" " 0 1
17125 (help-echo
17126 "mouse-1: select window, mouse-2: delete others ..."))
17127 (line-number-mode " Line %l ")
17128 global-mode-string
17129 @end group
17130 @group
17131 #(" %[(" 0 6
17132 (help-echo
17133 "mouse-1: select window, mouse-2: delete others ..."))
17134 (:eval (mode-line-mode-name))
17135 mode-line-process
17136 minor-mode-alist
17137 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17138 ")%] "
17139 (-3 . "%P")
17140 ;; "-%-"
17141 )))
17142 @end group
17143 @end smallexample
17144
17145 @noindent
17146 Here, I redefine the default mode line. Most of the parts are from
17147 the original; but I make a few changes. I set the @emph{default} mode
17148 line format so as to permit various modes, such as Info, to override
17149 it.
17150
17151 Many elements in the list are self-explanatory:
17152 @code{mode-line-modified} is a variable that tells whether the buffer
17153 has been modified, @code{mode-name} tells the name of the mode, and so
17154 on. However, the format looks complicated because of two features we
17155 have not discussed.
17156
17157 The first string in the mode line is a dash or hyphen, @samp{-}. In
17158 the old days, it would have been specified simply as @code{"-"}. But
17159 nowadays, Emacs can add properties to a string, such as highlighting
17160 or, as in this case, a help feature. If you place your mouse cursor
17161 over the hyphen, some help information appears (By default, you must
17162 wait one second before the information appears. You can change that
17163 timing by changing the value of @code{tooltip-delay}.)
17164
17165 @need 1000
17166 The new string format has a special syntax:
17167
17168 @smallexample
17169 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
17170 @end smallexample
17171
17172 @noindent
17173 The @code{#(} begins a list. The first element of the list is the
17174 string itself, just one @samp{-}. The second and third
17175 elements specify the range over which the fourth element applies. A
17176 range starts @emph{after} a character, so a zero means the range
17177 starts just before the first character; a 1 means that the range ends
17178 just after the first character. The third element is the property for
17179 the range. It consists of a property list, a
17180 property name, in this case, @samp{help-echo}, followed by a value, in this
17181 case, a string. The second, third, and fourth elements of this new
17182 string format can be repeated.
17183
17184 @xref{Text Props and Strings, , Text Properties in String, elisp, The
17185 GNU Emacs Lisp Reference Manual}, and see @ref{Mode Line Format, , Mode
17186 Line Format, elisp, The GNU Emacs Lisp Reference Manual}, for more
17187 information.
17188
17189 @code{mode-line-buffer-identification}
17190 displays the current buffer name. It is a list
17191 beginning @code{(#("%12b" 0 4 @dots{}}.
17192 The @code{#(} begins the list.
17193
17194 The @samp{"%12b"} displays the current buffer name, using the
17195 @code{buffer-name} function with which we are familiar; the `12'
17196 specifies the maximum number of characters that will be displayed.
17197 When a name has fewer characters, whitespace is added to fill out to
17198 this number. (Buffer names can and often should be longer than 12
17199 characters; this length works well in a typical 80 column wide
17200 window.)
17201
17202 @code{:eval} is a new feature in GNU Emacs version 21. It says to
17203 evaluate the following form and use the result as a string to display.
17204 In this case, the expression displays the first component of the full
17205 system name. The end of the first component is a @samp{.} (`period'),
17206 so I use the @code{string-match} function to tell me the length of the
17207 first component. The substring from the zeroth character to that
17208 length is the name of the machine.
17209
17210 @need 1250
17211 This is the expression:
17212
17213 @smallexample
17214 @group
17215 (:eval (substring
17216 (system-name) 0 (string-match "\\..+" (system-name))))
17217 @end group
17218 @end smallexample
17219
17220 @samp{%[} and @samp{%]} cause a pair of square brackets
17221 to appear for each recursive editing level. @samp{%n} says `Narrow'
17222 when narrowing is in effect. @samp{%P} tells you the percentage of
17223 the buffer that is above the bottom of the window, or `Top', `Bottom',
17224 or `All'. (A lower case @samp{p} tell you the percentage above the
17225 @emph{top} of the window.) @samp{%-} inserts enough dashes to fill
17226 out the line.
17227
17228 Remember, ``You don't have to like Emacs to like it'' --- your own
17229 Emacs can have different colors, different commands, and different
17230 keys than a default Emacs.
17231
17232 On the other hand, if you want to bring up a plain `out of the box'
17233 Emacs, with no customization, type:
17234
17235 @smallexample
17236 emacs -q
17237 @end smallexample
17238
17239 @noindent
17240 This will start an Emacs that does @emph{not} load your
17241 @file{~/.emacs} initialization file. A plain, default Emacs. Nothing
17242 more.
17243
17244 @node Debugging, Conclusion, Emacs Initialization, Top
17245 @chapter Debugging
17246 @cindex debugging
17247
17248 GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
17249 first is built into the internals of Emacs and is always with you;
17250 the second requires that you instrument a function before you can use it.
17251
17252 Both debuggers are described extensively in @ref{Debugging, ,
17253 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17254 In this chapter, I will walk through a short example of each.
17255
17256 @menu
17257 * debug:: How to use the built-in debugger.
17258 * debug-on-entry:: Start debugging when you call a function.
17259 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
17260 * edebug:: How to use Edebug, a source level debugger.
17261 * Debugging Exercises::
17262 @end menu
17263
17264 @node debug, debug-on-entry, Debugging, Debugging
17265 @section @code{debug}
17266 @findex debug
17267
17268 Suppose you have written a function definition that is intended to
17269 return the sum of the numbers 1 through a given number. (This is the
17270 @code{triangle} function discussed earlier. @xref{Decrementing
17271 Example, , Example with Decrementing Counter}, for a discussion.)
17272 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17273
17274 However, your function definition has a bug. You have mistyped
17275 @samp{1=} for @samp{1-}. Here is the broken definition:
17276
17277 @findex triangle-bugged
17278 @smallexample
17279 @group
17280 (defun triangle-bugged (number)
17281 "Return sum of numbers 1 through NUMBER inclusive."
17282 (let ((total 0))
17283 (while (> number 0)
17284 (setq total (+ total number))
17285 (setq number (1= number))) ; @r{Error here.}
17286 total))
17287 @end group
17288 @end smallexample
17289
17290 If you are reading this in Info, you can evaluate this definition in
17291 the normal fashion. You will see @code{triangle-bugged} appear in the
17292 echo area.
17293
17294 @need 1250
17295 Now evaluate the @code{triangle-bugged} function with an
17296 argument of 4:
17297
17298 @smallexample
17299 (triangle-bugged 4)
17300 @end smallexample
17301
17302 @noindent
17303 In GNU Emacs version 21, you will create and enter a
17304 @file{*Backtrace*} buffer that says:
17305
17306 @noindent
17307 @smallexample
17308 @group
17309 ---------- Buffer: *Backtrace* ----------
17310 Debugger entered--Lisp error: (void-function 1=)
17311 (1= number)
17312 (setq number (1= number))
17313 (while (> number 0) (setq total (+ total number))
17314 (setq number (1= number)))
17315 (let ((total 0)) (while (> number 0) (setq total ...)
17316 (setq number ...)) total)
17317 triangle-bugged(4)
17318 @end group
17319 @group
17320 eval((triangle-bugged 4))
17321 eval-last-sexp-1(nil)
17322 eval-last-sexp(nil)
17323 call-interactively(eval-last-sexp)
17324 ---------- Buffer: *Backtrace* ----------
17325 @end group
17326 @end smallexample
17327
17328 @noindent
17329 (I have reformatted this example slightly; the debugger does not fold
17330 long lines. As usual, you can quit the debugger by typing @kbd{q} in
17331 the @file{*Backtrace*} buffer.)
17332
17333 In practice, for a bug as simple as this, the `Lisp error' line will
17334 tell you what you need to know to correct the definition. The
17335 function @code{1=} is `void'.
17336
17337 @need 800
17338 In GNU Emacs 20 and before, you will see:
17339
17340 @smallexample
17341 Symbol's function definition is void:@: 1=
17342 @end smallexample
17343
17344 @noindent
17345 which has the same meaning as the @file{*Backtrace*} buffer line in
17346 version 21.
17347
17348 However, suppose you are not quite certain what is going on?
17349 You can read the complete backtrace.
17350
17351 In this case, you need to run GNU Emacs 21, which automatically starts
17352 the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17353 you need to start the debugger manually as described below.
17354
17355 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17356 what Emacs did that led to the error. Emacs made an interactive call
17357 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17358 of the @code{triangle-bugged} expression. Each line above tells you
17359 what the Lisp interpreter evaluated next.
17360
17361 @need 1250
17362 The third line from the top of the buffer is
17363
17364 @smallexample
17365 (setq number (1= number))
17366 @end smallexample
17367
17368 @noindent
17369 Emacs tried to evaluate this expression; in order to do so, it tried
17370 to evaluate the inner expression shown on the second line from the
17371 top:
17372
17373 @smallexample
17374 (1= number)
17375 @end smallexample
17376
17377 @need 1250
17378 @noindent
17379 This is where the error occurred; as the top line says:
17380
17381 @smallexample
17382 Debugger entered--Lisp error: (void-function 1=)
17383 @end smallexample
17384
17385 @noindent
17386 You can correct the mistake, re-evaluate the function definition, and
17387 then run your test again.
17388
17389 @node debug-on-entry, debug-on-quit, debug, Debugging
17390 @section @code{debug-on-entry}
17391 @findex debug-on-entry
17392
17393 GNU Emacs 21 starts the debugger automatically when your function has
17394 an error. GNU Emacs version 20 and before did not; it simply
17395 presented you with an error message. You had to start the debugger
17396 manually.
17397
17398 You can start the debugger manually for all versions of Emacs; the
17399 advantage is that the debugger runs even if you do not have a bug in
17400 your code. Sometimes your code will be free of bugs!
17401
17402 You can enter the debugger when you call the function by calling
17403 @code{debug-on-entry}.
17404
17405 @need 1250
17406 @noindent
17407 Type:
17408
17409 @smallexample
17410 M-x debug-on-entry RET triangle-bugged RET
17411 @end smallexample
17412
17413 @need 1250
17414 @noindent
17415 Now, evaluate the following:
17416
17417 @smallexample
17418 (triangle-bugged 5)
17419 @end smallexample
17420
17421 @noindent
17422 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17423 you that it is beginning to evaluate the @code{triangle-bugged}
17424 function:
17425
17426 @smallexample
17427 @group
17428 ---------- Buffer: *Backtrace* ----------
17429 Debugger entered--entering a function:
17430 * triangle-bugged(5)
17431 eval((triangle-bugged 5))
17432 @end group
17433 @group
17434 eval-last-sexp-1(nil)
17435 eval-last-sexp(nil)
17436 call-interactively(eval-last-sexp)
17437 ---------- Buffer: *Backtrace* ----------
17438 @end group
17439 @end smallexample
17440
17441 In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
17442 the first expression in @code{triangle-bugged}; the buffer will look
17443 like this:
17444
17445 @smallexample
17446 @group
17447 ---------- Buffer: *Backtrace* ----------
17448 Debugger entered--beginning evaluation of function call form:
17449 * (let ((total 0)) (while (> number 0) (setq total ...)
17450 (setq number ...)) total)
17451 * triangle-bugged(5)
17452 eval((triangle-bugged 5))
17453 @end group
17454 @group
17455 eval-last-sexp-1(nil)
17456 eval-last-sexp(nil)
17457 call-interactively(eval-last-sexp)
17458 ---------- Buffer: *Backtrace* ----------
17459 @end group
17460 @end smallexample
17461
17462 @noindent
17463 Now, type @kbd{d} again, eight times, slowly. Each time you type
17464 @kbd{d}, Emacs will evaluate another expression in the function
17465 definition.
17466
17467 @need 1750
17468 Eventually, the buffer will look like this:
17469
17470 @smallexample
17471 @group
17472 ---------- Buffer: *Backtrace* ----------
17473 Debugger entered--beginning evaluation of function call form:
17474 * (setq number (1= number))
17475 * (while (> number 0) (setq total (+ total number))
17476 (setq number (1= number)))
17477 @group
17478 @end group
17479 * (let ((total 0)) (while (> number 0) (setq total ...)
17480 (setq number ...)) total)
17481 * triangle-bugged(5)
17482 eval((triangle-bugged 5))
17483 @group
17484 @end group
17485 eval-last-sexp-1(nil)
17486 eval-last-sexp(nil)
17487 call-interactively(eval-last-sexp)
17488 ---------- Buffer: *Backtrace* ----------
17489 @end group
17490 @end smallexample
17491
17492 @noindent
17493 Finally, after you type @kbd{d} two more times, Emacs will reach the
17494 error, and the top two lines of the @file{*Backtrace*} buffer will look
17495 like this:
17496
17497 @smallexample
17498 @group
17499 ---------- Buffer: *Backtrace* ----------
17500 Debugger entered--Lisp error: (void-function 1=)
17501 * (1= number)
17502 @dots{}
17503 ---------- Buffer: *Backtrace* ----------
17504 @end group
17505 @end smallexample
17506
17507 By typing @kbd{d}, you were able to step through the function.
17508
17509 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17510 quits the trace, but does not cancel @code{debug-on-entry}.
17511
17512 @findex cancel-debug-on-entry
17513 To cancel the effect of @code{debug-on-entry}, call
17514 @code{cancel-debug-on-entry} and the name of the function, like this:
17515
17516 @smallexample
17517 M-x cancel-debug-on-entry RET triangle-bugged RET
17518 @end smallexample
17519
17520 @noindent
17521 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
17522
17523 @node debug-on-quit, edebug, debug-on-entry, Debugging
17524 @section @code{debug-on-quit} and @code{(debug)}
17525
17526 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17527 there are two other ways to start @code{debug}.
17528
17529 @findex debug-on-quit
17530 You can start @code{debug} whenever you type @kbd{C-g}
17531 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17532 @code{t}. This is useful for debugging infinite loops.
17533
17534 @need 1500
17535 @cindex @code{(debug)} in code
17536 Or, you can insert a line that says @code{(debug)} into your code
17537 where you want the debugger to start, like this:
17538
17539 @smallexample
17540 @group
17541 (defun triangle-bugged (number)
17542 "Return sum of numbers 1 through NUMBER inclusive."
17543 (let ((total 0))
17544 (while (> number 0)
17545 (setq total (+ total number))
17546 (debug) ; @r{Start debugger.}
17547 (setq number (1= number))) ; @r{Error here.}
17548 total))
17549 @end group
17550 @end smallexample
17551
17552 The @code{debug} function is described in detail in @ref{Debugger, ,
17553 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17554
17555 @node edebug, Debugging Exercises, debug-on-quit, Debugging
17556 @section The @code{edebug} Source Level Debugger
17557 @cindex Source level debugger
17558 @findex edebug
17559
17560 Edebug is a source level debugger. Edebug normally displays the
17561 source of the code you are debugging, with an arrow at the left that
17562 shows which line you are currently executing.
17563
17564 You can walk through the execution of a function, line by line, or run
17565 quickly until reaching a @dfn{breakpoint} where execution stops.
17566
17567 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17568 Lisp Reference Manual}.
17569
17570 Here is a bugged function definition for @code{triangle-recursively}.
17571 @xref{Recursive triangle function, , Recursion in place of a counter},
17572 for a review of it.
17573
17574 @smallexample
17575 @group
17576 (defun triangle-recursively-bugged (number)
17577 "Return sum of numbers 1 through NUMBER inclusive.
17578 Uses recursion."
17579 (if (= number 1)
17580 1
17581 (+ number
17582 (triangle-recursively-bugged
17583 (1= number))))) ; @r{Error here.}
17584 @end group
17585 @end smallexample
17586
17587 @noindent
17588 Normally, you would install this definition by positioning your cursor
17589 after the function's closing parenthesis and typing @kbd{C-x C-e}
17590 (@code{eval-last-sexp}) or else by positioning your cursor within the
17591 definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
17592 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17593 Interactive mode.)
17594
17595 @need 1500
17596 However, to prepare this function definition for Edebug, you must
17597 first @dfn{instrument} the code using a different command. You can do
17598 this by positioning your cursor within the definition and typing
17599
17600 @smallexample
17601 M-x edebug-defun RET
17602 @end smallexample
17603
17604 @noindent
17605 This will cause Emacs to load Edebug automatically if it is not
17606 already loaded, and properly instrument the function.
17607
17608 After instrumenting the function, place your cursor after the
17609 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17610
17611 @smallexample
17612 (triangle-recursively-bugged 3)
17613 @end smallexample
17614
17615 @noindent
17616 You will be jumped back to the source for
17617 @code{triangle-recursively-bugged} and the cursor positioned at the
17618 beginning of the @code{if} line of the function. Also, you will see
17619 an arrowhead at the left hand side of that line. The arrowhead marks
17620 the line where the function is executing. (In the following examples,
17621 we show the arrowhead with @samp{=>}; in a windowing system, you may
17622 see the arrowhead as a solid triangle in the window `fringe'.)
17623
17624 @smallexample
17625 =>@point{}(if (= number 1)
17626 @end smallexample
17627
17628 @noindent
17629 @iftex
17630 In the example, the location of point is displayed with a star,
17631 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17632 @end iftex
17633 @ifnottex
17634 In the example, the location of point is displayed as @samp{@point{}}
17635 (in a printed book, it is displayed with a five pointed star).
17636 @end ifnottex
17637
17638 If you now press @key{SPC}, point will move to the next expression to
17639 be executed; the line will look like this:
17640
17641 @smallexample
17642 =>(if @point{}(= number 1)
17643 @end smallexample
17644
17645 @noindent
17646 As you continue to press @key{SPC}, point will move from expression to
17647 expression. At the same time, whenever an expression returns a value,
17648 that value will be displayed in the echo area. For example, after you
17649 move point past @code{number}, you will see the following:
17650
17651 @smallexample
17652 Result: 3 = C-c
17653 @end smallexample
17654
17655 @noindent
17656 This means the value of @code{number} is 3, which is @sc{ascii}
17657 `control-c' (the third letter of the alphabet).
17658
17659 You can continue moving through the code until you reach the line with
17660 the error. Before evaluation, that line looks like this:
17661
17662 @smallexample
17663 => @point{}(1= number))))) ; @r{Error here.}
17664 @end smallexample
17665
17666 @need 1250
17667 @noindent
17668 When you press @key{SPC} once again, you will produce an error message
17669 that says:
17670
17671 @smallexample
17672 Symbol's function definition is void:@: 1=
17673 @end smallexample
17674
17675 @noindent
17676 This is the bug.
17677
17678 Press @kbd{q} to quit Edebug.
17679
17680 To remove instrumentation from a function definition, simply
17681 re-evaluate it with a command that does not instrument it.
17682 For example, you could place your cursor after the definition's
17683 closing parenthesis and type @kbd{C-x C-e}.
17684
17685 Edebug does a great deal more than walk with you through a function.
17686 You can set it so it races through on its own, stopping only at an
17687 error or at specified stopping points; you can cause it to display the
17688 changing values of various expressions; you can find out how many
17689 times a function is called, and more.
17690
17691 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17692 Lisp Reference Manual}.
17693
17694 @need 1500
17695 @node Debugging Exercises, , edebug, Debugging
17696 @section Debugging Exercises
17697
17698 @itemize @bullet
17699 @item
17700 Install the @code{count-words-region} function and then cause it to
17701 enter the built-in debugger when you call it. Run the command on a
17702 region containing two words. You will need to press @kbd{d} a
17703 remarkable number of times. On your system, is a `hook' called after
17704 the command finishes? (For information on hooks, see @ref{Command
17705 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17706 Manual}.)
17707
17708 @item
17709 Copy @code{count-words-region} into the @file{*scratch*} buffer,
17710 instrument the function for Edebug, and walk through its execution.
17711 The function does not need to have a bug, although you can introduce
17712 one if you wish. If the function lacks a bug, the walk-through
17713 completes without problems.
17714
17715 @item
17716 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17717 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17718 @kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17719 for commands made outside of the Edebug debugging buffer.)
17720
17721 @item
17722 In the Edebug debugging buffer, use the @kbd{p}
17723 (@code{edebug-bounce-point}) command to see where in the region the
17724 @code{count-words-region} is working.
17725
17726 @item
17727 Move point to some spot further down function and then type the
17728 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17729
17730 @item
17731 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17732 walk through the function on its own; use an upper case @kbd{T} for
17733 @code{edebug-Trace-fast-mode}.
17734
17735 @item
17736 Set a breakpoint, then run Edebug in Trace mode until it reaches the
17737 stopping point.
17738 @end itemize
17739
17740 @node Conclusion, the-the, Debugging, Top
17741 @chapter Conclusion
17742
17743 We have now reached the end of this Introduction. You have now
17744 learned enough about programming in Emacs Lisp to set values, to write
17745 simple @file{.emacs} files for yourself and your friends, and write
17746 simple customizations and extensions to Emacs.
17747
17748 This is a place to stop. Or, if you wish, you can now go onward, and
17749 teach yourself.
17750
17751 You have learned some of the basic nuts and bolts of programming. But
17752 only some. There are a great many more brackets and hinges that are
17753 easy to use that we have not touched.
17754
17755 A path you can follow right now lies among the sources to GNU Emacs
17756 and in
17757 @ifnotinfo
17758 @cite{The GNU Emacs Lisp Reference Manual}.
17759 @end ifnotinfo
17760 @ifinfo
17761 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17762 Emacs Lisp Reference Manual}.
17763 @end ifinfo
17764
17765 The Emacs Lisp sources are an adventure. When you read the sources and
17766 come across a function or expression that is unfamiliar, you need to
17767 figure out or find out what it does.
17768
17769 Go to the Reference Manual. It is a thorough, complete, and fairly
17770 easy-to-read description of Emacs Lisp. It is written not only for
17771 experts, but for people who know what you know. (The @cite{Reference
17772 Manual} comes with the standard GNU Emacs distribution. Like this
17773 introduction, it comes as a Texinfo source file, so you can read it
17774 on-line and as a typeset, printed book.)
17775
17776 Go to the other on-line help that is part of GNU Emacs: the on-line
17777 documentation for all functions, and @code{find-tags}, the program
17778 that takes you to sources.
17779
17780 Here is an example of how I explore the sources. Because of its name,
17781 @file{simple.el} is the file I looked at first, a long time ago. As
17782 it happens some of the functions in @file{simple.el} are complicated,
17783 or at least look complicated at first sight. The @code{open-line}
17784 function, for example, looks complicated.
17785
17786 You may want to walk through this function slowly, as we did with the
17787 @code{forward-sentence} function.
17788 @ifnottex
17789 (@xref{forward-sentence}.)
17790 @end ifnottex
17791 @iftex
17792 (@xref{forward-sentence, , @code{forward-sentence}}.)
17793 @end iftex
17794 Or you may want to skip that function and look at another, such as
17795 @code{split-line}. You don't need to read all the functions.
17796 According to @code{count-words-in-defun}, the @code{split-line}
17797 function contains 27 words and symbols.
17798
17799 Even though it is short, @code{split-line} contains four expressions
17800 we have not studied: @code{skip-chars-forward}, @code{indent-to},
17801 @code{current-column} and @samp{?\n}.
17802
17803 Consider the @code{skip-chars-forward} function. (It is part of the
17804 function definition for @code{back-to-indentation}, which is shown in
17805 @ref{Review, , Review}.)
17806
17807 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17808 typing @kbd{C-h f} (@code{describe-function}) and the name of the
17809 function. This gives you the function documentation.
17810
17811 You may be able to guess what is done by a well named function such as
17812 @code{indent-to}; or you can look it up, too. Incidentally, the
17813 @code{describe-function} function itself is in @file{help.el}; it is
17814 one of those long, but decipherable functions. You can look up
17815 @code{describe-function} using the @kbd{C-h f} command!
17816
17817 In this instance, since the code is Lisp, the @file{*Help*} buffer
17818 contains the name of the library containing the function's source.
17819 You can put point over the name of the library and press the RET key,
17820 which in this situation is bound to @code{help-follow}, and be taken
17821 directly to the source, in the same way as @kbd{M-.}
17822 (@code{find-tag}).
17823
17824 The definition for @code{describe-function} illustrates how to
17825 customize the @code{interactive} expression without using the standard
17826 character codes; and it shows how to create a temporary buffer.
17827
17828 (The @code{indent-to} function is written in C rather than Emacs Lisp;
17829 it is a `built-in' function. @code{help-follow} only provides you
17830 with the documentation of a built-in function; it does not take you to
17831 the source. But @code{find-tag} will take you to the source, if
17832 properly set up.)
17833
17834 You can look at a function's source using @code{find-tag}, which is
17835 bound to @kbd{M-.} Finally, you can find out what the Reference
17836 Manual has to say by visiting the manual in Info, and typing @kbd{i}
17837 (@code{Info-index}) and the name of the function, or by looking up
17838 @code{skip-chars-forward} in the index to a printed copy of the
17839 manual.
17840
17841 Similarly, you can find out what is meant by @samp{?\n}. You can try
17842 using @code{Info-index} with @samp{?\n}. It turns out that this
17843 action won't help; but don't give up. If you search the index for
17844 @samp{\n} without the @samp{?}, you will be taken directly to the
17845 relevant section of the manual. (@xref{Character Type, , Character
17846 Type, elisp, The GNU Emacs Lisp Reference Manual}. @samp{?\n} stands
17847 for the newline character.)
17848
17849 Other interesting source files include @file{paragraphs.el},
17850 @file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
17851 file includes short, easily understood functions as well as longer
17852 ones. The @file{loaddefs.el} file contains the many standard
17853 autoloads and many keymaps. I have never looked at it all; only at
17854 parts. @file{loadup.el} is the file that loads the standard parts of
17855 Emacs; it tells you a great deal about how Emacs is built.
17856 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17857 Reference Manual}, for more about building.)
17858
17859 As I said, you have learned some nuts and bolts; however, and very
17860 importantly, we have hardly touched major aspects of programming; I
17861 have said nothing about how to sort information, except to use the
17862 predefined @code{sort} function; I have said nothing about how to store
17863 information, except to use variables and lists; I have said nothing
17864 about how to write programs that write programs. These are topics for
17865 another, and different kind of book, a different kind of learning.
17866
17867 What you have done is learn enough for much practical work with GNU
17868 Emacs. What you have done is get started. This is the end of a
17869 beginning.
17870
17871 @c ================ Appendix ================
17872
17873 @node the-the, Kill Ring, Conclusion, Top
17874 @appendix The @code{the-the} Function
17875 @findex the-the
17876 @cindex Duplicated words function
17877 @cindex Words, duplicated
17878
17879 Sometimes when you you write text, you duplicate words---as with ``you
17880 you'' near the beginning of this sentence. I find that most
17881 frequently, I duplicate ``the'; hence, I call the function for
17882 detecting duplicated words, @code{the-the}.
17883
17884 @need 1250
17885 As a first step, you could use the following regular expression to
17886 search for duplicates:
17887
17888 @smallexample
17889 \\(\\w+[ \t\n]+\\)\\1
17890 @end smallexample
17891
17892 @noindent
17893 This regexp matches one or more word-constituent characters followed
17894 by one or more spaces, tabs, or newlines. However, it does not detect
17895 duplicated words on different lines, since the ending of the first
17896 word, the end of the line, is different from the ending of the second
17897 word, a space. (For more information about regular expressions, see
17898 @ref{Regexp Search, , Regular Expression Searches}, as well as
17899 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
17900 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
17901 The GNU Emacs Lisp Reference Manual}.)
17902
17903 You might try searching just for duplicated word-constituent
17904 characters but that does not work since the pattern detects doubles
17905 such as the two occurrences of `th' in `with the'.
17906
17907 Another possible regexp searches for word-constituent characters
17908 followed by non-word-constituent characters, reduplicated. Here,
17909 @w{@samp{\\w+}} matches one or more word-constituent characters and
17910 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
17911
17912 @smallexample
17913 \\(\\(\\w+\\)\\W*\\)\\1
17914 @end smallexample
17915
17916 @noindent
17917 Again, not useful.
17918
17919 Here is the pattern that I use. It is not perfect, but good enough.
17920 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
17921 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
17922 any characters that are @emph{not} an @@-sign, space, newline, or tab.
17923
17924 @smallexample
17925 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
17926 @end smallexample
17927
17928 One can write more complicated expressions, but I found that this
17929 expression is good enough, so I use it.
17930
17931 Here is the @code{the-the} function, as I include it in my
17932 @file{.emacs} file, along with a handy global key binding:
17933
17934 @smallexample
17935 @group
17936 (defun the-the ()
17937 "Search forward for for a duplicated word."
17938 (interactive)
17939 (message "Searching for for duplicated words ...")
17940 (push-mark)
17941 @end group
17942 @group
17943 ;; This regexp is not perfect
17944 ;; but is fairly good over all:
17945 (if (re-search-forward
17946 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
17947 (message "Found duplicated word.")
17948 (message "End of buffer")))
17949 @end group
17950
17951 @group
17952 ;; Bind `the-the' to C-c \
17953 (global-set-key "\C-c\\" 'the-the)
17954 @end group
17955 @end smallexample
17956
17957 @sp 1
17958 Here is test text:
17959
17960 @smallexample
17961 @group
17962 one two two three four five
17963 five six seven
17964 @end group
17965 @end smallexample
17966
17967 You can substitute the other regular expressions shown above in the
17968 function definition and try each of them on this list.
17969
17970 @node Kill Ring, Full Graph, the-the, Top
17971 @appendix Handling the Kill Ring
17972 @cindex Kill ring handling
17973 @cindex Handling the kill ring
17974 @cindex Ring, making a list like a
17975
17976 The kill ring is a list that is transformed into a ring by the
17977 workings of the @code{rotate-yank-pointer} function. The @code{yank}
17978 and @code{yank-pop} commands use the @code{rotate-yank-pointer}
17979 function. This appendix describes the @code{rotate-yank-pointer}
17980 function as well as both the @code{yank} and the @code{yank-pop}
17981 commands.
17982
17983 @menu
17984 * rotate-yank-pointer:: Move a pointer along a list and around.
17985 * yank:: Paste a copy of a clipped element.
17986 * yank-pop:: Insert first element pointed to.
17987 @end menu
17988
17989 @node rotate-yank-pointer, yank, Kill Ring, Kill Ring
17990 @comment node-name, next, previous, up
17991 @appendixsec The @code{rotate-yank-pointer} Function
17992 @findex rotate-yank-pointer
17993
17994 The @code{rotate-yank-pointer} function changes the element in the kill
17995 ring to which @code{kill-ring-yank-pointer} points. For example, it can
17996 change @code{kill-ring-yank-pointer} from pointing to the second
17997 element to point to the third element.
17998
17999 @need 800
18000 Here is the code for @code{rotate-yank-pointer}:
18001
18002 @smallexample
18003 @group
18004 (defun rotate-yank-pointer (arg)
18005 "Rotate the yanking point in the kill ring."
18006 (interactive "p")
18007 (let ((length (length kill-ring)))
18008 @end group
18009 @group
18010 (if (zerop length)
18011 ;; @r{then-part}
18012 (error "Kill ring is empty")
18013 @end group
18014 @group
18015 ;; @r{else-part}
18016 (setq kill-ring-yank-pointer
18017 (nthcdr (% (+ arg
18018 (- length
18019 (length
18020 kill-ring-yank-pointer)))
18021 length)
18022 kill-ring)))))
18023 @end group
18024 @end smallexample
18025
18026 @menu
18027 * Understanding rotate-yk-ptr::
18028 * rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
18029 @end menu
18030
18031 @node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18032 @ifnottex
18033 @unnumberedsubsec @code{rotate-yank-pointer} in Outline
18034 @end ifnottex
18035
18036 The @code{rotate-yank-pointer} function looks complex, but as usual,
18037 it can be understood by taking it apart piece by piece. First look at
18038 it in skeletal form:
18039
18040 @smallexample
18041 @group
18042 (defun rotate-yank-pointer (arg)
18043 "Rotate the yanking point in the kill ring."
18044 (interactive "p")
18045 (let @var{varlist}
18046 @var{body}@dots{})
18047 @end group
18048 @end smallexample
18049
18050 This function takes one argument, called @code{arg}. It has a brief
18051 documentation string; and it is interactive with a small @samp{p}, which
18052 means that the argument must be a processed prefix passed to the
18053 function as a number.
18054
18055 The body of the function definition is a @code{let} expression, which
18056 itself has a body as well as a @var{varlist}.
18057
18058 The @code{let} expression declares a variable that will be only usable
18059 within the bounds of this function. This variable is called
18060 @code{length} and is bound to a value that is equal to the number of
18061 items in the kill ring. This is done by using the function called
18062 @code{length}. (Note that this function has the same name as the
18063 variable called @code{length}; but one use of the word is to name the
18064 function and the other is to name the variable. The two are quite
18065 distinct. Similarly, an English speaker will distinguish between the
18066 meanings of the word @samp{ship} when he says: "I must ship this package
18067 immediately." and "I must get aboard the ship immediately.")
18068
18069 The function @code{length} tells the number of items there are in a list,
18070 so @code{(length kill-ring)} returns the number of items there are in the
18071 kill ring.
18072
18073 @node rotate-yk-ptr body, , Understanding rotate-yk-ptr, rotate-yank-pointer
18074 @comment node-name, next, previous, up
18075 @appendixsubsec The Body of @code{rotate-yank-pointer}
18076
18077 The body of @code{rotate-yank-pointer} is a @code{let} expression and
18078 the body of the @code{let} expression is an @code{if} expression.
18079
18080 The purpose of the @code{if} expression is to find out whether there is
18081 anything in the kill ring. If the kill ring is empty, the @code{error}
18082 function stops evaluation of the function and prints a message in the
18083 echo area. On the other hand, if the kill ring has something in it, the
18084 work of the function is done.
18085
18086 Here is the if-part and then-part of the @code{if} expression:
18087
18088 @findex zerop
18089 @findex error
18090 @smallexample
18091 @group
18092 (if (zerop length) ; @r{if-part}
18093 (error "Kill ring is empty") ; @r{then-part}
18094 @dots{}
18095 @end group
18096 @end smallexample
18097
18098 @noindent
18099 If there is not anything in the kill ring, its length must be zero and
18100 an error message sent to the user: @samp{Kill ring is empty}. The
18101 @code{if} expression uses the function @code{zerop} which returns true
18102 if the value it is testing is zero. When @code{zerop} tests true, the
18103 then-part of the @code{if} is evaluated. The then-part is a list
18104 starting with the function @code{error}, which is a function that is
18105 similar to the @code{message} function (@pxref{message}), in that it
18106 prints a one-line message in the echo area. However, in addition to
18107 printing a message, @code{error} also stops evaluation of the function
18108 within which it is embedded. This means that the rest of the function
18109 will not be evaluated if the length of the kill ring is zero.
18110
18111 @menu
18112 * Digression concerning error:: How to mislead humans, but not computers.
18113 * rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
18114 * Remainder Function:: The remainder, @code{%}, function.
18115 * rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
18116 * kill-rng-yk-ptr last elt:: Pointing to the last element.
18117 @end menu
18118
18119 @node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18120 @ifnottex
18121 @unnumberedsubsubsec Digression about the word `error'
18122 @end ifnottex
18123
18124 (In my opinion, it is slightly misleading, at least to humans, to use
18125 the term `error' as the name of the @code{error} function. A better
18126 term would be `cancel'. Strictly speaking, of course, you cannot
18127 point to, much less rotate a pointer to a list that has no length, so
18128 from the point of view of the computer, the word `error' is correct.
18129 But a human expects to attempt this sort of thing, if only to find out
18130 whether the kill ring is full or empty. This is an act of
18131 exploration.
18132
18133 (From the human point of view, the act of exploration and discovery is
18134 not necessarily an error, and therefore should not be labelled as one,
18135 even in the bowels of a computer. As it is, the code in Emacs implies
18136 that a human who is acting virtuously, by exploring his or her
18137 environment, is making an error. This is bad. Even though the computer
18138 takes the same steps as it does when there is an `error', a term such as
18139 `cancel' would have a clearer connotation.)
18140
18141 @node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18142 @unnumberedsubsubsec The else-part of the @code{if} expression
18143
18144 The else-part of the @code{if} expression is dedicated to setting the
18145 value of @code{kill-ring-yank-pointer} when the kill ring has something
18146 in it. The code looks like this:
18147
18148 @smallexample
18149 @group
18150 (setq kill-ring-yank-pointer
18151 (nthcdr (% (+ arg
18152 (- length
18153 (length kill-ring-yank-pointer)))
18154 length)
18155 kill-ring)))))
18156 @end group
18157 @end smallexample
18158
18159 This needs some examination. Clearly, @code{kill-ring-yank-pointer}
18160 is being set to be equal to some @sc{cdr} of the kill ring, using the
18161 @code{nthcdr} function that is described in an earlier section.
18162 (@xref{copy-region-as-kill}.) But exactly how does it do this?
18163
18164 Before looking at the details of the code let's first consider the
18165 purpose of the @code{rotate-yank-pointer} function.
18166
18167 The @code{rotate-yank-pointer} function changes what
18168 @code{kill-ring-yank-pointer} points to. If
18169 @code{kill-ring-yank-pointer} starts by pointing to the first element
18170 of a list, a call to @code{rotate-yank-pointer} causes it to point to
18171 the second element; and if @code{kill-ring-yank-pointer} points to the
18172 second element, a call to @code{rotate-yank-pointer} causes it to
18173 point to the third element. (And if @code{rotate-yank-pointer} is
18174 given an argument greater than 1, it jumps the pointer that many
18175 elements.)
18176
18177 The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18178 the @code{kill-ring-yank-pointer} points to. If
18179 @code{kill-ring-yank-pointer} points to the first element of the kill
18180 ring, then, in the simplest case, the @code{rotate-yank-pointer}
18181 function must cause it to point to the second element. Put another
18182 way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18183 to the @sc{cdr} of the kill ring.
18184
18185 @need 1250
18186 That is, under these circumstances,
18187
18188 @smallexample
18189 @group
18190 (setq kill-ring-yank-pointer
18191 ("some text" "a different piece of text" "yet more text"))
18192
18193 (setq kill-ring
18194 ("some text" "a different piece of text" "yet more text"))
18195 @end group
18196 @end smallexample
18197
18198 @need 800
18199 @noindent
18200 the code should do this:
18201
18202 @smallexample
18203 (setq kill-ring-yank-pointer (cdr kill-ring))
18204 @end smallexample
18205
18206 @need 1000
18207 @noindent
18208 As a result, the @code{kill-ring-yank-pointer} will look like this:
18209
18210 @smallexample
18211 @group
18212 kill-ring-yank-pointer
18213 @result{} ("a different piece of text" "yet more text"))
18214 @end group
18215 @end smallexample
18216
18217 The actual @code{setq} expression uses the @code{nthcdr} function to do
18218 the job.
18219
18220 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18221 works by repeatedly taking the @sc{cdr} of a list---it takes the
18222 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18223
18224 @need 800
18225 The two following expressions produce the same result:
18226
18227 @smallexample
18228 @group
18229 (setq kill-ring-yank-pointer (cdr kill-ring))
18230
18231 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18232 @end group
18233 @end smallexample
18234
18235 In the @code{rotate-yank-pointer} function, however, the first
18236 argument to @code{nthcdr} is a rather complex looking expression with
18237 lots of arithmetic inside of it:
18238
18239 @smallexample
18240 @group
18241 (% (+ arg
18242 (- length
18243 (length kill-ring-yank-pointer)))
18244 length)
18245 @end group
18246 @end smallexample
18247
18248 As usual, we need to look at the most deeply embedded expression first
18249 and then work our way towards the light.
18250
18251 The most deeply embedded expression is @code{(length
18252 kill-ring-yank-pointer)}. This finds the length of the current value of
18253 the @code{kill-ring-yank-pointer}. (Remember that the
18254 @code{kill-ring-yank-pointer} is the name of a variable whose value is a
18255 list.)
18256
18257 @need 800
18258 The measurement of the length is inside the expression:
18259
18260 @smallexample
18261 (- length (length kill-ring-yank-pointer))
18262 @end smallexample
18263
18264 @noindent
18265 In this expression, the first @code{length} is the variable that was
18266 assigned the length of the kill ring in the @code{let} statement at the
18267 beginning of the function. (One might think this function would be
18268 clearer if the variable @code{length} were named
18269 @code{length-of-kill-ring} instead; but if you look at the text of the
18270 whole function, you will see that it is so short that naming this
18271 variable @code{length} is not a bother, unless you are pulling the
18272 function apart into very tiny pieces as we are doing here.)
18273
18274 So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18275 difference between the length of the kill ring and the length of the list
18276 whose name is @code{kill-ring-yank-pointer}.
18277
18278 To see how all this fits into the @code{rotate-yank-pointer}
18279 function, let's begin by analyzing the case where
18280 @code{kill-ring-yank-pointer} points to the first element of the kill
18281 ring, just as @code{kill-ring} does, and see what happens when
18282 @code{rotate-yank-pointer} is called with an argument of 1.
18283
18284 The variable @code{length} and the value of the expression
18285 @code{(length kill-ring-yank-pointer)} will be the same since the
18286 variable @code{length} is the length of the kill ring and the
18287 @code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18288 Consequently, the value of
18289
18290 @smallexample
18291 (- length (length kill-ring-yank-pointer))
18292 @end smallexample
18293
18294 @noindent
18295 will be zero. Since the value of @code{arg} will be 1, this will mean
18296 that the value of the whole expression
18297
18298 @smallexample
18299 (+ arg (- length (length kill-ring-yank-pointer)))
18300 @end smallexample
18301
18302 @noindent
18303 will be 1.
18304
18305 Consequently, the argument to @code{nthcdr} will be found as the result of
18306 the expression
18307
18308 @smallexample
18309 (% 1 length)
18310 @end smallexample
18311
18312 @node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18313 @unnumberedsubsubsec The @code{%} remainder function
18314
18315 To understand @code{(% 1 length)}, we need to understand @code{%}.
18316 According to its documentation (which I just found by typing @kbd{C-h
18317 f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18318 its first argument divided by its second argument. For example, the
18319 remainder of 5 divided by 2 is 1. (2 goes into 5 twice with a
18320 remainder of 1.)
18321
18322 What surprises people who don't often do arithmetic is that a smaller
18323 number can be divided by a larger number and have a remainder. In the
18324 example we just used, 5 was divided by 2. We can reverse that and ask,
18325 what is the result of dividing 2 by 5? If you can use fractions, the
18326 answer is obviously 2/5 or .4; but if, as here, you can only use whole
18327 numbers, the result has to be something different. Clearly, 5 can go into
18328 2 zero times, but what of the remainder? To see what the answer is,
18329 consider a case that has to be familiar from childhood:
18330
18331 @itemize @bullet
18332 @item
18333 5 divided by 5 is 1 with a remainder of 0;
18334
18335 @item
18336 6 divided by 5 is 1 with a remainder of 1;
18337
18338 @item
18339 7 divided by 5 is 1 with a remainder of 2.
18340
18341 @item
18342 Similarly, 10 divided by 5 is 2 with a remainder of 0;
18343
18344 @item
18345 11 divided by 5 is 2 with a remainder of 1;
18346
18347 @item
18348 12 divided by 5 is 1 with a remainder of 2.
18349 @end itemize
18350
18351 @need 1250
18352 @noindent
18353 By considering the cases as parallel, we can see that
18354
18355 @itemize @bullet
18356 @item
18357 zero divided by 5 must be zero with a remainder of zero;
18358
18359 @item
18360 1 divided by 5 must be zero with a remainder of 1;
18361
18362 @item
18363 2 divided by 5 must be zero with a remainder of 2;
18364 @end itemize
18365
18366 @noindent
18367 and so on.
18368
18369 @need 1250
18370 So, in this code, if the value of @code{length} is 5, then the result of
18371 evaluating
18372
18373 @smallexample
18374 (% 1 5)
18375 @end smallexample
18376
18377 @noindent
18378 is 1. (I just checked this by placing the cursor after the expression
18379 and typing @kbd{C-x C-e}. Indeed, 1 is printed in the echo area.)
18380
18381 @node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18382 @unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18383
18384 When the @code{kill-ring-yank-pointer} points to the
18385 beginning of the kill ring, and the argument passed to
18386 @code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18387
18388 @smallexample
18389 @group
18390 (- length (length kill-ring-yank-pointer))
18391 @result{} 0
18392 @end group
18393 @end smallexample
18394
18395 @need 1250
18396 @noindent
18397 therefore,
18398
18399 @smallexample
18400 @group
18401 (+ arg (- length (length kill-ring-yank-pointer)))
18402 @result{} 1
18403 @end group
18404 @end smallexample
18405
18406 @need 1250
18407 @noindent
18408 and consequently:
18409
18410 @smallexample
18411 @group
18412 (% (+ arg (- length (length kill-ring-yank-pointer)))
18413 length)
18414 @result{} 1
18415 @end group
18416 @end smallexample
18417
18418 @noindent
18419 regardless of the value of @code{length}.
18420
18421 @need 1250
18422 @noindent
18423 As a result of this, the @code{setq kill-ring-yank-pointer} expression
18424 simplifies to:
18425
18426 @smallexample
18427 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18428 @end smallexample
18429
18430 @noindent
18431 What it does is now easy to understand. Instead of pointing as it did
18432 to the first element of the kill ring, the
18433 @code{kill-ring-yank-pointer} is set to point to the second element.
18434
18435 Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18436 the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18437 and so on for different values of the argument.
18438
18439 Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18440 the second element of the kill ring, its length is shorter than the
18441 length of the kill ring by 1, so the computation of the remainder is
18442 based on the expression @code{(% (+ arg 1) length)}. This means that
18443 the @code{kill-ring-yank-pointer} is moved from the second element of
18444 the kill ring to the third element if the argument passed to
18445 @code{rotate-yank-pointer} is 1.
18446
18447 @node kill-rng-yk-ptr last elt, , rotate-yk-ptr remainder, rotate-yk-ptr body
18448 @unnumberedsubsubsec Pointing to the last element
18449
18450 The final question is, what happens if the @code{kill-ring-yank-pointer}
18451 is set to the @emph{last} element of the kill ring? Will a call to
18452 @code{rotate-yank-pointer} mean that nothing more can be taken from the
18453 kill ring? The answer is no. What happens is different and useful.
18454 The @code{kill-ring-yank-pointer} is set to point to the beginning of
18455 the kill ring instead.
18456
18457 Let's see how this works by looking at the code, assuming the length of the
18458 kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18459 When the @code{kill-ring-yank-pointer} points to the last element of
18460 the kill ring, its length is 1. The code looks like this:
18461
18462 @smallexample
18463 (% (+ arg (- length (length kill-ring-yank-pointer))) length)
18464 @end smallexample
18465
18466 @need 1250
18467 When the variables are replaced by their numeric values, the expression
18468 looks like this:
18469
18470 @smallexample
18471 (% (+ 1 (- 5 1)) 5)
18472 @end smallexample
18473
18474 @noindent
18475 This expression can be evaluated by looking at the most embedded inner
18476 expression first and working outwards: The value of @code{(- 5 1)} is 4;
18477 the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18478 zero. So what @code{rotate-yank-pointer} will do is
18479
18480 @smallexample
18481 (setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18482 @end smallexample
18483
18484 @noindent
18485 which will set the @code{kill-ring-yank-pointer} to point to the beginning
18486 of the kill ring.
18487
18488 So what happens with successive calls to @code{rotate-yank-pointer} is that
18489 it moves the @code{kill-ring-yank-pointer} from element to element in the
18490 kill ring until it reaches the end; then it jumps back to the beginning.
18491 And this is why the kill ring is called a ring, since by jumping back to
18492 the beginning, it is as if the list has no end! (And what is a ring, but
18493 an entity with no end?)
18494
18495 @node yank, yank-pop, rotate-yank-pointer, Kill Ring
18496 @comment node-name, next, previous, up
18497 @appendixsec @code{yank}
18498 @findex yank
18499
18500 After learning about @code{rotate-yank-pointer}, the code for the
18501 @code{yank} function is almost easy. It has only one tricky part, which is
18502 the computation of the argument to be passed to @code{rotate-yank-pointer}.
18503
18504 @need 1250
18505 The code looks like this:
18506
18507 @smallexample
18508 @group
18509 (defun yank (&optional arg)
18510 "Reinsert the last stretch of killed text.
18511 More precisely, reinsert the stretch of killed text most
18512 recently killed OR yanked.
18513 With just C-U as argument, same but put point in front
18514 (and mark at end). With argument n, reinsert the nth
18515 most recently killed stretch of killed text.
18516 See also the command \\[yank-pop]."
18517 @end group
18518 @group
18519
18520 (interactive "*P")
18521 (rotate-yank-pointer (if (listp arg) 0
18522 (if (eq arg '-) -1
18523 (1- arg))))
18524 (push-mark (point))
18525 (insert (car kill-ring-yank-pointer))
18526 (if (consp arg)
18527 (exchange-point-and-mark)))
18528 @end group
18529 @end smallexample
18530
18531 Glancing over this code, we can understand the last few lines readily
18532 enough. The mark is pushed, that is, remembered; then the first element
18533 (the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18534 inserted; and then, if the argument passed the function is a
18535 @code{cons}, point and mark are exchanged so the point is put in the
18536 front of the inserted text rather than at the end. This option is
18537 explained in the documentation. The function itself is interactive with
18538 @code{"*P"}. This means it will not work on a read-only buffer, and that
18539 the unprocessed prefix argument is passed to the function.
18540
18541 @menu
18542 * rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
18543 * rotate-yk-ptr negative arg:: Pass a negative argument.
18544 @end menu
18545
18546 @node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18547 @unnumberedsubsubsec Passing the argument
18548
18549 The hard part of @code{yank} is understanding the computation that
18550 determines the value of the argument passed to
18551 @code{rotate-yank-pointer}. Fortunately, it is not so difficult as it
18552 looks at first sight.
18553
18554 What happens is that the result of evaluating one or both of the
18555 @code{if} expressions will be a number and that number will be the
18556 argument passed to @code{rotate-yank-pointer}.
18557
18558 @need 1250
18559 Laid out with comments, the code looks like this:
18560
18561 @smallexample
18562 @group
18563 (if (listp arg) ; @r{if-part}
18564 0 ; @r{then-part}
18565 (if (eq arg '-) ; @r{else-part, inner if}
18566 -1 ; @r{inner if's then-part}
18567 (1- arg)))) ; @r{inner if's else-part}
18568 @end group
18569 @end smallexample
18570
18571 @noindent
18572 This code consists of two @code{if} expression, one the else-part of
18573 the other.
18574
18575 The first or outer @code{if} expression tests whether the argument
18576 passed to @code{yank} is a list. Oddly enough, this will be true if
18577 @code{yank} is called without an argument---because then it will be
18578 passed the value of @code{nil} for the optional argument and an
18579 evaluation of @code{(listp nil)} returns true! So, if no argument is
18580 passed to @code{yank}, the argument passed to
18581 @code{rotate-yank-pointer} inside of @code{yank} is zero. This means
18582 the pointer is not moved and the first element to which
18583 @code{kill-ring-yank-pointer} points is inserted, as we expect.
18584 Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18585 read as a list, so again, a zero will be passed to
18586 @code{rotate-yank-pointer}. (@kbd{C-u} produces an unprocessed prefix
18587 argument of @code{(4)}, which is a list of one element.) At the same
18588 time, later in the function, this argument will be read as a
18589 @code{cons} so point will be put in the front and mark at the end of
18590 the insertion. (The @code{P} argument to @code{interactive} is
18591 designed to provide these values for the case when an optional
18592 argument is not provided or when it is @kbd{C-u}.)
18593
18594 The then-part of the outer @code{if} expression handles the case when
18595 there is no argument or when it is @kbd{C-u}. The else-part handles the
18596 other situations. The else-part is itself another @code{if} expression.
18597
18598 The inner @code{if} expression tests whether the argument is a minus
18599 sign. (This is done by pressing the @key{META} and @kbd{-} keys at the
18600 same time, or the @key{ESC} key and then the @kbd{-} key). In this
18601 case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18602 argument. This moves the @code{kill-ring-yank-pointer} backwards, which
18603 is what is desired.
18604
18605 If the true-or-false-test of the inner @code{if} expression is false
18606 (that is, if the argument is not a minus sign), the else-part of the
18607 expression is evaluated. This is the expression @code{(1- arg)}.
18608 Because of the two @code{if} expressions, it will only occur when the
18609 argument is a positive number or when it is a negative number (not
18610 just a minus sign on its own). What @code{(1- arg)} does is decrement
18611 the number and return it. (The @code{1-} function subtracts one from
18612 its argument.) This means that if the argument to
18613 @code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18614 the first element to which @code{kill-ring-yank-pointer} points is
18615 yanked back, as you would expect.
18616
18617 @node rotate-yk-ptr negative arg, , rotate-yk-ptr arg, yank
18618 @unnumberedsubsubsec Passing a negative argument
18619
18620 Finally, the question arises, what happens if either the remainder
18621 function, @code{%}, or the @code{nthcdr} function is passed a negative
18622 argument, as they quite well may?
18623
18624 The answers can be found by a quick test. When @code{(% -1 5)} is
18625 evaluated, a negative number is returned; and if @code{nthcdr} is
18626 called with a negative number, it returns the same value as if it were
18627 called with a first argument of zero. This can be seen be evaluating
18628 the following code.
18629
18630 Here the @samp{@result{}} points to the result of evaluating the code
18631 preceding it. This was done by positioning the cursor after the code
18632 and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18633 You can do this if you are reading this in Info inside of GNU Emacs.
18634
18635 @smallexample
18636 @group
18637 (% -1 5)
18638 @result{} -1
18639 @end group
18640
18641 @group
18642 (setq animals '(cats dogs elephants))
18643 @result{} (cats dogs elephants)
18644 @end group
18645
18646 @group
18647 (nthcdr 1 animals)
18648 @result{} (dogs elephants)
18649 @end group
18650
18651 @group
18652 (nthcdr 0 animals)
18653 @result{} (cats dogs elephants)
18654 @end group
18655
18656 @group
18657 (nthcdr -1 animals)
18658 @result{} (cats dogs elephants)
18659 @end group
18660 @end smallexample
18661
18662 So, if a minus sign or a negative number is passed to @code{yank}, the
18663 @code{kill-ring-yank-point} is rotated backwards until it reaches the
18664 beginning of the list. Then it stays there. Unlike the other case,
18665 when it jumps from the end of the list to the beginning of the list,
18666 making a ring, it stops. This makes sense. You often want to get back
18667 to the most recently clipped out piece of text, but you don't usually
18668 want to insert text from as many as thirty kill commands ago. So you
18669 need to work through the ring to get to the end, but won't cycle around
18670 it inadvertently if you are trying to come back to the beginning.
18671
18672 Incidentally, any number passed to @code{yank} with a minus sign
18673 preceding it will be treated as @minus{}1. This is evidently a
18674 simplification for writing the program. You don't need to jump back
18675 towards the beginning of the kill ring more than one place at a time
18676 and doing this is easier than writing a function to determine the
18677 magnitude of the number that follows the minus sign.
18678
18679 @node yank-pop, , yank, Kill Ring
18680 @comment node-name, next, previous, up
18681 @appendixsec @code{yank-pop}
18682 @findex yank-pop
18683
18684 After understanding @code{yank}, the @code{yank-pop} function is easy.
18685 Leaving out the documentation to save space, it looks like this:
18686
18687 @smallexample
18688 @group
18689 (defun yank-pop (arg)
18690 (interactive "*p")
18691 (if (not (eq last-command 'yank))
18692 (error "Previous command was not a yank"))
18693 @end group
18694 @group
18695 (setq this-command 'yank)
18696 (let ((before (< (point) (mark))))
18697 (delete-region (point) (mark))
18698 (rotate-yank-pointer arg)
18699 @end group
18700 @group
18701 (set-mark (point))
18702 (insert (car kill-ring-yank-pointer))
18703 (if before (exchange-point-and-mark))))
18704 @end group
18705 @end smallexample
18706
18707 The function is interactive with a small @samp{p} so the prefix
18708 argument is processed and passed to the function. The command can
18709 only be used after a previous yank; otherwise an error message is
18710 sent. This check uses the variable @code{last-command} which is
18711 discussed elsewhere. (@xref{copy-region-as-kill}.)
18712
18713 The @code{let} clause sets the variable @code{before} to true or false
18714 depending whether point is before or after mark and then the region
18715 between point and mark is deleted. This is the region that was just
18716 inserted by the previous yank and it is this text that will be
18717 replaced. Next the @code{kill-ring-yank-pointer} is rotated so that
18718 the previously inserted text is not reinserted yet again. Mark is set
18719 at the beginning of the place the new text will be inserted and then
18720 the first element to which @code{kill-ring-yank-pointer} points is
18721 inserted. This leaves point after the new text. If in the previous
18722 yank, point was left before the inserted text, point and mark are now
18723 exchanged so point is again left in front of the newly inserted text.
18724 That is all there is to it!
18725
18726 @node Full Graph, GNU Free Documentation License, Kill Ring, Top
18727 @appendix A Graph with Labelled Axes
18728
18729 Printed axes help you understand a graph. They convey scale. In an
18730 earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
18731 wrote the code to print the body of a graph. Here we write the code
18732 for printing and labelling vertical and horizontal axes, along with the
18733 body itself.
18734
18735 @menu
18736 * Labelled Example::
18737 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
18738 * print-Y-axis:: Print a label for the vertical axis.
18739 * print-X-axis:: Print a horizontal label.
18740 * Print Whole Graph:: The function to print a complete graph.
18741 @end menu
18742
18743 @node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18744 @ifnottex
18745 @unnumberedsec Labelled Example Graph
18746 @end ifnottex
18747
18748 Since insertions fill a buffer to the right and below point, the new
18749 graph printing function should first print the Y or vertical axis,
18750 then the body of the graph, and finally the X or horizontal axis.
18751 This sequence lays out for us the contents of the function:
18752
18753 @enumerate
18754 @item
18755 Set up code.
18756
18757 @item
18758 Print Y axis.
18759
18760 @item
18761 Print body of graph.
18762
18763 @item
18764 Print X axis.
18765 @end enumerate
18766
18767 @need 800
18768 Here is an example of how a finished graph should look:
18769
18770 @smallexample
18771 @group
18772 10 -
18773 *
18774 * *
18775 * **
18776 * ***
18777 5 - * *******
18778 * *** *******
18779 *************
18780 ***************
18781 1 - ****************
18782 | | | |
18783 1 5 10 15
18784 @end group
18785 @end smallexample
18786
18787 @noindent
18788 In this graph, both the vertical and the horizontal axes are labelled
18789 with numbers. However, in some graphs, the horizontal axis is time
18790 and would be better labelled with months, like this:
18791
18792 @smallexample
18793 @group
18794 5 - *
18795 * ** *
18796 *******
18797 ********** **
18798 1 - **************
18799 | ^ |
18800 Jan June Jan
18801 @end group
18802 @end smallexample
18803
18804 Indeed, with a little thought, we can easily come up with a variety of
18805 vertical and horizontal labelling schemes. Our task could become
18806 complicated. But complications breed confusion. Rather than permit
18807 this, it is better choose a simple labelling scheme for our first
18808 effort, and to modify or replace it later.
18809
18810 @need 1200
18811 These considerations suggest the following outline for the
18812 @code{print-graph} function:
18813
18814 @smallexample
18815 @group
18816 (defun print-graph (numbers-list)
18817 "@var{documentation}@dots{}"
18818 (let ((height @dots{}
18819 @dots{}))
18820 @end group
18821 @group
18822 (print-Y-axis height @dots{} )
18823 (graph-body-print numbers-list)
18824 (print-X-axis @dots{} )))
18825 @end group
18826 @end smallexample
18827
18828 We can work on each part of the @code{print-graph} function definition
18829 in turn.
18830
18831 @node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18832 @comment node-name, next, previous, up
18833 @appendixsec The @code{print-graph} Varlist
18834 @cindex @code{print-graph} varlist
18835
18836 In writing the @code{print-graph} function, the first task is to write
18837 the varlist in the @code{let} expression. (We will leave aside for the
18838 moment any thoughts about making the function interactive or about the
18839 contents of its documentation string.)
18840
18841 The varlist should set several values. Clearly, the top of the label
18842 for the vertical axis must be at least the height of the graph, which
18843 means that we must obtain this information here. Note that the
18844 @code{print-graph-body} function also requires this information. There
18845 is no reason to calculate the height of the graph in two different
18846 places, so we should change @code{print-graph-body} from the way we
18847 defined it earlier to take advantage of the calculation.
18848
18849 Similarly, both the function for printing the X axis labels and the
18850 @code{print-graph-body} function need to learn the value of the width of
18851 each symbol. We can perform the calculation here and change the
18852 definition for @code{print-graph-body} from the way we defined it in the
18853 previous chapter.
18854
18855 The length of the label for the horizontal axis must be at least as long
18856 as the graph. However, this information is used only in the function
18857 that prints the horizontal axis, so it does not need to be calculated here.
18858
18859 These thoughts lead us directly to the following form for the varlist
18860 in the @code{let} for @code{print-graph}:
18861
18862 @smallexample
18863 @group
18864 (let ((height (apply 'max numbers-list)) ; @r{First version.}
18865 (symbol-width (length graph-blank)))
18866 @end group
18867 @end smallexample
18868
18869 @noindent
18870 As we shall see, this expression is not quite right.
18871
18872 @node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
18873 @comment node-name, next, previous, up
18874 @appendixsec The @code{print-Y-axis} Function
18875 @cindex Axis, print vertical
18876 @cindex Y axis printing
18877 @cindex Vertical axis printing
18878 @cindex Print vertical axis
18879
18880 The job of the @code{print-Y-axis} function is to print a label for
18881 the vertical axis that looks like this:
18882
18883 @smallexample
18884 @group
18885 10 -
18886
18887
18888
18889
18890 5 -
18891
18892
18893
18894 1 -
18895 @end group
18896 @end smallexample
18897
18898 @noindent
18899 The function should be passed the height of the graph, and then should
18900 construct and insert the appropriate numbers and marks.
18901
18902 It is easy enough to see in the figure what the Y axis label should
18903 look like; but to say in words, and then to write a function
18904 definition to do the job is another matter. It is not quite true to
18905 say that we want a number and a tic every five lines: there are only
18906 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
18907 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
18908 and 9). It is better to say that we want a number and a tic mark on
18909 the base line (number 1) and then that we want a number and a tic on
18910 the fifth line from the bottom and on every line that is a multiple of
18911 five.
18912
18913 @menu
18914 * Height of label:: What height for the Y axis?
18915 * Compute a Remainder:: How to compute the remainder of a division.
18916 * Y Axis Element:: Construct a line for the Y axis.
18917 * Y-axis-column:: Generate a list of Y axis labels.
18918 * print-Y-axis Penultimate:: A not quite final version.
18919 @end menu
18920
18921 @node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
18922 @ifnottex
18923 @unnumberedsubsec What height should the label be?
18924 @end ifnottex
18925
18926 The next issue is what height the label should be? Suppose the maximum
18927 height of tallest column of the graph is seven. Should the highest
18928 label on the Y axis be @samp{5 -}, and should the graph stick up above
18929 the label? Or should the highest label be @samp{7 -}, and mark the peak
18930 of the graph? Or should the highest label be @code{10 -}, which is a
18931 multiple of five, and be higher than the topmost value of the graph?
18932
18933 The latter form is preferred. Most graphs are drawn within rectangles
18934 whose sides are an integral number of steps long---5, 10, 15, and so
18935 on for a step distance of five. But as soon as we decide to use a
18936 step height for the vertical axis, we discover that the simple
18937 expression in the varlist for computing the height is wrong. The
18938 expression is @code{(apply 'max numbers-list)}. This returns the
18939 precise height, not the maximum height plus whatever is necessary to
18940 round up to the nearest multiple of five. A more complex expression
18941 is required.
18942
18943 As usual in cases like this, a complex problem becomes simpler if it is
18944 divided into several smaller problems.
18945
18946 First, consider the case when the highest value of the graph is an
18947 integral multiple of five---when it is 5, 10, 15 ,or some higher
18948 multiple of five. We can use this value as the Y axis height.
18949
18950 A fairly simply way to determine whether a number is a multiple of
18951 five is to divide it by five and see if the division results in a
18952 remainder. If there is no remainder, the number is a multiple of
18953 five. Thus, seven divided by five has a remainder of two, and seven
18954 is not an integral multiple of five. Put in slightly different
18955 language, more reminiscent of the classroom, five goes into seven
18956 once, with a remainder of two. However, five goes into ten twice,
18957 with no remainder: ten is an integral multiple of five.
18958
18959 @node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
18960 @appendixsubsec Side Trip: Compute a Remainder
18961
18962 @findex % @r{(remainder function)}
18963 @cindex Remainder function, @code{%}
18964 In Lisp, the function for computing a remainder is @code{%}. The
18965 function returns the remainder of its first argument divided by its
18966 second argument. As it happens, @code{%} is a function in Emacs Lisp
18967 that you cannot discover using @code{apropos}: you find nothing if you
18968 type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
18969 learn of the existence of @code{%} is to read about it in a book such
18970 as this or in the Emacs Lisp sources. The @code{%} function is used
18971 in the code for @code{rotate-yank-pointer}, which is described in an
18972 appendix. (@xref{rotate-yk-ptr body, , The Body of
18973 @code{rotate-yank-pointer}}.)
18974
18975 You can try the @code{%} function by evaluating the following two
18976 expressions:
18977
18978 @smallexample
18979 @group
18980 (% 7 5)
18981
18982 (% 10 5)
18983 @end group
18984 @end smallexample
18985
18986 @noindent
18987 The first expression returns 2 and the second expression returns 0.
18988
18989 To test whether the returned value is zero or some other number, we
18990 can use the @code{zerop} function. This function returns @code{t} if
18991 its argument, which must be a number, is zero.
18992
18993 @smallexample
18994 @group
18995 (zerop (% 7 5))
18996 @result{} nil
18997
18998 (zerop (% 10 5))
18999 @result{} t
19000 @end group
19001 @end smallexample
19002
19003 Thus, the following expression will return @code{t} if the height
19004 of the graph is evenly divisible by five:
19005
19006 @smallexample
19007 (zerop (% height 5))
19008 @end smallexample
19009
19010 @noindent
19011 (The value of @code{height}, of course, can be found from @code{(apply
19012 'max numbers-list)}.)
19013
19014 On the other hand, if the value of @code{height} is not a multiple of
19015 five, we want to reset the value to the next higher multiple of five.
19016 This is straightforward arithmetic using functions with which we are
19017 already familiar. First, we divide the value of @code{height} by five
19018 to determine how many times five goes into the number. Thus, five
19019 goes into twelve twice. If we add one to this quotient and multiply by
19020 five, we will obtain the value of the next multiple of five that is
19021 larger than the height. Five goes into twelve twice. Add one to two,
19022 and multiply by five; the result is fifteen, which is the next multiple
19023 of five that is higher than twelve. The Lisp expression for this is:
19024
19025 @smallexample
19026 (* (1+ (/ height 5)) 5)
19027 @end smallexample
19028
19029 @noindent
19030 For example, if you evaluate the following, the result is 15:
19031
19032 @smallexample
19033 (* (1+ (/ 12 5)) 5)
19034 @end smallexample
19035
19036 All through this discussion, we have been using `five' as the value
19037 for spacing labels on the Y axis; but we may want to use some other
19038 value. For generality, we should replace `five' with a variable to
19039 which we can assign a value. The best name I can think of for this
19040 variable is @code{Y-axis-label-spacing}.
19041
19042 @need 1250
19043 Using this term, and an @code{if} expression, we produce the
19044 following:
19045
19046 @smallexample
19047 @group
19048 (if (zerop (% height Y-axis-label-spacing))
19049 height
19050 ;; @r{else}
19051 (* (1+ (/ height Y-axis-label-spacing))
19052 Y-axis-label-spacing))
19053 @end group
19054 @end smallexample
19055
19056 @noindent
19057 This expression returns the value of @code{height} itself if the height
19058 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19059 else it computes and returns a value of @code{height} that is equal to
19060 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19061
19062 We can now include this expression in the @code{let} expression of the
19063 @code{print-graph} function (after first setting the value of
19064 @code{Y-axis-label-spacing}):
19065 @vindex Y-axis-label-spacing
19066
19067 @smallexample
19068 @group
19069 (defvar Y-axis-label-spacing 5
19070 "Number of lines from one Y axis label to next.")
19071 @end group
19072
19073 @group
19074 @dots{}
19075 (let* ((height (apply 'max numbers-list))
19076 (height-of-top-line
19077 (if (zerop (% height Y-axis-label-spacing))
19078 height
19079 @end group
19080 @group
19081 ;; @r{else}
19082 (* (1+ (/ height Y-axis-label-spacing))
19083 Y-axis-label-spacing)))
19084 (symbol-width (length graph-blank))))
19085 @dots{}
19086 @end group
19087 @end smallexample
19088
19089 @noindent
19090 (Note use of the @code{let*} function: the initial value of height is
19091 computed once by the @code{(apply 'max numbers-list)} expression and
19092 then the resulting value of @code{height} is used to compute its
19093 final value. @xref{fwd-para let, , The @code{let*} expression}, for
19094 more about @code{let*}.)
19095
19096 @node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19097 @appendixsubsec Construct a Y Axis Element
19098
19099 When we print the vertical axis, we want to insert strings such as
19100 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19101 Moreover, we want the numbers and dashes to line up, so shorter
19102 numbers must be padded with leading spaces. If some of the strings
19103 use two digit numbers, the strings with single digit numbers must
19104 include a leading blank space before the number.
19105
19106 @findex number-to-string
19107 To figure out the length of the number, the @code{length} function is
19108 used. But the @code{length} function works only with a string, not with
19109 a number. So the number has to be converted from being a number to
19110 being a string. This is done with the @code{number-to-string} function.
19111 For example,
19112
19113 @smallexample
19114 @group
19115 (length (number-to-string 35))
19116 @result{} 2
19117
19118 (length (number-to-string 100))
19119 @result{} 3
19120 @end group
19121 @end smallexample
19122
19123 @noindent
19124 (@code{number-to-string} is also called @code{int-to-string}; you will
19125 see this alternative name in various sources.)
19126
19127 In addition, in each label, each number is followed by a string such
19128 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19129 This variable is defined with @code{defvar}:
19130
19131 @vindex Y-axis-tic
19132 @smallexample
19133 @group
19134 (defvar Y-axis-tic " - "
19135 "String that follows number in a Y axis label.")
19136 @end group
19137 @end smallexample
19138
19139 The length of the Y label is the sum of the length of the Y axis tic
19140 mark and the length of the number of the top of the graph.
19141
19142 @smallexample
19143 (length (concat (number-to-string height) Y-axis-tic)))
19144 @end smallexample
19145
19146 This value will be calculated by the @code{print-graph} function in
19147 its varlist as @code{full-Y-label-width} and passed on. (Note that we
19148 did not think to include this in the varlist when we first proposed it.)
19149
19150 To make a complete vertical axis label, a tic mark is concatenated
19151 with a number; and the two together may be preceded by one or more
19152 spaces depending on how long the number is. The label consists of
19153 three parts: the (optional) leading spaces, the number, and the tic
19154 mark. The function is passed the value of the number for the specific
19155 row, and the value of the width of the top line, which is calculated
19156 (just once) by @code{print-graph}.
19157
19158 @smallexample
19159 @group
19160 (defun Y-axis-element (number full-Y-label-width)
19161 "Construct a NUMBERed label element.
19162 A numbered element looks like this ` 5 - ',
19163 and is padded as needed so all line up with
19164 the element for the largest number."
19165 @end group
19166 @group
19167 (let* ((leading-spaces
19168 (- full-Y-label-width
19169 (length
19170 (concat (number-to-string number)
19171 Y-axis-tic)))))
19172 @end group
19173 @group
19174 (concat
19175 (make-string leading-spaces ? )
19176 (number-to-string number)
19177 Y-axis-tic)))
19178 @end group
19179 @end smallexample
19180
19181 The @code{Y-axis-element} function concatenates together the leading
19182 spaces, if any; the number, as a string; and the tic mark.
19183
19184 To figure out how many leading spaces the label will need, the
19185 function subtracts the actual length of the label---the length of the
19186 number plus the length of the tic mark---from the desired label width.
19187
19188 @findex make-string
19189 Blank spaces are inserted using the @code{make-string} function. This
19190 function takes two arguments: the first tells it how long the string
19191 will be and the second is a symbol for the character to insert, in a
19192 special format. The format is a question mark followed by a blank
19193 space, like this, @samp{? }. @xref{Character Type, , Character Type,
19194 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19195 syntax for characters.
19196
19197 The @code{number-to-string} function is used in the concatenation
19198 expression, to convert the number to a string that is concatenated
19199 with the leading spaces and the tic mark.
19200
19201 @node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19202 @appendixsubsec Create a Y Axis Column
19203
19204 The preceding functions provide all the tools needed to construct a
19205 function that generates a list of numbered and blank strings to insert
19206 as the label for the vertical axis:
19207
19208 @findex Y-axis-column
19209 @smallexample
19210 @group
19211 (defun Y-axis-column (height width-of-label)
19212 "Construct list of Y axis labels and blank strings.
19213 For HEIGHT of line above base and WIDTH-OF-LABEL."
19214 (let (Y-axis)
19215 @group
19216 @end group
19217 (while (> height 1)
19218 (if (zerop (% height Y-axis-label-spacing))
19219 ;; @r{Insert label.}
19220 (setq Y-axis
19221 (cons
19222 (Y-axis-element height width-of-label)
19223 Y-axis))
19224 @group
19225 @end group
19226 ;; @r{Else, insert blanks.}
19227 (setq Y-axis
19228 (cons
19229 (make-string width-of-label ? )
19230 Y-axis)))
19231 (setq height (1- height)))
19232 ;; @r{Insert base line.}
19233 (setq Y-axis
19234 (cons (Y-axis-element 1 width-of-label) Y-axis))
19235 (nreverse Y-axis)))
19236 @end group
19237 @end smallexample
19238
19239 In this function, we start with the value of @code{height} and
19240 repetitively subtract one from its value. After each subtraction, we
19241 test to see whether the value is an integral multiple of the
19242 @code{Y-axis-label-spacing}. If it is, we construct a numbered label
19243 using the @code{Y-axis-element} function; if not, we construct a
19244 blank label using the @code{make-string} function. The base line
19245 consists of the number one followed by a tic mark.
19246
19247 @node print-Y-axis Penultimate, , Y-axis-column, print-Y-axis
19248 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19249
19250 The list constructed by the @code{Y-axis-column} function is passed to
19251 the @code{print-Y-axis} function, which inserts the list as a column.
19252
19253 @findex print-Y-axis
19254 @smallexample
19255 @group
19256 (defun print-Y-axis (height full-Y-label-width)
19257 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19258 Height must be the maximum height of the graph.
19259 Full width is the width of the highest label element."
19260 ;; Value of height and full-Y-label-width
19261 ;; are passed by `print-graph'.
19262 @end group
19263 @group
19264 (let ((start (point)))
19265 (insert-rectangle
19266 (Y-axis-column height full-Y-label-width))
19267 ;; @r{Place point ready for inserting graph.}
19268 (goto-char start)
19269 ;; @r{Move point forward by value of} full-Y-label-width
19270 (forward-char full-Y-label-width)))
19271 @end group
19272 @end smallexample
19273
19274 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19275 insert the Y axis labels created by the @code{Y-axis-column} function.
19276 In addition, it places point at the correct position for printing the body of
19277 the graph.
19278
19279 You can test @code{print-Y-axis}:
19280
19281 @enumerate
19282 @item
19283 Install
19284
19285 @smallexample
19286 @group
19287 Y-axis-label-spacing
19288 Y-axis-tic
19289 Y-axis-element
19290 Y-axis-column
19291 print-Y-axis
19292 @end group
19293 @end smallexample
19294
19295 @item
19296 Copy the following expression:
19297
19298 @smallexample
19299 (print-Y-axis 12 5)
19300 @end smallexample
19301
19302 @item
19303 Switch to the @file{*scratch*} buffer and place the cursor where you
19304 want the axis labels to start.
19305
19306 @item
19307 Type @kbd{M-:} (@code{eval-expression}).
19308
19309 @item
19310 Yank the @code{graph-body-print} expression into the minibuffer
19311 with @kbd{C-y} (@code{yank)}.
19312
19313 @item
19314 Press @key{RET} to evaluate the expression.
19315 @end enumerate
19316
19317 Emacs will print labels vertically, the top one being
19318 @w{@samp{10 -@w{ }}}. (The @code{print-graph} function
19319 will pass the value of @code{height-of-top-line}, which
19320 in this case would end up as 15.)
19321
19322 @node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19323 @appendixsec The @code{print-X-axis} Function
19324 @cindex Axis, print horizontal
19325 @cindex X axis printing
19326 @cindex Print horizontal axis
19327 @cindex Horizontal axis printing
19328
19329 X axis labels are much like Y axis labels, except that the tics are on a
19330 line above the numbers. Labels should look like this:
19331
19332 @smallexample
19333 @group
19334 | | | |
19335 1 5 10 15
19336 @end group
19337 @end smallexample
19338
19339 The first tic is under the first column of the graph and is preceded by
19340 several blank spaces. These spaces provide room in rows above for the Y
19341 axis labels. The second, third, fourth, and subsequent tics are all
19342 spaced equally, according to the value of @code{X-axis-label-spacing}.
19343
19344 The second row of the X axis consists of numbers, preceded by several
19345 blank spaces and also separated according to the value of the variable
19346 @code{X-axis-label-spacing}.
19347
19348 The value of the variable @code{X-axis-label-spacing} should itself be
19349 measured in units of @code{symbol-width}, since you may want to change
19350 the width of the symbols that you are using to print the body of the
19351 graph without changing the ways the graph is labelled.
19352
19353 @menu
19354 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
19355 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
19356 @end menu
19357
19358 @node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19359 @ifnottex
19360 @unnumberedsubsec Similarities and differences
19361 @end ifnottex
19362
19363 The @code{print-X-axis} function is constructed in more or less the
19364 same fashion as the @code{print-Y-axis} function except that it has
19365 two lines: the line of tic marks and the numbers. We will write a
19366 separate function to print each line and then combine them within the
19367 @code{print-X-axis} function.
19368
19369 This is a three step process:
19370
19371 @enumerate
19372 @item
19373 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19374
19375 @item
19376 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19377
19378 @item
19379 Write a function to print both lines, the @code{print-X-axis} function,
19380 using @code{print-X-axis-tic-line} and
19381 @code{print-X-axis-numbered-line}.
19382 @end enumerate
19383
19384 @node X Axis Tic Marks, , Similarities differences, print-X-axis
19385 @appendixsubsec X Axis Tic Marks
19386
19387 The first function should print the X axis tic marks. We must specify
19388 the tic marks themselves and their spacing:
19389
19390 @smallexample
19391 @group
19392 (defvar X-axis-label-spacing
19393 (if (boundp 'graph-blank)
19394 (* 5 (length graph-blank)) 5)
19395 "Number of units from one X axis label to next.")
19396 @end group
19397 @end smallexample
19398
19399 @noindent
19400 (Note that the value of @code{graph-blank} is set by another
19401 @code{defvar}. The @code{boundp} predicate checks whether it has
19402 already been set; @code{boundp} returns @code{nil} if it has not.
19403 If @code{graph-blank} were unbound and we did not use this conditional
19404 construction, in GNU Emacs 21, we would enter the debugger and see an
19405 error message saying
19406 @samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19407
19408 @need 1200
19409 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19410
19411 @smallexample
19412 @group
19413 (defvar X-axis-tic-symbol "|"
19414 "String to insert to point to a column in X axis.")
19415 @end group
19416 @end smallexample
19417
19418 @need 1250
19419 The goal is to make a line that looks like this:
19420
19421 @smallexample
19422 | | | |
19423 @end smallexample
19424
19425 The first tic is indented so that it is under the first column, which is
19426 indented to provide space for the Y axis labels.
19427
19428 A tic element consists of the blank spaces that stretch from one tic to
19429 the next plus a tic symbol. The number of blanks is determined by the
19430 width of the tic symbol and the @code{X-axis-label-spacing}.
19431
19432 @need 1250
19433 The code looks like this:
19434
19435 @smallexample
19436 @group
19437 ;;; X-axis-tic-element
19438 @dots{}
19439 (concat
19440 (make-string
19441 ;; @r{Make a string of blanks.}
19442 (- (* symbol-width X-axis-label-spacing)
19443 (length X-axis-tic-symbol))
19444 ? )
19445 ;; @r{Concatenate blanks with tic symbol.}
19446 X-axis-tic-symbol)
19447 @dots{}
19448 @end group
19449 @end smallexample
19450
19451 Next, we determine how many blanks are needed to indent the first tic
19452 mark to the first column of the graph. This uses the value of
19453 @code{full-Y-label-width} passed it by the @code{print-graph} function.
19454
19455 @need 1250
19456 The code to make @code{X-axis-leading-spaces}
19457 looks like this:
19458
19459 @smallexample
19460 @group
19461 ;; X-axis-leading-spaces
19462 @dots{}
19463 (make-string full-Y-label-width ? )
19464 @dots{}
19465 @end group
19466 @end smallexample
19467
19468 We also need to determine the length of the horizontal axis, which is
19469 the length of the numbers list, and the number of tics in the horizontal
19470 axis:
19471
19472 @smallexample
19473 @group
19474 ;; X-length
19475 @dots{}
19476 (length numbers-list)
19477 @end group
19478
19479 @group
19480 ;; tic-width
19481 @dots{}
19482 (* symbol-width X-axis-label-spacing)
19483 @end group
19484
19485 @group
19486 ;; number-of-X-tics
19487 (if (zerop (% (X-length tic-width)))
19488 (/ (X-length tic-width))
19489 (1+ (/ (X-length tic-width))))
19490 @end group
19491 @end smallexample
19492
19493 @need 1250
19494 All this leads us directly to the function for printing the X axis tic line:
19495
19496 @findex print-X-axis-tic-line
19497 @smallexample
19498 @group
19499 (defun print-X-axis-tic-line
19500 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19501 "Print tics for X axis."
19502 (insert X-axis-leading-spaces)
19503 (insert X-axis-tic-symbol) ; @r{Under first column.}
19504 @end group
19505 @group
19506 ;; @r{Insert second tic in the right spot.}
19507 (insert (concat
19508 (make-string
19509 (- (* symbol-width X-axis-label-spacing)
19510 ;; @r{Insert white space up to second tic symbol.}
19511 (* 2 (length X-axis-tic-symbol)))
19512 ? )
19513 X-axis-tic-symbol))
19514 @end group
19515 @group
19516 ;; @r{Insert remaining tics.}
19517 (while (> number-of-X-tics 1)
19518 (insert X-axis-tic-element)
19519 (setq number-of-X-tics (1- number-of-X-tics))))
19520 @end group
19521 @end smallexample
19522
19523 The line of numbers is equally straightforward:
19524
19525 @need 1250
19526 First, we create a numbered element with blank spaces before each number:
19527
19528 @findex X-axis-element
19529 @smallexample
19530 @group
19531 (defun X-axis-element (number)
19532 "Construct a numbered X axis element."
19533 (let ((leading-spaces
19534 (- (* symbol-width X-axis-label-spacing)
19535 (length (number-to-string number)))))
19536 (concat (make-string leading-spaces ? )
19537 (number-to-string number))))
19538 @end group
19539 @end smallexample
19540
19541 Next, we create the function to print the numbered line, starting with
19542 the number ``1'' under the first column:
19543
19544 @findex print-X-axis-numbered-line
19545 @smallexample
19546 @group
19547 (defun print-X-axis-numbered-line
19548 (number-of-X-tics X-axis-leading-spaces)
19549 "Print line of X-axis numbers"
19550 (let ((number X-axis-label-spacing))
19551 (insert X-axis-leading-spaces)
19552 (insert "1")
19553 @end group
19554 @group
19555 (insert (concat
19556 (make-string
19557 ;; @r{Insert white space up to next number.}
19558 (- (* symbol-width X-axis-label-spacing) 2)
19559 ? )
19560 (number-to-string number)))
19561 @end group
19562 @group
19563 ;; @r{Insert remaining numbers.}
19564 (setq number (+ number X-axis-label-spacing))
19565 (while (> number-of-X-tics 1)
19566 (insert (X-axis-element number))
19567 (setq number (+ number X-axis-label-spacing))
19568 (setq number-of-X-tics (1- number-of-X-tics)))))
19569 @end group
19570 @end smallexample
19571
19572 Finally, we need to write the @code{print-X-axis} that uses
19573 @code{print-X-axis-tic-line} and
19574 @code{print-X-axis-numbered-line}.
19575
19576 The function must determine the local values of the variables used by both
19577 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19578 then it must call them. Also, it must print the carriage return that
19579 separates the two lines.
19580
19581 The function consists of a varlist that specifies five local variables,
19582 and calls to each of the two line printing functions:
19583
19584 @findex print-X-axis
19585 @smallexample
19586 @group
19587 (defun print-X-axis (numbers-list)
19588 "Print X axis labels to length of NUMBERS-LIST."
19589 (let* ((leading-spaces
19590 (make-string full-Y-label-width ? ))
19591 @end group
19592 @group
19593 ;; symbol-width @r{is provided by} graph-body-print
19594 (tic-width (* symbol-width X-axis-label-spacing))
19595 (X-length (length numbers-list))
19596 @end group
19597 @group
19598 (X-tic
19599 (concat
19600 (make-string
19601 @end group
19602 @group
19603 ;; @r{Make a string of blanks.}
19604 (- (* symbol-width X-axis-label-spacing)
19605 (length X-axis-tic-symbol))
19606 ? )
19607 @end group
19608 @group
19609 ;; @r{Concatenate blanks with tic symbol.}
19610 X-axis-tic-symbol))
19611 @end group
19612 @group
19613 (tic-number
19614 (if (zerop (% X-length tic-width))
19615 (/ X-length tic-width)
19616 (1+ (/ X-length tic-width)))))
19617 @end group
19618 @group
19619 (print-X-axis-tic-line tic-number leading-spaces X-tic)
19620 (insert "\n")
19621 (print-X-axis-numbered-line tic-number leading-spaces)))
19622 @end group
19623 @end smallexample
19624
19625 @need 1250
19626 You can test @code{print-X-axis}:
19627
19628 @enumerate
19629 @item
19630 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19631 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19632 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19633
19634 @item
19635 Copy the following expression:
19636
19637 @smallexample
19638 @group
19639 (progn
19640 (let ((full-Y-label-width 5)
19641 (symbol-width 1))
19642 (print-X-axis
19643 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19644 @end group
19645 @end smallexample
19646
19647 @item
19648 Switch to the @file{*scratch*} buffer and place the cursor where you
19649 want the axis labels to start.
19650
19651 @item
19652 Type @kbd{M-:} (@code{eval-expression}).
19653
19654 @item
19655 Yank the test expression into the minibuffer
19656 with @kbd{C-y} (@code{yank)}.
19657
19658 @item
19659 Press @key{RET} to evaluate the expression.
19660 @end enumerate
19661
19662 @need 1250
19663 Emacs will print the horizontal axis like this:
19664
19665 @smallexample
19666 @group
19667 | | | | |
19668 1 5 10 15 20
19669 @end group
19670 @end smallexample
19671
19672 @node Print Whole Graph, , print-X-axis, Full Graph
19673 @appendixsec Printing the Whole Graph
19674 @cindex Printing the whole graph
19675 @cindex Whole graph printing
19676 @cindex Graph, printing all
19677
19678 Now we are nearly ready to print the whole graph.
19679
19680 The function to print the graph with the proper labels follows the
19681 outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19682 Axes}), but with additions.
19683
19684 @need 1250
19685 Here is the outline:
19686
19687 @smallexample
19688 @group
19689 (defun print-graph (numbers-list)
19690 "@var{documentation}@dots{}"
19691 (let ((height @dots{}
19692 @dots{}))
19693 @end group
19694 @group
19695 (print-Y-axis height @dots{} )
19696 (graph-body-print numbers-list)
19697 (print-X-axis @dots{} )))
19698 @end group
19699 @end smallexample
19700
19701 @menu
19702 * The final version:: A few changes.
19703 * Test print-graph:: Run a short test.
19704 * Graphing words in defuns:: Executing the final code.
19705 * lambda:: How to write an anonymous function.
19706 * mapcar:: Apply a function to elements of a list.
19707 * Another Bug:: Yet another bug @dots{} most insidious.
19708 * Final printed graph:: The graph itself!
19709 @end menu
19710
19711 @node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19712 @ifnottex
19713 @unnumberedsubsec Changes for the Final Version
19714 @end ifnottex
19715
19716 The final version is different from what we planned in two ways:
19717 first, it contains additional values calculated once in the varlist;
19718 second, it carries an option to specify the labels' increment per row.
19719 This latter feature turns out to be essential; otherwise, a graph may
19720 have more rows than fit on a display or on a sheet of paper.
19721
19722 @need 1500
19723 This new feature requires a change to the @code{Y-axis-column}
19724 function, to add @code{vertical-step} to it. The function looks like
19725 this:
19726
19727 @findex Y-axis-column @r{Final version.}
19728 @smallexample
19729 @group
19730 ;;; @r{Final version.}
19731 (defun Y-axis-column
19732 (height width-of-label &optional vertical-step)
19733 "Construct list of labels for Y axis.
19734 HEIGHT is maximum height of graph.
19735 WIDTH-OF-LABEL is maximum width of label.
19736 VERTICAL-STEP, an option, is a positive integer
19737 that specifies how much a Y axis label increments
19738 for each line. For example, a step of 5 means
19739 that each line is five units of the graph."
19740 @end group
19741 @group
19742 (let (Y-axis
19743 (number-per-line (or vertical-step 1)))
19744 (while (> height 1)
19745 (if (zerop (% height Y-axis-label-spacing))
19746 @end group
19747 @group
19748 ;; @r{Insert label.}
19749 (setq Y-axis
19750 (cons
19751 (Y-axis-element
19752 (* height number-per-line)
19753 width-of-label)
19754 Y-axis))
19755 @end group
19756 @group
19757 ;; @r{Else, insert blanks.}
19758 (setq Y-axis
19759 (cons
19760 (make-string width-of-label ? )
19761 Y-axis)))
19762 (setq height (1- height)))
19763 @end group
19764 @group
19765 ;; @r{Insert base line.}
19766 (setq Y-axis (cons (Y-axis-element
19767 (or vertical-step 1)
19768 width-of-label)
19769 Y-axis))
19770 (nreverse Y-axis)))
19771 @end group
19772 @end smallexample
19773
19774 The values for the maximum height of graph and the width of a symbol
19775 are computed by @code{print-graph} in its @code{let} expression; so
19776 @code{graph-body-print} must be changed to accept them.
19777
19778 @findex graph-body-print @r{Final version.}
19779 @smallexample
19780 @group
19781 ;;; @r{Final version.}
19782 (defun graph-body-print (numbers-list height symbol-width)
19783 "Print a bar graph of the NUMBERS-LIST.
19784 The numbers-list consists of the Y-axis values.
19785 HEIGHT is maximum height of graph.
19786 SYMBOL-WIDTH is number of each column."
19787 @end group
19788 @group
19789 (let (from-position)
19790 (while numbers-list
19791 (setq from-position (point))
19792 (insert-rectangle
19793 (column-of-graph height (car numbers-list)))
19794 (goto-char from-position)
19795 (forward-char symbol-width)
19796 @end group
19797 @group
19798 ;; @r{Draw graph column by column.}
19799 (sit-for 0)
19800 (setq numbers-list (cdr numbers-list)))
19801 ;; @r{Place point for X axis labels.}
19802 (forward-line height)
19803 (insert "\n")))
19804 @end group
19805 @end smallexample
19806
19807 @need 1250
19808 Finally, the code for the @code{print-graph} function:
19809
19810 @findex print-graph @r{Final version.}
19811 @smallexample
19812 @group
19813 ;;; @r{Final version.}
19814 (defun print-graph
19815 (numbers-list &optional vertical-step)
19816 "Print labelled bar graph of the NUMBERS-LIST.
19817 The numbers-list consists of the Y-axis values.
19818 @end group
19819
19820 @group
19821 Optionally, VERTICAL-STEP, a positive integer,
19822 specifies how much a Y axis label increments for
19823 each line. For example, a step of 5 means that
19824 each row is five units."
19825 @end group
19826 @group
19827 (let* ((symbol-width (length graph-blank))
19828 ;; @code{height} @r{is both the largest number}
19829 ;; @r{and the number with the most digits.}
19830 (height (apply 'max numbers-list))
19831 @end group
19832 @group
19833 (height-of-top-line
19834 (if (zerop (% height Y-axis-label-spacing))
19835 height
19836 ;; @r{else}
19837 (* (1+ (/ height Y-axis-label-spacing))
19838 Y-axis-label-spacing)))
19839 @end group
19840 @group
19841 (vertical-step (or vertical-step 1))
19842 (full-Y-label-width
19843 (length
19844 @end group
19845 @group
19846 (concat
19847 (number-to-string
19848 (* height-of-top-line vertical-step))
19849 Y-axis-tic))))
19850 @end group
19851
19852 @group
19853 (print-Y-axis
19854 height-of-top-line full-Y-label-width vertical-step)
19855 @end group
19856 @group
19857 (graph-body-print
19858 numbers-list height-of-top-line symbol-width)
19859 (print-X-axis numbers-list)))
19860 @end group
19861 @end smallexample
19862
19863 @node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
19864 @appendixsubsec Testing @code{print-graph}
19865
19866 @need 1250
19867 We can test the @code{print-graph} function with a short list of numbers:
19868
19869 @enumerate
19870 @item
19871 Install the final versions of @code{Y-axis-column},
19872 @code{graph-body-print}, and @code{print-graph} (in addition to the
19873 rest of the code.)
19874
19875 @item
19876 Copy the following expression:
19877
19878 @smallexample
19879 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
19880 @end smallexample
19881
19882 @item
19883 Switch to the @file{*scratch*} buffer and place the cursor where you
19884 want the axis labels to start.
19885
19886 @item
19887 Type @kbd{M-:} (@code{eval-expression}).
19888
19889 @item
19890 Yank the test expression into the minibuffer
19891 with @kbd{C-y} (@code{yank)}.
19892
19893 @item
19894 Press @key{RET} to evaluate the expression.
19895 @end enumerate
19896
19897 @need 1250
19898 Emacs will print a graph that looks like this:
19899
19900 @smallexample
19901 @group
19902 10 -
19903
19904
19905 *
19906 ** *
19907 5 - **** *
19908 **** ***
19909 * *********
19910 ************
19911 1 - *************
19912
19913 | | | |
19914 1 5 10 15
19915 @end group
19916 @end smallexample
19917
19918 On the other hand, if you pass @code{print-graph} a
19919 @code{vertical-step} value of 2, by evaluating this expression:
19920
19921 @smallexample
19922 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
19923 @end smallexample
19924
19925 @need 1250
19926 @noindent
19927 The graph looks like this:
19928
19929 @smallexample
19930 @group
19931 20 -
19932
19933
19934 *
19935 ** *
19936 10 - **** *
19937 **** ***
19938 * *********
19939 ************
19940 2 - *************
19941
19942 | | | |
19943 1 5 10 15
19944 @end group
19945 @end smallexample
19946
19947 @noindent
19948 (A question: is the `2' on the bottom of the vertical axis a bug or a
19949 feature? If you think it is a bug, and should be a `1' instead, (or
19950 even a `0'), you can modify the sources.)
19951
19952 @node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
19953 @appendixsubsec Graphing Numbers of Words and Symbols
19954
19955 Now for the graph for which all this code was written: a graph that
19956 shows how many function definitions contain fewer than 10 words and
19957 symbols, how many contain between 10 and 19 words and symbols, how
19958 many contain between 20 and 29 words and symbols, and so on.
19959
19960 This is a multi-step process. First make sure you have loaded all the
19961 requisite code.
19962
19963 @need 1500
19964 It is a good idea to reset the value of @code{top-of-ranges} in case
19965 you have set it to some different value. You can evaluate the
19966 following:
19967
19968 @smallexample
19969 @group
19970 (setq top-of-ranges
19971 '(10 20 30 40 50
19972 60 70 80 90 100
19973 110 120 130 140 150
19974 160 170 180 190 200
19975 210 220 230 240 250
19976 260 270 280 290 300)
19977 @end group
19978 @end smallexample
19979
19980 @noindent
19981 Next create a list of the number of words and symbols in each range.
19982
19983 @need 1500
19984 @noindent
19985 Evaluate the following:
19986
19987 @smallexample
19988 @group
19989 (setq list-for-graph
19990 (defuns-per-range
19991 (sort
19992 (recursive-lengths-list-many-files
19993 (directory-files "/usr/local/emacs/lisp"
19994 t ".+el$"))
19995 '<)
19996 top-of-ranges))
19997 @end group
19998 @end smallexample
19999
20000 @noindent
20001 On my machine, this takes about an hour. It looks though 303 Lisp
20002 files in my copy of Emacs version 19.23. After all that computing,
20003 the @code{list-for-graph} has this value:
20004
20005 @smallexample
20006 @group
20007 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20008 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20009 @end group
20010 @end smallexample
20011
20012 @noindent
20013 This means that my copy of Emacs has 537 function definitions with
20014 fewer than 10 words or symbols in them, 1,027 function definitions
20015 with 10 to 19 words or symbols in them, 955 function definitions with
20016 20 to 29 words or symbols in them, and so on.
20017
20018 Clearly, just by looking at this list we can see that most function
20019 definitions contain ten to thirty words and symbols.
20020
20021 Now for printing. We do @emph{not} want to print a graph that is
20022 1,030 lines high @dots{} Instead, we should print a graph that is
20023 fewer than twenty-five lines high. A graph that height can be
20024 displayed on almost any monitor, and easily printed on a sheet of paper.
20025
20026 This means that each value in @code{list-for-graph} must be reduced to
20027 one-fiftieth its present value.
20028
20029 Here is a short function to do just that, using two functions we have
20030 not yet seen, @code{mapcar} and @code{lambda}.
20031
20032 @smallexample
20033 @group
20034 (defun one-fiftieth (full-range)
20035 "Return list, each number one-fiftieth of previous."
20036 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20037 @end group
20038 @end smallexample
20039
20040 @node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20041 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20042 @cindex Anonymous function
20043 @findex lambda
20044
20045 @code{lambda} is the symbol for an anonymous function, a function
20046 without a name. Every time you use an anonymous function, you need to
20047 include its whole body.
20048
20049 @need 1250
20050 @noindent
20051 Thus,
20052
20053 @smallexample
20054 (lambda (arg) (/ arg 50))
20055 @end smallexample
20056
20057 @noindent
20058 is a function definition that says `return the value resulting from
20059 dividing whatever is passed to me as @code{arg} by 50'.
20060
20061 Earlier, for example, we had a function @code{multiply-by-seven}; it
20062 multiplied its argument by 7. This function is similar, except it
20063 divides its argument by 50; and, it has no name. The anonymous
20064 equivalent of @code{multiply-by-seven} is:
20065
20066 @smallexample
20067 (lambda (number) (* 7 number))
20068 @end smallexample
20069
20070 @noindent
20071 (@xref{defun, , The @code{defun} Special Form}.)
20072
20073 @need 1250
20074 @noindent
20075 If we want to multiply 3 by 7, we can write:
20076
20077 @c !!! Clear print-postscript-figures if the computer formatting this
20078 @c document is too small and cannot handle all the diagrams and figures.
20079 @c clear print-postscript-figures
20080 @c set print-postscript-figures
20081 @c lambda example diagram #1
20082 @ifnottex
20083 @smallexample
20084 @group
20085 (multiply-by-seven 3)
20086 \_______________/ ^
20087 | |
20088 function argument
20089 @end group
20090 @end smallexample
20091 @end ifnottex
20092 @ifset print-postscript-figures
20093 @sp 1
20094 @tex
20095 @image{lambda-1}
20096 %%%% old method of including an image
20097 % \input /usr/local/lib/tex/inputs/psfig.tex
20098 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20099 % \catcode`\@=0 %
20100 @end tex
20101 @sp 1
20102 @end ifset
20103 @ifclear print-postscript-figures
20104 @iftex
20105 @smallexample
20106 @group
20107 (multiply-by-seven 3)
20108 \_______________/ ^
20109 | |
20110 function argument
20111 @end group
20112 @end smallexample
20113 @end iftex
20114 @end ifclear
20115
20116 @noindent
20117 This expression returns 21.
20118
20119 @need 1250
20120 @noindent
20121 Similarly, we can write:
20122
20123 @c lambda example diagram #2
20124 @ifnottex
20125 @smallexample
20126 @group
20127 ((lambda (number) (* 7 number)) 3)
20128 \____________________________/ ^
20129 | |
20130 anonymous function argument
20131 @end group
20132 @end smallexample
20133 @end ifnottex
20134 @ifset print-postscript-figures
20135 @sp 1
20136 @tex
20137 @image{lambda-2}
20138 %%%% old method of including an image
20139 % \input /usr/local/lib/tex/inputs/psfig.tex
20140 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20141 % \catcode`\@=0 %
20142 @end tex
20143 @sp 1
20144 @end ifset
20145 @ifclear print-postscript-figures
20146 @iftex
20147 @smallexample
20148 @group
20149 ((lambda (number) (* 7 number)) 3)
20150 \____________________________/ ^
20151 | |
20152 anonymous function argument
20153 @end group
20154 @end smallexample
20155 @end iftex
20156 @end ifclear
20157
20158 @need 1250
20159 @noindent
20160 If we want to divide 100 by 50, we can write:
20161
20162 @c lambda example diagram #3
20163 @ifnottex
20164 @smallexample
20165 @group
20166 ((lambda (arg) (/ arg 50)) 100)
20167 \______________________/ \_/
20168 | |
20169 anonymous function argument
20170 @end group
20171 @end smallexample
20172 @end ifnottex
20173 @ifset print-postscript-figures
20174 @sp 1
20175 @tex
20176 @image{lambda-3}
20177 %%%% old method of including an image
20178 % \input /usr/local/lib/tex/inputs/psfig.tex
20179 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20180 % \catcode`\@=0 %
20181 @end tex
20182 @sp 1
20183 @end ifset
20184 @ifclear print-postscript-figures
20185 @iftex
20186 @smallexample
20187 @group
20188 ((lambda (arg) (/ arg 50)) 100)
20189 \______________________/ \_/
20190 | |
20191 anonymous function argument
20192 @end group
20193 @end smallexample
20194 @end iftex
20195 @end ifclear
20196
20197 @noindent
20198 This expression returns 2. The 100 is passed to the function, which
20199 divides that number by 50.
20200
20201 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20202 Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
20203 expressions derive from the Lambda Calculus.
20204
20205 @node mapcar, Another Bug, lambda, Print Whole Graph
20206 @appendixsubsec The @code{mapcar} Function
20207 @findex mapcar
20208
20209 @code{mapcar} is a function that calls its first argument with each
20210 element of its second argument, in turn. The second argument must be
20211 a sequence.
20212
20213 The @samp{map} part of the name comes from the mathematical phrase,
20214 `mapping over a domain', meaning to apply a function to each of the
20215 elements in a domain. The mathematical phrase is based on the
20216 metaphor of a surveyor walking, one step at a time, over an area he is
20217 mapping. And @samp{car}, of course, comes from the Lisp notion of the
20218 first of a list.
20219
20220 @need 1250
20221 @noindent
20222 For example,
20223
20224 @smallexample
20225 @group
20226 (mapcar '1+ '(2 4 6))
20227 @result{} (3 5 7)
20228 @end group
20229 @end smallexample
20230
20231 @noindent
20232 The function @code{1+} which adds one to its argument, is executed on
20233 @emph{each} element of the list, and a new list is returned.
20234
20235 Contrast this with @code{apply}, which applies its first argument to
20236 all the remaining.
20237 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20238 @code{apply}.)
20239
20240 @need 1250
20241 In the definition of @code{one-fiftieth}, the first argument is the
20242 anonymous function:
20243
20244 @smallexample
20245 (lambda (arg) (/ arg 50))
20246 @end smallexample
20247
20248 @noindent
20249 and the second argument is @code{full-range}, which will be bound to
20250 @code{list-for-graph}.
20251
20252 @need 1250
20253 The whole expression looks like this:
20254
20255 @smallexample
20256 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20257 @end smallexample
20258
20259 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20260 Lisp Reference Manual}, for more about @code{mapcar}.
20261
20262 Using the @code{one-fiftieth} function, we can generate a list in
20263 which each element is one-fiftieth the size of the corresponding
20264 element in @code{list-for-graph}.
20265
20266 @smallexample
20267 @group
20268 (setq fiftieth-list-for-graph
20269 (one-fiftieth list-for-graph))
20270 @end group
20271 @end smallexample
20272
20273 @need 1250
20274 The resulting list looks like this:
20275
20276 @smallexample
20277 @group
20278 (10 20 19 15 11 9 6 5 4 3 3 2 2
20279 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20280 @end group
20281 @end smallexample
20282
20283 @noindent
20284 This, we are almost ready to print! (We also notice the loss of
20285 information: many of the higher ranges are 0, meaning that fewer than
20286 50 defuns had that many words or symbols---but not necessarily meaning
20287 that none had that many words or symbols.)
20288
20289 @node Another Bug, Final printed graph, mapcar, Print Whole Graph
20290 @appendixsubsec Another Bug @dots{} Most Insidious
20291 @cindex Bug, most insidious type
20292 @cindex Insidious type of bug
20293
20294 I said `almost ready to print'! Of course, there is a bug in the
20295 @code{print-graph} function @dots{} It has a @code{vertical-step}
20296 option, but not a @code{horizontal-step} option. The
20297 @code{top-of-range} scale goes from 10 to 300 by tens. But the
20298 @code{print-graph} function will print only by ones.
20299
20300 This is a classic example of what some consider the most insidious
20301 type of bug, the bug of omission. This is not the kind of bug you can
20302 find by studying the code, for it is not in the code; it is an omitted
20303 feature. Your best actions are to try your program early and often;
20304 and try to arrange, as much as you can, to write code that is easy to
20305 understand and easy to change. Try to be aware, whenever you can,
20306 that whatever you have written, @emph{will} be rewritten, if not soon,
20307 eventually. A hard maxim to follow.
20308
20309 It is the @code{print-X-axis-numbered-line} function that needs the
20310 work; and then the @code{print-X-axis} and the @code{print-graph}
20311 functions need to be adapted. Not much needs to be done; there is one
20312 nicety: the numbers ought to line up under the tic marks. This takes
20313 a little thought.
20314
20315 @need 1250
20316 Here is the corrected @code{print-X-axis-numbered-line}:
20317
20318 @smallexample
20319 @group
20320 (defun print-X-axis-numbered-line
20321 (number-of-X-tics X-axis-leading-spaces
20322 &optional horizontal-step)
20323 "Print line of X-axis numbers"
20324 (let ((number X-axis-label-spacing)
20325 (horizontal-step (or horizontal-step 1)))
20326 @end group
20327 @group
20328 (insert X-axis-leading-spaces)
20329 ;; @r{Delete extra leading spaces.}
20330 (delete-char
20331 (- (1-
20332 (length (number-to-string horizontal-step)))))
20333 (insert (concat
20334 (make-string
20335 @end group
20336 @group
20337 ;; @r{Insert white space.}
20338 (- (* symbol-width
20339 X-axis-label-spacing)
20340 (1-
20341 (length
20342 (number-to-string horizontal-step)))
20343 2)
20344 ? )
20345 (number-to-string
20346 (* number horizontal-step))))
20347 @end group
20348 @group
20349 ;; @r{Insert remaining numbers.}
20350 (setq number (+ number X-axis-label-spacing))
20351 (while (> number-of-X-tics 1)
20352 (insert (X-axis-element
20353 (* number horizontal-step)))
20354 (setq number (+ number X-axis-label-spacing))
20355 (setq number-of-X-tics (1- number-of-X-tics)))))
20356 @end group
20357 @end smallexample
20358
20359 @need 1500
20360 If you are reading this in Info, you can see the new versions of
20361 @code{print-X-axis} @code{print-graph} and evaluate them. If you are
20362 reading this in a printed book, you can see the changed lines here
20363 (the full text is too much to print).
20364
20365 @iftex
20366 @smallexample
20367 @group
20368 (defun print-X-axis (numbers-list horizontal-step)
20369 @dots{}
20370 (print-X-axis-numbered-line
20371 tic-number leading-spaces horizontal-step))
20372 @end group
20373 @end smallexample
20374
20375 @smallexample
20376 @group
20377 (defun print-graph
20378 (numbers-list
20379 &optional vertical-step horizontal-step)
20380 @dots{}
20381 (print-X-axis numbers-list horizontal-step))
20382 @end group
20383 @end smallexample
20384 @end iftex
20385
20386 @ifnottex
20387 @smallexample
20388 @group
20389 (defun print-X-axis (numbers-list horizontal-step)
20390 "Print X axis labels to length of NUMBERS-LIST.
20391 Optionally, HORIZONTAL-STEP, a positive integer,
20392 specifies how much an X axis label increments for
20393 each column."
20394 @end group
20395 @group
20396 ;; Value of symbol-width and full-Y-label-width
20397 ;; are passed by `print-graph'.
20398 (let* ((leading-spaces
20399 (make-string full-Y-label-width ? ))
20400 ;; symbol-width @r{is provided by} graph-body-print
20401 (tic-width (* symbol-width X-axis-label-spacing))
20402 (X-length (length numbers-list))
20403 @end group
20404 @group
20405 (X-tic
20406 (concat
20407 (make-string
20408 ;; @r{Make a string of blanks.}
20409 (- (* symbol-width X-axis-label-spacing)
20410 (length X-axis-tic-symbol))
20411 ? )
20412 @end group
20413 @group
20414 ;; @r{Concatenate blanks with tic symbol.}
20415 X-axis-tic-symbol))
20416 (tic-number
20417 (if (zerop (% X-length tic-width))
20418 (/ X-length tic-width)
20419 (1+ (/ X-length tic-width)))))
20420 @end group
20421
20422 @group
20423 (print-X-axis-tic-line
20424 tic-number leading-spaces X-tic)
20425 (insert "\n")
20426 (print-X-axis-numbered-line
20427 tic-number leading-spaces horizontal-step)))
20428 @end group
20429 @end smallexample
20430
20431 @smallexample
20432 @group
20433 (defun print-graph
20434 (numbers-list &optional vertical-step horizontal-step)
20435 "Print labelled bar graph of the NUMBERS-LIST.
20436 The numbers-list consists of the Y-axis values.
20437 @end group
20438
20439 @group
20440 Optionally, VERTICAL-STEP, a positive integer,
20441 specifies how much a Y axis label increments for
20442 each line. For example, a step of 5 means that
20443 each row is five units.
20444 @end group
20445
20446 @group
20447 Optionally, HORIZONTAL-STEP, a positive integer,
20448 specifies how much an X axis label increments for
20449 each column."
20450 (let* ((symbol-width (length graph-blank))
20451 ;; @code{height} @r{is both the largest number}
20452 ;; @r{and the number with the most digits.}
20453 (height (apply 'max numbers-list))
20454 @end group
20455 @group
20456 (height-of-top-line
20457 (if (zerop (% height Y-axis-label-spacing))
20458 height
20459 ;; @r{else}
20460 (* (1+ (/ height Y-axis-label-spacing))
20461 Y-axis-label-spacing)))
20462 @end group
20463 @group
20464 (vertical-step (or vertical-step 1))
20465 (full-Y-label-width
20466 (length
20467 (concat
20468 (number-to-string
20469 (* height-of-top-line vertical-step))
20470 Y-axis-tic))))
20471 @end group
20472 @group
20473 (print-Y-axis
20474 height-of-top-line full-Y-label-width vertical-step)
20475 (graph-body-print
20476 numbers-list height-of-top-line symbol-width)
20477 (print-X-axis numbers-list horizontal-step)))
20478 @end group
20479 @end smallexample
20480 @end ifnottex
20481
20482 @ignore
20483 Graphing Definitions Re-listed
20484
20485 @need 1250
20486 Here are all the graphing definitions in their final form:
20487
20488 @smallexample
20489 @group
20490 (defvar top-of-ranges
20491 '(10 20 30 40 50
20492 60 70 80 90 100
20493 110 120 130 140 150
20494 160 170 180 190 200
20495 210 220 230 240 250)
20496 "List specifying ranges for `defuns-per-range'.")
20497 @end group
20498
20499 @group
20500 (defvar graph-symbol "*"
20501 "String used as symbol in graph, usually an asterisk.")
20502 @end group
20503
20504 @group
20505 (defvar graph-blank " "
20506 "String used as blank in graph, usually a blank space.
20507 graph-blank must be the same number of columns wide
20508 as graph-symbol.")
20509 @end group
20510
20511 @group
20512 (defvar Y-axis-tic " - "
20513 "String that follows number in a Y axis label.")
20514 @end group
20515
20516 @group
20517 (defvar Y-axis-label-spacing 5
20518 "Number of lines from one Y axis label to next.")
20519 @end group
20520
20521 @group
20522 (defvar X-axis-tic-symbol "|"
20523 "String to insert to point to a column in X axis.")
20524 @end group
20525
20526 @group
20527 (defvar X-axis-label-spacing
20528 (if (boundp 'graph-blank)
20529 (* 5 (length graph-blank)) 5)
20530 "Number of units from one X axis label to next.")
20531 @end group
20532 @end smallexample
20533
20534 @smallexample
20535 @group
20536 (defun count-words-in-defun ()
20537 "Return the number of words and symbols in a defun."
20538 (beginning-of-defun)
20539 (let ((count 0)
20540 (end (save-excursion (end-of-defun) (point))))
20541 @end group
20542
20543 @group
20544 (while
20545 (and (< (point) end)
20546 (re-search-forward
20547 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20548 end t))
20549 (setq count (1+ count)))
20550 count))
20551 @end group
20552 @end smallexample
20553
20554 @smallexample
20555 @group
20556 (defun lengths-list-file (filename)
20557 "Return list of definitions' lengths within FILE.
20558 The returned list is a list of numbers.
20559 Each number is the number of words or
20560 symbols in one function definition."
20561 @end group
20562
20563 @group
20564 (message "Working on `%s' ... " filename)
20565 (save-excursion
20566 (let ((buffer (find-file-noselect filename))
20567 (lengths-list))
20568 (set-buffer buffer)
20569 (setq buffer-read-only t)
20570 (widen)
20571 (goto-char (point-min))
20572 @end group
20573
20574 @group
20575 (while (re-search-forward "^(defun" nil t)
20576 (setq lengths-list
20577 (cons (count-words-in-defun) lengths-list)))
20578 (kill-buffer buffer)
20579 lengths-list)))
20580 @end group
20581 @end smallexample
20582
20583 @smallexample
20584 @group
20585 (defun lengths-list-many-files (list-of-files)
20586 "Return list of lengths of defuns in LIST-OF-FILES."
20587 (let (lengths-list)
20588 ;;; @r{true-or-false-test}
20589 (while list-of-files
20590 (setq lengths-list
20591 (append
20592 lengths-list
20593 @end group
20594 @group
20595 ;;; @r{Generate a lengths' list.}
20596 (lengths-list-file
20597 (expand-file-name (car list-of-files)))))
20598 ;;; @r{Make files' list shorter.}
20599 (setq list-of-files (cdr list-of-files)))
20600 ;;; @r{Return final value of lengths' list.}
20601 lengths-list))
20602 @end group
20603 @end smallexample
20604
20605 @smallexample
20606 @group
20607 (defun defuns-per-range (sorted-lengths top-of-ranges)
20608 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20609 (let ((top-of-range (car top-of-ranges))
20610 (number-within-range 0)
20611 defuns-per-range-list)
20612 @end group
20613
20614 @group
20615 ;; @r{Outer loop.}
20616 (while top-of-ranges
20617
20618 ;; @r{Inner loop.}
20619 (while (and
20620 ;; @r{Need number for numeric test.}
20621 (car sorted-lengths)
20622 (< (car sorted-lengths) top-of-range))
20623
20624 ;; @r{Count number of definitions within current range.}
20625 (setq number-within-range (1+ number-within-range))
20626 (setq sorted-lengths (cdr sorted-lengths)))
20627 @end group
20628
20629 @group
20630 ;; @r{Exit inner loop but remain within outer loop.}
20631
20632 (setq defuns-per-range-list
20633 (cons number-within-range defuns-per-range-list))
20634 (setq number-within-range 0) ; @r{Reset count to zero.}
20635
20636 ;; @r{Move to next range.}
20637 (setq top-of-ranges (cdr top-of-ranges))
20638 ;; @r{Specify next top of range value.}
20639 (setq top-of-range (car top-of-ranges)))
20640 @end group
20641
20642 @group
20643 ;; @r{Exit outer loop and count the number of defuns larger than}
20644 ;; @r{ the largest top-of-range value.}
20645 (setq defuns-per-range-list
20646 (cons
20647 (length sorted-lengths)
20648 defuns-per-range-list))
20649
20650 ;; @r{Return a list of the number of definitions within each range,}
20651 ;; @r{ smallest to largest.}
20652 (nreverse defuns-per-range-list)))
20653 @end group
20654 @end smallexample
20655
20656 @smallexample
20657 @group
20658 (defun column-of-graph (max-graph-height actual-height)
20659 "Return list of MAX-GRAPH-HEIGHT strings;
20660 ACTUAL-HEIGHT are graph-symbols.
20661 The graph-symbols are contiguous entries at the end
20662 of the list.
20663 The list will be inserted as one column of a graph.
20664 The strings are either graph-blank or graph-symbol."
20665 @end group
20666
20667 @group
20668 (let ((insert-list nil)
20669 (number-of-top-blanks
20670 (- max-graph-height actual-height)))
20671
20672 ;; @r{Fill in @code{graph-symbols}.}
20673 (while (> actual-height 0)
20674 (setq insert-list (cons graph-symbol insert-list))
20675 (setq actual-height (1- actual-height)))
20676 @end group
20677
20678 @group
20679 ;; @r{Fill in @code{graph-blanks}.}
20680 (while (> number-of-top-blanks 0)
20681 (setq insert-list (cons graph-blank insert-list))
20682 (setq number-of-top-blanks
20683 (1- number-of-top-blanks)))
20684
20685 ;; @r{Return whole list.}
20686 insert-list))
20687 @end group
20688 @end smallexample
20689
20690 @smallexample
20691 @group
20692 (defun Y-axis-element (number full-Y-label-width)
20693 "Construct a NUMBERed label element.
20694 A numbered element looks like this ` 5 - ',
20695 and is padded as needed so all line up with
20696 the element for the largest number."
20697 @end group
20698 @group
20699 (let* ((leading-spaces
20700 (- full-Y-label-width
20701 (length
20702 (concat (number-to-string number)
20703 Y-axis-tic)))))
20704 @end group
20705 @group
20706 (concat
20707 (make-string leading-spaces ? )
20708 (number-to-string number)
20709 Y-axis-tic)))
20710 @end group
20711 @end smallexample
20712
20713 @smallexample
20714 @group
20715 (defun print-Y-axis
20716 (height full-Y-label-width &optional vertical-step)
20717 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20718 Height must be the maximum height of the graph.
20719 Full width is the width of the highest label element.
20720 Optionally, print according to VERTICAL-STEP."
20721 @end group
20722 @group
20723 ;; Value of height and full-Y-label-width
20724 ;; are passed by `print-graph'.
20725 (let ((start (point)))
20726 (insert-rectangle
20727 (Y-axis-column height full-Y-label-width vertical-step))
20728 @end group
20729 @group
20730 ;; @r{Place point ready for inserting graph.}
20731 (goto-char start)
20732 ;; @r{Move point forward by value of} full-Y-label-width
20733 (forward-char full-Y-label-width)))
20734 @end group
20735 @end smallexample
20736
20737 @smallexample
20738 @group
20739 (defun print-X-axis-tic-line
20740 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20741 "Print tics for X axis."
20742 (insert X-axis-leading-spaces)
20743 (insert X-axis-tic-symbol) ; @r{Under first column.}
20744 @end group
20745 @group
20746 ;; @r{Insert second tic in the right spot.}
20747 (insert (concat
20748 (make-string
20749 (- (* symbol-width X-axis-label-spacing)
20750 ;; @r{Insert white space up to second tic symbol.}
20751 (* 2 (length X-axis-tic-symbol)))
20752 ? )
20753 X-axis-tic-symbol))
20754 @end group
20755 @group
20756 ;; @r{Insert remaining tics.}
20757 (while (> number-of-X-tics 1)
20758 (insert X-axis-tic-element)
20759 (setq number-of-X-tics (1- number-of-X-tics))))
20760 @end group
20761 @end smallexample
20762
20763 @smallexample
20764 @group
20765 (defun X-axis-element (number)
20766 "Construct a numbered X axis element."
20767 (let ((leading-spaces
20768 (- (* symbol-width X-axis-label-spacing)
20769 (length (number-to-string number)))))
20770 (concat (make-string leading-spaces ? )
20771 (number-to-string number))))
20772 @end group
20773 @end smallexample
20774
20775 @smallexample
20776 @group
20777 (defun graph-body-print (numbers-list height symbol-width)
20778 "Print a bar graph of the NUMBERS-LIST.
20779 The numbers-list consists of the Y-axis values.
20780 HEIGHT is maximum height of graph.
20781 SYMBOL-WIDTH is number of each column."
20782 @end group
20783 @group
20784 (let (from-position)
20785 (while numbers-list
20786 (setq from-position (point))
20787 (insert-rectangle
20788 (column-of-graph height (car numbers-list)))
20789 (goto-char from-position)
20790 (forward-char symbol-width)
20791 @end group
20792 @group
20793 ;; @r{Draw graph column by column.}
20794 (sit-for 0)
20795 (setq numbers-list (cdr numbers-list)))
20796 ;; @r{Place point for X axis labels.}
20797 (forward-line height)
20798 (insert "\n")))
20799 @end group
20800 @end smallexample
20801
20802 @smallexample
20803 @group
20804 (defun Y-axis-column
20805 (height width-of-label &optional vertical-step)
20806 "Construct list of labels for Y axis.
20807 HEIGHT is maximum height of graph.
20808 WIDTH-OF-LABEL is maximum width of label.
20809 @end group
20810 @group
20811 VERTICAL-STEP, an option, is a positive integer
20812 that specifies how much a Y axis label increments
20813 for each line. For example, a step of 5 means
20814 that each line is five units of the graph."
20815 (let (Y-axis
20816 (number-per-line (or vertical-step 1)))
20817 @end group
20818 @group
20819 (while (> height 1)
20820 (if (zerop (% height Y-axis-label-spacing))
20821 ;; @r{Insert label.}
20822 (setq Y-axis
20823 (cons
20824 (Y-axis-element
20825 (* height number-per-line)
20826 width-of-label)
20827 Y-axis))
20828 @end group
20829 @group
20830 ;; @r{Else, insert blanks.}
20831 (setq Y-axis
20832 (cons
20833 (make-string width-of-label ? )
20834 Y-axis)))
20835 (setq height (1- height)))
20836 @end group
20837 @group
20838 ;; @r{Insert base line.}
20839 (setq Y-axis (cons (Y-axis-element
20840 (or vertical-step 1)
20841 width-of-label)
20842 Y-axis))
20843 (nreverse Y-axis)))
20844 @end group
20845 @end smallexample
20846
20847 @smallexample
20848 @group
20849 (defun print-X-axis-numbered-line
20850 (number-of-X-tics X-axis-leading-spaces
20851 &optional horizontal-step)
20852 "Print line of X-axis numbers"
20853 (let ((number X-axis-label-spacing)
20854 (horizontal-step (or horizontal-step 1)))
20855 @end group
20856 @group
20857 (insert X-axis-leading-spaces)
20858 ;; line up number
20859 (delete-char (- (1- (length (number-to-string horizontal-step)))))
20860 (insert (concat
20861 (make-string
20862 ;; @r{Insert white space up to next number.}
20863 (- (* symbol-width X-axis-label-spacing)
20864 (1- (length (number-to-string horizontal-step)))
20865 2)
20866 ? )
20867 (number-to-string (* number horizontal-step))))
20868 @end group
20869 @group
20870 ;; @r{Insert remaining numbers.}
20871 (setq number (+ number X-axis-label-spacing))
20872 (while (> number-of-X-tics 1)
20873 (insert (X-axis-element (* number horizontal-step)))
20874 (setq number (+ number X-axis-label-spacing))
20875 (setq number-of-X-tics (1- number-of-X-tics)))))
20876 @end group
20877 @end smallexample
20878
20879 @smallexample
20880 @group
20881 (defun print-X-axis (numbers-list horizontal-step)
20882 "Print X axis labels to length of NUMBERS-LIST.
20883 Optionally, HORIZONTAL-STEP, a positive integer,
20884 specifies how much an X axis label increments for
20885 each column."
20886 @end group
20887 @group
20888 ;; Value of symbol-width and full-Y-label-width
20889 ;; are passed by `print-graph'.
20890 (let* ((leading-spaces
20891 (make-string full-Y-label-width ? ))
20892 ;; symbol-width @r{is provided by} graph-body-print
20893 (tic-width (* symbol-width X-axis-label-spacing))
20894 (X-length (length numbers-list))
20895 @end group
20896 @group
20897 (X-tic
20898 (concat
20899 (make-string
20900 ;; @r{Make a string of blanks.}
20901 (- (* symbol-width X-axis-label-spacing)
20902 (length X-axis-tic-symbol))
20903 ? )
20904 @end group
20905 @group
20906 ;; @r{Concatenate blanks with tic symbol.}
20907 X-axis-tic-symbol))
20908 (tic-number
20909 (if (zerop (% X-length tic-width))
20910 (/ X-length tic-width)
20911 (1+ (/ X-length tic-width)))))
20912 @end group
20913
20914 @group
20915 (print-X-axis-tic-line
20916 tic-number leading-spaces X-tic)
20917 (insert "\n")
20918 (print-X-axis-numbered-line
20919 tic-number leading-spaces horizontal-step)))
20920 @end group
20921 @end smallexample
20922
20923 @smallexample
20924 @group
20925 (defun one-fiftieth (full-range)
20926 "Return list, each number of which is 1/50th previous."
20927 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20928 @end group
20929 @end smallexample
20930
20931 @smallexample
20932 @group
20933 (defun print-graph
20934 (numbers-list &optional vertical-step horizontal-step)
20935 "Print labelled bar graph of the NUMBERS-LIST.
20936 The numbers-list consists of the Y-axis values.
20937 @end group
20938
20939 @group
20940 Optionally, VERTICAL-STEP, a positive integer,
20941 specifies how much a Y axis label increments for
20942 each line. For example, a step of 5 means that
20943 each row is five units.
20944 @end group
20945
20946 @group
20947 Optionally, HORIZONTAL-STEP, a positive integer,
20948 specifies how much an X axis label increments for
20949 each column."
20950 (let* ((symbol-width (length graph-blank))
20951 ;; @code{height} @r{is both the largest number}
20952 ;; @r{and the number with the most digits.}
20953 (height (apply 'max numbers-list))
20954 @end group
20955 @group
20956 (height-of-top-line
20957 (if (zerop (% height Y-axis-label-spacing))
20958 height
20959 ;; @r{else}
20960 (* (1+ (/ height Y-axis-label-spacing))
20961 Y-axis-label-spacing)))
20962 @end group
20963 @group
20964 (vertical-step (or vertical-step 1))
20965 (full-Y-label-width
20966 (length
20967 (concat
20968 (number-to-string
20969 (* height-of-top-line vertical-step))
20970 Y-axis-tic))))
20971 @end group
20972 @group
20973
20974 (print-Y-axis
20975 height-of-top-line full-Y-label-width vertical-step)
20976 (graph-body-print
20977 numbers-list height-of-top-line symbol-width)
20978 (print-X-axis numbers-list horizontal-step)))
20979 @end group
20980 @end smallexample
20981 @end ignore
20982
20983 @page
20984 @node Final printed graph, , Another Bug, Print Whole Graph
20985 @appendixsubsec The Printed Graph
20986
20987 When made and installed, you can call the @code{print-graph} command
20988 like this:
20989
20990 @smallexample
20991 @group
20992 (print-graph fiftieth-list-for-graph 50 10)
20993 @end group
20994 @end smallexample
20995
20996 Here is the graph:
20997
20998 @sp 2
20999
21000 @smallexample
21001 @group
21002 1000 - *
21003 **
21004 **
21005 **
21006 **
21007 750 - ***
21008 ***
21009 ***
21010 ***
21011 ****
21012 500 - *****
21013 ******
21014 ******
21015 ******
21016 *******
21017 250 - ********
21018 ********* *
21019 *********** *
21020 ************* *
21021 50 - ***************** * *
21022 | | | | | | | |
21023 10 50 100 150 200 250 300 350
21024 @end group
21025 @end smallexample
21026
21027 @sp 2
21028
21029 The largest group of functions contain 10 -- 19 words and symbols each.
21030
21031 @node GNU Free Documentation License, Index, Full Graph, Top
21032 @appendix GNU Free Documentation License
21033
21034 @cindex FDL, GNU Free Documentation License
21035 @center Version 1.1, March 2000
21036
21037 @display
21038 Copyright @copyright{} 2000 Free Software Foundation, Inc.
21039 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
21040
21041 Everyone is permitted to copy and distribute verbatim copies
21042 of this license document, but changing it is not allowed.
21043 @end display
21044
21045 @enumerate 0
21046 @item
21047 PREAMBLE
21048
21049 The purpose of this License is to make a manual, textbook, or other
21050 written document @dfn{free} in the sense of freedom: to assure everyone
21051 the effective freedom to copy and redistribute it, with or without
21052 modifying it, either commercially or noncommercially. Secondarily,
21053 this License preserves for the author and publisher a way to get
21054 credit for their work, while not being considered responsible for
21055 modifications made by others.
21056
21057 This License is a kind of ``copyleft'', which means that derivative
21058 works of the document must themselves be free in the same sense. It
21059 complements the GNU General Public License, which is a copyleft
21060 license designed for free software.
21061
21062 We have designed this License in order to use it for manuals for free
21063 software, because free software needs free documentation: a free
21064 program should come with manuals providing the same freedoms that the
21065 software does. But this License is not limited to software manuals;
21066 it can be used for any textual work, regardless of subject matter or
21067 whether it is published as a printed book. We recommend this License
21068 principally for works whose purpose is instruction or reference.
21069
21070 @item
21071 APPLICABILITY AND DEFINITIONS
21072
21073 This License applies to any manual or other work that contains a
21074 notice placed by the copyright holder saying it can be distributed
21075 under the terms of this License. The ``Document'', below, refers to any
21076 such manual or work. Any member of the public is a licensee, and is
21077 addressed as ``you''.
21078
21079 A ``Modified Version'' of the Document means any work containing the
21080 Document or a portion of it, either copied verbatim, or with
21081 modifications and/or translated into another language.
21082
21083 A ``Secondary Section'' is a named appendix or a front-matter section of
21084 the Document that deals exclusively with the relationship of the
21085 publishers or authors of the Document to the Document's overall subject
21086 (or to related matters) and contains nothing that could fall directly
21087 within that overall subject. (For example, if the Document is in part a
21088 textbook of mathematics, a Secondary Section may not explain any
21089 mathematics.) The relationship could be a matter of historical
21090 connection with the subject or with related matters, or of legal,
21091 commercial, philosophical, ethical or political position regarding
21092 them.
21093
21094 The ``Invariant Sections'' are certain Secondary Sections whose titles
21095 are designated, as being those of Invariant Sections, in the notice
21096 that says that the Document is released under this License.
21097
21098 The ``Cover Texts'' are certain short passages of text that are listed,
21099 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
21100 the Document is released under this License.
21101
21102 A ``Transparent'' copy of the Document means a machine-readable copy,
21103 represented in a format whose specification is available to the
21104 general public, whose contents can be viewed and edited directly and
21105 straightforwardly with generic text editors or (for images composed of
21106 pixels) generic paint programs or (for drawings) some widely available
21107 drawing editor, and that is suitable for input to text formatters or
21108 for automatic translation to a variety of formats suitable for input
21109 to text formatters. A copy made in an otherwise Transparent file
21110 format whose markup has been designed to thwart or discourage
21111 subsequent modification by readers is not Transparent. A copy that is
21112 not ``Transparent'' is called ``Opaque''.
21113
21114 Examples of suitable formats for Transparent copies include plain
21115 @sc{ascii} without markup, Texinfo input format, La@TeX{} input format,
21116 @acronym{SGML} or @acronym{XML} using a publicly available
21117 @acronym{DTD}, and standard-conforming simple @acronym{HTML} designed
21118 for human modification. Opaque formats include PostScript,
21119 @acronym{PDF}, proprietary formats that can be read and edited only by
21120 proprietary word processors, @acronym{SGML} or @acronym{XML} for which
21121 the @acronym{DTD} and/or processing tools are not generally available,
21122 and the machine-generated @acronym{HTML} produced by some word
21123 processors for output purposes only.
21124
21125 The ``Title Page'' means, for a printed book, the title page itself,
21126 plus such following pages as are needed to hold, legibly, the material
21127 this License requires to appear in the title page. For works in
21128 formats which do not have any title page as such, ``Title Page'' means
21129 the text near the most prominent appearance of the work's title,
21130 preceding the beginning of the body of the text.
21131
21132 @item
21133 VERBATIM COPYING
21134
21135 You may copy and distribute the Document in any medium, either
21136 commercially or noncommercially, provided that this License, the
21137 copyright notices, and the license notice saying this License applies
21138 to the Document are reproduced in all copies, and that you add no other
21139 conditions whatsoever to those of this License. You may not use
21140 technical measures to obstruct or control the reading or further
21141 copying of the copies you make or distribute. However, you may accept
21142 compensation in exchange for copies. If you distribute a large enough
21143 number of copies you must also follow the conditions in section 3.
21144
21145 You may also lend copies, under the same conditions stated above, and
21146 you may publicly display copies.
21147
21148 @item
21149 COPYING IN QUANTITY
21150
21151 If you publish printed copies of the Document numbering more than 100,
21152 and the Document's license notice requires Cover Texts, you must enclose
21153 the copies in covers that carry, clearly and legibly, all these Cover
21154 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21155 the back cover. Both covers must also clearly and legibly identify
21156 you as the publisher of these copies. The front cover must present
21157 the full title with all words of the title equally prominent and
21158 visible. You may add other material on the covers in addition.
21159 Copying with changes limited to the covers, as long as they preserve
21160 the title of the Document and satisfy these conditions, can be treated
21161 as verbatim copying in other respects.
21162
21163 If the required texts for either cover are too voluminous to fit
21164 legibly, you should put the first ones listed (as many as fit
21165 reasonably) on the actual cover, and continue the rest onto adjacent
21166 pages.
21167
21168 If you publish or distribute Opaque copies of the Document numbering
21169 more than 100, you must either include a machine-readable Transparent
21170 copy along with each Opaque copy, or state in or with each Opaque copy
21171 a publicly-accessible computer-network location containing a complete
21172 Transparent copy of the Document, free of added material, which the
21173 general network-using public has access to download anonymously at no
21174 charge using public-standard network protocols. If you use the latter
21175 option, you must take reasonably prudent steps, when you begin
21176 distribution of Opaque copies in quantity, to ensure that this
21177 Transparent copy will remain thus accessible at the stated location
21178 until at least one year after the last time you distribute an Opaque
21179 copy (directly or through your agents or retailers) of that edition to
21180 the public.
21181
21182 It is requested, but not required, that you contact the authors of the
21183 Document well before redistributing any large number of copies, to give
21184 them a chance to provide you with an updated version of the Document.
21185
21186 @item
21187 MODIFICATIONS
21188
21189 You may copy and distribute a Modified Version of the Document under
21190 the conditions of sections 2 and 3 above, provided that you release
21191 the Modified Version under precisely this License, with the Modified
21192 Version filling the role of the Document, thus licensing distribution
21193 and modification of the Modified Version to whoever possesses a copy
21194 of it. In addition, you must do these things in the Modified Version:
21195
21196 @enumerate A
21197 @item
21198 Use in the Title Page (and on the covers, if any) a title distinct
21199 from that of the Document, and from those of previous versions
21200 (which should, if there were any, be listed in the History section
21201 of the Document). You may use the same title as a previous version
21202 if the original publisher of that version gives permission.
21203
21204 @item
21205 List on the Title Page, as authors, one or more persons or entities
21206 responsible for authorship of the modifications in the Modified
21207 Version, together with at least five of the principal authors of the
21208 Document (all of its principal authors, if it has less than five).
21209
21210 @item
21211 State on the Title page the name of the publisher of the
21212 Modified Version, as the publisher.
21213
21214 @item
21215 Preserve all the copyright notices of the Document.
21216
21217 @item
21218 Add an appropriate copyright notice for your modifications
21219 adjacent to the other copyright notices.
21220
21221 @item
21222 Include, immediately after the copyright notices, a license notice
21223 giving the public permission to use the Modified Version under the
21224 terms of this License, in the form shown in the Addendum below.
21225
21226 @item
21227 Preserve in that license notice the full lists of Invariant Sections
21228 and required Cover Texts given in the Document's license notice.
21229
21230 @item
21231 Include an unaltered copy of this License.
21232
21233 @item
21234 Preserve the section entitled ``History'', and its title, and add to
21235 it an item stating at least the title, year, new authors, and
21236 publisher of the Modified Version as given on the Title Page. If
21237 there is no section entitled ``History'' in the Document, create one
21238 stating the title, year, authors, and publisher of the Document as
21239 given on its Title Page, then add an item describing the Modified
21240 Version as stated in the previous sentence.
21241
21242 @item
21243 Preserve the network location, if any, given in the Document for
21244 public access to a Transparent copy of the Document, and likewise
21245 the network locations given in the Document for previous versions
21246 it was based on. These may be placed in the ``History'' section.
21247 You may omit a network location for a work that was published at
21248 least four years before the Document itself, or if the original
21249 publisher of the version it refers to gives permission.
21250
21251 @item
21252 In any section entitled ``Acknowledgments'' or ``Dedications'',
21253 preserve the section's title, and preserve in the section all the
21254 substance and tone of each of the contributor acknowledgments
21255 and/or dedications given therein.
21256
21257 @item
21258 Preserve all the Invariant Sections of the Document,
21259 unaltered in their text and in their titles. Section numbers
21260 or the equivalent are not considered part of the section titles.
21261
21262 @item
21263 Delete any section entitled ``Endorsements''. Such a section
21264 may not be included in the Modified Version.
21265
21266 @item
21267 Do not retitle any existing section as ``Endorsements''
21268 or to conflict in title with any Invariant Section.
21269 @end enumerate
21270
21271 If the Modified Version includes new front-matter sections or
21272 appendices that qualify as Secondary Sections and contain no material
21273 copied from the Document, you may at your option designate some or all
21274 of these sections as invariant. To do this, add their titles to the
21275 list of Invariant Sections in the Modified Version's license notice.
21276 These titles must be distinct from any other section titles.
21277
21278 You may add a section entitled ``Endorsements'', provided it contains
21279 nothing but endorsements of your Modified Version by various
21280 parties---for example, statements of peer review or that the text has
21281 been approved by an organization as the authoritative definition of a
21282 standard.
21283
21284 You may add a passage of up to five words as a Front-Cover Text, and a
21285 passage of up to 25 words as a Back-Cover Text, to the end of the list
21286 of Cover Texts in the Modified Version. Only one passage of
21287 Front-Cover Text and one of Back-Cover Text may be added by (or
21288 through arrangements made by) any one entity. If the Document already
21289 includes a cover text for the same cover, previously added by you or
21290 by arrangement made by the same entity you are acting on behalf of,
21291 you may not add another; but you may replace the old one, on explicit
21292 permission from the previous publisher that added the old one.
21293
21294 The author(s) and publisher(s) of the Document do not by this License
21295 give permission to use their names for publicity for or to assert or
21296 imply endorsement of any Modified Version.
21297
21298 @item
21299 COMBINING DOCUMENTS
21300
21301 You may combine the Document with other documents released under this
21302 License, under the terms defined in section 4 above for modified
21303 versions, provided that you include in the combination all of the
21304 Invariant Sections of all of the original documents, unmodified, and
21305 list them all as Invariant Sections of your combined work in its
21306 license notice.
21307
21308 The combined work need only contain one copy of this License, and
21309 multiple identical Invariant Sections may be replaced with a single
21310 copy. If there are multiple Invariant Sections with the same name but
21311 different contents, make the title of each such section unique by
21312 adding at the end of it, in parentheses, the name of the original
21313 author or publisher of that section if known, or else a unique number.
21314 Make the same adjustment to the section titles in the list of
21315 Invariant Sections in the license notice of the combined work.
21316
21317 In the combination, you must combine any sections entitled ``History''
21318 in the various original documents, forming one section entitled
21319 ``History''; likewise combine any sections entitled ``Acknowledgments'',
21320 and any sections entitled ``Dedications''. You must delete all sections
21321 entitled ``Endorsements.''
21322
21323 @item
21324 COLLECTIONS OF DOCUMENTS
21325
21326 You may make a collection consisting of the Document and other documents
21327 released under this License, and replace the individual copies of this
21328 License in the various documents with a single copy that is included in
21329 the collection, provided that you follow the rules of this License for
21330 verbatim copying of each of the documents in all other respects.
21331
21332 You may extract a single document from such a collection, and distribute
21333 it individually under this License, provided you insert a copy of this
21334 License into the extracted document, and follow this License in all
21335 other respects regarding verbatim copying of that document.
21336
21337 @item
21338 AGGREGATION WITH INDEPENDENT WORKS
21339
21340 A compilation of the Document or its derivatives with other separate
21341 and independent documents or works, in or on a volume of a storage or
21342 distribution medium, does not as a whole count as a Modified Version
21343 of the Document, provided no compilation copyright is claimed for the
21344 compilation. Such a compilation is called an ``aggregate'', and this
21345 License does not apply to the other self-contained works thus compiled
21346 with the Document, on account of their being thus compiled, if they
21347 are not themselves derivative works of the Document.
21348
21349 If the Cover Text requirement of section 3 is applicable to these
21350 copies of the Document, then if the Document is less than one quarter
21351 of the entire aggregate, the Document's Cover Texts may be placed on
21352 covers that surround only the Document within the aggregate.
21353 Otherwise they must appear on covers around the whole aggregate.
21354
21355 @item
21356 TRANSLATION
21357
21358 Translation is considered a kind of modification, so you may
21359 distribute translations of the Document under the terms of section 4.
21360 Replacing Invariant Sections with translations requires special
21361 permission from their copyright holders, but you may include
21362 translations of some or all Invariant Sections in addition to the
21363 original versions of these Invariant Sections. You may include a
21364 translation of this License provided that you also include the
21365 original English version of this License. In case of a disagreement
21366 between the translation and the original English version of this
21367 License, the original English version will prevail.
21368
21369 @item
21370 TERMINATION
21371
21372 You may not copy, modify, sublicense, or distribute the Document except
21373 as expressly provided for under this License. Any other attempt to
21374 copy, modify, sublicense or distribute the Document is void, and will
21375 automatically terminate your rights under this License. However,
21376 parties who have received copies, or rights, from you under this
21377 License will not have their licenses terminated so long as such
21378 parties remain in full compliance.
21379
21380 @item
21381 FUTURE REVISIONS OF THIS LICENSE
21382
21383 The Free Software Foundation may publish new, revised versions
21384 of the GNU Free Documentation License from time to time. Such new
21385 versions will be similar in spirit to the present version, but may
21386 differ in detail to address new problems or concerns. See
21387 @uref{http://www.gnu.org/copyleft/}.
21388
21389 Each version of the License is given a distinguishing version number.
21390 If the Document specifies that a particular numbered version of this
21391 License ``or any later version'' applies to it, you have the option of
21392 following the terms and conditions either of that specified version or
21393 of any later version that has been published (not as a draft) by the
21394 Free Software Foundation. If the Document does not specify a version
21395 number of this License, you may choose any version ever published (not
21396 as a draft) by the Free Software Foundation.
21397 @end enumerate
21398
21399 @node Index, About the Author, GNU Free Documentation License, Top
21400 @comment node-name, next, previous, up
21401 @unnumbered Index
21402
21403 @ignore
21404 MENU ENTRY: NODE NAME.
21405 @end ignore
21406
21407 @printindex cp
21408
21409 @iftex
21410 @c Place biographical information on right-hand (verso) page
21411
21412 @tex
21413 \ifodd\pageno
21414 \par\vfill\supereject
21415 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21416 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21417 \page\hbox{}\page
21418 \else
21419 \par\vfill\supereject
21420 \par\vfill\supereject
21421 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21422 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21423 \page\hbox{}\page
21424 \page\hbox{}\page
21425 \fi
21426 @end tex
21427
21428 @page
21429 @w{ }
21430
21431 @c ================ Biographical information ================
21432
21433 @w{ }
21434 @sp 8
21435 @center About the Author
21436 @sp 1
21437 @end iftex
21438
21439 @ifnottex
21440 @node About the Author, , Index, Top
21441 @unnumbered About the Author
21442 @end ifnottex
21443
21444 @quotation
21445 Robert J. Chassell has worked with GNU Emacs since 1985. He writes
21446 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21447 world on software freedom. Chassell was a founding Director and
21448 Treasurer of the Free Software Foundation, Inc. He is co-author of
21449 the @cite{Texinfo} manual, and has edited more than a dozen other
21450 books. He graduated from Cambridge University, in England. He has an
21451 abiding interest in social and economic history and flies his own
21452 airplane.
21453 @end quotation
21454
21455 @page
21456 @w{ }
21457
21458 @c Prevent page number on blank verso, so eject it first.
21459 @tex
21460 \par\vfill\supereject
21461 @end tex
21462
21463 @iftex
21464 @headings off
21465 @evenheading @thispage @| @| @thistitle
21466 @oddheading @| @| @thispage
21467 @end iftex
21468
21469 @bye