comparison lispintro/emacs-lisp-intro.texi @ 41421:7a66b17d124d

Modified slightly for inclusion in the Emacs distribution.
author Eli Zaretskii <eliz@gnu.org>
date Sat, 24 Nov 2001 09:57:24 +0000
parents
children f2ffeff1bf1e
comparison
equal deleted inserted replaced
41420:29ff891c49ec 41421:7a66b17d124d
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 <<<< Now set for smallbook, which works well with all
13 @c sizes of paper and no included PostScript figures
14 @c (this setting uses ASCII figures instead). >>>>
15
16 @c @smallbook
17 @c @clear largebook
18 @c @clear print-postscript-figures
19 @set largebook
20 @set print-postscript-figures
21 @c ---------
22
23 @comment %**end of header
24
25 @set edition-number 2.01
26 @set update-date 2001 Nov 24
27
28 @ignore
29 ## Summary of shell commands to create various output formats:
30
31 ## Info output
32 makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
33
34 ## DVI output
35 texi2dvi emacs-lisp-intro.texi
36
37 ## HTML output
38 texi2html emacs-lisp-intro.texi
39 makeinfo --html --no-split --verbose emacs-lisp-intro.texi
40
41 ## Plain text output
42 makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
43 --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
44
45 @end ignore
46
47 @c ================ Included Figures ================
48
49 @c Set print-postscript-figures if you print PostScript figures.
50 @c If you clear this, the ten figures will be printed as ASCII diagrams.
51 @c (This is not relevant to Info, since Info only handles ASCII.)
52 @c Your site may require editing changes to print PostScript; in this
53 @c case, search for `print-postscript-figures' and make appropriate changes.
54
55
56 @c ================ How to Create an Info file ================
57
58 @c If you have `makeinfo' installed, run the following command
59
60 @c makeinfo emacs-lisp-intro.texi
61
62 @c or, if you want a single, large Info file, and no paragraph indents:
63 @c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
64
65 @c After creating the Info file, edit your Info `dir' file, if the
66 @c START-INFO-DIR-ENTRY section below does not enable your system to
67 @c install the manual automatically.
68 @c (The `dir' file is often in the `/usr/local/info/' directory.)
69
70 @c ================ How to Create an HTML file ================
71
72 @c To convert to HTML format
73 @c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
74
75 @c ================ How to Print a Book in Various Sizes ================
76
77 @c This book can be printed in any of three different sizes.
78 @c In the above header, set @-commands appropriately.
79
80 @c 7 by 9.25 inches:
81 @c @smallbook
82 @c @clear largebook
83
84 @c 8.5 by 11 inches:
85 @c @c smallbook
86 @c @set largebook
87
88 @c European A4 size paper:
89 @c @c smallbook
90 @c @afourpaper
91 @c @set largebook
92
93 @c ================ How to Typeset and Print ================
94
95 @c If you do not include PostScript figures, run either of the
96 @c following command sequences, or similar commands suited to your
97 @c system:
98
99 @c texi2dvi emacs-lisp-intro.texi
100 @c lpr -d emacs-lisp-intro.dvi
101
102 @c or else:
103
104 @c tex emacs-lisp-intro.texi
105 @c texindex emacs-lisp-intro.??
106 @c tex emacs-lisp-intro.texi
107 @c lpr -d emacs-lisp-intro.dvi
108
109 @c If you include the PostScript figures, you must convert the .dvi
110 @c file to a .ps file before printing. Run either of the
111 @c following command sequences, or one similar:
112 @c
113 @c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
114 @c
115 @c or else:
116 @c
117 @c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
118 @c
119
120 @c (Note: if you edit the book so as to change the length of the
121 @c table of contents, you may have to change the value of `pageno' below.)
122
123 @c Remember that TeX places the Table of Contents at the end of the
124 @c print run; you need to put those pages in front of the Preface.
125
126 @c ================ End of Formatting Sections ================
127
128 @c For next or subsequent edition:
129 @c create function using with-output-to-temp-buffer
130 @c create a major mode, with keymaps
131 @c run an asynchronous process, like grep or diff
132
133 @c For smallbook format, use smaller than normal amounts of
134 @c whitespace between chapters, sections, and paragraphs.
135 @tex
136 \global\chapheadingskip = 15pt plus 4pt minus 2pt
137 \global\secheadingskip = 12pt plus 3pt minus 2pt
138 \global\subsecheadingskip = 9pt plus 2pt minus 2pt \global\parskip 2pt
139 plus 1pt
140 @end tex
141
142 @c For 8.5 by 11 inch format: do not use such a small amount of
143 @c whitespace between paragraphs as above:
144 @ifset largebook
145 @tex
146 \global\parskip 6pt plus 1pt
147 @end tex
148 @end ifset
149
150 @c For all sized formats: print within-book cross
151 @c reference with ``...'' rather than [...]
152 @tex
153 % Need following so comma appears after section numbers.
154 \global\def\Ysectionnumberandtype{%
155 \ifnum\secno=0 \putwordChapter\xreftie\the\chapno, \space %
156 \else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno, \space %
157 \else \ifnum \subsubsecno=0 %
158 \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno, \space %
159 \else %
160 \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno, \space%
161 \fi \fi \fi }
162
163 \global\def\Yappendixletterandtype{%
164 \ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}, \space%
165 \else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno, \space %
166 \else \ifnum \subsubsecno=0 %
167 \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno, \space %
168 \else %
169 \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno, \space %
170 \fi \fi \fi }
171
172 \global\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
173 \def\printedmanual{\ignorespaces #5}%
174 \def\printednodename{\ignorespaces #3}%
175 \setbox1=\hbox{\printedmanual}%
176 \setbox0=\hbox{\printednodename}%
177 \ifdim \wd0 = 0pt
178 % No printed node name was explicitly given.
179 \ifx\SETxref-automatic-section-title\relax %
180 % Use the actual chapter/section title appear inside
181 % the square brackets. Use the real section title if we have it.
182 \ifdim \wd1>0pt%
183 % It is in another manual, so we don't have it.
184 \def\printednodename{\ignorespaces #1}%
185 \else
186 \ifhavexrefs
187 % We know the real title if we have the xref values.
188 \def\printednodename{\refx{#1-title}}%
189 \else
190 % Otherwise just copy the Info node name.
191 \def\printednodename{\ignorespaces #1}%
192 \fi%
193 \fi
194 \def\printednodename{#1-title}%
195 \else
196 % Use the node name inside the square brackets.
197 \def\printednodename{\ignorespaces #1}%
198 \fi
199 \fi
200 %
201 % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not
202 % insert empty discretionaries after hyphens, which means that it will
203 % not find a line break at a hyphen in a node names. Since some manuals
204 % are best written with fairly long node names, containing hyphens, this
205 % is a loss. Therefore, we give the text of the node name again, so it
206 % is as if TeX is seeing it for the first time.
207 \ifdim \wd1 > 0pt
208 \putwordsection{} ``\printednodename'' in \cite{\printedmanual}%
209 \else
210 % _ (for example) has to be the character _ for the purposes of the
211 % control sequence corresponding to the node, but it has to expand
212 % into the usual \leavevmode...\vrule stuff for purposes of
213 % printing. So we \turnoffactive for the \refx-snt, back on for the
214 % printing, back off for the \refx-pg.
215 {\turnoffactive \refx{#1-snt}{}}%
216 % \space [\printednodename],\space % <= original
217 % \putwordsection{} ``\printednodename'',\space
218 ``\printednodename'',\space
219 \turnoffactive \putwordpage\tie\refx{#1-pg}{}%
220 \fi
221 \endgroup}
222 @end tex
223
224 @c ----------------------------------------------------
225
226 @ignore
227 @ifinfo
228 @format
229 START-INFO-DIR-ENTRY
230 * Emacs Lisp Intro: (emacs-lisp-intro).
231 A simple introduction to Emacs Lisp programming.
232 END-INFO-DIR-ENTRY
233 @end format
234 @end ifinfo
235 @end ignore
236
237 @ifinfo
238 This is an introduction to @cite{Programming in Emacs Lisp}, for
239 people who are not programmers.
240
241 Edition @value{edition-number}, @value{update-date}
242
243 Copyright (C) 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software Foundation, Inc.
244
245 Permission is granted to copy, distribute and/or modify this document
246 under the terms of the GNU Free Documentation License, Version 1.1 or
247 any later version published by the Free Software Foundation; with the
248 Invariant Section being the Preface, with the Front-Cover Texts being
249 no Front-Cover Texts, and with the Back-Cover Texts being no
250 Back-Cover Texts. A copy of the license is included in the section
251 entitled ``GNU Free Documentation License''.
252 @end ifinfo
253
254 @c half title; two lines here, so do not use `shorttitlepage'
255 @tex
256 {\begingroup%
257 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
258 \endgroup}%
259 {\begingroup\hbox{}\vskip 0.25in \chaprm%
260 \centerline{Programming in Emacs Lisp}%
261 \endgroup\page\hbox{}\page}
262 @end tex
263
264 @titlepage
265 @sp 6
266 @center @titlefont{An Introduction to}
267 @sp 2
268 @center @titlefont{Programming in Emacs Lisp}
269 @sp 2
270 @center Second Edition
271 @sp 4
272 @center by Robert J. Chassell
273
274 @page
275 @vskip 0pt plus 1filll
276 Copyright @copyright{} 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software Foundation, Inc.
277 @sp 2
278
279 Published by the Free Software Foundation, Inc.@*
280 59 Temple Place, Suite 330@*
281 Boston, MA 02111-1307 USA@*
282
283 Edition @value{edition-number}, @value{update-date}
284
285 @c Printed copies are available for $20 each.@*
286 ISBN-1882114-41-8
287
288 Permission is granted to copy, distribute and/or modify this document
289 under the terms of the GNU Free Documentation License, Version 1.1 or
290 any later version published by the Free Software Foundation; with the
291 Invariant Section being the Preface, with the Front-Cover Texts being
292 no Front-Cover Texts, and with the Back-Cover Texts being no
293 Back-Cover Texts. A copy of the license is included in the section
294 entitled ``GNU Free Documentation License''.
295 @end titlepage
296
297 @iftex
298 @headings off
299 @evenheading @thispage @| @| @thischapter
300 @oddheading @thissection @| @| @thispage
301 @end iftex
302
303 @ifnottex
304 @node Top, Preface, (dir), (dir)
305 @top An Introduction to Programming in Emacs Lisp
306
307 This is an introduction to @cite{Programming in Emacs Lisp}, for
308 people who are not programmers.
309
310 This master menu first lists each chapter and index; then it lists
311 every node in every chapter.
312 @end ifnottex
313
314 @c >>>> Set pageno appropriately <<<<
315
316 @c The first page of the Preface is a roman numeral; it is the first
317 @c right handed page after the Table of Contents; hence the following
318 @c setting must be for an odd negative number.
319
320 @c if largebook, there are 8 pages in Table of Contents
321 @ifset largebook
322 @iftex
323 @pageno = -9
324 @end iftex
325 @end ifset
326
327 @c if smallbook, there are 10 pages in Table of Contents
328 @ifclear largebook
329 @iftex
330 @pageno = -11
331 @end iftex
332 @end ifclear
333
334 @menu
335 * Preface:: What to look for.
336 * List Processing:: What is Lisp?
337 * Practicing Evaluation:: Running several programs.
338 * Writing Defuns:: How to write function definitions.
339 * Buffer Walk Through:: Exploring a few buffer-related functions.
340 * More Complex:: A few, even more complex functions.
341 * Narrowing & Widening:: Restricting your and Emacs attention to
342 a region.
343 * car cdr & cons:: Fundamental functions in Lisp.
344 * Cutting & Storing Text:: Removing text and saving it.
345 * List Implementation:: How lists are implemented in the computer.
346 * Yanking:: Pasting stored text.
347 * Loops & Recursion:: How to repeat a process.
348 * Regexp Search:: Regular expression searches.
349 * Counting Words:: A review of repetition and regexps.
350 * Words in a defun:: Counting words in a @code{defun}.
351 * Readying a Graph:: A prototype graph printing function.
352 * Emacs Initialization:: How to write a @file{.emacs} file.
353 * Debugging:: How to run the Emacs Lisp debuggers.
354 * Conclusion:: Now you have the basics.
355 * the-the:: An appendix: how to find reduplicated words.
356 * Kill Ring:: An appendix: how the kill ring works.
357 * Full Graph:: How to create a graph with labelled axes.
358 * GNU Free Documentation License::
359 * Index::
360 * About the Author::
361
362 @detailmenu
363 --- The Detailed Node Listing ---
364
365 Preface
366
367 * Why:: Why learn Emacs Lisp?
368 * On Reading this Text:: Read, gain familiarity, pick up habits....
369 * Who You Are:: For whom this is written.
370 * Lisp History::
371 * Note for Novices:: You can read this as a novice.
372 * Thank You::
373
374 List Processing
375
376 * Lisp Lists:: What are lists?
377 * Run a Program:: Any list in Lisp is a program ready to run.
378 * Making Errors:: Generating an error message.
379 * Names & Definitions:: Names of symbols and function definitions.
380 * Lisp Interpreter:: What the Lisp interpreter does.
381 * Evaluation:: Running a program.
382 * Variables:: Returning a value from a variable.
383 * Arguments:: Passing information to a function.
384 * set & setq:: Setting the value of a variable.
385 * Summary:: The major points.
386 * Error Message Exercises::
387
388 Lisp Lists
389
390 * Numbers Lists:: List have numbers, other lists, in them.
391 * Lisp Atoms:: Elemental entities.
392 * Whitespace in Lists:: Formating lists to be readable.
393 * Typing Lists:: How GNU Emacs helps you type lists.
394
395 The Lisp Interpreter
396
397 * Complications:: Variables, Special forms, Lists within.
398 * Byte Compiling:: Specially processing code for speed.
399
400 Evaluation
401
402 * Evaluating Inner Lists:: Lists within lists...
403
404 Variables
405
406 * fill-column Example::
407 * Void Function:: The error message for a symbol
408 without a function.
409 * Void Variable:: The error message for a symbol without a value.
410
411 Arguments
412
413 * Data types:: Types of data passed to a function.
414 * Args as Variable or List:: An argument can be the value
415 of a variable or list.
416 * Variable Number of Arguments:: Some functions may take a
417 variable number of arguments.
418 * Wrong Type of Argument:: Passing an argument of the wrong type
419 to a function.
420 * message:: A useful function for sending messages.
421
422 Setting the Value of a Variable
423
424 * Using set:: Setting values.
425 * Using setq:: Setting a quoted value.
426 * Counting:: Using @code{setq} to count.
427
428 Practicing Evaluation
429
430 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
431 causes evaluation.
432 * Buffer Names:: Buffers and files are different.
433 * Getting Buffers:: Getting a buffer itself, not merely its name.
434 * Switching Buffers:: How to change to another buffer.
435 * Buffer Size & Locations:: Where point is located and the size of
436 the buffer.
437 * Evaluation Exercise::
438
439 How To Write Function Definitions
440
441 * Primitive Functions::
442 * defun:: The @code{defun} special form.
443 * Install:: Install a function definition.
444 * Interactive:: Making a function interactive.
445 * Interactive Options:: Different options for @code{interactive}.
446 * Permanent Installation:: Installing code permanently.
447 * let:: Creating and initializing local variables.
448 * if:: What if?
449 * else:: If--then--else expressions.
450 * Truth & Falsehood:: What Lisp considers false and true.
451 * save-excursion:: Keeping track of point, mark, and buffer.
452 * Review::
453 * defun Exercises::
454
455 Install a Function Definition
456
457 * Effect of installation::
458 * Change a defun:: How to change a function definition.
459
460 Make a Function Interactive
461
462 * Interactive multiply-by-seven:: An overview.
463 * multiply-by-seven in detail:: The interactive version.
464
465 @code{let}
466
467 * Prevent confusion::
468 * Parts of let Expression::
469 * Sample let Expression::
470 * Uninitialized let Variables::
471
472 The @code{if} Special Form
473
474 * if in more detail::
475 * type-of-animal in detail:: An example of an @code{if} expression.
476
477 Truth and Falsehood in Emacs Lisp
478
479 * nil explained:: @code{nil} has two meanings.
480
481 @code{save-excursion}
482
483 * Point and mark:: A review of various locations.
484 * Template for save-excursion::
485
486 A Few Buffer--Related Functions
487
488 * Finding More:: How to find more information.
489 * simplified-beginning-of-buffer:: Shows @code{goto-char},
490 @code{point-min}, and @code{push-mark}.
491 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
492 * append-to-buffer:: Uses @code{save-excursion} and
493 @code{insert-buffer-substring}.
494 * Buffer Related Review:: Review.
495 * Buffer Exercises::
496
497 The Definition of @code{mark-whole-buffer}
498
499 * mark-whole-buffer overview::
500 * Body of mark-whole-buffer:: Only three lines of code.
501
502 The Definition of @code{append-to-buffer}
503
504 * append-to-buffer overview::
505 * append interactive:: A two part interactive expression.
506 * append-to-buffer body:: Incorporates a @code{let} expression.
507 * append save-excursion:: How the @code{save-excursion} works.
508
509 A Few More Complex Functions
510
511 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
512 * insert-buffer:: Read-only, and with @code{or}.
513 * beginning-of-buffer:: Shows @code{goto-char},
514 @code{point-min}, and @code{push-mark}.
515 * Second Buffer Related Review::
516 * optional Exercise::
517
518 The Definition of @code{insert-buffer}
519
520 * insert-buffer code::
521 * insert-buffer interactive:: When you can read, but not write.
522 * insert-buffer body:: The body has an @code{or} and a @code{let}.
523 * if & or:: Using an @code{if} instead of an @code{or}.
524 * Insert or:: How the @code{or} expression works.
525 * Insert let:: Two @code{save-excursion} expressions.
526
527 The Interactive Expression in @code{insert-buffer}
528
529 * Read-only buffer:: When a buffer cannot be modified.
530 * b for interactive:: An existing buffer or else its name.
531
532 Complete Definition of @code{beginning-of-buffer}
533
534 * Optional Arguments::
535 * beginning-of-buffer opt arg:: Example with optional argument.
536 * beginning-of-buffer complete::
537
538 @code{beginning-of-buffer} with an Argument
539
540 * Disentangle beginning-of-buffer::
541 * Large buffer case::
542 * Small buffer case::
543
544 Narrowing and Widening
545
546 * Narrowing advantages:: The advantages of narrowing
547 * save-restriction:: The @code{save-restriction} special form.
548 * what-line:: The number of the line that point is on.
549 * narrow Exercise::
550
551 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
552
553 * Strange Names:: An historical aside: why the strange names?
554 * car & cdr:: Functions for extracting part of a list.
555 * cons:: Constructing a list.
556 * nthcdr:: Calling @code{cdr} repeatedly.
557 * nth::
558 * setcar:: Changing the first element of a list.
559 * setcdr:: Changing the rest of a list.
560 * cons Exercise::
561
562 @code{cons}
563
564 * Build a list::
565 * length:: How to find the length of a list.
566
567 Cutting and Storing Text
568
569 * Storing Text:: Text is stored in a list.
570 * zap-to-char:: Cutting out text up to a character.
571 * kill-region:: Cutting text out of a region.
572 * Digression into C:: Minor note on C programming language macros.
573 * defvar:: How to give a variable an initial value.
574 * copy-region-as-kill:: A definition for copying text.
575 * cons & search-fwd Review::
576 * search Exercises::
577
578 @code{zap-to-char}
579
580 * Complete zap-to-char:: The complete implementation.
581 * zap-to-char interactive:: A three part interactive expression.
582 * zap-to-char body:: A short overview.
583 * search-forward:: How to search for a string.
584 * progn:: The @code{progn} special form.
585 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
586
587 @code{kill-region}
588
589 * Complete kill-region:: The function definition.
590 * condition-case:: Dealing with a problem.
591 * delete-and-extract-region:: Doing the work.
592
593 Initializing a Variable with @code{defvar}
594
595 * See variable current value::
596 * defvar and asterisk:: An old-time convention.
597
598 @code{copy-region-as-kill}
599
600 * Complete copy-region-as-kill:: The complete function definition.
601 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
602
603 The Body of @code{copy-region-as-kill}
604
605 * last-command & this-command::
606 * kill-append function::
607 * kill-new function::
608
609 How Lists are Implemented
610
611 * Lists diagrammed::
612 * Symbols as Chest:: Exploring a powerful metaphor.
613 * List Exercise::
614
615 Yanking Text Back
616
617 * Kill Ring Overview:: The kill ring is a list.
618 * kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
619 * yank nthcdr Exercises::
620
621 Loops and Recursion
622
623 * while:: Causing a stretch of code to repeat.
624 * dolist dotimes::
625 * Recursion:: Causing a function to call itself.
626 * Looping exercise::
627
628 @code{while}
629
630 * Looping with while:: Repeat so long as test returns true.
631 * Loop Example:: A @code{while} loop that uses a list.
632 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
633 * Incrementing Loop:: A loop with an incrementing counter.
634 * Decrementing Loop:: A loop with a decrementing counter.
635
636 A Loop with an Incrementing Counter
637
638 * Incrementing Example:: Counting pebbles in a triangle.
639 * Inc Example parts:: The parts of the function definition.
640 * Inc Example altogether:: Putting the function definition together.
641
642 Loop with a Decrementing Counter
643
644 * Decrementing Example:: More pebbles on the beach.
645 * Dec Example parts:: The parts of the function definition.
646 * Dec Example altogether:: Putting the function definition together.
647
648 Save your time: @code{dolist} and @code{dotimes}
649
650 * dolist::
651 * dotimes::
652
653 Recursion
654
655 * Building Robots:: Same model, different serial number ...
656 * Recursive Definition Parts:: Walk until you stop ...
657 * Recursion with list:: Using a list as the test whether to recurse.
658 * Recursive triangle function::
659 * Recursion with cond::
660 * Recursive Patterns:: Often used templates.
661 * No Deferment:: Don't store up work ...
662 * No deferment solution::
663
664 Recursion in Place of a Counter
665
666 * Recursive Example arg of 1 or 2::
667 * Recursive Example arg of 3 or 4::
668
669 Recursive Patterns
670
671 * Every::
672 * Accumulate::
673 * Keep::
674
675 Regular Expression Searches
676
677 * sentence-end:: The regular expression for @code{sentence-end}.
678 * re-search-forward:: Very similar to @code{search-forward}.
679 * forward-sentence:: A straightforward example of regexp search.
680 * forward-paragraph:: A somewhat complex example.
681 * etags:: How to create your own @file{TAGS} table.
682 * Regexp Review::
683 * re-search Exercises::
684
685 @code{forward-sentence}
686
687 * Complete forward-sentence::
688 * fwd-sentence while loops:: Two @code{while} loops.
689 * fwd-sentence re-search:: A regular expression search.
690
691 @code{forward-paragraph}: a Goldmine of Functions
692
693 * forward-paragraph in brief:: Key parts of the function definition.
694 * fwd-para let:: The @code{let*} expression.
695 * fwd-para while:: The forward motion @code{while} loop.
696 * fwd-para between paragraphs:: Movement between paragraphs.
697 * fwd-para within paragraph:: Movement within paragraphs.
698 * fwd-para no fill prefix:: When there is no fill prefix.
699 * fwd-para with fill prefix:: When there is a fill prefix.
700 * fwd-para summary:: Summary of @code{forward-paragraph} code.
701
702 Counting: Repetition and Regexps
703
704 * Why Count Words::
705 * count-words-region:: Use a regexp, but find a problem.
706 * recursive-count-words:: Start with case of no words in region.
707 * Counting Exercise::
708
709 The @code{count-words-region} Function
710
711 * Design count-words-region:: The definition using a @code{while} loop.
712 * Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
713
714 Counting Words in a @code{defun}
715
716 * Divide and Conquer::
717 * Words and Symbols:: What to count?
718 * Syntax:: What constitutes a word or symbol?
719 * count-words-in-defun:: Very like @code{count-words}.
720 * Several defuns:: Counting several defuns in a file.
721 * Find a File:: Do you want to look at a file?
722 * lengths-list-file:: A list of the lengths of many definitions.
723 * Several files:: Counting in definitions in different files.
724 * Several files recursively:: Recursively counting in different files.
725 * Prepare the data:: Prepare the data for display in a graph.
726
727 Count Words in @code{defuns} in Different Files
728
729 * lengths-list-many-files:: Return a list of the lengths of defuns.
730 * append:: Attach one list to another.
731
732 Prepare the Data for Display in a Graph
733
734 * Sorting:: Sorting lists.
735 * Files List:: Making a list of files.
736 * Counting function definitions::
737
738 Readying a Graph
739
740 * Columns of a graph::
741 * graph-body-print:: How to print the body of a graph.
742 * recursive-graph-body-print::
743 * Printed Axes::
744 * Line Graph Exercise::
745
746 Your @file{.emacs} File
747
748 * Default Configuration::
749 * Site-wide Init:: You can write site-wide init files.
750 * defcustom:: Emacs will write code for you.
751 * Beginning a .emacs File:: How to write a @code{.emacs file}.
752 * Text and Auto-fill:: Automatically wrap lines.
753 * Mail Aliases:: Use abbreviations for email addresses.
754 * Indent Tabs Mode:: Don't use tabs with @TeX{}
755 * Keybindings:: Create some personal keybindings.
756 * Keymaps:: More about key binding.
757 * Loading Files:: Load (i.e., evaluate) files automatically.
758 * Autoload:: Make functions available.
759 * Simple Extension:: Define a function; bind it to a key.
760 * X11 Colors:: Colors in version 19 in X.
761 * Miscellaneous::
762 * Mode Line:: How to customize your mode line.
763
764 Debugging
765
766 * debug:: How to use the built-in debugger.
767 * debug-on-entry:: Start debugging when you call a function.
768 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
769 * edebug:: How to use Edebug, a source level debugger.
770 * Debugging Exercises::
771
772 Handling the Kill Ring
773
774 * rotate-yank-pointer:: Move a pointer along a list and around.
775 * yank:: Paste a copy of a clipped element.
776 * yank-pop:: Insert first element pointed to.
777
778 The @code{rotate-yank-pointer} Function
779
780 * Understanding rotate-yk-ptr::
781 * rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
782
783 The Body of @code{rotate-yank-pointer}
784
785 * Digression concerning error:: How to mislead humans, but not computers.
786 * rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
787 * Remainder Function:: The remainder, @code{%}, function.
788 * rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
789 * kill-rng-yk-ptr last elt:: Pointing to the last element.
790
791 @code{yank}
792
793 * rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
794 * rotate-yk-ptr negative arg:: Pass a negative argument.
795
796 A Graph with Labelled Axes
797
798 * Labelled Example::
799 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
800 * print-Y-axis:: Print a label for the vertical axis.
801 * print-X-axis:: Print a horizontal label.
802 * Print Whole Graph:: The function to print a complete graph.
803
804 The @code{print-Y-axis} Function
805
806 * Height of label:: What height for the Y axis?
807 * Compute a Remainder:: How to compute the remainder of a division.
808 * Y Axis Element:: Construct a line for the Y axis.
809 * Y-axis-column:: Generate a list of Y axis labels.
810 * print-Y-axis Penultimate:: A not quite final version.
811
812 The @code{print-X-axis} Function
813
814 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
815 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
816
817 Printing the Whole Graph
818
819 * The final version:: A few changes.
820 * Test print-graph:: Run a short test.
821 * Graphing words in defuns:: Executing the final code.
822 * lambda:: How to write an anonymous function.
823 * mapcar:: Apply a function to elements of a list.
824 * Another Bug:: Yet another bug @dots{} most insidious.
825 * Final printed graph:: The graph itself!
826
827 @end detailmenu
828 @end menu
829
830 @node Preface, List Processing, Top, Top
831 @comment node-name, next, previous, up
832 @unnumbered Preface
833
834 Most of the GNU Emacs integrated environment is written in the programming
835 language called Emacs Lisp. The code written in this programming
836 language is the software---the sets of instructions---that tell the
837 computer what to do when you give it commands. Emacs is designed so
838 that you can write new code in Emacs Lisp and easily install it as an
839 extension to the editor.
840
841 (GNU Emacs is sometimes called an ``extensible editor'', but it does
842 much more than provide editing capabilities. It is better to refer to
843 Emacs as an ``extensible computing environment''. However, that
844 phrase is quite a mouthful. It is easier to refer to Emacs simply as
845 an editor. Moreover, everything you do in Emacs---find the Mayan date
846 and phases of the moon, simplify polynomials, debug code, manage
847 files, read letters, write books---all these activities are kinds of
848 editing in the most general sense of the word.)
849
850 @menu
851 * Why:: Why learn Emacs Lisp?
852 * On Reading this Text:: Read, gain familiarity, pick up habits....
853 * Who You Are:: For whom this is written.
854 * Lisp History::
855 * Note for Novices:: You can read this as a novice.
856 * Thank You::
857 @end menu
858
859 @node Why, On Reading this Text, Preface, Preface
860 @ifnottex
861 @unnumberedsec Why Study Emacs Lisp?
862 @end ifnottex
863
864 Although Emacs Lisp is usually thought of in association only with Emacs,
865 it is a full computer programming language. You can use Emacs Lisp as
866 you would any other programming language.
867
868 Perhaps you want to understand programming; perhaps you want to extend
869 Emacs; or perhaps you want to become a programmer. This introduction to
870 Emacs Lisp is designed to get you started: to guide you in learning the
871 fundamentals of programming, and more importantly, to show you how you
872 can teach yourself to go further.
873
874 @node On Reading this Text, Who You Are, Why, Preface
875 @comment node-name, next, previous, up
876 @unnumberedsec On Reading this Text
877
878 All through this document, you will see little sample programs you can
879 run inside of Emacs. If you read this document in Info inside of GNU
880 Emacs, you can run the programs as they appear. (This is easy to do and
881 is explained when the examples are presented.) Alternatively, you can
882 read this introduction as a printed book while sitting beside a computer
883 running Emacs. (This is what I like to do; I like printed books.) If
884 you don't have a running Emacs beside you, you can still read this book,
885 but in this case, it is best to treat it as a novel or as a travel guide
886 to a country not yet visited: interesting, but not the same as being
887 there.
888
889 Much of this introduction is dedicated to walk-throughs or guided tours
890 of code used in GNU Emacs. These tours are designed for two purposes:
891 first, to give you familiarity with real, working code (code you use
892 every day); and, second, to give you familiarity with the way Emacs
893 works. It is interesting to see how a working environment is
894 implemented.
895 Also, I
896 hope that you will pick up the habit of browsing through source code.
897 You can learn from it and mine it for ideas. Having GNU Emacs is like
898 having a dragon's cave of treasures.
899
900 In addition to learning about Emacs as an editor and Emacs Lisp as a
901 programming language, the examples and guided tours will give you an
902 opportunity to get acquainted with Emacs as a Lisp programming
903 environment. GNU Emacs supports programming and provides tools that
904 you will want to become comfortable using, such as @kbd{M-.} (the key
905 which invokes the @code{find-tag} command). You will also learn about
906 buffers and other objects that are part of the environment.
907 Learning about these features of Emacs is like learning new routes
908 around your home town.
909
910 @ignore
911 In addition, I have written several programs as extended examples.
912 Although these are examples, the programs are real. I use them.
913 Other people use them. You may use them. Beyond the fragments of
914 programs used for illustrations, there is very little in here that is
915 `just for teaching purposes'; what you see is used. This is a great
916 advantage of Emacs Lisp: it is easy to learn to use it for work.
917 @end ignore
918
919 Finally, I hope to convey some of the skills for using Emacs to
920 learn aspects of programming that you don't know. You can often use
921 Emacs to help you understand what puzzles you or to find out how to do
922 something new. This self-reliance is not only a pleasure, but an
923 advantage.
924
925 @node Who You Are, Lisp History, On Reading this Text, Preface
926 @comment node-name, next, previous, up
927 @unnumberedsec For Whom This is Written
928
929 This text is written as an elementary introduction for people who are
930 not programmers. If you are a programmer, you may not be satisfied with
931 this primer. The reason is that you may have become expert at reading
932 reference manuals and be put off by the way this text is organized.
933
934 An expert programmer who reviewed this text said to me:
935
936 @quotation
937 @i{I prefer to learn from reference manuals. I ``dive into'' each
938 paragraph, and ``come up for air'' between paragraphs.}
939
940 @i{When I get to the end of a paragraph, I assume that that subject is
941 done, finished, that I know everything I need (with the
942 possible exception of the case when the next paragraph starts talking
943 about it in more detail). I expect that a well written reference manual
944 will not have a lot of redundancy, and that it will have excellent
945 pointers to the (one) place where the information I want is.}
946 @end quotation
947
948 This introduction is not written for this person!
949
950 Firstly, I try to say everything at least three times: first, to
951 introduce it; second, to show it in context; and third, to show it in a
952 different context, or to review it.
953
954 Secondly, I hardly ever put all the information about a subject in one
955 place, much less in one paragraph. To my way of thinking, that imposes
956 too heavy a burden on the reader. Instead I try to explain only what
957 you need to know at the time. (Sometimes I include a little extra
958 information so you won't be surprised later when the additional
959 information is formally introduced.)
960
961 When you read this text, you are not expected to learn everything the
962 first time. Frequently, you need only make, as it were, a `nodding
963 acquaintance' with some of the items mentioned. My hope is that I have
964 structured the text and given you enough hints that you will be alert to
965 what is important, and concentrate on it.
966
967 You will need to ``dive into'' some paragraphs; there is no other way
968 to read them. But I have tried to keep down the number of such
969 paragraphs. This book is intended as an approachable hill, rather than
970 as a daunting mountain.
971
972 This introduction to @cite{Programming in Emacs Lisp} has a companion
973 document,
974 @iftex
975 @cite{The GNU Emacs Lisp Reference Manual}.
976 @end iftex
977 @ifnottex
978 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
979 Emacs Lisp Reference Manual}.
980 @end ifnottex
981 The reference manual has more detail than this introduction. In the
982 reference manual, all the information about one topic is concentrated
983 in one place. You should turn to it if you are like the programmer
984 quoted above. And, of course, after you have read this
985 @cite{Introduction}, you will find the @cite{Reference Manual} useful
986 when you are writing your own programs.
987
988 @node Lisp History, Note for Novices, Who You Are, Preface
989 @unnumberedsec Lisp History
990 @cindex Lisp history
991
992 Lisp was first developed in the late 1950s at the Massachusetts
993 Institute of Technology for research in artificial intelligence. The
994 great power of the Lisp language makes it superior for other purposes as
995 well, such as writing editor commands and integrated environments.
996
997 @cindex Maclisp
998 @cindex Common Lisp
999 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1000 in the 1960s. It is somewhat inspired by Common Lisp, which became a
1001 standard in the 1980s. However, Emacs Lisp is much simpler than Common
1002 Lisp. (The standard Emacs distribution contains an optional extensions
1003 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1004
1005 @node Note for Novices, Thank You, Lisp History, Preface
1006 @comment node-name, next, previous, up
1007 @unnumberedsec A Note for Novices
1008
1009 If you don't know GNU Emacs, you can still read this document
1010 profitably. However, I recommend you learn Emacs, if only to learn to
1011 move around your computer screen. You can teach yourself how to use
1012 Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1013 means you press and release the @key{CTRL} key and the @kbd{h} at the
1014 same time, and then press and release @kbd{t}.)
1015
1016 Also, I often refer to one of Emacs' standard commands by listing the
1017 keys which you press to invoke the command and then giving the name of
1018 the command in parentheses, like this: @kbd{M-C-\}
1019 (@code{indent-region}). What this means is that the
1020 @code{indent-region} command is customarily invoked by typing
1021 @kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1022 invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1023 Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1024 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1025 (On many modern keyboards the @key{META} key is labelled
1026 @key{ALT}.)
1027 Sometimes a combination like this is called a keychord, since it is
1028 similar to the way you play a chord on a piano. If your keyboard does
1029 not have a @key{META} key, the @key{ESC} key prefix is used in place
1030 of it. In this case, @kbd{M-C-\} means that you press and release your
1031 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1032 the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
1033 along with the key that is labelled @key{ALT} and, at the same time,
1034 press the @key{\} key.
1035
1036 In addition to typing a lone keychord, you can prefix what you type
1037 with @kbd{C-u}, which is called the `universal argument'. The
1038 @kbd{C-u} keychord passes an argument to the subsequent command.
1039 Thus, to indent a region of plain text by 6 spaces, mark the region,
1040 and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1041 Emacs either passes the number 4 to the command or otherwise runs the
1042 command differently than it would otherwise.) @xref{Arguments, ,
1043 Numeric Arguments, emacs, The GNU Emacs Manual}.
1044
1045 If you are reading this in Info using GNU Emacs, you can read through
1046 this whole document just by pressing the space bar, @key{SPC}.
1047 (To learn about Info, type @kbd{C-h i} and then select Info.)
1048
1049 A note on terminology: when I use the word Lisp alone, I often am
1050 referring to the various dialects of Lisp in general, but when I speak
1051 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1052
1053 @node Thank You, , Note for Novices, Preface
1054 @comment node-name, next, previous, up
1055 @unnumberedsec Thank You
1056
1057 My thanks to all who helped me with this book. My especial thanks to
1058 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1059 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1060 Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1061 @w{Philip Johnson} and @w{David Stampe} for their patient
1062 encouragement. My mistakes are my own.
1063
1064 @flushright
1065 Robert J. Chassell
1066 @end flushright
1067
1068 @c ================ Beginning of main text ================
1069
1070 @c Start main text on right-hand (verso) page
1071
1072 @tex
1073 \par\vfill\supereject
1074 \headings off
1075 \ifodd\pageno
1076 \par\vfill\supereject
1077 \else
1078 \par\vfill\supereject
1079 \page\hbox{}\page
1080 \par\vfill\supereject
1081 \fi
1082 @end tex
1083
1084 @iftex
1085 @headings off
1086 @evenheading @thispage @| @| @thischapter
1087 @oddheading @thissection @| @| @thispage
1088 @pageno = 1
1089 @end iftex
1090
1091 @node List Processing, Practicing Evaluation, Preface, Top
1092 @comment node-name, next, previous, up
1093 @chapter List Processing
1094
1095 To the untutored eye, Lisp is a strange programming language. In Lisp
1096 code there are parentheses everywhere. Some people even claim that the
1097 name stands for `Lots of Isolated Silly Parentheses'. But the claim is
1098 unwarranted. Lisp stands for LISt Processing, and the programming
1099 language handles @emph{lists} (and lists of lists) by putting them
1100 between parentheses. The parentheses mark the boundaries of the list.
1101 Sometimes a list is preceded by a single apostrophe or quotation mark,
1102 @samp{'}. Lists are the basis of Lisp.
1103
1104 @menu
1105 * Lisp Lists:: What are lists?
1106 * Run a Program:: Any list in Lisp is a program ready to run.
1107 * Making Errors:: Generating an error message.
1108 * Names & Definitions:: Names of symbols and function definitions.
1109 * Lisp Interpreter:: What the Lisp interpreter does.
1110 * Evaluation:: Running a program.
1111 * Variables:: Returning a value from a variable.
1112 * Arguments:: Passing information to a function.
1113 * set & setq:: Setting the value of a variable.
1114 * Summary:: The major points.
1115 * Error Message Exercises::
1116 @end menu
1117
1118 @node Lisp Lists, Run a Program, List Processing, List Processing
1119 @comment node-name, next, previous, up
1120 @section Lisp Lists
1121 @cindex Lisp Lists
1122
1123 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1124 This list is preceded by a single apostrophe. It could just as well be
1125 written as follows, which looks more like the kind of list you are likely
1126 to be familiar with:
1127
1128 @smallexample
1129 @group
1130 '(rose
1131 violet
1132 daisy
1133 buttercup)
1134 @end group
1135 @end smallexample
1136
1137 @noindent
1138 The elements of this list are the names of the four different flowers,
1139 separated from each other by whitespace and surrounded by parentheses,
1140 like flowers in a field with a stone wall around them.
1141 @cindex Flowers in a field
1142
1143 @menu
1144 * Numbers Lists:: List have numbers, other lists, in them.
1145 * Lisp Atoms:: Elemental entities.
1146 * Whitespace in Lists:: Formating lists to be readable.
1147 * Typing Lists:: How GNU Emacs helps you type lists.
1148 @end menu
1149
1150 @node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1151 @ifnottex
1152 @unnumberedsubsec Numbers, Lists inside of Lists
1153 @end ifnottex
1154
1155 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1156 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1157 separated by whitespace.
1158
1159 In Lisp, both data and programs are represented the same way; that is,
1160 they are both lists of words, numbers, or other lists, separated by
1161 whitespace and surrounded by parentheses. (Since a program looks like
1162 data, one program may easily serve as data for another; this is a very
1163 powerful feature of Lisp.) (Incidentally, these two parenthetical
1164 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1165 @samp{.} as punctuation marks.)
1166
1167 @need 1200
1168 Here is another list, this time with a list inside of it:
1169
1170 @smallexample
1171 '(this list has (a list inside of it))
1172 @end smallexample
1173
1174 The components of this list are the words @samp{this}, @samp{list},
1175 @samp{has}, and the list @samp{(a list inside of it)}. The interior
1176 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1177 @samp{of}, @samp{it}.
1178
1179 @node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1180 @comment node-name, next, previous, up
1181 @subsection Lisp Atoms
1182 @cindex Lisp Atoms
1183
1184 In Lisp, what we have been calling words are called @dfn{atoms}. This
1185 term comes from the historical meaning of the word atom, which means
1186 `indivisible'. As far as Lisp is concerned, the words we have been
1187 using in the lists cannot be divided into any smaller parts and still
1188 mean the same thing as part of a program; likewise with numbers and
1189 single character symbols like @samp{+}. On the other hand, unlike an
1190 atom, a list can be split into parts. (@xref{car cdr & cons, ,
1191 @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1192
1193 In a list, atoms are separated from each other by whitespace. They can be
1194 right next to a parenthesis.
1195
1196 @cindex @samp{empty list} defined
1197 Technically speaking, a list in Lisp consists of parentheses surrounding
1198 atoms separated by whitespace or surrounding other lists or surrounding
1199 both atoms and other lists. A list can have just one atom in it or
1200 have nothing in it at all. A list with nothing in it looks like this:
1201 @code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1202 empty list is considered both an atom and a list at the same time.
1203
1204 @cindex Symbolic expressions, introduced
1205 @cindex @samp{expression} defined
1206 @cindex @samp{form} defined
1207 The printed representation of both atoms and lists are called
1208 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1209 The word @dfn{expression} by itself can refer to either the printed
1210 representation, or to the atom or list as it is held internally in the
1211 computer. Often, people use the term @dfn{expression}
1212 indiscriminately. (Also, in many texts, the word @dfn{form} is used
1213 as a synonym for expression.)
1214
1215 Incidentally, the atoms that make up our universe were named such when
1216 they were thought to be indivisible; but it has been found that physical
1217 atoms are not indivisible. Parts can split off an atom or it can
1218 fission into two parts of roughly equal size. Physical atoms were named
1219 prematurely, before their truer nature was found. In Lisp, certain
1220 kinds of atom, such as an array, can be separated into parts; but the
1221 mechanism for doing this is different from the mechanism for splitting a
1222 list. As far as list operations are concerned, the atoms of a list are
1223 unsplittable.
1224
1225 As in English, the meanings of the component letters of a Lisp atom
1226 are different from the meaning the letters make as a word. For
1227 example, the word for the South American sloth, the @samp{ai}, is
1228 completely different from the two words, @samp{a}, and @samp{i}.
1229
1230 There are many kinds of atom in nature but only a few in Lisp: for
1231 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1232 as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1233 listed in the examples above are all symbols. In everyday Lisp
1234 conversation, the word ``atom'' is not often used, because programmers
1235 usually try to be more specific about what kind of atom they are dealing
1236 with. Lisp programming is mostly about symbols (and sometimes numbers)
1237 within lists. (Incidentally, the preceding three word parenthetical
1238 remark is a proper list in Lisp, since it consists of atoms, which in
1239 this case are symbols, separated by whitespace and enclosed by
1240 parentheses, without any non-Lisp punctuation.)
1241
1242 @need 1250
1243 In addition, text between double quotation marks---even sentences or
1244 paragraphs---is an atom. Here is an example:
1245 @cindex Text between double quotation marks
1246
1247 @smallexample
1248 '(this list includes "text between quotation marks.")
1249 @end smallexample
1250
1251 @cindex @samp{string} defined
1252 @noindent
1253 In Lisp, all of the quoted text including the punctuation mark and the
1254 blank spaces is a single atom. This kind of atom is called a
1255 @dfn{string} (for `string of characters') and is the sort of thing that
1256 is used for messages that a computer can print for a human to read.
1257 Strings are a different kind of atom than numbers or symbols and are
1258 used differently.
1259
1260 @node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1261 @comment node-name, next, previous, up
1262 @subsection Whitespace in Lists
1263 @cindex Whitespace in lists
1264
1265 @need 1200
1266 The amount of whitespace in a list does not matter. From the point of view
1267 of the Lisp language,
1268
1269 @smallexample
1270 @group
1271 '(this list
1272 looks like this)
1273 @end group
1274 @end smallexample
1275
1276 @need 800
1277 @noindent
1278 is exactly the same as this:
1279
1280 @smallexample
1281 '(this list looks like this)
1282 @end smallexample
1283
1284 Both examples show what to Lisp is the same list, the list made up of
1285 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1286 @samp{this} in that order.
1287
1288 Extra whitespace and newlines are designed to make a list more readable
1289 by humans. When Lisp reads the expression, it gets rid of all the extra
1290 whitespace (but it needs to have at least one space between atoms in
1291 order to tell them apart.)
1292
1293 Odd as it seems, the examples we have seen cover almost all of what Lisp
1294 lists look like! Every other list in Lisp looks more or less like one
1295 of these examples, except that the list may be longer and more complex.
1296 In brief, a list is between parentheses, a string is between quotation
1297 marks, a symbol looks like a word, and a number looks like a number.
1298 (For certain situations, square brackets, dots and a few other special
1299 characters may be used; however, we will go quite far without them.)
1300
1301 @node Typing Lists, , Whitespace in Lists, Lisp Lists
1302 @comment node-name, next, previous, up
1303 @subsection GNU Emacs Helps You Type Lists
1304 @cindex Help typing lists
1305 @cindex Formatting help
1306
1307 When you type a Lisp expression in GNU Emacs using either Lisp
1308 Interaction mode or Emacs Lisp mode, you have available to you several
1309 commands to format the Lisp expression so it is easy to read. For
1310 example, pressing the @key{TAB} key automatically indents the line the
1311 cursor is on by the right amount. A command to properly indent the
1312 code in a region is customarily bound to @kbd{M-C-\}. Indentation is
1313 designed so that you can see which elements of a list belongs to which
1314 list---elements of a sub-list are indented more than the elements of
1315 the enclosing list.
1316
1317 In addition, when you type a closing parenthesis, Emacs momentarily
1318 jumps the cursor back to the matching opening parenthesis, so you can
1319 see which one it is. This is very useful, since every list you type
1320 in Lisp must have its closing parenthesis match its opening
1321 parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1322 Manual}, for more information about Emacs' modes.)
1323
1324 @node Run a Program, Making Errors, Lisp Lists, List Processing
1325 @comment node-name, next, previous, up
1326 @section Run a Program
1327 @cindex Run a program
1328 @cindex Program, running one
1329
1330 @cindex @samp{evaluate} defined
1331 A list in Lisp---any list---is a program ready to run. If you run it
1332 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1333 of three things: do nothing except return to you the list itself; send
1334 you an error message; or, treat the first symbol in the list as a
1335 command to do something. (Usually, of course, it is the last of these
1336 three things that you really want!)
1337
1338 @c use code for the single apostrophe, not samp.
1339 The single apostrophe, @code{'}, that I put in front of some of the
1340 example lists in preceding sections is called a @dfn{quote}; when it
1341 precedes a list, it tells Lisp to do nothing with the list, other than
1342 take it as it is written. But if there is no quote preceding a list,
1343 the first item of the list is special: it is a command for the computer
1344 to obey. (In Lisp, these commands are called @emph{functions}.) The list
1345 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1346 understands that the @code{+} is an instruction to do something with the
1347 rest of the list: add the numbers that follow.
1348
1349 @need 1250
1350 If you are reading this inside of GNU Emacs in Info, here is how you can
1351 evaluate such a list: place your cursor immediately after the right
1352 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1353
1354 @smallexample
1355 (+ 2 2)
1356 @end smallexample
1357
1358 @c use code for the number four, not samp.
1359 @noindent
1360 You will see the number @code{4} appear in the echo area. (In the
1361 jargon, what you have just done is ``evaluate the list.'' The echo area
1362 is the line at the bottom of the screen that displays or ``echoes''
1363 text.) Now try the same thing with a quoted list: place the cursor
1364 right after the following list and type @kbd{C-x C-e}:
1365
1366 @smallexample
1367 '(this is a quoted list)
1368 @end smallexample
1369
1370 @noindent
1371 You will see @code{(this is a quoted list)} appear in the echo area.
1372
1373 @cindex Lisp interpreter, explained
1374 @cindex Interpreter, Lisp, explained
1375 In both cases, what you are doing is giving a command to the program
1376 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1377 interpreter a command to evaluate the expression. The name of the Lisp
1378 interpreter comes from the word for the task done by a human who comes
1379 up with the meaning of an expression---who ``interprets'' it.
1380
1381 You can also evaluate an atom that is not part of a list---one that is
1382 not surrounded by parentheses; again, the Lisp interpreter translates
1383 from the humanly readable expression to the language of the computer.
1384 But before discussing this (@pxref{Variables}), we will discuss what the
1385 Lisp interpreter does when you make an error.
1386
1387 @node Making Errors, Names & Definitions, Run a Program, List Processing
1388 @comment node-name, next, previous, up
1389 @section Generate an Error Message
1390 @cindex Generate an error message
1391 @cindex Error message generation
1392
1393 Partly so you won't worry if you do it accidentally, we will now give
1394 a command to the Lisp interpreter that generates an error message.
1395 This is a harmless activity; and indeed, we will often try to generate
1396 error messages intentionally. Once you understand the jargon, error
1397 messages can be informative. Instead of being called ``error''
1398 messages, they should be called ``help'' messages. They are like
1399 signposts to a traveller in a strange country; deciphering them can be
1400 hard, but once understood, they can point the way.
1401
1402 The error message is generated by a built-in GNU Emacs debugger. We
1403 will `enter the debugger'. You get out of the debugger by typing @code{q}.
1404
1405 What we will do is evaluate a list that is not quoted and does not
1406 have a meaningful command as its first element. Here is a list almost
1407 exactly the same as the one we just used, but without the single-quote
1408 in front of it. Position the cursor right after it and type @kbd{C-x
1409 C-e}:
1410
1411 @smallexample
1412 (this is an unquoted list)
1413 @end smallexample
1414
1415 @noindent
1416 What you see depends on which version of Emacs you are running. GNU
1417 Emacs version 21 provides more information than version 20 and before.
1418 First, the more recent result of generating an error; then the
1419 earlier, version 20 result.
1420
1421 @need 1250
1422 @noindent
1423 In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1424 you will see the following in it:
1425
1426 @smallexample
1427 @group
1428 ---------- Buffer: *Backtrace* ----------
1429 Debugger entered--Lisp error: (void-function this)
1430 (this is an unquoted list)
1431 eval((this is an unquoted list))
1432 eval-last-sexp-1(nil)
1433 eval-last-sexp(nil)
1434 call-interactively(eval-last-sexp)
1435 ---------- Buffer: *Backtrace* ----------
1436 @end group
1437 @end smallexample
1438
1439 @need 1200
1440 @noindent
1441 Your cursor will be in this window (you may have to wait a few seconds
1442 before it becomes visible). To quit the debugger and make the
1443 debugger window go away, type:
1444
1445 @smallexample
1446 q
1447 @end smallexample
1448
1449 @noindent
1450 Please type @kbd{q} right now, so you become confident that you can
1451 get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1452 it.
1453
1454 @cindex @samp{function} defined
1455 Based on what we already know, we can almost read this error message.
1456
1457 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1458 you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1459 interactive call to the command @code{eval-last-sexp}. @code{eval} is
1460 an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1461 `symbolic expression'. The command means `evaluate last symbolic
1462 expression', which is the expression just before your cursor.
1463
1464 Each line above tells you what the Lisp interpreter evaluated next.
1465 The most recent action is at the top. The buffer is called the
1466 @file{*Backtrace*} buffer because it enables you to track Emacs
1467 backwards.
1468
1469 @need 800
1470 At the top of the @file{*Backtrace*} buffer, you see the line:
1471
1472 @smallexample
1473 Debugger entered--Lisp error: (void-function this)
1474 @end smallexample
1475
1476 @noindent
1477 The Lisp interpreter tried to evaluate the first atom of the list, the
1478 word @samp{this}. It is this action that generated the error message
1479 @samp{void-function this}.
1480
1481 The message contains the words @samp{void-function} and @samp{this}.
1482
1483 @cindex @samp{function} defined
1484 The word @samp{function} was mentioned once before. It is a very
1485 important word. For our purposes, we can define it by saying that a
1486 @dfn{function} is a set of instructions to the computer that tell the
1487 computer to do something.
1488
1489 Now we can begin to understand the error message: @samp{void-function
1490 this}. The function (that is, the word @samp{this}) does not have a
1491 definition of any set of instructions for the computer to carry out.
1492
1493 The slightly odd word, @samp{void-function}, is designed to cover the
1494 way Emacs Lisp is implemented, which is that when a symbol does not
1495 have a function definition attached to it, the place that should
1496 contain the instructions is `void'.
1497
1498 On the other hand, since we were able to add 2 plus 2 successfully, by
1499 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1500 have a set of instructions for the computer to obey and those
1501 instructions must be to add the numbers that follow the @code{+}.
1502
1503 @need 1250
1504 In GNU Emacs version 20, and in earlier versions, you will see only
1505 one line of error message; it will appear in the echo area and look
1506 like this:
1507
1508 @smallexample
1509 Symbol's function definition is void:@: this
1510 @end smallexample
1511
1512 @noindent
1513 (Also, your terminal may beep at you---some do, some don't; and others
1514 blink. This is just a device to get your attention.) The message goes
1515 away as soon as you type another key, even just to move the cursor.
1516
1517 We know the meaning of the word @samp{Symbol}. It refers to the first
1518 atom of the list, the word @samp{this}. The word @samp{function}
1519 refers to the instructions that tell the computer what to do.
1520 (Technically, the symbol tells the computer where to find the
1521 instructions, but this is a complication we can ignore for the
1522 moment.)
1523
1524 The error message can be understood: @samp{Symbol's function
1525 definition is void:@: this}. The symbol (that is, the word
1526 @samp{this}) lacks instructions for the computer to carry out.
1527
1528 @node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1529 @comment node-name, next, previous, up
1530 @section Symbol Names and Function Definitions
1531 @cindex Symbol names
1532
1533 We can articulate another characteristic of Lisp based on what we have
1534 discussed so far---an important characteristic: a symbol, like
1535 @code{+}, is not itself the set of instructions for the computer to
1536 carry out. Instead, the symbol is used, perhaps temporarily, as a way
1537 of locating the definition or set of instructions. What we see is the
1538 name through which the instructions can be found. Names of people
1539 work the same way. I can be referred to as @samp{Bob}; however, I am
1540 not the letters @samp{B}, @samp{o}, @samp{b} but am the consciousness
1541 consistently associated with a particular life-form. The name is not
1542 me, but it can be used to refer to me.
1543
1544 In Lisp, one set of instructions can be attached to several names.
1545 For example, the computer instructions for adding numbers can be
1546 linked to the symbol @code{plus} as well as to the symbol @code{+}
1547 (and are in some dialects of Lisp). Among humans, I can be referred
1548 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1549
1550 On the other hand, a symbol can have only one function definition
1551 attached to it at a time. Otherwise, the computer would be confused as
1552 to which definition to use. If this were the case among people, only
1553 one person in the world could be named @samp{Bob}. However, the function
1554 definition to which the name refers can be changed readily.
1555 (@xref{Install, , Install a Function Definition}.)
1556
1557 Since Emacs Lisp is large, it is customary to name symbols in a way
1558 that identifies the part of Emacs to which the function belongs.
1559 Thus, all the names for functions that deal with Texinfo start with
1560 @samp{texinfo-} and those for functions that deal with reading mail
1561 start with @samp{rmail-}.
1562
1563 @node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1564 @comment node-name, next, previous, up
1565 @section The Lisp Interpreter
1566 @cindex Lisp interpreter, what it does
1567 @cindex Interpreter, what it does
1568
1569 Based on what we have seen, we can now start to figure out what the
1570 Lisp interpreter does when we command it to evaluate a list.
1571 First, it looks to see whether there is a quote before the list; if
1572 there is, the interpreter just gives us the list. On the other
1573 hand, if there is no quote, the interpreter looks at the first element
1574 in the list and sees whether it has a function definition. If it does,
1575 the interpreter carries out the instructions in the function definition.
1576 Otherwise, the interpreter prints an error message.
1577
1578 This is how Lisp works. Simple. There are added complications which we
1579 will get to in a minute, but these are the fundamentals. Of course, to
1580 write Lisp programs, you need to know how to write function definitions
1581 and attach them to names, and how to do this without confusing either
1582 yourself or the computer.
1583
1584 @menu
1585 * Complications:: Variables, Special forms, Lists within.
1586 * Byte Compiling:: Specially processing code for speed.
1587 @end menu
1588
1589 @node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1590 @ifnottex
1591 @unnumberedsubsec Complications
1592 @end ifnottex
1593
1594 Now, for the first complication. In addition to lists, the Lisp
1595 interpreter can evaluate a symbol that is not quoted and does not have
1596 parentheses around it. The Lisp interpreter will attempt to determine
1597 the symbol's value as a @dfn{variable}. This situation is described
1598 in the section on variables. (@xref{Variables}.)
1599
1600 @cindex Special form
1601 The second complication occurs because some functions are unusual and do
1602 not work in the usual manner. Those that don't are called @dfn{special
1603 forms}. They are used for special jobs, like defining a function, and
1604 there are not many of them. In the next few chapters, you will be
1605 introduced to several of the more important special forms.
1606
1607 The third and final complication is this: if the function that the
1608 Lisp interpreter is looking at is not a special form, and if it is part
1609 of a list, the Lisp interpreter looks to see whether the list has a list
1610 inside of it. If there is an inner list, the Lisp interpreter first
1611 figures out what it should do with the inside list, and then it works on
1612 the outside list. If there is yet another list embedded inside the
1613 inner list, it works on that one first, and so on. It always works on
1614 the innermost list first. The interpreter works on the innermost list
1615 first, to evaluate the result of that list. The result may be
1616 used by the enclosing expression.
1617
1618 Otherwise, the interpreter works left to right, from one expression to
1619 the next.
1620
1621 @node Byte Compiling, , Complications, Lisp Interpreter
1622 @subsection Byte Compiling
1623 @cindex Byte compiling
1624
1625 One other aspect of interpreting: the Lisp interpreter is able to
1626 interpret two kinds of entity: humanly readable code, on which we will
1627 focus exclusively, and specially processed code, called @dfn{byte
1628 compiled} code, which is not humanly readable. Byte compiled code
1629 runs faster than humanly readable code.
1630
1631 You can transform humanly readable code into byte compiled code by
1632 running one of the compile commands such as @code{byte-compile-file}.
1633 Byte compiled code is usually stored in a file that ends with a
1634 @file{.elc} extension rather than a @file{.el} extension. You will
1635 see both kinds of file in the @file{emacs/lisp} directory; the files
1636 to read are those with @file{.el} extensions.
1637
1638 As a practical matter, for most things you might do to customize or
1639 extend Emacs, you do not need to byte compile; and I will not discuss
1640 the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1641 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1642 compilation.
1643
1644 @node Evaluation, Variables, Lisp Interpreter, List Processing
1645 @comment node-name, next, previous, up
1646 @section Evaluation
1647 @cindex Evaluation
1648
1649 When the Lisp interpreter works on an expression, the term for the
1650 activity is called @dfn{evaluation}. We say that the interpreter
1651 `evaluates the expression'. I've used this term several times before.
1652 The word comes from its use in everyday language, `to ascertain the
1653 value or amount of; to appraise', according to @cite{Webster's New
1654 Collegiate Dictionary}.
1655
1656 After evaluating an expression, the Lisp interpreter will most likely
1657 @dfn{return} the value that the computer produces by carrying out the
1658 instructions it found in the function definition, or perhaps it will
1659 give up on that function and produce an error message. (The interpreter
1660 may also find itself tossed, so to speak, to a different function or it
1661 may attempt to repeat continually what it is doing for ever and ever in
1662 what is called an `infinite loop'. These actions are less common; and
1663 we can ignore them.) Most frequently, the interpreter returns a value.
1664
1665 @cindex @samp{side effect} defined
1666 At the same time the interpreter returns a value, it may do something
1667 else as well, such as move a cursor or copy a file; this other kind of
1668 action is called a @dfn{side effect}. Actions that we humans think are
1669 important, such as printing results, are often ``side effects'' to the
1670 Lisp interpreter. The jargon can sound peculiar, but it turns out that
1671 it is fairly easy to learn to use side effects.
1672
1673 In summary, evaluating a symbolic expression most commonly causes the
1674 Lisp interpreter to return a value and perhaps carry out a side effect;
1675 or else produce an error.
1676
1677 @menu
1678 * Evaluating Inner Lists:: Lists within lists...
1679 @end menu
1680
1681 @node Evaluating Inner Lists, , Evaluation, Evaluation
1682 @comment node-name, next, previous, up
1683 @subsection Evaluating Inner Lists
1684 @cindex Inner list evaluation
1685 @cindex Evaluating inner lists
1686
1687 If evaluation applies to a list that is inside another list, the outer
1688 list may use the value returned by the first evaluation as information
1689 when the outer list is evaluated. This explains why inner expressions
1690 are evaluated first: the values they return are used by the outer
1691 expressions.
1692
1693 @need 1250
1694 We can investigate this process by evaluating another addition example.
1695 Place your cursor after the following expression and type @kbd{C-x C-e}:
1696
1697 @smallexample
1698 (+ 2 (+ 3 3))
1699 @end smallexample
1700
1701 @noindent
1702 The number 8 will appear in the echo area.
1703
1704 What happens is that the Lisp interpreter first evaluates the inner
1705 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1706 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1707 returns the value 8. Since there are no more enclosing expressions to
1708 evaluate, the interpreter prints that value in the echo area.
1709
1710 Now it is easy to understand the name of the command invoked by the
1711 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1712 letters @code{sexp} are an abbreviation for `symbolic expression', and
1713 @code{eval} is an abbreviation for `evaluate'. The command means
1714 `evaluate last symbolic expression'.
1715
1716 As an experiment, you can try evaluating the expression by putting the
1717 cursor at the beginning of the next line immediately following the
1718 expression, or inside the expression.
1719
1720 @need 800
1721 Here is another copy of the expression:
1722
1723 @smallexample
1724 (+ 2 (+ 3 3))
1725 @end smallexample
1726
1727 @noindent
1728 If you place the cursor at the beginning of the blank line that
1729 immediately follows the expression and type @kbd{C-x C-e}, you will
1730 still get the value 8 printed in the echo area. Now try putting the
1731 cursor inside the expression. If you put it right after the next to
1732 last parenthesis (so it appears to sit on top of the last parenthesis),
1733 you will get a 6 printed in the echo area! This is because the command
1734 evaluates the expression @code{(+ 3 3)}.
1735
1736 Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1737 you will get the number itself. In Lisp, if you evaluate a number, you
1738 get the number itself---this is how numbers differ from symbols. If you
1739 evaluate a list starting with a symbol like @code{+}, you will get a
1740 value returned that is the result of the computer carrying out the
1741 instructions in the function definition attached to that name. If a
1742 symbol by itself is evaluated, something different happens, as we will
1743 see in the next section.
1744
1745 @node Variables, Arguments, Evaluation, List Processing
1746 @comment node-name, next, previous, up
1747 @section Variables
1748 @cindex Variables
1749
1750 In Emacs Lisp, a symbol can have a value attached to it just as it can
1751 have a function definition attached to it. The two are different.
1752 The function definition is a set of instructions that a computer will
1753 obey. A value, on the other hand, is something, such as number or a
1754 name, that can vary (which is why such a symbol is called a variable).
1755 The value of a symbol can be any expression in Lisp, such as a symbol,
1756 number, list, or string. A symbol that has a value is often called a
1757 @dfn{variable}.
1758
1759 A symbol can have both a function definition and a value attached to
1760 it at the same time. Or it can have just one or the other.
1761 The two are separate. This is somewhat similar
1762 to the way the name Cambridge can refer to the city in Massachusetts
1763 and have some information attached to the name as well, such as
1764 ``great programming center''.
1765
1766 @ignore
1767 (Incidentally, in Emacs Lisp, a symbol can have two
1768 other things attached to it, too: a property list and a documentation
1769 string; these are discussed later.)
1770 @end ignore
1771
1772 Another way to think about this is to imagine a symbol as being a chest
1773 of drawers. The function definition is put in one drawer, the value in
1774 another, and so on. What is put in the drawer holding the value can be
1775 changed without affecting the contents of the drawer holding the
1776 function definition, and vice-versa.
1777
1778 @menu
1779 * fill-column Example::
1780 * Void Function:: The error message for a symbol
1781 without a function.
1782 * Void Variable:: The error message for a symbol without a value.
1783 @end menu
1784
1785 @node fill-column Example, Void Function, Variables, Variables
1786 @ifnottex
1787 @unnumberedsubsec @code{fill-column}, an Example Variable
1788 @end ifnottex
1789
1790 @findex fill-column, @r{an example variable}
1791 @cindex Example variable, @code{fill-column}
1792 @cindex Variable, example of, @code{fill-column}
1793 The variable @code{fill-column} illustrates a symbol with a value
1794 attached to it: in every GNU Emacs buffer, this symbol is set to some
1795 value, usually 72 or 70, but sometimes to some other value. To find the
1796 value of this symbol, evaluate it by itself. If you are reading this in
1797 Info inside of GNU Emacs, you can do this by putting the cursor after
1798 the symbol and typing @kbd{C-x C-e}:
1799
1800 @smallexample
1801 fill-column
1802 @end smallexample
1803
1804 @noindent
1805 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1806 area. This is the value for which @code{fill-column} is set for me as I
1807 write this. It may be different for you in your Info buffer. Notice
1808 that the value returned as a variable is printed in exactly the same way
1809 as the value returned by a function carrying out its instructions. From
1810 the point of view of the Lisp interpreter, a value returned is a value
1811 returned. What kind of expression it came from ceases to matter once
1812 the value is known.
1813
1814 A symbol can have any value attached to it or, to use the jargon, we can
1815 @dfn{bind} the variable to a value: to a number, such as 72; to a
1816 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1817 oak)}; we can even bind a variable to a function definition.
1818
1819 A symbol can be bound to a value in several ways. @xref{set & setq, ,
1820 Setting the Value of a Variable}, for information about one way to do
1821 this.
1822
1823 @node Void Function, Void Variable, fill-column Example, Variables
1824 @comment node-name, next, previous, up
1825 @subsection Error Message for a Symbol Without a Function
1826 @cindex Symbol without function error
1827 @cindex Error for symbol without function
1828
1829 When we evaluated @code{fill-column} to find its value as a variable,
1830 we did not place parentheses around the word. This is because we did
1831 not intend to use it as a function name.
1832
1833 If @code{fill-column} were the first or only element of a list, the
1834 Lisp interpreter would attempt to find the function definition
1835 attached to it. But @code{fill-column} has no function definition.
1836 Try evaluating this:
1837
1838 @smallexample
1839 (fill-column)
1840 @end smallexample
1841
1842 @need 1250
1843 @noindent
1844 In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1845 that says:
1846
1847 @smallexample
1848 @group
1849 ---------- Buffer: *Backtrace* ----------
1850 Debugger entered--Lisp error: (void-function fill-column)
1851 (fill-column)
1852 eval((fill-column))
1853 eval-last-sexp-1(nil)
1854 eval-last-sexp(nil)
1855 call-interactively(eval-last-sexp)
1856 ---------- Buffer: *Backtrace* ----------
1857 @end group
1858 @end smallexample
1859
1860 @noindent
1861 (Remember, to quit the debugger and make the debugger window go away,
1862 type @kbd{q} in the @file{*Backtrace*} buffer.)
1863
1864 @need 800
1865 In GNU Emacs 20 and before, you will produce an error message that says:
1866
1867 @smallexample
1868 Symbol's function definition is void:@: fill-column
1869 @end smallexample
1870
1871 @noindent
1872 (The message will go away away as soon as you move the cursor or type
1873 another key.)
1874
1875 @node Void Variable, , Void Function, Variables
1876 @comment node-name, next, previous, up
1877 @subsection Error Message for a Symbol Without a Value
1878 @cindex Symbol without value error
1879 @cindex Error for symbol without value
1880
1881 If you attempt to evaluate a symbol that does not have a value bound to
1882 it, you will receive an error message. You can see this by
1883 experimenting with our 2 plus 2 addition. In the following expression,
1884 put your cursor right after the @code{+}, before the first number 2,
1885 type @kbd{C-x C-e}:
1886
1887 @smallexample
1888 (+ 2 2)
1889 @end smallexample
1890
1891 @need 1500
1892 @noindent
1893 In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1894 says:
1895
1896 @smallexample
1897 @group
1898 ---------- Buffer: *Backtrace* ----------
1899 Debugger entered--Lisp error: (void-variable +)
1900 eval(+)
1901 eval-last-sexp-1(nil)
1902 eval-last-sexp(nil)
1903 call-interactively(eval-last-sexp)
1904 ---------- Buffer: *Backtrace* ----------
1905 @end group
1906 @end smallexample
1907
1908 @noindent
1909 (As with the other times we entered the debugger, you can quit by
1910 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1911
1912 This backtrace is different from the very first error message we saw,
1913 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1914 In this case, the function does not have a value as a variable; while
1915 in the other error message, the function (the word `this') did not
1916 have a definition.
1917
1918 In this experiment with the @code{+}, what we did was cause the Lisp
1919 interpreter to evaluate the @code{+} and look for the value of the
1920 variable instead of the function definition. We did this by placing the
1921 cursor right after the symbol rather than after the parenthesis of the
1922 enclosing list as we did before. As a consequence, the Lisp interpreter
1923 evaluated the preceding s-expression, which in this case was the
1924 @code{+} by itself.
1925
1926 Since @code{+} does not have a value bound to it, just the function
1927 definition, the error message reported that the symbol's value as a
1928 variable was void.
1929
1930 @need 800
1931 In GNU Emacs version 20 and before, your error message will say:
1932
1933 @example
1934 Symbol's value as variable is void:@: +
1935 @end example
1936
1937 @noindent
1938 The meaning is the same as in GNU Emacs 21.
1939
1940 @node Arguments, set & setq, Variables, List Processing
1941 @comment node-name, next, previous, up
1942 @section Arguments
1943 @cindex Arguments
1944 @cindex Passing information to functions
1945
1946 To see how information is passed to functions, let's look again at
1947 our old standby, the addition of two plus two. In Lisp, this is written
1948 as follows:
1949
1950 @smallexample
1951 (+ 2 2)
1952 @end smallexample
1953
1954 If you evaluate this expression, the number 4 will appear in your echo
1955 area. What the Lisp interpreter does is add the numbers that follow
1956 the @code{+}.
1957
1958 @cindex @samp{argument} defined
1959 The numbers added by @code{+} are called the @dfn{arguments} of the
1960 function @code{+}. These numbers are the information that is given to
1961 or @dfn{passed} to the function.
1962
1963 The word `argument' comes from the way it is used in mathematics and
1964 does not refer to a disputation between two people; instead it refers to
1965 the information presented to the function, in this case, to the
1966 @code{+}. In Lisp, the arguments to a function are the atoms or lists
1967 that follow the function. The values returned by the evaluation of
1968 these atoms or lists are passed to the function. Different functions
1969 require different numbers of arguments; some functions require none at
1970 all.@footnote{It is curious to track the path by which the word `argument'
1971 came to have two different meanings, one in mathematics and the other in
1972 everyday English. According to the @cite{Oxford English Dictionary},
1973 the word derives from the Latin for @samp{to make clear, prove}; thus it
1974 came to mean, by one thread of derivation, `the evidence offered as
1975 proof', which is to say, `the information offered', which led to its
1976 meaning in Lisp. But in the other thread of derivation, it came to mean
1977 `to assert in a manner against which others may make counter
1978 assertions', which led to the meaning of the word as a disputation.
1979 (Note here that the English word has two different definitions attached
1980 to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1981 have two different function definitions at the same time.)}
1982
1983 @menu
1984 * Data types:: Types of data passed to a function.
1985 * Args as Variable or List:: An argument can be the value
1986 of a variable or list.
1987 * Variable Number of Arguments:: Some functions may take a
1988 variable number of arguments.
1989 * Wrong Type of Argument:: Passing an argument of the wrong type
1990 to a function.
1991 * message:: A useful function for sending messages.
1992 @end menu
1993
1994 @node Data types, Args as Variable or List, Arguments, Arguments
1995 @comment node-name, next, previous, up
1996 @subsection Arguments' Data Types
1997 @cindex Data types
1998 @cindex Types of data
1999 @cindex Arguments' data types
2000
2001 The type of data that should be passed to a function depends on what
2002 kind of information it uses. The arguments to a function such as
2003 @code{+} must have values that are numbers, since @code{+} adds numbers.
2004 Other functions use different kinds of data for their arguments.
2005
2006 @findex concat
2007 For example, the @code{concat} function links together or unites two or
2008 more strings of text to produce a string. The arguments are strings.
2009 Concatenating the two character strings @code{abc}, @code{def} produces
2010 the single string @code{abcdef}. This can be seen by evaluating the
2011 following:
2012
2013 @smallexample
2014 (concat "abc" "def")
2015 @end smallexample
2016
2017 @noindent
2018 The value produced by evaluating this expression is @code{"abcdef"}.
2019
2020 A function such as @code{substring} uses both a string and numbers as
2021 arguments. The function returns a part of the string, a substring of
2022 the first argument. This function takes three arguments. Its first
2023 argument is the string of characters, the second and third arguments are
2024 numbers that indicate the beginning and end of the substring. The
2025 numbers are a count of the number of characters (including spaces and
2026 punctuations) from the beginning of the string.
2027
2028 @need 800
2029 For example, if you evaluate the following:
2030
2031 @smallexample
2032 (substring "The quick brown fox jumped." 16 19)
2033 @end smallexample
2034
2035 @noindent
2036 you will see @code{"fox"} appear in the echo area. The arguments are the
2037 string and the two numbers.
2038
2039 Note that the string passed to @code{substring} is a single atom even
2040 though it is made up of several words separated by spaces. Lisp counts
2041 everything between the two quotation marks as part of the string,
2042 including the spaces. You can think of the @code{substring} function as
2043 a kind of `atom smasher' since it takes an otherwise indivisible atom
2044 and extracts a part. However, @code{substring} is only able to extract
2045 a substring from an argument that is a string, not from another type of
2046 atom such as a number or symbol.
2047
2048 @node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2049 @comment node-name, next, previous, up
2050 @subsection An Argument as the Value of a Variable or List
2051
2052 An argument can be a symbol that returns a value when it is evaluated.
2053 For example, when the symbol @code{fill-column} by itself is evaluated,
2054 it returns a number. This number can be used in an addition.
2055
2056 @need 1250
2057 Position the cursor after the following expression and type @kbd{C-x
2058 C-e}:
2059
2060 @smallexample
2061 (+ 2 fill-column)
2062 @end smallexample
2063
2064 @noindent
2065 The value will be a number two more than what you get by evaluating
2066 @code{fill-column} alone. For me, this is 74, because the value of
2067 @code{fill-column} is 72.
2068
2069 As we have just seen, an argument can be a symbol that returns a value
2070 when evaluated. In addition, an argument can be a list that returns a
2071 value when it is evaluated. For example, in the following expression,
2072 the arguments to the function @code{concat} are the strings
2073 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2074 @code{(number-to-string (+ 2 fill-column))}.
2075
2076 @c For Emacs 21, need number-to-string
2077 @smallexample
2078 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2079 @end smallexample
2080
2081 @noindent
2082 If you evaluate this expression---and if, as with my Emacs,
2083 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2084 appear in the echo area. (Note that you must put spaces after the
2085 word @samp{The} and before the word @samp{red} so they will appear in
2086 the final string. The function @code{number-to-string} converts the
2087 integer that the addition function returns to a string.
2088 @code{number-to-string} is also known as @code{int-to-string}.)
2089
2090 @node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2091 @comment node-name, next, previous, up
2092 @subsection Variable Number of Arguments
2093 @cindex Variable number of arguments
2094 @cindex Arguments, variable number of
2095
2096 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2097 number of arguments. (The @code{*} is the symbol for multiplication.)
2098 This can be seen by evaluating each of the following expressions in
2099 the usual way. What you will see in the echo area is printed in this
2100 text after @samp{@result{}}, which you may read as `evaluates to'.
2101
2102 @need 1250
2103 In the first set, the functions have no arguments:
2104
2105 @smallexample
2106 @group
2107 (+) @result{} 0
2108
2109 (*) @result{} 1
2110 @end group
2111 @end smallexample
2112
2113 @need 1250
2114 In this set, the functions have one argument each:
2115
2116 @smallexample
2117 @group
2118 (+ 3) @result{} 3
2119
2120 (* 3) @result{} 3
2121 @end group
2122 @end smallexample
2123
2124 @need 1250
2125 In this set, the functions have three arguments each:
2126
2127 @smallexample
2128 @group
2129 (+ 3 4 5) @result{} 12
2130
2131 (* 3 4 5) @result{} 60
2132 @end group
2133 @end smallexample
2134
2135 @node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2136 @comment node-name, next, previous, up
2137 @subsection Using the Wrong Type Object as an Argument
2138 @cindex Wrong type of argument
2139 @cindex Argument, wrong type of
2140
2141 When a function is passed an argument of the wrong type, the Lisp
2142 interpreter produces an error message. For example, the @code{+}
2143 function expects the values of its arguments to be numbers. As an
2144 experiment we can pass it the quoted symbol @code{hello} instead of a
2145 number. Position the cursor after the following expression and type
2146 @kbd{C-x C-e}:
2147
2148 @smallexample
2149 (+ 2 'hello)
2150 @end smallexample
2151
2152 @noindent
2153 When you do this you will generate an error message. What has happened
2154 is that @code{+} has tried to add the 2 to the value returned by
2155 @code{'hello}, but the value returned by @code{'hello} is the symbol
2156 @code{hello}, not a number. Only numbers can be added. So @code{+}
2157 could not carry out its addition.
2158
2159 @need 1250
2160 In GNU Emacs version 21, you will create and enter a
2161 @file{*Backtrace*} buffer that says:
2162
2163 @noindent
2164 @smallexample
2165 @group
2166 ---------- Buffer: *Backtrace* ----------
2167 Debugger entered--Lisp error:
2168 (wrong-type-argument number-or-marker-p hello)
2169 +(2 hello)
2170 eval((+ 2 (quote hello)))
2171 eval-last-sexp-1(nil)
2172 eval-last-sexp(nil)
2173 call-interactively(eval-last-sexp)
2174 ---------- Buffer: *Backtrace* ----------
2175 @end group
2176 @end smallexample
2177
2178 @need 1250
2179 As usual, the error message tries to be helpful and makes sense after you
2180 learn how to read it.
2181
2182 The first part of the error message is straightforward; it says
2183 @samp{wrong type argument}. Next comes the mysterious jargon word
2184 @w{@samp{number-or-marker-p}}. This word is trying to tell you what
2185 kind of argument the @code{+} expected.
2186
2187 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2188 trying to determine whether the information presented it (the value of
2189 the argument) is a number or a marker (a special object representing a
2190 buffer position). What it does is test to see whether the @code{+} is
2191 being given numbers to add. It also tests to see whether the
2192 argument is something called a marker, which is a specific feature of
2193 Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2194 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2195 its position is kept as a marker. The mark can be considered a
2196 number---the number of characters the location is from the beginning
2197 of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2198 numeric value of marker positions as numbers.
2199
2200 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2201 practice started in the early days of Lisp programming. The @samp{p}
2202 stands for `predicate'. In the jargon used by the early Lisp
2203 researchers, a predicate refers to a function to determine whether some
2204 property is true or false. So the @samp{p} tells us that
2205 @code{number-or-marker-p} is the name of a function that determines
2206 whether it is true or false that the argument supplied is a number or
2207 a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2208 a function that tests whether its argument has the value of zero, and
2209 @code{listp}, a function that tests whether its argument is a list.
2210
2211 Finally, the last part of the error message is the symbol @code{hello}.
2212 This is the value of the argument that was passed to @code{+}. If the
2213 addition had been passed the correct type of object, the value passed
2214 would have been a number, such as 37, rather than a symbol like
2215 @code{hello}. But then you would not have got the error message.
2216
2217 @need 1250
2218 In GNU Emacs version 20 and before, the echo area displays an error
2219 message that says:
2220
2221 @smallexample
2222 Wrong type argument:@: number-or-marker-p, hello
2223 @end smallexample
2224
2225 This says, in different words, the same as the top line of the
2226 @file{*Backtrace*} buffer.
2227
2228 @node message, , Wrong Type of Argument, Arguments
2229 @comment node-name, next, previous, up
2230 @subsection The @code{message} Function
2231 @findex message
2232
2233 Like @code{+}, the @code{message} function takes a variable number of
2234 arguments. It is used to send messages to the user and is so useful
2235 that we will describe it here.
2236
2237 @need 1250
2238 A message is printed in the echo area. For example, you can print a
2239 message in your echo area by evaluating the following list:
2240
2241 @smallexample
2242 (message "This message appears in the echo area!")
2243 @end smallexample
2244
2245 The whole string between double quotation marks is a single argument
2246 and is printed @i{in toto}. (Note that in this example, the message
2247 itself will appear in the echo area within double quotes; that is
2248 because you see the value returned by the @code{message} function. In
2249 most uses of @code{message} in programs that you write, the text will
2250 be printed in the echo area as a side-effect, without the quotes.
2251 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2252 detail}, for an example of this.)
2253
2254 However, if there is a @samp{%s} in the quoted string of characters, the
2255 @code{message} function does not print the @samp{%s} as such, but looks
2256 to the argument that follows the string. It evaluates the second
2257 argument and prints the value at the location in the string where the
2258 @samp{%s} is.
2259
2260 @need 1250
2261 You can see this by positioning the cursor after the following
2262 expression and typing @kbd{C-x C-e}:
2263
2264 @smallexample
2265 (message "The name of this buffer is: %s." (buffer-name))
2266 @end smallexample
2267
2268 @noindent
2269 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2270 echo area. The function @code{buffer-name} returns the name of the
2271 buffer as a string, which the @code{message} function inserts in place
2272 of @code{%s}.
2273
2274 To print a value as an integer, use @samp{%d} in the same way as
2275 @samp{%s}. For example, to print a message in the echo area that
2276 states the value of the @code{fill-column}, evaluate the following:
2277
2278 @smallexample
2279 (message "The value of fill-column is %d." fill-column)
2280 @end smallexample
2281
2282 @noindent
2283 On my system, when I evaluate this list, @code{"The value of
2284 fill-column is 72."} appears in my echo area@footnote{Actually, you
2285 can use @code{%s} to print a number. It is non-specific. @code{%d}
2286 prints only the part of a number left of a decimal point, and not
2287 anything that is not a number.}.
2288
2289 If there is more than one @samp{%s} in the quoted string, the value of
2290 the first argument following the quoted string is printed at the
2291 location of the first @samp{%s} and the value of the second argument is
2292 printed at the location of the second @samp{%s}, and so on.
2293
2294 @need 1250
2295 For example, if you evaluate the following,
2296
2297 @smallexample
2298 @group
2299 (message "There are %d %s in the office!"
2300 (- fill-column 14) "pink elephants")
2301 @end group
2302 @end smallexample
2303
2304 @noindent
2305 a rather whimsical message will appear in your echo area. On my system
2306 it says, @code{"There are 58 pink elephants in the office!"}.
2307
2308 The expression @code{(- fill-column 14)} is evaluated and the resulting
2309 number is inserted in place of the @samp{%d}; and the string in double
2310 quotes, @code{"pink elephants"}, is treated as a single argument and
2311 inserted in place of the @samp{%s}. (That is to say, a string between
2312 double quotes evaluates to itself, like a number.)
2313
2314 Finally, here is a somewhat complex example that not only illustrates
2315 the computation of a number, but also shows how you can use an
2316 expression within an expression to generate the text that is substituted
2317 for @samp{%s}:
2318
2319 @smallexample
2320 @group
2321 (message "He saw %d %s"
2322 (- fill-column 34)
2323 (concat "red "
2324 (substring
2325 "The quick brown foxes jumped." 16 21)
2326 " leaping."))
2327 @end group
2328 @end smallexample
2329
2330 In this example, @code{message} has three arguments: the string,
2331 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2332 the expression beginning with the function @code{concat}. The value
2333 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2334 in place of the @samp{%d}; and the value returned by the expression
2335 beginning with @code{concat} is inserted in place of the @samp{%s}.
2336
2337 When I evaluate the expression, the message @code{"He saw 38 red
2338 foxes leaping."} appears in my echo area.
2339
2340 @node set & setq, Summary, Arguments, List Processing
2341 @comment node-name, next, previous, up
2342 @section Setting the Value of a Variable
2343 @cindex Variable, setting value
2344 @cindex Setting value of variable
2345
2346 @cindex @samp{bind} defined
2347 There are several ways by which a variable can be given a value. One of
2348 the ways is to use either the function @code{set} or the function
2349 @code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2350 jargon for this process is to @dfn{bind} a variable to a value.)
2351
2352 The following sections not only describe how @code{set} and @code{setq}
2353 work but also illustrate how arguments are passed.
2354
2355 @menu
2356 * Using set:: Setting values.
2357 * Using setq:: Setting a quoted value.
2358 * Counting:: Using @code{setq} to count.
2359 @end menu
2360
2361 @node Using set, Using setq, set & setq, set & setq
2362 @comment node-name, next, previous, up
2363 @subsection Using @code{set}
2364 @findex set
2365
2366 To set the value of the symbol @code{flowers} to the list @code{'(rose
2367 violet daisy buttercup)}, evaluate the following expression by
2368 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2369
2370 @smallexample
2371 (set 'flowers '(rose violet daisy buttercup))
2372 @end smallexample
2373
2374 @noindent
2375 The list @code{(rose violet daisy buttercup)} will appear in the echo
2376 area. This is what is @emph{returned} by the @code{set} function. As a
2377 side effect, the symbol @code{flowers} is bound to the list ; that is,
2378 the symbol @code{flowers}, which can be viewed as a variable, is given
2379 the list as its value. (This process, by the way, illustrates how a
2380 side effect to the Lisp interpreter, setting the value, can be the
2381 primary effect that we humans are interested in. This is because every
2382 Lisp function must return a value if it does not get an error, but it
2383 will only have a side effect if it is designed to have one.)
2384
2385 After evaluating the @code{set} expression, you can evaluate the symbol
2386 @code{flowers} and it will return the value you just set. Here is the
2387 symbol. Place your cursor after it and type @kbd{C-x C-e}.
2388
2389 @smallexample
2390 flowers
2391 @end smallexample
2392
2393 @noindent
2394 When you evaluate @code{flowers}, the list
2395 @code{(rose violet daisy buttercup)} appears in the echo area.
2396
2397 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2398 in front of it, what you will see in the echo area is the symbol itself,
2399 @code{flowers}. Here is the quoted symbol, so you can try this:
2400
2401 @smallexample
2402 'flowers
2403 @end smallexample
2404
2405 Note also, that when you use @code{set}, you need to quote both
2406 arguments to @code{set}, unless you want them evaluated. Since we do
2407 not want either argument evaluated, neither the variable
2408 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2409 are quoted. (When you use @code{set} without quoting its first
2410 argument, the first argument is evaluated before anything else is
2411 done. If you did this and @code{flowers} did not have a value
2412 already, you would get an error message that the @samp{Symbol's value
2413 as variable is void}; on the other hand, if @code{flowers} did return
2414 a value after it was evaluated, the @code{set} would attempt to set
2415 the value that was returned. There are situations where this is the
2416 right thing for the function to do; but such situations are rare.)
2417
2418 @node Using setq, Counting, Using set, set & setq
2419 @comment node-name, next, previous, up
2420 @subsection Using @code{setq}
2421 @findex setq
2422
2423 As a practical matter, you almost always quote the first argument to
2424 @code{set}. The combination of @code{set} and a quoted first argument
2425 is so common that it has its own name: the special form @code{setq}.
2426 This special form is just like @code{set} except that the first argument
2427 is quoted automatically, so you don't need to type the quote mark
2428 yourself. Also, as an added convenience, @code{setq} permits you to set
2429 several different variables to different values, all in one expression.
2430
2431 To set the value of the variable @code{carnivores} to the list
2432 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2433 is used:
2434
2435 @smallexample
2436 (setq carnivores '(lion tiger leopard))
2437 @end smallexample
2438
2439 @noindent
2440 This is exactly the same as using @code{set} except the first argument
2441 is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2442 means @code{quote}.)
2443
2444 @need 1250
2445 With @code{set}, the expression would look like this:
2446
2447 @smallexample
2448 (set 'carnivores '(lion tiger leopard))
2449 @end smallexample
2450
2451 Also, @code{setq} can be used to assign different values to
2452 different variables. The first argument is bound to the value
2453 of the second argument, the third argument is bound to the value of the
2454 fourth argument, and so on. For example, you could use the following to
2455 assign a list of trees to the symbol @code{trees} and a list of herbivores
2456 to the symbol @code{herbivores}:
2457
2458 @smallexample
2459 @group
2460 (setq trees '(pine fir oak maple)
2461 herbivores '(gazelle antelope zebra))
2462 @end group
2463 @end smallexample
2464
2465 @noindent
2466 (The expression could just as well have been on one line, but it might
2467 not have fit on a page; and humans find it easier to read nicely
2468 formatted lists.)
2469
2470 Although I have been using the term `assign', there is another way of
2471 thinking about the workings of @code{set} and @code{setq}; and that is to
2472 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2473 list. This latter way of thinking is very common and in forthcoming
2474 chapters we shall come upon at least one symbol that has `pointer' as
2475 part of its name. The name is chosen because the symbol has a value,
2476 specifically a list, attached to it; or, expressed another way,
2477 the symbol is set to ``point'' to the list.
2478
2479 @node Counting, , Using setq, set & setq
2480 @comment node-name, next, previous, up
2481 @subsection Counting
2482 @cindex Counting
2483
2484 Here is an example that shows how to use @code{setq} in a counter. You
2485 might use this to count how many times a part of your program repeats
2486 itself. First set a variable to zero; then add one to the number each
2487 time the program repeats itself. To do this, you need a variable that
2488 serves as a counter, and two expressions: an initial @code{setq}
2489 expression that sets the counter variable to zero; and a second
2490 @code{setq} expression that increments the counter each time it is
2491 evaluated.
2492
2493 @smallexample
2494 @group
2495 (setq counter 0) ; @r{Let's call this the initializer.}
2496
2497 (setq counter (+ counter 1)) ; @r{This is the incrementer.}
2498
2499 counter ; @r{This is the counter.}
2500 @end group
2501 @end smallexample
2502
2503 @noindent
2504 (The text following the @samp{;} are comments. @xref{Change a
2505 defun, , Change a Function Definition}.)
2506
2507 If you evaluate the first of these expressions, the initializer,
2508 @code{(setq counter 0)}, and then evaluate the third expression,
2509 @code{counter}, the number @code{0} will appear in the echo area. If
2510 you then evaluate the second expression, the incrementer, @code{(setq
2511 counter (+ counter 1))}, the counter will get the value 1. So if you
2512 again evaluate @code{counter}, the number @code{1} will appear in the
2513 echo area. Each time you evaluate the second expression, the value of
2514 the counter will be incremented.
2515
2516 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2517 the Lisp interpreter first evaluates the innermost list; this is the
2518 addition. In order to evaluate this list, it must evaluate the variable
2519 @code{counter} and the number @code{1}. When it evaluates the variable
2520 @code{counter}, it receives its current value. It passes this value and
2521 the number @code{1} to the @code{+} which adds them together. The sum
2522 is then returned as the value of the inner list and passed to the
2523 @code{setq} which sets the variable @code{counter} to this new value.
2524 Thus, the value of the variable, @code{counter}, is changed.
2525
2526 @node Summary, Error Message Exercises, set & setq, List Processing
2527 @comment node-name, next, previous, up
2528 @section Summary
2529
2530 Learning Lisp is like climbing a hill in which the first part is the
2531 steepest. You have now climbed the most difficult part; what remains
2532 becomes easier as you progress onwards.
2533
2534 In summary,
2535
2536 @itemize @bullet
2537
2538 @item
2539 Lisp programs are made up of expressions, which are lists or single atoms.
2540
2541 @item
2542 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2543 surrounded by parentheses. A list can be empty.
2544
2545 @item
2546 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2547 character symbols like @code{+}, strings of characters between double
2548 quotation marks, or numbers.
2549
2550 @item
2551 A number evaluates to itself.
2552
2553 @item
2554 A string between double quotes also evaluates to itself.
2555
2556 @item
2557 When you evaluate a symbol by itself, its value is returned.
2558
2559 @item
2560 When you evaluate a list, the Lisp interpreter looks at the first symbol
2561 in the list and then at the function definition bound to that symbol.
2562 Then the instructions in the function definition are carried out.
2563
2564 @item
2565 A single-quote, @code{'}, tells the Lisp interpreter that it should
2566 return the following expression as written, and not evaluate it as it
2567 would if the quote were not there.
2568
2569 @item
2570 Arguments are the information passed to a function. The arguments to a
2571 function are computed by evaluating the rest of the elements of the list
2572 of which the function is the first element.
2573
2574 @item
2575 A function always returns a value when it is evaluated (unless it gets
2576 an error); in addition, it may also carry out some action called a
2577 ``side effect''. In many cases, a function's primary purpose is to
2578 create a side effect.
2579 @end itemize
2580
2581 @node Error Message Exercises, , Summary, List Processing
2582 @comment node-name, next, previous, up
2583 @section Exercises
2584
2585 A few simple exercises:
2586
2587 @itemize @bullet
2588 @item
2589 Generate an error message by evaluating an appropriate symbol that is
2590 not within parentheses.
2591
2592 @item
2593 Generate an error message by evaluating an appropriate symbol that is
2594 between parentheses.
2595
2596 @item
2597 Create a counter that increments by two rather than one.
2598
2599 @item
2600 Write an expression that prints a message in the echo area when
2601 evaluated.
2602 @end itemize
2603
2604 @node Practicing Evaluation, Writing Defuns, List Processing, Top
2605 @comment node-name, next, previous, up
2606 @chapter Practicing Evaluation
2607 @cindex Practicing evaluation
2608 @cindex Evaluation practice
2609
2610 Before learning how to write a function definition in Emacs Lisp, it is
2611 useful to spend a little time evaluating various expressions that have
2612 already been written. These expressions will be lists with the
2613 functions as their first (and often only) element. Since some of the
2614 functions associated with buffers are both simple and interesting, we
2615 will start with those. In this section, we will evaluate a few of
2616 these. In another section, we will study the code of several other
2617 buffer-related functions, to see how they were written.
2618
2619 @menu
2620 * How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2621 causes evaluation.
2622 * Buffer Names:: Buffers and files are different.
2623 * Getting Buffers:: Getting a buffer itself, not merely its name.
2624 * Switching Buffers:: How to change to another buffer.
2625 * Buffer Size & Locations:: Where point is located and the size of
2626 the buffer.
2627 * Evaluation Exercise::
2628 @end menu
2629
2630 @node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2631 @ifnottex
2632 @unnumberedsec How to Evaluate
2633 @end ifnottex
2634
2635 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2636 command to move the cursor or to scroll the screen, @i{you are evaluating
2637 an expression,} the first element of which is a function. @i{This is
2638 how Emacs works.}
2639
2640 @cindex @samp{interactive function} defined
2641 @cindex @samp{command} defined
2642 When you type keys, you cause the Lisp interpreter to evaluate an
2643 expression and that is how you get your results. Even typing plain text
2644 involves evaluating an Emacs Lisp function, in this case, one that uses
2645 @code{self-insert-command}, which simply inserts the character you
2646 typed. The functions you evaluate by typing keystrokes are called
2647 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2648 interactive will be illustrated in the chapter on how to write function
2649 definitions. @xref{Interactive, , Making a Function Interactive}.
2650
2651 In addition to typing keyboard commands, we have seen a second way to
2652 evaluate an expression: by positioning the cursor after a list and
2653 typing @kbd{C-x C-e}. This is what we will do in the rest of this
2654 section. There are other ways to evaluate an expression as well; these
2655 will be described as we come to them.
2656
2657 Besides being used for practicing evaluation, the functions shown in the
2658 next few sections are important in their own right. A study of these
2659 functions makes clear the distinction between buffers and files, how to
2660 switch to a buffer, and how to determine a location within it.
2661
2662 @node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2663 @comment node-name, next, previous, up
2664 @section Buffer Names
2665 @findex buffer-name
2666 @findex buffer-file-name
2667
2668 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2669 the difference between a file and a buffer. When you evaluate the
2670 following expression, @code{(buffer-name)}, the name of the buffer
2671 appears in the echo area. When you evaluate @code{(buffer-file-name)},
2672 the name of the file to which the buffer refers appears in the echo
2673 area. Usually, the name returned by @code{(buffer-name)} is the same as
2674 the name of the file to which it refers, and the name returned by
2675 @code{(buffer-file-name)} is the full path-name of the file.
2676
2677 A file and a buffer are two different entities. A file is information
2678 recorded permanently in the computer (unless you delete it). A buffer,
2679 on the other hand, is information inside of Emacs that will vanish at
2680 the end of the editing session (or when you kill the buffer). Usually,
2681 a buffer contains information that you have copied from a file; we say
2682 the buffer is @dfn{visiting} that file. This copy is what you work on
2683 and modify. Changes to the buffer do not change the file, until you
2684 save the buffer. When you save the buffer, the buffer is copied to the file
2685 and is thus saved permanently.
2686
2687 @need 1250
2688 If you are reading this in Info inside of GNU Emacs, you can evaluate
2689 each of the following expressions by positioning the cursor after it and
2690 typing @kbd{C-x C-e}.
2691
2692 @smallexample
2693 @group
2694 (buffer-name)
2695
2696 (buffer-file-name)
2697 @end group
2698 @end smallexample
2699
2700 @noindent
2701 When I do this, @file{"introduction.texinfo"} is the value returned by
2702 evaluating @code{(buffer-name)}, and
2703 @file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2704 evaluating @code{(buffer-file-name)}. The former is the name of the
2705 buffer and the latter is the name of the file. (In the expressions, the
2706 parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2707 @code{buffer-file-name} as functions; without the parentheses, the
2708 interpreter would attempt to evaluate the symbols as variables.
2709 @xref{Variables}.)
2710
2711 In spite of the distinction between files and buffers, you will often
2712 find that people refer to a file when they mean a buffer and vice-versa.
2713 Indeed, most people say, ``I am editing a file,'' rather than saying,
2714 ``I am editing a buffer which I will soon save to a file.'' It is
2715 almost always clear from context what people mean. When dealing with
2716 computer programs, however, it is important to keep the distinction in mind,
2717 since the computer is not as smart as a person.
2718
2719 @cindex Buffer, history of word
2720 The word `buffer', by the way, comes from the meaning of the word as a
2721 cushion that deadens the force of a collision. In early computers, a
2722 buffer cushioned the interaction between files and the computer's
2723 central processing unit. The drums or tapes that held a file and the
2724 central processing unit were pieces of equipment that were very
2725 different from each other, working at their own speeds, in spurts. The
2726 buffer made it possible for them to work together effectively.
2727 Eventually, the buffer grew from being an intermediary, a temporary
2728 holding place, to being the place where work is done. This
2729 transformation is rather like that of a small seaport that grew into a
2730 great city: once it was merely the place where cargo was warehoused
2731 temporarily before being loaded onto ships; then it became a business
2732 and cultural center in its own right.
2733
2734 Not all buffers are associated with files. For example, when you start
2735 an Emacs session by typing the command @code{emacs} alone, without
2736 naming any files, Emacs will start with the @file{*scratch*} buffer on
2737 the screen. This buffer is not visiting any file. Similarly, a
2738 @file{*Help*} buffer is not associated with any file.
2739
2740 @cindex @code{nil}, history of word
2741 If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2742 position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2743 expression, the name @code{"*scratch*"} is returned and will appear in
2744 the echo area. @code{"*scratch*"} is the name of the buffer. However,
2745 if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2746 evaluate that, @code{nil} will appear in the echo area. @code{nil} is
2747 from the Latin word for `nothing'; in this case, it means that the
2748 @file{*scratch*} buffer is not associated with any file. (In Lisp,
2749 @code{nil} is also used to mean `false' and is a synonym for the empty
2750 list, @code{()}.)
2751
2752 Incidentally, if you are in the @file{*scratch*} buffer and want the
2753 value returned by an expression to appear in the @file{*scratch*}
2754 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2755 instead of @kbd{C-x C-e}. This causes the value returned to appear
2756 after the expression. The buffer will look like this:
2757
2758 @smallexample
2759 (buffer-name)"*scratch*"
2760 @end smallexample
2761
2762 @noindent
2763 You cannot do this in Info since Info is read-only and it will not allow
2764 you to change the contents of the buffer. But you can do this in any
2765 buffer you can edit; and when you write code or documentation (such as
2766 this book), this feature is very useful.
2767
2768 @node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2769 @comment node-name, next, previous, up
2770 @section Getting Buffers
2771 @findex current-buffer
2772 @findex other-buffer
2773 @cindex Getting a buffer
2774
2775 The @code{buffer-name} function returns the @emph{name} of the buffer;
2776 to get the buffer @emph{itself}, a different function is needed: the
2777 @code{current-buffer} function. If you use this function in code, what
2778 you get is the buffer itself.
2779
2780 A name and the object or entity to which the name refers are different
2781 from each other. You are not your name. You are a person to whom
2782 others refer by name. If you ask to speak to George and someone hands you
2783 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2784 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2785 not be satisfied. You do not want to speak to the name, but to the
2786 person to whom the name refers. A buffer is similar: the name of the
2787 scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2788 get a buffer itself, you need to use a function such as
2789 @code{current-buffer}.
2790
2791 However, there is a slight complication: if you evaluate
2792 @code{current-buffer} in an expression on its own, as we will do here,
2793 what you see is a printed representation of the name of the buffer
2794 without the contents of the buffer. Emacs works this way for two
2795 reasons: the buffer may be thousands of lines long---too long to be
2796 conveniently displayed; and, another buffer may have the same contents
2797 but a different name, and it is important to distinguish between them.
2798
2799 @need 800
2800 Here is an expression containing the function:
2801
2802 @smallexample
2803 (current-buffer)
2804 @end smallexample
2805
2806 @noindent
2807 If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2808 appears in the echo area. The special format indicates that the
2809 buffer itself is being returned, rather than just its name.
2810
2811 Incidentally, while you can type a number or symbol into a program, you
2812 cannot do that with the printed representation of a buffer: the only way
2813 to get a buffer itself is with a function such as @code{current-buffer}.
2814
2815 A related function is @code{other-buffer}. This returns the most
2816 recently selected buffer other than the one you are in currently. If
2817 you have recently switched back and forth from the @file{*scratch*}
2818 buffer, @code{other-buffer} will return that buffer.
2819
2820 @need 800
2821 You can see this by evaluating the expression:
2822
2823 @smallexample
2824 (other-buffer)
2825 @end smallexample
2826
2827 @noindent
2828 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2829 the name of whatever other buffer you switched back from most
2830 recently@footnote{Actually, by default, if the buffer from which you
2831 just switched is visible to you in another window, @code{other-buffer}
2832 will choose the most recent buffer that you cannot see; this is a
2833 subtlety that I often forget.}.
2834
2835 @node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2836 @comment node-name, next, previous, up
2837 @section Switching Buffers
2838 @findex switch-to-buffer
2839 @findex set-buffer
2840 @cindex Switching to a buffer
2841
2842 The @code{other-buffer} function actually provides a buffer when it is
2843 used as an argument to a function that requires one. We can see this
2844 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2845 different buffer.
2846
2847 But first, a brief introduction to the @code{switch-to-buffer}
2848 function. When you switched back and forth from Info to the
2849 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2850 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2851 rather, to save typing, you probably typed just part of the name, such
2852 as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2853 expand to the full name; and then typed your @kbd{RET} key.} when
2854 prompted in the minibuffer for the name of the buffer to which you
2855 wanted to switch. The keystrokes, @kbd{C-x b}, cause the Lisp
2856 interpreter to evaluate the interactive function
2857 @code{switch-to-buffer}. As we said before, this is how Emacs works:
2858 different keystrokes call or run different functions. For example,
2859 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2860 @code{forward-sentence}, and so on.
2861
2862 By writing @code{switch-to-buffer} in an expression, and giving it a
2863 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2864 does.
2865
2866 @need 1000
2867 Here is the Lisp expression:
2868
2869 @smallexample
2870 (switch-to-buffer (other-buffer))
2871 @end smallexample
2872
2873 @noindent
2874 The symbol @code{switch-to-buffer} is the first element of the list,
2875 so the Lisp interpreter will treat it as a function and carry out the
2876 instructions that are attached to it. But before doing that, the
2877 interpreter will note that @code{other-buffer} is inside parentheses
2878 and work on that symbol first. @code{other-buffer} is the first (and
2879 in this case, the only) element of this list, so the Lisp interpreter
2880 calls or runs the function. It returns another buffer. Next, the
2881 interpreter runs @code{switch-to-buffer}, passing to it, as an
2882 argument, the other buffer, which is what Emacs will switch to. If
2883 you are reading this in Info, try this now. Evaluate the expression.
2884 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2885 expression will move you to your most recent other buffer that you
2886 cannot see. If you really want to go to your most recently selected
2887 buffer, even if you can still see it, you need to evaluate the
2888 following more complex expression:
2889
2890 @smallexample
2891 (switch-to-buffer (other-buffer (current-buffer) t))
2892 @end smallexample
2893
2894 @noindent
2895 In this case, the first argument to @code{other-buffer} tells it which
2896 buffer to skip---the current one---and the second argument tells
2897 @code{other-buffer} it is OK to switch to a visible buffer.
2898 In regular use, @code{switch-to-buffer} takes you to an invisible
2899 window since you would most likely use @kbd{C-x o} (@code{other-window})
2900 to go to another visible buffer.}
2901
2902 In the programming examples in later sections of this document, you will
2903 see the function @code{set-buffer} more often than
2904 @code{switch-to-buffer}. This is because of a difference between
2905 computer programs and humans: humans have eyes and expect to see the
2906 buffer on which they are working on their computer terminals. This is
2907 so obvious, it almost goes without saying. However, programs do not
2908 have eyes. When a computer program works on a buffer, that buffer does
2909 not need to be visible on the screen.
2910
2911 @code{switch-to-buffer} is designed for humans and does two different
2912 things: it switches the buffer to which Emacs' attention is directed; and
2913 it switches the buffer displayed in the window to the new buffer.
2914 @code{set-buffer}, on the other hand, does only one thing: it switches
2915 the attention of the computer program to a different buffer. The buffer
2916 on the screen remains unchanged (of course, normally nothing happens
2917 there until the command finishes running).
2918
2919 @cindex @samp{call} defined
2920 Also, we have just introduced another jargon term, the word @dfn{call}.
2921 When you evaluate a list in which the first symbol is a function, you
2922 are calling that function. The use of the term comes from the notion of
2923 the function as an entity that can do something for you if you `call'
2924 it---just as a plumber is an entity who can fix a leak if you call him
2925 or her.
2926
2927 @node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2928 @comment node-name, next, previous, up
2929 @section Buffer Size and the Location of Point
2930 @cindex Size of buffer
2931 @cindex Buffer size
2932 @cindex Point location
2933 @cindex Location of point
2934
2935 Finally, let's look at several rather simple functions,
2936 @code{buffer-size}, @code{point}, @code{point-min}, and
2937 @code{point-max}. These give information about the size of a buffer and
2938 the location of point within it.
2939
2940 The function @code{buffer-size} tells you the size of the current
2941 buffer; that is, the function returns a count of the number of
2942 characters in the buffer.
2943
2944 @smallexample
2945 (buffer-size)
2946 @end smallexample
2947
2948 @noindent
2949 You can evaluate this in the usual way, by positioning the
2950 cursor after the expression and typing @kbd{C-x C-e}.
2951
2952 @cindex @samp{point} defined
2953 In Emacs, the current position of the cursor is called @dfn{point}.
2954 The expression @code{(point)} returns a number that tells you where the
2955 cursor is located as a count of the number of characters from the
2956 beginning of the buffer up to point.
2957
2958 @need 1250
2959 You can see the character count for point in this buffer by evaluating
2960 the following expression in the usual way:
2961
2962 @smallexample
2963 (point)
2964 @end smallexample
2965
2966 @noindent
2967 As I write this, the value of @code{point} is 65724. The @code{point}
2968 function is frequently used in some of the examples later in this
2969 book.
2970
2971 @need 1250
2972 The value of point depends, of course, on its location within the
2973 buffer. If you evaluate point in this spot, the number will be larger:
2974
2975 @smallexample
2976 (point)
2977 @end smallexample
2978
2979 @noindent
2980 For me, the value of point in this location is 66043, which means that
2981 there are 319 characters (including spaces) between the two expressions.
2982
2983 @cindex @samp{narrowing} defined
2984 The function @code{point-min} is somewhat similar to @code{point}, but
2985 it returns the value of the minimum permissible value of point in the
2986 current buffer. This is the number 1 unless @dfn{narrowing} is in
2987 effect. (Narrowing is a mechanism whereby you can restrict yourself,
2988 or a program, to operations on just a part of a buffer.
2989 @xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
2990 function @code{point-max} returns the value of the maximum permissible
2991 value of point in the current buffer.
2992
2993 @node Evaluation Exercise, , Buffer Size & Locations, Practicing Evaluation
2994 @section Exercise
2995
2996 Find a file with which you are working and move towards its middle.
2997 Find its buffer name, file name, length, and your position in the file.
2998
2999 @node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
3000 @comment node-name, next, previous, up
3001 @chapter How To Write Function Definitions
3002 @cindex Definition writing
3003 @cindex Function definition writing
3004 @cindex Writing a function definition
3005
3006 When the Lisp interpreter evaluates a list, it looks to see whether the
3007 first symbol on the list has a function definition attached to it; or,
3008 put another way, whether the symbol points to a function definition. If
3009 it does, the computer carries out the instructions in the definition. A
3010 symbol that has a function definition is called, simply, a function
3011 (although, properly speaking, the definition is the function and the
3012 symbol refers to it.)
3013
3014 @menu
3015 * Primitive Functions::
3016 * defun:: The @code{defun} special form.
3017 * Install:: Install a function definition.
3018 * Interactive:: Making a function interactive.
3019 * Interactive Options:: Different options for @code{interactive}.
3020 * Permanent Installation:: Installing code permanently.
3021 * let:: Creating and initializing local variables.
3022 * if:: What if?
3023 * else:: If--then--else expressions.
3024 * Truth & Falsehood:: What Lisp considers false and true.
3025 * save-excursion:: Keeping track of point, mark, and buffer.
3026 * Review::
3027 * defun Exercises::
3028 @end menu
3029
3030 @node Primitive Functions, defun, Writing Defuns, Writing Defuns
3031 @ifnottex
3032 @unnumberedsec An Aside about Primitive Functions
3033 @end ifnottex
3034 @cindex Primitive functions
3035 @cindex Functions, primitive
3036
3037 @cindex C language primitives
3038 @cindex Primitives written in C
3039 All functions are defined in terms of other functions, except for a few
3040 @dfn{primitive} functions that are written in the C programming
3041 language. When you write functions' definitions, you will write them in
3042 Emacs Lisp and use other functions as your building blocks. Some of the
3043 functions you will use will themselves be written in Emacs Lisp (perhaps
3044 by you) and some will be primitives written in C. The primitive
3045 functions are used exactly like those written in Emacs Lisp and behave
3046 like them. They are written in C so we can easily run GNU Emacs on any
3047 computer that has sufficient power and can run C.
3048
3049 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3050 distinguish between the use of functions written in C and the use of
3051 functions written in Emacs Lisp. The difference is irrelevant. I
3052 mention the distinction only because it is interesting to know. Indeed,
3053 unless you investigate, you won't know whether an already-written
3054 function is written in Emacs Lisp or C.
3055
3056 @node defun, Install, Primitive Functions, Writing Defuns
3057 @comment node-name, next, previous, up
3058 @section The @code{defun} Special Form
3059 @findex defun
3060 @cindex Special form of @code{defun}
3061
3062 @cindex @samp{function definition} defined
3063 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3064 it that tells the computer what to do when the function is called.
3065 This code is called the @dfn{function definition} and is created by
3066 evaluating a Lisp expression that starts with the symbol @code{defun}
3067 (which is an abbreviation for @emph{define function}). Because
3068 @code{defun} does not evaluate its arguments in the usual way, it is
3069 called a @dfn{special form}.
3070
3071 In subsequent sections, we will look at function definitions from the
3072 Emacs source code, such as @code{mark-whole-buffer}. In this section,
3073 we will describe a simple function definition so you can see how it
3074 looks. This function definition uses arithmetic because it makes for a
3075 simple example. Some people dislike examples using arithmetic; however,
3076 if you are such a person, do not despair. Hardly any of the code we
3077 will study in the remainder of this introduction involves arithmetic or
3078 mathematics. The examples mostly involve text in one way or another.
3079
3080 A function definition has up to five parts following the word
3081 @code{defun}:
3082
3083 @enumerate
3084 @item
3085 The name of the symbol to which the function definition should be
3086 attached.
3087
3088 @item
3089 A list of the arguments that will be passed to the function. If no
3090 arguments will be passed to the function, this is an empty list,
3091 @code{()}.
3092
3093 @item
3094 Documentation describing the function. (Technically optional, but
3095 strongly recommended.)
3096
3097 @item
3098 Optionally, an expression to make the function interactive so you can
3099 use it by typing @kbd{M-x} and then the name of the function; or by
3100 typing an appropriate key or keychord.
3101
3102 @cindex @samp{body} defined
3103 @item
3104 The code that instructs the computer what to do: the @dfn{body} of the
3105 function definition.
3106 @end enumerate
3107
3108 It is helpful to think of the five parts of a function definition as
3109 being organized in a template, with slots for each part:
3110
3111 @smallexample
3112 @group
3113 (defun @var{function-name} (@var{arguments}@dots{})
3114 "@var{optional-documentation}@dots{}"
3115 (interactive @var{argument-passing-info}) ; @r{optional}
3116 @var{body}@dots{})
3117 @end group
3118 @end smallexample
3119
3120 As an example, here is the code for a function that multiplies its
3121 argument by 7. (This example is not interactive. @xref{Interactive,
3122 , Making a Function Interactive}, for that information.)
3123
3124 @smallexample
3125 @group
3126 (defun multiply-by-seven (number)
3127 "Multiply NUMBER by seven."
3128 (* 7 number))
3129 @end group
3130 @end smallexample
3131
3132 This definition begins with a parenthesis and the symbol @code{defun},
3133 followed by the name of the function.
3134
3135 @cindex @samp{argument list} defined
3136 The name of the function is followed by a list that contains the
3137 arguments that will be passed to the function. This list is called
3138 the @dfn{argument list}. In this example, the list has only one
3139 element, the symbol, @code{number}. When the function is used, the
3140 symbol will be bound to the value that is used as the argument to the
3141 function.
3142
3143 Instead of choosing the word @code{number} for the name of the argument,
3144 I could have picked any other name. For example, I could have chosen
3145 the word @code{multiplicand}. I picked the word `number' because it
3146 tells what kind of value is intended for this slot; but I could just as
3147 well have chosen the word `multiplicand' to indicate the role that the
3148 value placed in this slot will play in the workings of the function. I
3149 could have called it @code{foogle}, but that would have been a bad
3150 choice because it would not tell humans what it means. The choice of
3151 name is up to the programmer and should be chosen to make the meaning of
3152 the function clear.
3153
3154 Indeed, you can choose any name you wish for a symbol in an argument
3155 list, even the name of a symbol used in some other function: the name
3156 you use in an argument list is private to that particular definition.
3157 In that definition, the name refers to a different entity than any use
3158 of the same name outside the function definition. Suppose you have a
3159 nick-name `Shorty' in your family; when your family members refer to
3160 `Shorty', they mean you. But outside your family, in a movie, for
3161 example, the name `Shorty' refers to someone else. Because a name in an
3162 argument list is private to the function definition, you can change the
3163 value of such a symbol inside the body of a function without changing
3164 its value outside the function. The effect is similar to that produced
3165 by a @code{let} expression. (@xref{let, , @code{let}}.)
3166
3167 @ignore
3168 Note also that we discuss the word `number' in two different ways: as a
3169 symbol that appears in the code, and as the name of something that will
3170 be replaced by a something else during the evaluation of the function.
3171 In the first case, @code{number} is a symbol, not a number; it happens
3172 that within the function, it is a variable who value is the number in
3173 question, but our primary interest in it is as a symbol. On the other
3174 hand, when we are talking about the function, our interest is that we
3175 will substitute a number for the word @var{number}. To keep this
3176 distinction clear, we use different typography for the two
3177 circumstances. When we talk about this function, or about how it works,
3178 we refer to this number by writing @var{number}. In the function
3179 itself, we refer to it by writing @code{number}.
3180 @end ignore
3181
3182 The argument list is followed by the documentation string that
3183 describes the function. This is what you see when you type
3184 @w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3185 write a documentation string like this, you should make the first line
3186 a complete sentence since some commands, such as @code{apropos}, print
3187 only the first line of a multi-line documentation string. Also, you
3188 should not indent the second line of a documentation string, if you
3189 have one, because that looks odd when you use @kbd{C-h f}
3190 (@code{describe-function}). The documentation string is optional, but
3191 it is so useful, it should be included in almost every function you
3192 write.
3193
3194 @findex * @r{(multiplication)}
3195 The third line of the example consists of the body of the function
3196 definition. (Most functions' definitions, of course, are longer than
3197 this.) In this function, the body is the list, @code{(* 7 number)}, which
3198 says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3199 @code{*} is the function for multiplication, just as @code{+} is the
3200 function for addition.)
3201
3202 When you use the @code{multiply-by-seven} function, the argument
3203 @code{number} evaluates to the actual number you want used. Here is an
3204 example that shows how @code{multiply-by-seven} is used; but don't try
3205 to evaluate this yet!
3206
3207 @smallexample
3208 (multiply-by-seven 3)
3209 @end smallexample
3210
3211 @noindent
3212 The symbol @code{number}, specified in the function definition in the
3213 next section, is given or ``bound to'' the value 3 in the actual use of
3214 the function. Note that although @code{number} was inside parentheses
3215 in the function definition, the argument passed to the
3216 @code{multiply-by-seven} function is not in parentheses. The
3217 parentheses are written in the function definition so the computer can
3218 figure out where the argument list ends and the rest of the function
3219 definition begins.
3220
3221 If you evaluate this example, you are likely to get an error message.
3222 (Go ahead, try it!) This is because we have written the function
3223 definition, but not yet told the computer about the definition---we have
3224 not yet installed (or `loaded') the function definition in Emacs.
3225 Installing a function is the process that tells the Lisp interpreter the
3226 definition of the function. Installation is described in the next
3227 section.
3228
3229 @node Install, Interactive, defun, Writing Defuns
3230 @comment node-name, next, previous, up
3231 @section Install a Function Definition
3232 @cindex Install a Function Definition
3233 @cindex Definition installation
3234 @cindex Function definition installation
3235
3236 If you are reading this inside of Info in Emacs, you can try out the
3237 @code{multiply-by-seven} function by first evaluating the function
3238 definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3239 the function definition follows. Place the cursor after the last
3240 parenthesis of the function definition and type @kbd{C-x C-e}. When you
3241 do this, @code{multiply-by-seven} will appear in the echo area. (What
3242 this means is that when a function definition is evaluated, the value it
3243 returns is the name of the defined function.) At the same time, this
3244 action installs the function definition.
3245
3246 @smallexample
3247 @group
3248 (defun multiply-by-seven (number)
3249 "Multiply NUMBER by seven."
3250 (* 7 number))
3251 @end group
3252 @end smallexample
3253
3254 @noindent
3255 By evaluating this @code{defun}, you have just installed
3256 @code{multiply-by-seven} in Emacs. The function is now just as much a
3257 part of Emacs as @code{forward-word} or any other editing function you
3258 use. (@code{multiply-by-seven} will stay installed until you quit
3259 Emacs. To reload code automatically whenever you start Emacs, see
3260 @ref{Permanent Installation, , Installing Code Permanently}.)
3261
3262
3263 @menu
3264 * Effect of installation::
3265 * Change a defun:: How to change a function definition.
3266 @end menu
3267
3268 @node Effect of installation, Change a defun, Install, Install
3269 @ifnottex
3270 @unnumberedsubsec The effect of installation
3271 @end ifnottex
3272
3273
3274 You can see the effect of installing @code{multiply-by-seven} by
3275 evaluating the following sample. Place the cursor after the following
3276 expression and type @kbd{C-x C-e}. The number 21 will appear in the
3277 echo area.
3278
3279 @smallexample
3280 (multiply-by-seven 3)
3281 @end smallexample
3282
3283 If you wish, you can read the documentation for the function by typing
3284 @kbd{C-h f} (@code{describe-function}) and then the name of the
3285 function, @code{multiply-by-seven}. When you do this, a
3286 @file{*Help*} window will appear on your screen that says:
3287
3288 @smallexample
3289 @group
3290 multiply-by-seven:
3291 Multiply NUMBER by seven.
3292 @end group
3293 @end smallexample
3294
3295 @noindent
3296 (To return to a single window on your screen, type @kbd{C-x 1}.)
3297
3298 @node Change a defun, , Effect of installation, Install
3299 @comment node-name, next, previous, up
3300 @subsection Change a Function Definition
3301 @cindex Changing a function definition
3302 @cindex Function definition, how to change
3303 @cindex Definition, how to change
3304
3305 If you want to change the code in @code{multiply-by-seven}, just rewrite
3306 it. To install the new version in place of the old one, evaluate the
3307 function definition again. This is how you modify code in Emacs. It is
3308 very simple.
3309
3310 As an example, you can change the @code{multiply-by-seven} function to
3311 add the number to itself seven times instead of multiplying the number
3312 by seven. It produces the same answer, but by a different path. At
3313 the same time, we will add a comment to the code; a comment is text
3314 that the Lisp interpreter ignores, but that a human reader may find
3315 useful or enlightening. The comment is that this is the ``second
3316 version''.
3317
3318 @smallexample
3319 @group
3320 (defun multiply-by-seven (number) ; @r{Second version.}
3321 "Multiply NUMBER by seven."
3322 (+ number number number number number number number))
3323 @end group
3324 @end smallexample
3325
3326 @cindex Comments in Lisp code
3327 The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3328 line that follows a semicolon is a comment. The end of the line is the
3329 end of the comment. To stretch a comment over two or more lines, begin
3330 each line with a semicolon.
3331
3332 @xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3333 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3334 Reference Manual}, for more about comments.
3335
3336 You can install this version of the @code{multiply-by-seven} function by
3337 evaluating it in the same way you evaluated the first function: place
3338 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3339
3340 In summary, this is how you write code in Emacs Lisp: you write a
3341 function; install it; test it; and then make fixes or enhancements and
3342 install it again.
3343
3344 @node Interactive, Interactive Options, Install, Writing Defuns
3345 @comment node-name, next, previous, up
3346 @section Make a Function Interactive
3347 @cindex Interactive functions
3348 @findex interactive
3349
3350 You make a function interactive by placing a list that begins with
3351 the special form @code{interactive} immediately after the
3352 documentation. A user can invoke an interactive function by typing
3353 @kbd{M-x} and then the name of the function; or by typing the keys to
3354 which it is bound, for example, by typing @kbd{C-n} for
3355 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3356
3357 Interestingly, when you call an interactive function interactively,
3358 the value returned is not automatically displayed in the echo area.
3359 This is because you often call an interactive function for its side
3360 effects, such as moving forward by a word or line, and not for the
3361 value returned. If the returned value were displayed in the echo area
3362 each time you typed a key, it would be very distracting.
3363
3364 @menu
3365 * Interactive multiply-by-seven:: An overview.
3366 * multiply-by-seven in detail:: The interactive version.
3367 @end menu
3368
3369 @node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3370 @ifnottex
3371 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3372 @end ifnottex
3373
3374 Both the use of the special form @code{interactive} and one way to
3375 display a value in the echo area can be illustrated by creating an
3376 interactive version of @code{multiply-by-seven}.
3377
3378 @need 1250
3379 Here is the code:
3380
3381 @smallexample
3382 @group
3383 (defun multiply-by-seven (number) ; @r{Interactive version.}
3384 "Multiply NUMBER by seven."
3385 (interactive "p")
3386 (message "The result is %d" (* 7 number)))
3387 @end group
3388 @end smallexample
3389
3390 @noindent
3391 You can install this code by placing your cursor after it and typing
3392 @kbd{C-x C-e}. The name of the function will appear in your echo area.
3393 Then, you can use this code by typing @kbd{C-u} and a number and then
3394 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3395 @samp{The result is @dots{}} followed by the product will appear in the
3396 echo area.
3397
3398 Speaking more generally, you invoke a function like this in either of two
3399 ways:
3400
3401 @enumerate
3402 @item
3403 By typing a prefix argument that contains the number to be passed, and
3404 then typing @kbd{M-x} and the name of the function, as with
3405 @kbd{C-u 3 M-x forward-sentence}; or,
3406
3407 @item
3408 By typing whatever key or keychord the function is bound to, as with
3409 @kbd{C-u 3 M-e}.
3410 @end enumerate
3411
3412 @noindent
3413 Both the examples just mentioned work identically to move point forward
3414 three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3415 it could not be used as an example of key binding.)
3416
3417 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3418 to a key.)
3419
3420 A prefix argument is passed to an interactive function by typing the
3421 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3422 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3423 type @kbd{C-u} without a number, it defaults to 4).
3424
3425 @node multiply-by-seven in detail, , Interactive multiply-by-seven, Interactive
3426 @comment node-name, next, previous, up
3427 @subsection An Interactive @code{multiply-by-seven}
3428
3429 Let's look at the use of the special form @code{interactive} and then at
3430 the function @code{message} in the interactive version of
3431 @code{multiply-by-seven}. You will recall that the function definition
3432 looks like this:
3433
3434 @smallexample
3435 @group
3436 (defun multiply-by-seven (number) ; @r{Interactive version.}
3437 "Multiply NUMBER by seven."
3438 (interactive "p")
3439 (message "The result is %d" (* 7 number)))
3440 @end group
3441 @end smallexample
3442
3443 In this function, the expression, @code{(interactive "p")}, is a list of
3444 two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3445 the function and use its value for the argument of the function.
3446
3447 @need 1000
3448 The argument will be a number. This means that the symbol
3449 @code{number} will be bound to a number in the line:
3450
3451 @smallexample
3452 (message "The result is %d" (* 7 number))
3453 @end smallexample
3454
3455 @need 1250
3456 @noindent
3457 For example, if your prefix argument is 5, the Lisp interpreter will
3458 evaluate the line as if it were:
3459
3460 @smallexample
3461 (message "The result is %d" (* 7 5))
3462 @end smallexample
3463
3464 @noindent
3465 (If you are reading this in GNU Emacs, you can evaluate this expression
3466 yourself.) First, the interpreter will evaluate the inner list, which
3467 is @code{(* 7 5)}. This returns a value of 35. Next, it
3468 will evaluate the outer list, passing the values of the second and
3469 subsequent elements of the list to the function @code{message}.
3470
3471 As we have seen, @code{message} is an Emacs Lisp function especially
3472 designed for sending a one line message to a user. (@xref{message, , The
3473 @code{message} function}.)
3474 In summary, the @code{message} function prints its first argument in the
3475 echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3476 @samp{%c}. When it sees one of these control sequences, the function
3477 looks to the second and subsequent arguments and prints the value of the
3478 argument in the location in the string where the control sequence is
3479 located.
3480
3481 In the interactive @code{multiply-by-seven} function, the control string
3482 is @samp{%d}, which requires a number, and the value returned by
3483 evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3484 is printed in place of the @samp{%d} and the message is @samp{The result
3485 is 35}.
3486
3487 (Note that when you call the function @code{multiply-by-seven}, the
3488 message is printed without quotes, but when you call @code{message}, the
3489 text is printed in double quotes. This is because the value returned by
3490 @code{message} is what appears in the echo area when you evaluate an
3491 expression whose first element is @code{message}; but when embedded in a
3492 function, @code{message} prints the text as a side effect without
3493 quotes.)
3494
3495 @node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3496 @comment node-name, next, previous, up
3497 @section Different Options for @code{interactive}
3498 @cindex Options for @code{interactive}
3499 @cindex Interactive options
3500
3501 In the example, @code{multiply-by-seven} used @code{"p"} as the
3502 argument to @code{interactive}. This argument told Emacs to interpret
3503 your typing either @kbd{C-u} followed by a number or @key{META}
3504 followed by a number as a command to pass that number to the function
3505 as its argument. Emacs has more than twenty characters predefined for
3506 use with @code{interactive}. In almost every case, one of these
3507 options will enable you to pass the right information interactively to
3508 a function. (@xref{Interactive Codes, , Code Characters for
3509 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3510
3511 @need 1250
3512 For example, the character @samp{r} causes Emacs to pass the beginning
3513 and end of the region (the current values of point and mark) to the
3514 function as two separate arguments. It is used as follows:
3515
3516 @smallexample
3517 (interactive "r")
3518 @end smallexample
3519
3520 On the other hand, a @samp{B} tells Emacs to ask for the name of a
3521 buffer that will be passed to the function. When it sees a @samp{B},
3522 Emacs will ask for the name by prompting the user in the minibuffer,
3523 using a string that follows the @samp{B}, as in @code{"BAppend to
3524 buffer:@: "}. Not only will Emacs prompt for the name, but Emacs will
3525 complete the name if you type enough of it and press @key{TAB}.
3526
3527 A function with two or more arguments can have information passed to
3528 each argument by adding parts to the string that follows
3529 @code{interactive}. When you do this, the information is passed to
3530 each argument in the same order it is specified in the
3531 @code{interactive} list. In the string, each part is separated from
3532 the next part by a @samp{\n}, which is a newline. For example, you
3533 could follow @code{"BAppend to buffer:@: "} with a @samp{\n}) and an
3534 @samp{r}. This would cause Emacs to pass the values of point and mark
3535 to the function as well as prompt you for the buffer---three arguments
3536 in all.
3537
3538 In this case, the function definition would look like the following,
3539 where @code{buffer}, @code{start}, and @code{end} are the symbols to
3540 which @code{interactive} binds the buffer and the current values of the
3541 beginning and ending of the region:
3542
3543 @smallexample
3544 @group
3545 (defun @var{name-of-function} (buffer start end)
3546 "@var{documentation}@dots{}"
3547 (interactive "BAppend to buffer:@: \nr")
3548 @var{body-of-function}@dots{})
3549 @end group
3550 @end smallexample
3551
3552 @noindent
3553 (The space after the colon in the prompt makes it look better when you
3554 are prompted. The @code{append-to-buffer} function looks exactly like
3555 this. @xref{append-to-buffer, , The Definition of
3556 @code{append-to-buffer}}.)
3557
3558 If a function does not have arguments, then @code{interactive} does not
3559 require any. Such a function contains the simple expression
3560 @code{(interactive)}. The @code{mark-whole-buffer} function is like
3561 this.
3562
3563 Alternatively, if the special letter-codes are not right for your
3564 application, you can pass your own arguments to @code{interactive} as
3565 a list. @xref{interactive, , Using @code{Interactive}, elisp, The
3566 GNU Emacs Lisp Reference Manual}, for more information about this advanced
3567 technique.
3568
3569 @node Permanent Installation, let, Interactive Options, Writing Defuns
3570 @comment node-name, next, previous, up
3571 @section Install Code Permanently
3572 @cindex Install code permanently
3573 @cindex Permanent code installation
3574 @cindex Code installation
3575
3576 When you install a function definition by evaluating it, it will stay
3577 installed until you quit Emacs. The next time you start a new session
3578 of Emacs, the function will not be installed unless you evaluate the
3579 function definition again.
3580
3581 At some point, you may want to have code installed automatically
3582 whenever you start a new session of Emacs. There are several ways of
3583 doing this:
3584
3585 @itemize @bullet
3586 @item
3587 If you have code that is just for yourself, you can put the code for the
3588 function definition in your @file{.emacs} initialization file. When you
3589 start Emacs, your @file{.emacs} file is automatically evaluated and all
3590 the function definitions within it are installed.
3591 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3592
3593 @item
3594 Alternatively, you can put the function definitions that you want
3595 installed in one or more files of their own and use the @code{load}
3596 function to cause Emacs to evaluate and thereby install each of the
3597 functions in the files.
3598 @xref{Loading Files, , Loading Files}.
3599
3600 @item
3601 On the other hand, if you have code that your whole site will use, it
3602 is usual to put it in a file called @file{site-init.el} that is loaded
3603 when Emacs is built. This makes the code available to everyone who
3604 uses your machine. (See the @file{INSTALL} file that is part of the
3605 Emacs distribution.)
3606 @end itemize
3607
3608 Finally, if you have code that everyone who uses Emacs may want, you
3609 can post it on a computer network or send a copy to the Free Software
3610 Foundation. (When you do this, please license the code and its
3611 documentation under a license that permits other people to run, copy,
3612 study, modify, and redistribute the code and which protects you from
3613 having your work taken from you.) If you send a copy of your code to
3614 the Free Software Foundation, and properly protect yourself and
3615 others, it may be included in the next release of Emacs. In large
3616 part, this is how Emacs has grown over the past years, by donations.
3617
3618 @node let, if, Permanent Installation, Writing Defuns
3619 @comment node-name, next, previous, up
3620 @section @code{let}
3621 @findex let
3622
3623 The @code{let} expression is a special form in Lisp that you will need
3624 to use in most function definitions.
3625
3626 @code{let} is used to attach or bind a symbol to a value in such a way
3627 that the Lisp interpreter will not confuse the variable with a
3628 variable of the same name that is not part of the function.
3629
3630 To understand why the @code{let} special form is necessary, consider
3631 the situation in which you own a home that you generally refer to as
3632 `the house', as in the sentence, ``The house needs painting.'' If you
3633 are visiting a friend and your host refers to `the house', he is
3634 likely to be referring to @emph{his} house, not yours, that is, to a
3635 different house.
3636
3637 If your friend is referring to his house and you think he is referring
3638 to your house, you may be in for some confusion. The same thing could
3639 happen in Lisp if a variable that is used inside of one function has
3640 the same name as a variable that is used inside of another function,
3641 and the two are not intended to refer to the same value. The
3642 @code{let} special form prevents this kind of confusion.
3643
3644 @menu
3645 * Prevent confusion::
3646 * Parts of let Expression::
3647 * Sample let Expression::
3648 * Uninitialized let Variables::
3649 @end menu
3650
3651 @node Prevent confusion, Parts of let Expression, let, let
3652 @ifnottex
3653 @unnumberedsubsec @code{let} Prevents Confusion
3654 @end ifnottex
3655
3656 @cindex @samp{local variable} defined
3657 The @code{let} special form prevents confusion. @code{let} creates a
3658 name for a @dfn{local variable} that overshadows any use of the same
3659 name outside the @code{let} expression. This is like understanding
3660 that whenever your host refers to `the house', he means his house, not
3661 yours. (Symbols used in argument lists work the same way.
3662 @xref{defun, , The @code{defun} Special Form}.)
3663
3664 Local variables created by a @code{let} expression retain their value
3665 @emph{only} within the @code{let} expression itself (and within
3666 expressions called within the @code{let} expression); the local
3667 variables have no effect outside the @code{let} expression.
3668
3669 Another way to think about @code{let} is that it is like a @code{setq}
3670 that is temporary and local. The values set by @code{let} are
3671 automatically undone when the @code{let} is finished. The setting
3672 only effects expressions that are inside the bounds of the @code{let}
3673 expression. In computer science jargon, we would say ``the binding of
3674 a symbol is visible only in functions called in the @code{let} form;
3675 in Emacs Lisp, scoping is dynamic, not lexical.''
3676
3677 @code{let} can create more than one variable at once. Also,
3678 @code{let} gives each variable it creates an initial value, either a
3679 value specified by you, or @code{nil}. (In the jargon, this is called
3680 `binding the variable to the value'.) After @code{let} has created
3681 and bound the variables, it executes the code in the body of the
3682 @code{let}, and returns the value of the last expression in the body,
3683 as the value of the whole @code{let} expression. (`Execute' is a jargon
3684 term that means to evaluate a list; it comes from the use of the word
3685 meaning `to give practical effect to' (@cite{Oxford English
3686 Dictionary}). Since you evaluate an expression to perform an action,
3687 `execute' has evolved as a synonym to `evaluate'.)
3688
3689 @node Parts of let Expression, Sample let Expression, Prevent confusion, let
3690 @comment node-name, next, previous, up
3691 @subsection The Parts of a @code{let} Expression
3692 @cindex @code{let} expression, parts of
3693 @cindex Parts of @code{let} expression
3694
3695 @cindex @samp{varlist} defined
3696 A @code{let} expression is a list of three parts. The first part is
3697 the symbol @code{let}. The second part is a list, called a
3698 @dfn{varlist}, each element of which is either a symbol by itself or a
3699 two-element list, the first element of which is a symbol. The third
3700 part of the @code{let} expression is the body of the @code{let}. The
3701 body usually consists of one or more lists.
3702
3703 @need 800
3704 A template for a @code{let} expression looks like this:
3705
3706 @smallexample
3707 (let @var{varlist} @var{body}@dots{})
3708 @end smallexample
3709
3710 @noindent
3711 The symbols in the varlist are the variables that are given initial
3712 values by the @code{let} special form. Symbols by themselves are given
3713 the initial value of @code{nil}; and each symbol that is the first
3714 element of a two-element list is bound to the value that is returned
3715 when the Lisp interpreter evaluates the second element.
3716
3717 Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3718 this case, in a @code{let} expression, Emacs binds the symbol
3719 @code{thread} to an initial value of @code{nil}, and binds the symbol
3720 @code{needles} to an initial value of 3.
3721
3722 When you write a @code{let} expression, what you do is put the
3723 appropriate expressions in the slots of the @code{let} expression
3724 template.
3725
3726 If the varlist is composed of two-element lists, as is often the case,
3727 the template for the @code{let} expression looks like this:
3728
3729 @smallexample
3730 @group
3731 (let ((@var{variable} @var{value})
3732 (@var{variable} @var{value})
3733 @dots{})
3734 @var{body}@dots{})
3735 @end group
3736 @end smallexample
3737
3738 @node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3739 @comment node-name, next, previous, up
3740 @subsection Sample @code{let} Expression
3741 @cindex Sample @code{let} expression
3742 @cindex @code{let} expression sample
3743
3744 The following expression creates and gives initial values
3745 to the two variables @code{zebra} and @code{tiger}. The body of the
3746 @code{let} expression is a list which calls the @code{message} function.
3747
3748 @smallexample
3749 @group
3750 (let ((zebra 'stripes)
3751 (tiger 'fierce))
3752 (message "One kind of animal has %s and another is %s."
3753 zebra tiger))
3754 @end group
3755 @end smallexample
3756
3757 Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3758
3759 The two variables are @code{zebra} and @code{tiger}. Each variable is
3760 the first element of a two-element list and each value is the second
3761 element of its two-element list. In the varlist, Emacs binds the
3762 variable @code{zebra} to the value @code{stripes}, and binds the
3763 variable @code{tiger} to the value @code{fierce}. In this example,
3764 both values are symbols preceded by a quote. The values could just as
3765 well have been another list or a string. The body of the @code{let}
3766 follows after the list holding the variables. In this example, the body
3767 is a list that uses the @code{message} function to print a string in
3768 the echo area.
3769
3770 @need 1500
3771 You may evaluate the example in the usual fashion, by placing the
3772 cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3773 this, the following will appear in the echo area:
3774
3775 @smallexample
3776 "One kind of animal has stripes and another is fierce."
3777 @end smallexample
3778
3779 As we have seen before, the @code{message} function prints its first
3780 argument, except for @samp{%s}. In this example, the value of the variable
3781 @code{zebra} is printed at the location of the first @samp{%s} and the
3782 value of the variable @code{tiger} is printed at the location of the
3783 second @samp{%s}.
3784
3785 @node Uninitialized let Variables, , Sample let Expression, let
3786 @comment node-name, next, previous, up
3787 @subsection Uninitialized Variables in a @code{let} Statement
3788 @cindex Uninitialized @code{let} variables
3789 @cindex @code{let} variables uninitialized
3790
3791 If you do not bind the variables in a @code{let} statement to specific
3792 initial values, they will automatically be bound to an initial value of
3793 @code{nil}, as in the following expression:
3794
3795 @smallexample
3796 @group
3797 (let ((birch 3)
3798 pine
3799 fir
3800 (oak 'some))
3801 (message
3802 "Here are %d variables with %s, %s, and %s value."
3803 birch pine fir oak))
3804 @end group
3805 @end smallexample
3806
3807 @noindent
3808 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3809
3810 @need 1250
3811 If you evaluate this expression in the usual way, the following will
3812 appear in your echo area:
3813
3814 @smallexample
3815 "Here are 3 variables with nil, nil, and some value."
3816 @end smallexample
3817
3818 @noindent
3819 In this example, Emacs binds the symbol @code{birch} to the number 3,
3820 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3821 the symbol @code{oak} to the value @code{some}.
3822
3823 Note that in the first part of the @code{let}, the variables @code{pine}
3824 and @code{fir} stand alone as atoms that are not surrounded by
3825 parentheses; this is because they are being bound to @code{nil}, the
3826 empty list. But @code{oak} is bound to @code{some} and so is a part of
3827 the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3828 number 3 and so is in a list with that number. (Since a number
3829 evaluates to itself, the number does not need to be quoted. Also, the
3830 number is printed in the message using a @samp{%d} rather than a
3831 @samp{%s}.) The four variables as a group are put into a list to
3832 delimit them from the body of the @code{let}.
3833
3834 @node if, else, let, Writing Defuns
3835 @comment node-name, next, previous, up
3836 @section The @code{if} Special Form
3837 @findex if
3838 @cindex Conditional with @code{if}
3839
3840 A third special form, in addition to @code{defun} and @code{let}, is the
3841 conditional @code{if}. This form is used to instruct the computer to
3842 make decisions. You can write function definitions without using
3843 @code{if}, but it is used often enough, and is important enough, to be
3844 included here. It is used, for example, in the code for the
3845 function @code{beginning-of-buffer}.
3846
3847 The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3848 @emph{then} an expression is evaluated.'' If the test is not true, the
3849 expression is not evaluated. For example, you might make a decision
3850 such as, ``if it is warm and sunny, then go to the beach!''
3851
3852 @menu
3853 * if in more detail::
3854 * type-of-animal in detail:: An example of an @code{if} expression.
3855 @end menu
3856
3857 @node if in more detail, type-of-animal in detail, if, if
3858 @ifnottex
3859 @unnumberedsubsec @code{if} in more detail
3860 @end ifnottex
3861
3862 @cindex @samp{if-part} defined
3863 @cindex @samp{then-part} defined
3864 An @code{if} expression written in Lisp does not use the word `then';
3865 the test and the action are the second and third elements of the list
3866 whose first element is @code{if}. Nonetheless, the test part of an
3867 @code{if} expression is often called the @dfn{if-part} and the second
3868 argument is often called the @dfn{then-part}.
3869
3870 Also, when an @code{if} expression is written, the true-or-false-test
3871 is usually written on the same line as the symbol @code{if}, but the
3872 action to carry out if the test is true, the ``then-part'', is written
3873 on the second and subsequent lines. This makes the @code{if}
3874 expression easier to read.
3875
3876 @smallexample
3877 @group
3878 (if @var{true-or-false-test}
3879 @var{action-to-carry-out-if-test-is-true})
3880 @end group
3881 @end smallexample
3882
3883 @noindent
3884 The true-or-false-test will be an expression that
3885 is evaluated by the Lisp interpreter.
3886
3887 Here is an example that you can evaluate in the usual manner. The test
3888 is whether the number 5 is greater than the number 4. Since it is, the
3889 message @samp{5 is greater than 4!} will be printed.
3890
3891 @smallexample
3892 @group
3893 (if (> 5 4) ; @r{if-part}
3894 (message "5 is greater than 4!")) ; @r{then-part}
3895 @end group
3896 @end smallexample
3897
3898 @noindent
3899 (The function @code{>} tests whether its first argument is greater than
3900 its second argument and returns true if it is.)
3901 @findex > (greater than)
3902
3903 Of course, in actual use, the test in an @code{if} expression will not
3904 be fixed for all time as it is by the expression @code{(> 5 4)}.
3905 Instead, at least one of the variables used in the test will be bound to
3906 a value that is not known ahead of time. (If the value were known ahead
3907 of time, we would not need to run the test!)
3908
3909 For example, the value may be bound to an argument of a function
3910 definition. In the following function definition, the character of the
3911 animal is a value that is passed to the function. If the value bound to
3912 @code{characteristic} is @code{fierce}, then the message, @samp{It's a
3913 tiger!} will be printed; otherwise, @code{nil} will be returned.
3914
3915 @smallexample
3916 @group
3917 (defun type-of-animal (characteristic)
3918 "Print message in echo area depending on CHARACTERISTIC.
3919 If the CHARACTERISTIC is the symbol `fierce',
3920 then warn of a tiger."
3921 (if (equal characteristic 'fierce)
3922 (message "It's a tiger!")))
3923 @end group
3924 @end smallexample
3925
3926 @need 1500
3927 @noindent
3928 If you are reading this inside of GNU Emacs, you can evaluate the
3929 function definition in the usual way to install it in Emacs, and then you
3930 can evaluate the following two expressions to see the results:
3931
3932 @smallexample
3933 @group
3934 (type-of-animal 'fierce)
3935
3936 (type-of-animal 'zebra)
3937
3938 @end group
3939 @end smallexample
3940
3941 @c Following sentences rewritten to prevent overfull hbox.
3942 @noindent
3943 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3944 following message printed in the echo area: @code{"It's a tiger!"}; and
3945 when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3946 printed in the echo area.
3947
3948 @node type-of-animal in detail, , if in more detail, if
3949 @comment node-name, next, previous, up
3950 @subsection The @code{type-of-animal} Function in Detail
3951
3952 Let's look at the @code{type-of-animal} function in detail.
3953
3954 The function definition for @code{type-of-animal} was written by filling
3955 the slots of two templates, one for a function definition as a whole, and
3956 a second for an @code{if} expression.
3957
3958 @need 1250
3959 The template for every function that is not interactive is:
3960
3961 @smallexample
3962 @group
3963 (defun @var{name-of-function} (@var{argument-list})
3964 "@var{documentation}@dots{}"
3965 @var{body}@dots{})
3966 @end group
3967 @end smallexample
3968
3969 @need 800
3970 The parts of the function that match this template look like this:
3971
3972 @smallexample
3973 @group
3974 (defun type-of-animal (characteristic)
3975 "Print message in echo area depending on CHARACTERISTIC.
3976 If the CHARACTERISTIC is the symbol `fierce',
3977 then warn of a tiger."
3978 @var{body: the} @code{if} @var{expression})
3979 @end group
3980 @end smallexample
3981
3982 The name of function is @code{type-of-animal}; it is passed the value
3983 of one argument. The argument list is followed by a multi-line
3984 documentation string. The documentation string is included in the
3985 example because it is a good habit to write documentation string for
3986 every function definition. The body of the function definition
3987 consists of the @code{if} expression.
3988
3989 @need 800
3990 The template for an @code{if} expression looks like this:
3991
3992 @smallexample
3993 @group
3994 (if @var{true-or-false-test}
3995 @var{action-to-carry-out-if-the-test-returns-true})
3996 @end group
3997 @end smallexample
3998
3999 @need 1250
4000 In the @code{type-of-animal} function, the code for the @code{if}
4001 looks like this:
4002
4003 @smallexample
4004 @group
4005 (if (equal characteristic 'fierce)
4006 (message "It's a tiger!")))
4007 @end group
4008 @end smallexample
4009
4010 @need 800
4011 Here, the true-or-false-test is the expression:
4012
4013 @smallexample
4014 (equal characteristic 'fierce)
4015 @end smallexample
4016
4017 @noindent
4018 In Lisp, @code{equal} is a function that determines whether its first
4019 argument is equal to its second argument. The second argument is the
4020 quoted symbol @code{'fierce} and the first argument is the value of the
4021 symbol @code{characteristic}---in other words, the argument passed to
4022 this function.
4023
4024 In the first exercise of @code{type-of-animal}, the argument
4025 @code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4026 is equal to @code{fierce}, the expression, @code{(equal characteristic
4027 'fierce)}, returns a value of true. When this happens, the @code{if}
4028 evaluates the second argument or then-part of the @code{if}:
4029 @code{(message "It's tiger!")}.
4030
4031 On the other hand, in the second exercise of @code{type-of-animal}, the
4032 argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4033 is not equal to @code{fierce}, so the then-part is not evaluated and
4034 @code{nil} is returned by the @code{if} expression.
4035
4036 @node else, Truth & Falsehood, if, Writing Defuns
4037 @comment node-name, next, previous, up
4038 @section If--then--else Expressions
4039 @cindex Else
4040
4041 An @code{if} expression may have an optional third argument, called
4042 the @dfn{else-part}, for the case when the true-or-false-test returns
4043 false. When this happens, the second argument or then-part of the
4044 overall @code{if} expression is @emph{not} evaluated, but the third or
4045 else-part @emph{is} evaluated. You might think of this as the cloudy
4046 day alternative for the decision `if it is warm and sunny, then go to
4047 the beach, else read a book!''.
4048
4049 The word ``else'' is not written in the Lisp code; the else-part of an
4050 @code{if} expression comes after the then-part. In the written Lisp, the
4051 else-part is usually written to start on a line of its own and is
4052 indented less than the then-part:
4053
4054 @smallexample
4055 @group
4056 (if @var{true-or-false-test}
4057 @var{action-to-carry-out-if-the-test-returns-true}
4058 @var{action-to-carry-out-if-the-test-returns-false})
4059 @end group
4060 @end smallexample
4061
4062 For example, the following @code{if} expression prints the message @samp{4
4063 is not greater than 5!} when you evaluate it in the usual way:
4064
4065 @smallexample
4066 @group
4067 (if (> 4 5) ; @r{if-part}
4068 (message "5 is greater than 4!") ; @r{then-part}
4069 (message "4 is not greater than 5!")) ; @r{else-part}
4070 @end group
4071 @end smallexample
4072
4073 @noindent
4074 Note that the different levels of indentation make it easy to
4075 distinguish the then-part from the else-part. (GNU Emacs has several
4076 commands that automatically indent @code{if} expressions correctly.
4077 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4078
4079 We can extend the @code{type-of-animal} function to include an
4080 else-part by simply incorporating an additional part to the @code{if}
4081 expression.
4082
4083 @need 1500
4084 You can see the consequences of doing this if you evaluate the following
4085 version of the @code{type-of-animal} function definition to install it
4086 and then evaluate the two subsequent expressions to pass different
4087 arguments to the function.
4088
4089 @smallexample
4090 @group
4091 (defun type-of-animal (characteristic) ; @r{Second version.}
4092 "Print message in echo area depending on CHARACTERISTIC.
4093 If the CHARACTERISTIC is the symbol `fierce',
4094 then warn of a tiger;
4095 else say it's not fierce."
4096 (if (equal characteristic 'fierce)
4097 (message "It's a tiger!")
4098 (message "It's not fierce!")))
4099 @end group
4100 @end smallexample
4101 @sp 1
4102
4103 @smallexample
4104 @group
4105 (type-of-animal 'fierce)
4106
4107 (type-of-animal 'zebra)
4108
4109 @end group
4110 @end smallexample
4111
4112 @c Following sentence rewritten to prevent overfull hbox.
4113 @noindent
4114 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4115 following message printed in the echo area: @code{"It's a tiger!"}; but
4116 when you evaluate @code{(type-of-animal 'zebra)}, you will see
4117 @code{"It's not fierce!"}.
4118
4119 (Of course, if the @var{characteristic} were @code{ferocious}, the
4120 message @code{"It's not fierce!"} would be printed; and it would be
4121 misleading! When you write code, you need to take into account the
4122 possibility that some such argument will be tested by the @code{if} and
4123 write your program accordingly.)
4124
4125 @node Truth & Falsehood, save-excursion, else, Writing Defuns
4126 @comment node-name, next, previous, up
4127 @section Truth and Falsehood in Emacs Lisp
4128 @cindex Truth and falsehood in Emacs Lisp
4129 @cindex Falsehood and truth in Emacs Lisp
4130 @findex nil
4131
4132 There is an important aspect to the truth test in an @code{if}
4133 expression. So far, we have spoken of `true' and `false' as values of
4134 predicates as if they were new kinds of Emacs Lisp objects. In fact,
4135 `false' is just our old friend @code{nil}. Anything else---anything
4136 at all---is `true'.
4137
4138 The expression that tests for truth is interpreted as @dfn{true}
4139 if the result of evaluating it is a value that is not @code{nil}. In
4140 other words, the result of the test is considered true if the value
4141 returned is a number such as 47, a string such as @code{"hello"}, or a
4142 symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4143 even a buffer!
4144
4145 @menu
4146 * nil explained:: @code{nil} has two meanings.
4147 @end menu
4148
4149 @node nil explained, , Truth & Falsehood, Truth & Falsehood
4150 @ifnottex
4151 @unnumberedsubsec An explanation of @code{nil}
4152 @end ifnottex
4153
4154 Before illustrating a test for truth, we need an explanation of @code{nil}.
4155
4156 In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4157 empty list. Second, it means false and is the value returned when a
4158 true-or-false-test tests false. @code{nil} can be written as an empty
4159 list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4160 concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4161 to use @code{nil} for false and @code{()} for the empty list.
4162
4163 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4164 list---is considered true. This means that if an evaluation returns
4165 something that is not an empty list, an @code{if} expression will test
4166 true. For example, if a number is put in the slot for the test, it
4167 will be evaluated and will return itself, since that is what numbers
4168 do when evaluated. In this conditional, the @code{if} expression will
4169 test true. The expression tests false only when @code{nil}, an empty
4170 list, is returned by evaluating the expression.
4171
4172 You can see this by evaluating the two expressions in the following examples.
4173
4174 In the first example, the number 4 is evaluated as the test in the
4175 @code{if} expression and returns itself; consequently, the then-part
4176 of the expression is evaluated and returned: @samp{true} appears in
4177 the echo area. In the second example, the @code{nil} indicates false;
4178 consequently, the else-part of the expression is evaluated and
4179 returned: @samp{false} appears in the echo area.
4180
4181 @smallexample
4182 @group
4183 (if 4
4184 'true
4185 'false)
4186 @end group
4187
4188 @group
4189 (if nil
4190 'true
4191 'false)
4192 @end group
4193 @end smallexample
4194
4195 @need 1250
4196 Incidentally, if some other useful value is not available for a test that
4197 returns true, then the Lisp interpreter will return the symbol @code{t}
4198 for true. For example, the expression @code{(> 5 4)} returns @code{t}
4199 when evaluated, as you can see by evaluating it in the usual way:
4200
4201 @smallexample
4202 (> 5 4)
4203 @end smallexample
4204
4205 @need 1250
4206 @noindent
4207 On the other hand, this function returns @code{nil} if the test is false.
4208
4209 @smallexample
4210 (> 4 5)
4211 @end smallexample
4212
4213 @node save-excursion, Review, Truth & Falsehood, Writing Defuns
4214 @comment node-name, next, previous, up
4215 @section @code{save-excursion}
4216 @findex save-excursion
4217 @cindex Region, what it is
4218 @cindex Preserving point, mark, and buffer
4219 @cindex Point, mark, buffer preservation
4220 @findex point
4221 @findex mark
4222
4223 The @code{save-excursion} function is the fourth and final special form
4224 that we will discuss in this chapter.
4225
4226 In Emacs Lisp programs used for editing, the @code{save-excursion}
4227 function is very common. It saves the location of point and mark,
4228 executes the body of the function, and then restores point and mark to
4229 their previous positions if their locations were changed. Its primary
4230 purpose is to keep the user from being surprised and disturbed by
4231 unexpected movement of point or mark.
4232
4233 @menu
4234 * Point and mark:: A review of various locations.
4235 * Template for save-excursion::
4236 @end menu
4237
4238 @node Point and mark, Template for save-excursion, save-excursion, save-excursion
4239 @ifnottex
4240 @unnumberedsubsec Point and Mark
4241 @end ifnottex
4242
4243 Before discussing @code{save-excursion}, however, it may be useful
4244 first to review what point and mark are in GNU Emacs. @dfn{Point} is
4245 the current location of the cursor. Wherever the cursor
4246 is, that is point. More precisely, on terminals where the cursor
4247 appears to be on top of a character, point is immediately before the
4248 character. In Emacs Lisp, point is an integer. The first character in
4249 a buffer is number one, the second is number two, and so on. The
4250 function @code{point} returns the current position of the cursor as a
4251 number. Each buffer has its own value for point.
4252
4253 The @dfn{mark} is another position in the buffer; its value can be set
4254 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4255 a mark has been set, you can use the command @kbd{C-x C-x}
4256 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4257 and set the mark to be the previous position of point. In addition, if
4258 you set another mark, the position of the previous mark is saved in the
4259 mark ring. Many mark positions can be saved this way. You can jump the
4260 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4261 times.
4262
4263 The part of the buffer between point and mark is called @dfn{the
4264 region}. Numerous commands work on the region, including
4265 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4266 @code{print-region}.
4267
4268 The @code{save-excursion} special form saves the locations of point and
4269 mark and restores those positions after the code within the body of the
4270 special form is evaluated by the Lisp interpreter. Thus, if point were
4271 in the beginning of a piece of text and some code moved point to the end
4272 of the buffer, the @code{save-excursion} would put point back to where
4273 it was before, after the expressions in the body of the function were
4274 evaluated.
4275
4276 In Emacs, a function frequently moves point as part of its internal
4277 workings even though a user would not expect this. For example,
4278 @code{count-lines-region} moves point. To prevent the user from being
4279 bothered by jumps that are both unexpected and (from the user's point of
4280 view) unnecessary, @code{save-excursion} is often used to keep point and
4281 mark in the location expected by the user. The use of
4282 @code{save-excursion} is good housekeeping.
4283
4284 To make sure the house stays clean, @code{save-excursion} restores the
4285 values of point and mark even if something goes wrong in the code inside
4286 of it (or, to be more precise and to use the proper jargon, ``in case of
4287 abnormal exit''). This feature is very helpful.
4288
4289 In addition to recording the values of point and mark,
4290 @code{save-excursion} keeps track of the current buffer, and restores
4291 it, too. This means you can write code that will change the buffer and
4292 have @code{save-excursion} switch you back to the original buffer. This
4293 is how @code{save-excursion} is used in @code{append-to-buffer}.
4294 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4295
4296 @node Template for save-excursion, , Point and mark, save-excursion
4297 @comment node-name, next, previous, up
4298 @subsection Template for a @code{save-excursion} Expression
4299
4300 @need 800
4301 The template for code using @code{save-excursion} is simple:
4302
4303 @smallexample
4304 @group
4305 (save-excursion
4306 @var{body}@dots{})
4307 @end group
4308 @end smallexample
4309
4310 @noindent
4311 The body of the function is one or more expressions that will be
4312 evaluated in sequence by the Lisp interpreter. If there is more than
4313 one expression in the body, the value of the last one will be returned
4314 as the value of the @code{save-excursion} function. The other
4315 expressions in the body are evaluated only for their side effects; and
4316 @code{save-excursion} itself is used only for its side effect (which
4317 is restoring the positions of point and mark).
4318
4319 @need 1250
4320 In more detail, the template for a @code{save-excursion} expression
4321 looks like this:
4322
4323 @smallexample
4324 @group
4325 (save-excursion
4326 @var{first-expression-in-body}
4327 @var{second-expression-in-body}
4328 @var{third-expression-in-body}
4329 @dots{}
4330 @var{last-expression-in-body})
4331 @end group
4332 @end smallexample
4333
4334 @noindent
4335 An expression, of course, may be a symbol on its own or a list.
4336
4337 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4338 within the body of a @code{let} expression. It looks like this:
4339
4340 @smallexample
4341 @group
4342 (let @var{varlist}
4343 (save-excursion
4344 @var{body}@dots{}))
4345 @end group
4346 @end smallexample
4347
4348 @node Review, defun Exercises, save-excursion, Writing Defuns
4349 @comment node-name, next, previous, up
4350 @section Review
4351
4352 In the last few chapters we have introduced a fair number of functions
4353 and special forms. Here they are described in brief, along with a few
4354 similar functions that have not been mentioned yet.
4355
4356 @table @code
4357 @item eval-last-sexp
4358 Evaluate the last symbolic expression before the current location of
4359 point. The value is printed in the echo area unless the function is
4360 invoked with an argument; in that case, the output is printed in the
4361 current buffer. This command is normally bound to @kbd{C-x C-e}.
4362
4363 @item defun
4364 Define function. This special form has up to five parts: the name,
4365 a template for the arguments that will be passed to the function,
4366 documentation, an optional interactive declaration, and the body of the
4367 definition.
4368
4369 @need 1250
4370 For example:
4371
4372 @smallexample
4373 @group
4374 (defun back-to-indentation ()
4375 "Move point to first visible character on line."
4376 (interactive)
4377 (beginning-of-line 1)
4378 (skip-chars-forward " \t"))
4379 @end group
4380 @end smallexample
4381
4382 @item interactive
4383 Declare to the interpreter that the function can be used
4384 interactively. This special form may be followed by a string with one
4385 or more parts that pass the information to the arguments of the
4386 function, in sequence. These parts may also tell the interpreter to
4387 prompt for information. Parts of the string are separated by
4388 newlines, @samp{\n}.
4389
4390 Common code characters are:
4391
4392 @table @code
4393 @item b
4394 The name of an existing buffer.
4395
4396 @item f
4397 The name of an existing file.
4398
4399 @item p
4400 The numeric prefix argument. (Note that this `p' is lower case.)
4401
4402 @item r
4403 Point and the mark, as two numeric arguments, smallest first. This
4404 is the only code letter that specifies two successive arguments
4405 rather than one.
4406 @end table
4407
4408 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4409 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4410 code characters.
4411
4412 @item let
4413 Declare that a list of variables is for use within the body of the
4414 @code{let} and give them an initial value, either @code{nil} or a
4415 specified value; then evaluate the rest of the expressions in the body
4416 of the @code{let} and return the value of the last one. Inside the
4417 body of the @code{let}, the Lisp interpreter does not see the values of
4418 the variables of the same names that are bound outside of the
4419 @code{let}.
4420
4421 @need 1250
4422 For example,
4423
4424 @smallexample
4425 @group
4426 (let ((foo (buffer-name))
4427 (bar (buffer-size)))
4428 (message
4429 "This buffer is %s and has %d characters."
4430 foo bar))
4431 @end group
4432 @end smallexample
4433
4434 @item save-excursion
4435 Record the values of point and mark and the current buffer before
4436 evaluating the body of this special form. Restore the values of point
4437 and mark and buffer afterward.
4438
4439 @need 1250
4440 For example,
4441
4442 @smallexample
4443 @group
4444 (message "We are %d characters into this buffer."
4445 (- (point)
4446 (save-excursion
4447 (goto-char (point-min)) (point))))
4448 @end group
4449 @end smallexample
4450
4451 @item if
4452 Evaluate the first argument to the function; if it is true, evaluate
4453 the second argument; else evaluate the third argument, if there is one.
4454
4455 The @code{if} special form is called a @dfn{conditional}. There are
4456 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4457 commonly used.
4458
4459 @need 1250
4460 For example,
4461
4462 @smallexample
4463 @group
4464 (if (string-equal
4465 (number-to-string 21)
4466 (substring (emacs-version) 10 12))
4467 (message "This is version 21 Emacs")
4468 (message "This is not version 21 Emacs"))
4469 @end group
4470 @end smallexample
4471
4472 @item equal
4473 @itemx eq
4474 Test whether two objects are the same. @code{equal} uses one meaning
4475 of the word `same' and @code{eq} uses another: @code{equal} returns
4476 true if the two objects have a similar structure and contents, such as
4477 two copies of the same book. On the other hand, @code{eq}, returns
4478 true if both arguments are actually the same object.
4479 @findex equal
4480 @findex eq
4481
4482 @need 1250
4483 @item <
4484 @itemx >
4485 @itemx <=
4486 @itemx >=
4487 The @code{<} function tests whether its first argument is smaller than
4488 its second argument. A corresponding function, @code{>}, tests whether
4489 the first argument is greater than the second. Likewise, @code{<=}
4490 tests whether the first argument is less than or equal to the second and
4491 @code{>=} tests whether the first argument is greater than or equal to
4492 the second. In all cases, both arguments must be numbers or markers
4493 (markers indicate positions in buffers).
4494
4495 @item string<
4496 @itemx string-lessp
4497 @itemx string=
4498 @itemx string-equal
4499 The @code{string-lessp} function tests whether its first argument is
4500 smaller than the second argument. A shorter, alternative name for the
4501 same function (a @code{defalias}) is @code{string<}.
4502
4503 The arguments to @code{string-lessp} must be strings or symbols; the
4504 ordering is lexicographic, so case is significant. The print names of
4505 symbols are used instead of the symbols themselves.
4506
4507 @code{string-equal} provides the corresponding test for equality. Its
4508 shorter, alternative name is @code{string=}. There are no string test
4509 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4510
4511 @item message
4512 Print a message in the echo area. The first argument is a string that
4513 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4514 arguments that follow the string. The argument used by @samp{%s} must
4515 be a string or a symbol; the argument used by @samp{%d} must be a
4516 number. The argument used by @samp{%c} must be an ascii code number;
4517 it will be printed as the character with that @sc{ascii} code.
4518
4519 @item setq
4520 @itemx set
4521 The @code{setq} function sets the value of its first argument to the
4522 value of the second argument. The first argument is automatically
4523 quoted by @code{setq}. It does the same for succeeding pairs of
4524 arguments. Another function, @code{set}, takes only two arguments and
4525 evaluates both of them before setting the value returned by its first
4526 argument to the value returned by its second argument.
4527
4528 @item buffer-name
4529 Without an argument, return the name of the buffer, as a string.
4530
4531 @itemx buffer-file-name
4532 Without an argument, return the name of the file the buffer is
4533 visiting.
4534
4535 @item current-buffer
4536 Return the buffer in which Emacs is active; it may not be
4537 the buffer that is visible on the screen.
4538
4539 @item other-buffer
4540 Return the most recently selected buffer (other than the buffer passed
4541 to @code{other-buffer} as an argument and other than the current
4542 buffer).
4543
4544 @item switch-to-buffer
4545 Select a buffer for Emacs to be active in and display it in the current
4546 window so users can look at it. Usually bound to @kbd{C-x b}.
4547
4548 @item set-buffer
4549 Switch Emacs' attention to a buffer on which programs will run. Don't
4550 alter what the window is showing.
4551
4552 @item buffer-size
4553 Return the number of characters in the current buffer.
4554
4555 @item point
4556 Return the value of the current position of the cursor, as an
4557 integer counting the number of characters from the beginning of the
4558 buffer.
4559
4560 @item point-min
4561 Return the minimum permissible value of point in
4562 the current buffer. This is 1, unless narrowing is in effect.
4563
4564 @item point-max
4565 Return the value of the maximum permissible value of point in the
4566 current buffer. This is the end of the buffer, unless narrowing is in
4567 effect.
4568 @end table
4569
4570 @need 1500
4571 @node defun Exercises, , Review, Writing Defuns
4572 @section Exercises
4573
4574 @itemize @bullet
4575 @item
4576 Write a non-interactive function that doubles the value of its
4577 argument, a number. Make that function interactive.
4578
4579 @item
4580 Write a function that tests whether the current value of
4581 @code{fill-column} is greater than the argument passed to the function,
4582 and if so, prints an appropriate message.
4583 @end itemize
4584
4585 @node Buffer Walk Through, More Complex, Writing Defuns, Top
4586 @comment node-name, next, previous, up
4587 @chapter A Few Buffer--Related Functions
4588
4589 In this chapter we study in detail several of the functions used in GNU
4590 Emacs. This is called a ``walk-through''. These functions are used as
4591 examples of Lisp code, but are not imaginary examples; with the
4592 exception of the first, simplified function definition, these functions
4593 show the actual code used in GNU Emacs. You can learn a great deal from
4594 these definitions. The functions described here are all related to
4595 buffers. Later, we will study other functions.
4596
4597 @menu
4598 * Finding More:: How to find more information.
4599 * simplified-beginning-of-buffer:: Shows @code{goto-char},
4600 @code{point-min}, and @code{push-mark}.
4601 * mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4602 * append-to-buffer:: Uses @code{save-excursion} and
4603 @code{insert-buffer-substring}.
4604 * Buffer Related Review:: Review.
4605 * Buffer Exercises::
4606 @end menu
4607
4608 @node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4609 @section Finding More Information
4610
4611 @findex describe-function, @r{introduced}
4612 @cindex Find function documentation
4613 In this walk-through, I will describe each new function as we come to
4614 it, sometimes in detail and sometimes briefly. If you are interested,
4615 you can get the full documentation of any Emacs Lisp function at any
4616 time by typing @kbd{C-h f} and then the name of the function (and then
4617 @key{RET}). Similarly, you can get the full documentation for a
4618 variable by typing @kbd{C-h v} and then the name of the variable (and
4619 then @key{RET}).
4620
4621 @cindex Find source of function
4622 In versions 20 and higher, when a function is written in Emacs Lisp,
4623 @code{describe-function} will also tell you the location of the
4624 function definition. If you move point over the file name and press
4625 the @key{RET} key, which is this case means @code{help-follow} rather
4626 than `return' or `enter', Emacs will take you directly to the function
4627 definition.
4628
4629 More generally, if you want to see a function in its original source
4630 file, you can use the @code{find-tags} function to jump to it.
4631 @code{find-tags} works with a wide variety of languages, not just
4632 Lisp, and C, and it works with non-programming text as well. For
4633 example, @code{find-tags} will jump to the various nodes in the
4634 Texinfo source file of this document.
4635
4636 The @code{find-tags} function depends on `tags tables' that record
4637 the locations of the functions, variables, and other items to which
4638 @code{find-tags} jumps.
4639
4640 To use the @code{find-tags} command, type @kbd{M-.} (i.e., type the
4641 @key{META} key and the period key at the same time, or else type the
4642 @key{ESC} key and then type the period key), and then, at the prompt,
4643 type in the name of the function whose source code you want to see,
4644 such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4645 switch buffers and display the source code for the function on your
4646 screen. To switch back to your current buffer, type @kbd{C-x b
4647 @key{RET}}. (On some keyboards, the @key{META} key is labelled
4648 @key{ALT}.)
4649
4650 @c !!! 21.0.100 tags table location in this paragraph
4651 @cindex TAGS table, specifying
4652 @findex find-tags
4653 Depending on how the initial default values of your copy of Emacs are
4654 set, you may also need to specify the location of your `tags table',
4655 which is a file called @file{TAGS}. For example, if you are
4656 interested in Emacs sources, the tags table you will most likely want,
4657 if it has already been created for you, will be in a subdirectory of
4658 the @file{/usr/local/share/emacs/} directory; thus you would use the
4659 @code{M-x visit-tags-table} command and specify a pathname such as
4660 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
4661 @file{/usr/local/src/emacs/lisp/TAGS}. If the tags table has
4662 not already been created, you will have to create it yourself.
4663
4664 @need 1250
4665 To create a @file{TAGS} file in a specific directory, switch to that
4666 directory in Emacs using @kbd{M-x cd} command, or list the directory
4667 with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4668 @w{@code{etags *.el}} as the command to execute
4669
4670 @smallexample
4671 M-x compile RET etags *.el RET
4672 @end smallexample
4673
4674 For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4675
4676 After you become more familiar with Emacs Lisp, you will find that you will
4677 frequently use @code{find-tags} to navigate your way around source code;
4678 and you will create your own @file{TAGS} tables.
4679
4680 @cindex Library, as term for `file'
4681 Incidentally, the files that contain Lisp code are conventionally
4682 called @dfn{libraries}. The metaphor is derived from that of a
4683 specialized library, such as a law library or an engineering library,
4684 rather than a general library. Each library, or file, contains
4685 functions that relate to a particular topic or activity, such as
4686 @file{abbrev.el} for handling abbreviations and other typing
4687 shortcuts, and @file{help.el} for on-line help. (Sometimes several
4688 libraries provide code for a single activity, as the various
4689 @file{rmail@dots{}} files provide code for reading electronic mail.)
4690 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4691 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4692 by topic keywords.''
4693
4694 @node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4695 @comment node-name, next, previous, up
4696 @section A Simplified @code{beginning-of-buffer} Definition
4697 @findex simplified-beginning-of-buffer
4698
4699 The @code{beginning-of-buffer} command is a good function to start with
4700 since you are likely to be familiar with it and it is easy to
4701 understand. Used as an interactive command, @code{beginning-of-buffer}
4702 moves the cursor to the beginning of the buffer, leaving the mark at the
4703 previous position. It is generally bound to @kbd{M-<}.
4704
4705 In this section, we will discuss a shortened version of the function
4706 that shows how it is most frequently used. This shortened function
4707 works as written, but it does not contain the code for a complex option.
4708 In another section, we will describe the entire function.
4709 (@xref{beginning-of-buffer, , Complete Definition of
4710 @code{beginning-of-buffer}}.)
4711
4712 Before looking at the code, let's consider what the function
4713 definition has to contain: it must include an expression that makes
4714 the function interactive so it can be called by typing @kbd{M-x
4715 beginning-of-buffer} or by typing a keychord such as @kbd{C-<}; it
4716 must include code to leave a mark at the original position in the
4717 buffer; and it must include code to move the cursor to the beginning
4718 of the buffer.
4719
4720 @need 1250
4721 Here is the complete text of the shortened version of the function:
4722
4723 @smallexample
4724 @group
4725 (defun simplified-beginning-of-buffer ()
4726 "Move point to the beginning of the buffer;
4727 leave mark at previous position."
4728 (interactive)
4729 (push-mark)
4730 (goto-char (point-min)))
4731 @end group
4732 @end smallexample
4733
4734 Like all function definitions, this definition has five parts following
4735 the special form @code{defun}:
4736
4737 @enumerate
4738 @item
4739 The name: in this example, @code{simplified-beginning-of-buffer}.
4740
4741 @item
4742 A list of the arguments: in this example, an empty list, @code{()},
4743
4744 @item
4745 The documentation string.
4746
4747 @item
4748 The interactive expression.
4749
4750 @item
4751 The body.
4752 @end enumerate
4753
4754 @noindent
4755 In this function definition, the argument list is empty; this means that
4756 this function does not require any arguments. (When we look at the
4757 definition for the complete function, we will see that it may be passed
4758 an optional argument.)
4759
4760 The interactive expression tells Emacs that the function is intended to
4761 be used interactively. In this example, @code{interactive} does not have
4762 an argument because @code{simplified-beginning-of-buffer} does not
4763 require one.
4764
4765 @need 800
4766 The body of the function consists of the two lines:
4767
4768 @smallexample
4769 @group
4770 (push-mark)
4771 (goto-char (point-min))
4772 @end group
4773 @end smallexample
4774
4775 The first of these lines is the expression, @code{(push-mark)}. When
4776 this expression is evaluated by the Lisp interpreter, it sets a mark at
4777 the current position of the cursor, wherever that may be. The position
4778 of this mark is saved in the mark ring.
4779
4780 The next line is @code{(goto-char (point-min))}. This expression
4781 jumps the cursor to the minimum point in the buffer, that is, to the
4782 beginning of the buffer (or to the beginning of the accessible portion
4783 of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4784 Narrowing and Widening}.)
4785
4786 The @code{push-mark} command sets a mark at the place where the cursor
4787 was located before it was moved to the beginning of the buffer by the
4788 @code{(goto-char (point-min))} expression. Consequently, you can, if
4789 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4790
4791 That is all there is to the function definition!
4792
4793 @findex describe-function
4794 When you are reading code such as this and come upon an unfamiliar
4795 function, such as @code{goto-char}, you can find out what it does by
4796 using the @code{describe-function} command. To use this command, type
4797 @kbd{C-h f} and then type in the name of the function and press
4798 @key{RET}. The @code{describe-function} command will print the
4799 function's documentation string in a @file{*Help*} window. For
4800 example, the documentation for @code{goto-char} is:
4801
4802 @smallexample
4803 @group
4804 One arg, a number. Set point to that number.
4805 Beginning of buffer is position (point-min),
4806 end is (point-max).
4807 @end group
4808 @end smallexample
4809
4810 @noindent
4811 (The prompt for @code{describe-function} will offer you the symbol
4812 under or preceding the cursor, so you can save typing by positioning
4813 the cursor right over or after the function and then typing @kbd{C-h f
4814 @key{RET}}.)
4815
4816 The @code{end-of-buffer} function definition is written in the same way as
4817 the @code{beginning-of-buffer} definition except that the body of the
4818 function contains the expression @code{(goto-char (point-max))} in place
4819 of @code{(goto-char (point-min))}.
4820
4821 @node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4822 @comment node-name, next, previous, up
4823 @section The Definition of @code{mark-whole-buffer}
4824 @findex mark-whole-buffer
4825
4826 The @code{mark-whole-buffer} function is no harder to understand than the
4827 @code{simplified-beginning-of-buffer} function. In this case, however,
4828 we will look at the complete function, not a shortened version.
4829
4830 The @code{mark-whole-buffer} function is not as commonly used as the
4831 @code{beginning-of-buffer} function, but is useful nonetheless: it
4832 marks a whole buffer as a region by putting point at the beginning and
4833 a mark at the end of the buffer. It is generally bound to @kbd{C-x
4834 h}.
4835
4836
4837 @menu
4838 * mark-whole-buffer overview::
4839 * Body of mark-whole-buffer:: Only three lines of code.
4840 @end menu
4841
4842
4843 @node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4844 @ifnottex
4845 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4846 @end ifnottex
4847
4848 @need 1250
4849 In GNU Emacs 20, the code for the complete function looks like this:
4850
4851 @smallexample
4852 @group
4853 (defun mark-whole-buffer ()
4854 "Put point at beginning and mark at end of buffer."
4855 (interactive)
4856 (push-mark (point))
4857 (push-mark (point-max))
4858 (goto-char (point-min)))
4859 @end group
4860 @end smallexample
4861
4862 @need 1250
4863 Like all other functions, the @code{mark-whole-buffer} function fits
4864 into the template for a function definition. The template looks like
4865 this:
4866
4867 @smallexample
4868 @group
4869 (defun @var{name-of-function} (@var{argument-list})
4870 "@var{documentation}@dots{}"
4871 (@var{interactive-expression}@dots{})
4872 @var{body}@dots{})
4873 @end group
4874 @end smallexample
4875
4876 Here is how the function works: the name of the function is
4877 @code{mark-whole-buffer}; it is followed by an empty argument list,
4878 @samp{()}, which means that the function does not require arguments.
4879 The documentation comes next.
4880
4881 The next line is an @code{(interactive)} expression that tells Emacs
4882 that the function will be used interactively. These details are similar
4883 to the @code{simplified-beginning-of-buffer} function described in the
4884 previous section.
4885
4886 @node Body of mark-whole-buffer, , mark-whole-buffer overview, mark-whole-buffer
4887 @comment node-name, next, previous, up
4888 @subsection Body of @code{mark-whole-buffer}
4889
4890 The body of the @code{mark-whole-buffer} function consists of three
4891 lines of code:
4892
4893 @smallexample
4894 @group
4895 (push-mark (point))
4896 (push-mark (point-max))
4897 (goto-char (point-min))
4898 @end group
4899 @end smallexample
4900
4901 The first of these lines is the expression, @code{(push-mark (point))}.
4902
4903 This line does exactly the same job as the first line of the body of
4904 the @code{simplified-beginning-of-buffer} function, which is written
4905 @code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4906 at the current position of the cursor.
4907
4908 I don't know why the expression in @code{mark-whole-buffer} is written
4909 @code{(push-mark (point))} and the expression in
4910 @code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4911 whoever wrote the code did not know that the arguments for
4912 @code{push-mark} are optional and that if @code{push-mark} is not
4913 passed an argument, the function automatically sets mark at the
4914 location of point by default. Or perhaps the expression was written
4915 so as to parallel the structure of the next line. In any case, the
4916 line causes Emacs to determine the position of point and set a mark
4917 there.
4918
4919 The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4920 This expression sets a mark at the point in the buffer
4921 that has the highest number. This will be the end of the buffer (or,
4922 if the buffer is narrowed, the end of the accessible portion of the
4923 buffer. @xref{Narrowing & Widening, , Narrowing and Widening}, for
4924 more about narrowing.) After this mark has been set, the previous
4925 mark, the one set at point, is no longer set, but Emacs remembers its
4926 position, just as all other recent marks are always remembered. This
4927 means that you can, if you wish, go back to that position by typing
4928 @kbd{C-u C-@key{SPC}} twice.
4929
4930 (In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4931 complicated than shown here. The line reads
4932
4933 @smallexample
4934 (push-mark (point-max) nil t)
4935 @end smallexample
4936
4937 @noindent
4938 (The expression works nearly the same as before. It sets a mark at
4939 the highest numbered place in the buffer that it can. However, in
4940 this version, @code{push-mark} has two additional arguments The second
4941 argument to @code{push-mark} is @code{nil}. This tells the function
4942 it should @emph{not} display a message that says `Mark set' when it
4943 pushes the mark. The third argument is @code{t}. This tells
4944 @code{push-mark} to activate the mark when Transient Mark mode is
4945 turned on. Transient Mark mode highlights the currently active
4946 region. It is usually turned off.)
4947
4948 Finally, the last line of the function is @code{(goto-char
4949 (point-min)))}. This is written exactly the same way as it is written
4950 in @code{beginning-of-buffer}. The expression moves the cursor to
4951 the minimum point in the buffer, that is, to the beginning of the buffer
4952 (or to the beginning of the accessible portion of the buffer). As a
4953 result of this, point is placed at the beginning of the buffer and mark
4954 is set at the end of the buffer. The whole buffer is, therefore, the
4955 region.
4956
4957 @node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4958 @comment node-name, next, previous, up
4959 @section The Definition of @code{append-to-buffer}
4960 @findex append-to-buffer
4961
4962 The @code{append-to-buffer} command is very nearly as simple as the
4963 @code{mark-whole-buffer} command. What it does is copy the region (that
4964 is, the part of the buffer between point and mark) from the current
4965 buffer to a specified buffer.
4966
4967 @menu
4968 * append-to-buffer overview::
4969 * append interactive:: A two part interactive expression.
4970 * append-to-buffer body:: Incorporates a @code{let} expression.
4971 * append save-excursion:: How the @code{save-excursion} works.
4972 @end menu
4973
4974 @node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4975 @ifnottex
4976 @unnumberedsubsec An Overview of @code{append-to-buffer}
4977 @end ifnottex
4978
4979 @findex insert-buffer-substring
4980 The @code{append-to-buffer} command uses the
4981 @code{insert-buffer-substring} function to copy the region.
4982 @code{insert-buffer-substring} is described by its name: it takes a
4983 string of characters from part of a buffer, a ``substring'', and
4984 inserts them into another buffer. Most of @code{append-to-buffer} is
4985 concerned with setting up the conditions for
4986 @code{insert-buffer-substring} to work: the code must specify both the
4987 buffer to which the text will go and the region that will be copied.
4988 Here is the complete text of the function:
4989
4990 @smallexample
4991 @group
4992 (defun append-to-buffer (buffer start end)
4993 "Append to specified buffer the text of the region.
4994 It is inserted into that buffer before its point.
4995 @end group
4996
4997 @group
4998 When calling from a program, give three arguments:
4999 a buffer or the name of one, and two character numbers
5000 specifying the portion of the current buffer to be copied."
5001 (interactive "BAppend to buffer:@: \nr")
5002 (let ((oldbuf (current-buffer)))
5003 (save-excursion
5004 (set-buffer (get-buffer-create buffer))
5005 (insert-buffer-substring oldbuf start end))))
5006 @end group
5007 @end smallexample
5008
5009 The function can be understood by looking at it as a series of
5010 filled-in templates.
5011
5012 The outermost template is for the function definition. In this
5013 function, it looks like this (with several slots filled in):
5014
5015 @smallexample
5016 @group
5017 (defun append-to-buffer (buffer start end)
5018 "@var{documentation}@dots{}"
5019 (interactive "BAppend to buffer:@: \nr")
5020 @var{body}@dots{})
5021 @end group
5022 @end smallexample
5023
5024 The first line of the function includes its name and three arguments.
5025 The arguments are the @code{buffer} to which the text will be copied, and
5026 the @code{start} and @code{end} of the region in the current buffer that
5027 will be copied.
5028
5029 The next part of the function is the documentation, which is clear and
5030 complete.
5031
5032 @node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
5033 @comment node-name, next, previous, up
5034 @subsection The @code{append-to-buffer} Interactive Expression
5035
5036 Since the @code{append-to-buffer} function will be used interactively,
5037 the function must have an @code{interactive} expression. (For a
5038 review of @code{interactive}, see @ref{Interactive, , Making a
5039 Function Interactive}.) The expression reads as follows:
5040
5041 @smallexample
5042 (interactive "BAppend to buffer:@: \nr")
5043 @end smallexample
5044
5045 @noindent
5046 This expression has an argument inside of quotation marks and that
5047 argument has two parts, separated by @samp{\n}.
5048
5049 The first part is @samp{BAppend to buffer:@: }. Here, the @samp{B}
5050 tells Emacs to ask for the name of the buffer that will be passed to the
5051 function. Emacs will ask for the name by prompting the user in the
5052 minibuffer, using the string following the @samp{B}, which is the string
5053 @samp{Append to buffer:@: }. Emacs then binds the variable @code{buffer}
5054 in the function's argument list to the specified buffer.
5055
5056 The newline, @samp{\n}, separates the first part of the argument from
5057 the second part. It is followed by an @samp{r} that tells Emacs to bind
5058 the two arguments that follow the symbol @code{buffer} in the function's
5059 argument list (that is, @code{start} and @code{end}) to the values of
5060 point and mark.
5061
5062 @node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5063 @comment node-name, next, previous, up
5064 @subsection The Body of @code{append-to-buffer}
5065
5066 The body of the @code{append-to-buffer} function begins with @code{let}.
5067
5068 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5069 @code{let} expression is to create and give initial values to one or
5070 more variables that will only be used within the body of the
5071 @code{let}. This means that such a variable will not be confused with
5072 any variable of the same name outside the @code{let} expression.
5073
5074 We can see how the @code{let} expression fits into the function as a
5075 whole by showing a template for @code{append-to-buffer} with the
5076 @code{let} expression in outline:
5077
5078 @smallexample
5079 @group
5080 (defun append-to-buffer (buffer start end)
5081 "@var{documentation}@dots{}"
5082 (interactive "BAppend to buffer:@: \nr")
5083 (let ((@var{variable} @var{value}))
5084 @var{body}@dots{})
5085 @end group
5086 @end smallexample
5087
5088 The @code{let} expression has three elements:
5089
5090 @enumerate
5091 @item
5092 The symbol @code{let};
5093
5094 @item
5095 A varlist containing, in this case, a single two-element list,
5096 @code{(@var{variable} @var{value})};
5097
5098 @item
5099 The body of the @code{let} expression.
5100 @end enumerate
5101
5102 @need 800
5103 In the @code{append-to-buffer} function, the varlist looks like this:
5104
5105 @smallexample
5106 (oldbuf (current-buffer))
5107 @end smallexample
5108
5109 @noindent
5110 In this part of the @code{let} expression, the one variable,
5111 @code{oldbuf}, is bound to the value returned by the
5112 @code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5113 used to keep track of the buffer in which you are working and from
5114 which you will copy.
5115
5116 The element or elements of a varlist are surrounded by a set of
5117 parentheses so the Lisp interpreter can distinguish the varlist from
5118 the body of the @code{let}. As a consequence, the two-element list
5119 within the varlist is surrounded by a circumscribing set of parentheses.
5120 The line looks like this:
5121
5122 @smallexample
5123 @group
5124 (let ((oldbuf (current-buffer)))
5125 @dots{} )
5126 @end group
5127 @end smallexample
5128
5129 @noindent
5130 The two parentheses before @code{oldbuf} might surprise you if you did
5131 not realize that the first parenthesis before @code{oldbuf} marks the
5132 boundary of the varlist and the second parenthesis marks the beginning
5133 of the two-element list, @code{(oldbuf (current-buffer))}.
5134
5135 @node append save-excursion, , append-to-buffer body, append-to-buffer
5136 @comment node-name, next, previous, up
5137 @subsection @code{save-excursion} in @code{append-to-buffer}
5138
5139 The body of the @code{let} expression in @code{append-to-buffer}
5140 consists of a @code{save-excursion} expression.
5141
5142 The @code{save-excursion} function saves the locations of point and
5143 mark, and restores them to those positions after the expressions in the
5144 body of the @code{save-excursion} complete execution. In addition,
5145 @code{save-excursion} keeps track of the original buffer, and
5146 restores it. This is how @code{save-excursion} is used in
5147 @code{append-to-buffer}.
5148
5149 @need 1500
5150 @cindex Indentation for formatting
5151 @cindex Formatting convention
5152 Incidentally, it is worth noting here that a Lisp function is normally
5153 formatted so that everything that is enclosed in a multi-line spread is
5154 indented more to the right than the first symbol. In this function
5155 definition, the @code{let} is indented more than the @code{defun}, and
5156 the @code{save-excursion} is indented more than the @code{let}, like
5157 this:
5158
5159 @smallexample
5160 @group
5161 (defun @dots{}
5162 @dots{}
5163 @dots{}
5164 (let@dots{}
5165 (save-excursion
5166 @dots{}
5167 @end group
5168 @end smallexample
5169
5170 @need 1500
5171 @noindent
5172 This formatting convention makes it easy to see that the two lines in
5173 the body of the @code{save-excursion} are enclosed by the parentheses
5174 associated with @code{save-excursion}, just as the
5175 @code{save-excursion} itself is enclosed by the parentheses associated
5176 with the @code{let}:
5177
5178 @smallexample
5179 @group
5180 (let ((oldbuf (current-buffer)))
5181 (save-excursion
5182 (set-buffer (get-buffer-create buffer))
5183 (insert-buffer-substring oldbuf start end))))
5184 @end group
5185 @end smallexample
5186
5187 @need 1200
5188 The use of the @code{save-excursion} function can be viewed as a process
5189 of filling in the slots of a template:
5190
5191 @smallexample
5192 @group
5193 (save-excursion
5194 @var{first-expression-in-body}
5195 @var{second-expression-in-body}
5196 @dots{}
5197 @var{last-expression-in-body})
5198 @end group
5199 @end smallexample
5200
5201 @need 1200
5202 @noindent
5203 In this function, the body of the @code{save-excursion} contains only
5204 two expressions. The body looks like this:
5205
5206 @smallexample
5207 @group
5208 (set-buffer (get-buffer-create buffer))
5209 (insert-buffer-substring oldbuf start end)
5210 @end group
5211 @end smallexample
5212
5213 When the @code{append-to-buffer} function is evaluated, the two
5214 expressions in the body of the @code{save-excursion} are evaluated in
5215 sequence. The value of the last expression is returned as the value of
5216 the @code{save-excursion} function; the other expression is evaluated
5217 only for its side effects.
5218
5219 The first line in the body of the @code{save-excursion} uses the
5220 @code{set-buffer} function to change the current buffer to the one
5221 specified in the first argument to @code{append-to-buffer}. (Changing
5222 the buffer is the side effect; as we have said before, in Lisp, a side
5223 effect is often the primary thing we want.) The second line does the
5224 primary work of the function.
5225
5226 The @code{set-buffer} function changes Emacs' attention to the buffer to
5227 which the text will be copied and from which @code{save-excursion} will
5228 return.
5229
5230 @need 800
5231 The line looks like this:
5232
5233 @smallexample
5234 (set-buffer (get-buffer-create buffer))
5235 @end smallexample
5236
5237 The innermost expression of this list is @code{(get-buffer-create
5238 buffer)}. This expression uses the @code{get-buffer-create} function,
5239 which either gets the named buffer, or if it does not exist, creates one
5240 with the given name. This means you can use @code{append-to-buffer} to
5241 put text into a buffer that did not previously exist.
5242
5243 @code{get-buffer-create} also keeps @code{set-buffer} from getting an
5244 unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5245 were to specify a buffer that does not exist, Emacs would baulk.
5246 Since @code{get-buffer-create} will create a buffer if none exists,
5247 @code{set-buffer} is always provided with a buffer.
5248
5249 @need 1250
5250 The last line of @code{append-to-buffer} does the work of appending
5251 the text:
5252
5253 @smallexample
5254 (insert-buffer-substring oldbuf start end)
5255 @end smallexample
5256
5257 @noindent
5258 The @code{insert-buffer-substring} function copies a string @emph{from}
5259 the buffer specified as its first argument and inserts the string into
5260 the present buffer. In this case, the argument to
5261 @code{insert-buffer-substring} is the value of the variable created and
5262 bound by the @code{let}, namely the value of @code{oldbuf}, which was
5263 the current buffer when you gave the @code{append-to-buffer} command.
5264
5265 After @code{insert-buffer-substring} has done its work,
5266 @code{save-excursion} will restore the action to the original buffer and
5267 @code{append-to-buffer} will have done its job.
5268
5269 @need 800
5270 Written in skeletal form, the workings of the body look like this:
5271
5272 @smallexample
5273 @group
5274 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5275 (save-excursion ; @r{Keep track of buffer.}
5276 @var{change-buffer}
5277 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5278
5279 @var{change-back-to-original-buffer-when-finished}
5280 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5281
5282 @end group
5283 @end smallexample
5284
5285 In summary, @code{append-to-buffer} works as follows: it saves the value
5286 of the current buffer in the variable called @code{oldbuf}. It gets the
5287 new buffer, creating one if need be, and switches Emacs to it. Using
5288 the value of @code{oldbuf}, it inserts the region of text from the old
5289 buffer into the new buffer; and then using @code{save-excursion}, it
5290 brings you back to your original buffer.
5291
5292 In looking at @code{append-to-buffer}, you have explored a fairly
5293 complex function. It shows how to use @code{let} and
5294 @code{save-excursion}, and how to change to and come back from another
5295 buffer. Many function definitions use @code{let},
5296 @code{save-excursion}, and @code{set-buffer} this way.
5297
5298 @node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5299 @comment node-name, next, previous, up
5300 @section Review
5301
5302 Here is a brief summary of the various functions discussed in this chapter.
5303
5304 @table @code
5305 @item describe-function
5306 @itemx describe-variable
5307 Print the documentation for a function or variable.
5308 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5309
5310 @item find-tag
5311 Find the file containing the source for a function or variable and
5312 switch buffers to it, positioning point at the beginning of the item.
5313 Conventionally bound to @kbd{M-.} (that's a period following the
5314 @key{META} key).
5315
5316 @item save-excursion
5317 Save the location of point and mark and restore their values after the
5318 arguments to @code{save-excursion} have been evaluated. Also, remember
5319 the current buffer and return to it.
5320
5321 @item push-mark
5322 Set mark at a location and record the value of the previous mark on the
5323 mark ring. The mark is a location in the buffer that will keep its
5324 relative position even if text is added to or removed from the buffer.
5325
5326 @item goto-char
5327 Set point to the location specified by the value of the argument, which
5328 can be a number, a marker, or an expression that returns the number of
5329 a position, such as @code{(point-min)}.
5330
5331 @item insert-buffer-substring
5332 Copy a region of text from a buffer that is passed to the function as
5333 an argument and insert the region into the current buffer.
5334
5335 @item mark-whole-buffer
5336 Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5337
5338 @item set-buffer
5339 Switch the attention of Emacs to another buffer, but do not change the
5340 window being displayed. Used when the program rather than a human is
5341 to work on a different buffer.
5342
5343 @item get-buffer-create
5344 @itemx get-buffer
5345 Find a named buffer or create one if a buffer of that name does not
5346 exist. The @code{get-buffer} function returns @code{nil} if the named
5347 buffer does not exist.
5348 @end table
5349
5350 @need 1500
5351 @node Buffer Exercises, , Buffer Related Review, Buffer Walk Through
5352 @section Exercises
5353
5354 @itemize @bullet
5355 @item
5356 Write your own @code{simplified-end-of-buffer} function definition;
5357 then test it to see whether it works.
5358
5359 @item
5360 Use @code{if} and @code{get-buffer} to write a function that prints a
5361 message telling you whether a buffer exists.
5362
5363 @item
5364 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5365 function.
5366 @end itemize
5367
5368 @node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5369 @comment node-name, next, previous, up
5370 @chapter A Few More Complex Functions
5371
5372 In this chapter, we build on what we have learned in previous chapters
5373 by looking at more complex functions. The @code{copy-to-buffer}
5374 function illustrates use of two @code{save-excursion} expressions in
5375 one definition, while the @code{insert-buffer} function illustrates
5376 use of an asterisk in an @code{interactive} expression, use of
5377 @code{or}, and the important distinction between a name and the object
5378 to which the name refers.
5379
5380 @menu
5381 * copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5382 * insert-buffer:: Read-only, and with @code{or}.
5383 * beginning-of-buffer:: Shows @code{goto-char},
5384 @code{point-min}, and @code{push-mark}.
5385 * Second Buffer Related Review::
5386 * optional Exercise::
5387 @end menu
5388
5389 @node copy-to-buffer, insert-buffer, More Complex, More Complex
5390 @comment node-name, next, previous, up
5391 @section The Definition of @code{copy-to-buffer}
5392 @findex copy-to-buffer
5393
5394 After understanding how @code{append-to-buffer} works, it is easy to
5395 understand @code{copy-to-buffer}. This function copies text into a
5396 buffer, but instead of adding to the second buffer, it replaces the
5397 previous text in the second buffer. The code for the
5398 @code{copy-to-buffer} function is almost the same as the code for
5399 @code{append-to-buffer}, except that @code{erase-buffer} and a second
5400 @code{save-excursion} are used. (@xref{append-to-buffer, , The
5401 Definition of @code{append-to-buffer}}, for the description of
5402 @code{append-to-buffer}.)
5403
5404 @need 800
5405 The body of @code{copy-to-buffer} looks like this
5406
5407 @smallexample
5408 @group
5409 @dots{}
5410 (interactive "BCopy to buffer:@: \nr")
5411 (let ((oldbuf (current-buffer)))
5412 (save-excursion
5413 (set-buffer (get-buffer-create buffer))
5414 (erase-buffer)
5415 (save-excursion
5416 (insert-buffer-substring oldbuf start end)))))
5417 @end group
5418 @end smallexample
5419
5420 This code is similar to the code in @code{append-to-buffer}: it is
5421 only after changing to the buffer to which the text will be copied
5422 that the definition for this function diverges from the definition for
5423 @code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5424 buffer's former contents. (This is what is meant by `replacement'; to
5425 replace text, Emacs erases the previous text and then inserts new
5426 text.) After erasing the previous contents of the buffer,
5427 @code{save-excursion} is used for a second time and the new text is
5428 inserted.
5429
5430 Why is @code{save-excursion} used twice? Consider again what the
5431 function does.
5432
5433 @need 1250
5434 In outline, the body of @code{copy-to-buffer} looks like this:
5435
5436 @smallexample
5437 @group
5438 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5439 (save-excursion ; @r{First use of @code{save-excursion}.}
5440 @var{change-buffer}
5441 (erase-buffer)
5442 (save-excursion ; @r{Second use of @code{save-excursion}.}
5443 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5444 @end group
5445 @end smallexample
5446
5447 The first use of @code{save-excursion} returns Emacs to the buffer from
5448 which the text is being copied. That is clear, and is just like its use
5449 in @code{append-to-buffer}. Why the second use? The reason is that
5450 @code{insert-buffer-substring} always leaves point at the @emph{end} of
5451 the region being inserted. The second @code{save-excursion} causes
5452 Emacs to leave point at the beginning of the text being inserted. In
5453 most circumstances, users prefer to find point at the beginning of
5454 inserted text. (Of course, the @code{copy-to-buffer} function returns
5455 the user to the original buffer when done---but if the user @emph{then}
5456 switches to the copied-to buffer, point will go to the beginning of the
5457 text. Thus, this use of a second @code{save-excursion} is a little
5458 nicety.)
5459
5460 @node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5461 @comment node-name, next, previous, up
5462 @section The Definition of @code{insert-buffer}
5463 @findex insert-buffer
5464
5465 @code{insert-buffer} is yet another buffer-related function. This
5466 command copies another buffer @emph{into} the current buffer. It is the
5467 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5468 copy a region of text @emph{from} the current buffer to another buffer.
5469
5470 In addition, this code illustrates the use of @code{interactive} with a
5471 buffer that might be @dfn{read-only} and the important distinction
5472 between the name of an object and the object actually referred to.
5473
5474 @menu
5475 * insert-buffer code::
5476 * insert-buffer interactive:: When you can read, but not write.
5477 * insert-buffer body:: The body has an @code{or} and a @code{let}.
5478 * if & or:: Using an @code{if} instead of an @code{or}.
5479 * Insert or:: How the @code{or} expression works.
5480 * Insert let:: Two @code{save-excursion} expressions.
5481 @end menu
5482
5483 @node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5484 @ifnottex
5485 @unnumberedsubsec The Code for @code{insert-buffer}
5486 @end ifnottex
5487
5488 @need 800
5489 Here is the code:
5490
5491 @smallexample
5492 @group
5493 (defun insert-buffer (buffer)
5494 "Insert after point the contents of BUFFER.
5495 Puts mark after the inserted text.
5496 BUFFER may be a buffer or a buffer name."
5497 (interactive "*bInsert buffer:@: ")
5498 @end group
5499 @group
5500 (or (bufferp buffer)
5501 (setq buffer (get-buffer buffer)))
5502 (let (start end newmark)
5503 (save-excursion
5504 (save-excursion
5505 (set-buffer buffer)
5506 (setq start (point-min) end (point-max)))
5507 @end group
5508 @group
5509 (insert-buffer-substring buffer start end)
5510 (setq newmark (point)))
5511 (push-mark newmark)))
5512 @end group
5513 @end smallexample
5514
5515 @need 1200
5516 As with other function definitions, you can use a template to see an
5517 outline of the function:
5518
5519 @smallexample
5520 @group
5521 (defun insert-buffer (buffer)
5522 "@var{documentation}@dots{}"
5523 (interactive "*bInsert buffer:@: ")
5524 @var{body}@dots{})
5525 @end group
5526 @end smallexample
5527
5528 @node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5529 @comment node-name, next, previous, up
5530 @subsection The Interactive Expression in @code{insert-buffer}
5531 @findex interactive, @r{example use of}
5532
5533 In @code{insert-buffer}, the argument to the @code{interactive}
5534 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5535 buffer:@: }.
5536
5537 @menu
5538 * Read-only buffer:: When a buffer cannot be modified.
5539 * b for interactive:: An existing buffer or else its name.
5540 @end menu
5541
5542 @node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5543 @comment node-name, next, previous, up
5544 @unnumberedsubsubsec A Read-only Buffer
5545 @cindex Read-only buffer
5546 @cindex Asterisk for read-only buffer
5547 @findex * @r{for read-only buffer}
5548
5549 The asterisk is for the situation when the buffer is a read-only
5550 buffer---a buffer that cannot be modified. If @code{insert-buffer} is
5551 called on a buffer that is read-only, a message to this effect is
5552 printed in the echo area and the terminal may beep or blink at you;
5553 you will not be permitted to insert anything into current buffer. The
5554 asterisk does not need to be followed by a newline to separate it from
5555 the next argument.
5556
5557 @node b for interactive, , Read-only buffer, insert-buffer interactive
5558 @comment node-name, next, previous, up
5559 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5560
5561 The next argument in the interactive expression starts with a lower
5562 case @samp{b}. (This is different from the code for
5563 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5564 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5565 The lower-case @samp{b} tells the Lisp interpreter that the argument
5566 for @code{insert-buffer} should be an existing buffer or else its
5567 name. (The upper-case @samp{B} option provides for the possibility
5568 that the buffer does not exist.) Emacs will prompt you for the name
5569 of the buffer, offering you a default buffer, with name completion
5570 enabled. If the buffer does not exist, you receive a message that
5571 says ``No match''; your terminal may beep at you as well.
5572
5573 @node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5574 @comment node-name, next, previous, up
5575 @subsection The Body of the @code{insert-buffer} Function
5576
5577 The body of the @code{insert-buffer} function has two major parts: an
5578 @code{or} expression and a @code{let} expression. The purpose of the
5579 @code{or} expression is to ensure that the argument @code{buffer} is
5580 bound to a buffer and not just the name of a buffer. The body of the
5581 @code{let} expression contains the code which copies the other buffer
5582 into the current buffer.
5583
5584 @need 1250
5585 In outline, the two expressions fit into the @code{insert-buffer}
5586 function like this:
5587
5588 @smallexample
5589 @group
5590 (defun insert-buffer (buffer)
5591 "@var{documentation}@dots{}"
5592 (interactive "*bInsert buffer:@: ")
5593 (or @dots{}
5594 @dots{}
5595 @end group
5596 @group
5597 (let (@var{varlist})
5598 @var{body-of-}@code{let}@dots{} )
5599 @end group
5600 @end smallexample
5601
5602 To understand how the @code{or} expression ensures that the argument
5603 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5604 is first necessary to understand the @code{or} function.
5605
5606 Before doing this, let me rewrite this part of the function using
5607 @code{if} so that you can see what is done in a manner that will be familiar.
5608
5609 @node if & or, Insert or, insert-buffer body, insert-buffer
5610 @comment node-name, next, previous, up
5611 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5612
5613 The job to be done is to make sure the value of @code{buffer} is a
5614 buffer itself and not the name of a buffer. If the value is the name,
5615 then the buffer itself must be got.
5616
5617 You can imagine yourself at a conference where an usher is wandering
5618 around holding a list with your name on it and looking for you: the
5619 usher is ``bound'' to your name, not to you; but when the usher finds
5620 you and takes your arm, the usher becomes ``bound'' to you.
5621
5622 @need 800
5623 In Lisp, you might describe this situation like this:
5624
5625 @smallexample
5626 @group
5627 (if (not (holding-on-to-guest))
5628 (find-and-take-arm-of-guest))
5629 @end group
5630 @end smallexample
5631
5632 We want to do the same thing with a buffer---if we do not have the
5633 buffer itself, we want to get it.
5634
5635 @need 1200
5636 Using a predicate called @code{bufferp} that tells us whether we have a
5637 buffer (rather than its name), we can write the code like this:
5638
5639 @smallexample
5640 @group
5641 (if (not (bufferp buffer)) ; @r{if-part}
5642 (setq buffer (get-buffer buffer))) ; @r{then-part}
5643 @end group
5644 @end smallexample
5645
5646 @noindent
5647 Here, the true-or-false-test of the @code{if} expression is
5648 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5649 @w{@code{(setq buffer (get-buffer buffer))}}.
5650
5651 In the test, the function @code{bufferp} returns true if its argument is
5652 a buffer---but false if its argument is the name of the buffer. (The
5653 last character of the function name @code{bufferp} is the character
5654 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5655 indicates that the function is a predicate, which is a term that means
5656 that the function will determine whether some property is true or false.
5657 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5658 Argument}.)
5659
5660 @need 1200
5661 The function @code{not} precedes the expression @code{(bufferp buffer)},
5662 so the true-or-false-test looks like this:
5663
5664 @smallexample
5665 (not (bufferp buffer))
5666 @end smallexample
5667
5668 @noindent
5669 @code{not} is a function that returns true if its argument is false
5670 and false if its argument is true. So if @code{(bufferp buffer)}
5671 returns true, the @code{not} expression returns false and vice-versa:
5672 what is ``not true'' is false and what is ``not false'' is true.
5673
5674 Using this test, the @code{if} expression works as follows: when the
5675 value of the variable @code{buffer} is actually a buffer rather then
5676 its name, the true-or-false-test returns false and the @code{if}
5677 expression does not evaluate the then-part. This is fine, since we do
5678 not need to do anything to the variable @code{buffer} if it really is
5679 a buffer.
5680
5681 On the other hand, when the value of @code{buffer} is not a buffer
5682 itself, but the name of a buffer, the true-or-false-test returns true
5683 and the then-part of the expression is evaluated. In this case, the
5684 then-part is @code{(setq buffer (get-buffer buffer))}. This
5685 expression uses the @code{get-buffer} function to return an actual
5686 buffer itself, given its name. The @code{setq} then sets the variable
5687 @code{buffer} to the value of the buffer itself, replacing its previous
5688 value (which was the name of the buffer).
5689
5690 @node Insert or, Insert let, if & or, insert-buffer
5691 @comment node-name, next, previous, up
5692 @subsection The @code{or} in the Body
5693
5694 The purpose of the @code{or} expression in the @code{insert-buffer}
5695 function is to ensure that the argument @code{buffer} is bound to a
5696 buffer and not just to the name of a buffer. The previous section shows
5697 how the job could have been done using an @code{if} expression.
5698 However, the @code{insert-buffer} function actually uses @code{or}.
5699 To understand this, it is necessary to understand how @code{or} works.
5700
5701 @findex or
5702 An @code{or} function can have any number of arguments. It evaluates
5703 each argument in turn and returns the value of the first of its
5704 arguments that is not @code{nil}. Also, and this is a crucial feature
5705 of @code{or}, it does not evaluate any subsequent arguments after
5706 returning the first non-@code{nil} value.
5707
5708 @need 800
5709 The @code{or} expression looks like this:
5710
5711 @smallexample
5712 @group
5713 (or (bufferp buffer)
5714 (setq buffer (get-buffer buffer)))
5715 @end group
5716 @end smallexample
5717
5718 @noindent
5719 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5720 This expression returns true (a non-@code{nil} value) if the buffer is
5721 actually a buffer, and not just the name of a buffer. In the @code{or}
5722 expression, if this is the case, the @code{or} expression returns this
5723 true value and does not evaluate the next expression---and this is fine
5724 with us, since we do not want to do anything to the value of
5725 @code{buffer} if it really is a buffer.
5726
5727 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5728 which it will be if the value of @code{buffer} is the name of a buffer,
5729 the Lisp interpreter evaluates the next element of the @code{or}
5730 expression. This is the expression @code{(setq buffer (get-buffer
5731 buffer))}. This expression returns a non-@code{nil} value, which
5732 is the value to which it sets the variable @code{buffer}---and this
5733 value is a buffer itself, not the name of a buffer.
5734
5735 The result of all this is that the symbol @code{buffer} is always
5736 bound to a buffer itself rather than to the name of a buffer. All
5737 this is necessary because the @code{set-buffer} function in a
5738 following line only works with a buffer itself, not with the name to a
5739 buffer.
5740
5741 @need 1250
5742 Incidentally, using @code{or}, the situation with the usher would be
5743 written like this:
5744
5745 @smallexample
5746 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5747 @end smallexample
5748
5749 @node Insert let, , Insert or, insert-buffer
5750 @comment node-name, next, previous, up
5751 @subsection The @code{let} Expression in @code{insert-buffer}
5752
5753 After ensuring that the variable @code{buffer} refers to a buffer itself
5754 and not just to the name of a buffer, the @code{insert-buffer function}
5755 continues with a @code{let} expression. This specifies three local
5756 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5757 to the initial value @code{nil}. These variables are used inside the
5758 remainder of the @code{let} and temporarily hide any other occurrence of
5759 variables of the same name in Emacs until the end of the @code{let}.
5760
5761 @need 1200
5762 The body of the @code{let} contains two @code{save-excursion}
5763 expressions. First, we will look at the inner @code{save-excursion}
5764 expression in detail. The expression looks like this:
5765
5766 @smallexample
5767 @group
5768 (save-excursion
5769 (set-buffer buffer)
5770 (setq start (point-min) end (point-max)))
5771 @end group
5772 @end smallexample
5773
5774 @noindent
5775 The expression @code{(set-buffer buffer)} changes Emacs' attention
5776 from the current buffer to the one from which the text will copied.
5777 In that buffer, the variables @code{start} and @code{end} are set to
5778 the beginning and end of the buffer, using the commands
5779 @code{point-min} and @code{point-max}. Note that we have here an
5780 illustration of how @code{setq} is able to set two variables in the
5781 same expression. The first argument of @code{setq} is set to the
5782 value of its second, and its third argument is set to the value of its
5783 fourth.
5784
5785 After the body of the inner @code{save-excursion} is evaluated, the
5786 @code{save-excursion} restores the original buffer, but @code{start} and
5787 @code{end} remain set to the values of the beginning and end of the
5788 buffer from which the text will be copied.
5789
5790 @need 1250
5791 The outer @code{save-excursion} expression looks like this:
5792
5793 @smallexample
5794 @group
5795 (save-excursion
5796 (@var{inner-}@code{save-excursion}@var{-expression}
5797 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5798 (insert-buffer-substring buffer start end)
5799 (setq newmark (point)))
5800 @end group
5801 @end smallexample
5802
5803 @noindent
5804 The @code{insert-buffer-substring} function copies the text
5805 @emph{into} the current buffer @emph{from} the region indicated by
5806 @code{start} and @code{end} in @code{buffer}. Since the whole of the
5807 second buffer lies between @code{start} and @code{end}, the whole of
5808 the second buffer is copied into the buffer you are editing. Next,
5809 the value of point, which will be at the end of the inserted text, is
5810 recorded in the variable @code{newmark}.
5811
5812 After the body of the outer @code{save-excursion} is evaluated, point
5813 and mark are relocated to their original places.
5814
5815 However, it is convenient to locate a mark at the end of the newly
5816 inserted text and locate point at its beginning. The @code{newmark}
5817 variable records the end of the inserted text. In the last line of
5818 the @code{let} expression, the @code{(push-mark newmark)} expression
5819 function sets a mark to this location. (The previous location of the
5820 mark is still accessible; it is recorded on the mark ring and you can
5821 go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5822 located at the beginning of the inserted text, which is where it was
5823 before you called the insert function.
5824
5825 @need 1250
5826 The whole @code{let} expression looks like this:
5827
5828 @smallexample
5829 @group
5830 (let (start end newmark)
5831 (save-excursion
5832 (save-excursion
5833 (set-buffer buffer)
5834 (setq start (point-min) end (point-max)))
5835 (insert-buffer-substring buffer start end)
5836 (setq newmark (point)))
5837 (push-mark newmark))
5838 @end group
5839 @end smallexample
5840
5841 Like the @code{append-to-buffer} function, the @code{insert-buffer}
5842 function uses @code{let}, @code{save-excursion}, and
5843 @code{set-buffer}. In addition, the function illustrates one way to
5844 use @code{or}. All these functions are building blocks that we will
5845 find and use again and again.
5846
5847 @node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5848 @comment node-name, next, previous, up
5849 @section Complete Definition of @code{beginning-of-buffer}
5850 @findex beginning-of-buffer
5851
5852 The basic structure of the @code{beginning-of-buffer} function has
5853 already been discussed. (@xref{simplified-beginning-of-buffer, , A
5854 Simplified @code{beginning-of-buffer} Definition}.)
5855 This section describes the complex part of the definition.
5856
5857 As previously described, when invoked without an argument,
5858 @code{beginning-of-buffer} moves the cursor to the beginning of the
5859 buffer, leaving the mark at the previous position. However, when the
5860 command is invoked with a number between one and ten, the function
5861 considers that number to be a fraction of the length of the buffer,
5862 measured in tenths, and Emacs moves the cursor that fraction of the way
5863 from the beginning of the buffer. Thus, you can either call this
5864 function with the key command @kbd{M-<}, which will move the cursor to
5865 the beginning of the buffer, or with a key command such as @kbd{C-u 7
5866 M-<} which will move the cursor to a point 70% of the way through the
5867 buffer. If a number bigger than ten is used for the argument, it moves
5868 to the end of the buffer.
5869
5870 The @code{beginning-of-buffer} function can be called with or without an
5871 argument. The use of the argument is optional.
5872
5873 @menu
5874 * Optional Arguments::
5875 * beginning-of-buffer opt arg:: Example with optional argument.
5876 * beginning-of-buffer complete::
5877 @end menu
5878
5879 @node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5880 @subsection Optional Arguments
5881
5882 Unless told otherwise, Lisp expects that a function with an argument in
5883 its function definition will be called with a value for that argument.
5884 If that does not happen, you get an error and a message that says
5885 @samp{Wrong number of arguments}.
5886
5887 @cindex Optional arguments
5888 @cindex Keyword
5889 @findex optional
5890 However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5891 be used to tell the Lisp interpreter that an argument is optional.
5892 The keyword is @code{&optional}. (The @samp{&} in front of
5893 @samp{optional} is part of the keyword.) In a function definition, if
5894 an argument follows the keyword @code{&optional}, a value does not
5895 need to be passed to that argument when the function is called.
5896
5897 @need 1200
5898 The first line of the function definition of @code{beginning-of-buffer}
5899 therefore looks like this:
5900
5901 @smallexample
5902 (defun beginning-of-buffer (&optional arg)
5903 @end smallexample
5904
5905 @need 1250
5906 In outline, the whole function looks like this:
5907
5908 @smallexample
5909 @group
5910 (defun beginning-of-buffer (&optional arg)
5911 "@var{documentation}@dots{}"
5912 (interactive "P")
5913 (push-mark)
5914 (goto-char
5915 (@var{if-there-is-an-argument}
5916 @var{figure-out-where-to-go}
5917 @var{else-go-to}
5918 (point-min))))
5919 @end group
5920 @end smallexample
5921
5922 The function is similar to the @code{simplified-beginning-of-buffer}
5923 function except that the @code{interactive} expression has @code{"P"}
5924 as an argument and the @code{goto-char} function is followed by an
5925 if-then-else expression that figures out where to put the cursor if
5926 there is an argument.
5927
5928 The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5929 a prefix argument, if there is one, to the function. A prefix argument
5930 is made by typing the @key{META} key followed by a number, or by typing
5931 @kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5932 defaults to 4).
5933
5934 The true-or-false-test of the @code{if} expression is simple: it is
5935 simply the argument @code{arg}. If @code{arg} has a value that is not
5936 @code{nil}, which will be the case if @code{beginning-of-buffer} is
5937 called with an argument, then this true-or-false-test will return true
5938 and the then-part of the @code{if} expression will be evaluated. On the
5939 other hand, if @code{beginning-of-buffer} is not called with an
5940 argument, the value of @code{arg} will be @code{nil} and the else-part
5941 of the @code{if} expression will be evaluated. The else-part is simply
5942 @code{point-min}, and when this is the outcome, the whole
5943 @code{goto-char} expression is @code{(goto-char (point-min))}, which is
5944 how we saw the @code{beginning-of-buffer} function in its simplified
5945 form.
5946
5947 @node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5948 @subsection @code{beginning-of-buffer} with an Argument
5949
5950 When @code{beginning-of-buffer} is called with an argument, an
5951 expression is evaluated which calculates what value to pass to
5952 @code{goto-char}. This expression is rather complicated at first sight.
5953 It includes an inner @code{if} expression and much arithmetic. It looks
5954 like this:
5955
5956 @smallexample
5957 @group
5958 (if (> (buffer-size) 10000)
5959 ;; @r{Avoid overflow for large buffer sizes!}
5960 (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5961 (/
5962 (+ 10
5963 (*
5964 (buffer-size) (prefix-numeric-value arg))) 10))
5965 @end group
5966 @end smallexample
5967
5968 @menu
5969 * Disentangle beginning-of-buffer::
5970 * Large buffer case::
5971 * Small buffer case::
5972 @end menu
5973
5974 @node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5975 @ifnottex
5976 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5977 @end ifnottex
5978
5979 Like other complex-looking expressions, the conditional expression
5980 within @code{beginning-of-buffer} can be disentangled by looking at it
5981 as parts of a template, in this case, the template for an if-then-else
5982 expression. In skeletal form, the expression looks like this:
5983
5984 @smallexample
5985 @group
5986 (if (@var{buffer-is-large}
5987 @var{divide-buffer-size-by-10-and-multiply-by-arg}
5988 @var{else-use-alternate-calculation}
5989 @end group
5990 @end smallexample
5991
5992 The true-or-false-test of this inner @code{if} expression checks the
5993 size of the buffer. The reason for this is that the old Version 18
5994 Emacs used numbers that are no bigger than eight million or so
5995 and in the computation that followed, the programmer feared that Emacs
5996 might try to use over-large numbers if the buffer were large. The
5997 term `overflow', mentioned in the comment, means numbers that are over
5998 large. Version 21 Emacs uses larger numbers, but this code has not
5999 been touched, if only because people now look at buffers that are far,
6000 far larger than ever before.
6001
6002 There are two cases: if the buffer is large and if it is not.
6003
6004 @node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
6005 @comment node-name, next, previous, up
6006 @unnumberedsubsubsec What happens in a large buffer
6007
6008 In @code{beginning-of-buffer}, the inner @code{if} expression tests
6009 whether the size of the buffer is greater than 10,000 characters. To do
6010 this, it uses the @code{>} function and the @code{buffer-size} function.
6011
6012 @need 800
6013 The line looks like this:
6014
6015 @smallexample
6016 (if (> (buffer-size) 10000)
6017 @end smallexample
6018
6019 @need 1200
6020 @noindent
6021 When the buffer is large, the then-part of the @code{if} expression is
6022 evaluated. It reads like this (after formatting for easy reading):
6023
6024 @smallexample
6025 @group
6026 (*
6027 (prefix-numeric-value arg)
6028 (/ (buffer-size) 10))
6029 @end group
6030 @end smallexample
6031
6032 @noindent
6033 This expression is a multiplication, with two arguments to the function
6034 @code{*}.
6035
6036 The first argument is @code{(prefix-numeric-value arg)}. When
6037 @code{"P"} is used as the argument for @code{interactive}, the value
6038 passed to the function as its argument is passed a ``raw prefix
6039 argument'', and not a number. (It is a number in a list.) To perform
6040 the arithmetic, a conversion is necessary, and
6041 @code{prefix-numeric-value} does the job.
6042
6043 @findex / @r{(division)}
6044 @cindex Division
6045 The second argument is @code{(/ (buffer-size) 10)}. This expression
6046 divides the numeric value of the buffer by ten. This produces a number
6047 that tells how many characters make up one tenth of the buffer size.
6048 (In Lisp, @code{/} is used for division, just as @code{*} is
6049 used for multiplication.)
6050
6051 @need 1200
6052 In the multiplication expression as a whole, this amount is multiplied
6053 by the value of the prefix argument---the multiplication looks like this:
6054
6055 @smallexample
6056 @group
6057 (* @var{numeric-value-of-prefix-arg}
6058 @var{number-of-characters-in-one-tenth-of-the-buffer})
6059 @end group
6060 @end smallexample
6061
6062 @noindent
6063 If, for example, the prefix argument is @samp{7}, the one-tenth value
6064 will be multiplied by 7 to give a position 70% of the way through the
6065 buffer.
6066
6067 @need 1200
6068 The result of all this is that if the buffer is large, the
6069 @code{goto-char} expression reads like this:
6070
6071 @smallexample
6072 @group
6073 (goto-char (* (prefix-numeric-value arg)
6074 (/ (buffer-size) 10)))
6075 @end group
6076 @end smallexample
6077
6078 This puts the cursor where we want it.
6079
6080 @node Small buffer case, , Large buffer case, beginning-of-buffer opt arg
6081 @comment node-name, next, previous, up
6082 @unnumberedsubsubsec What happens in a small buffer
6083
6084 If the buffer contains fewer than 10,000 characters, a slightly
6085 different computation is performed. You might think this is not
6086 necessary, since the first computation could do the job. However, in
6087 a small buffer, the first method may not put the cursor on exactly the
6088 desired line; the second method does a better job.
6089
6090 @need 800
6091 The code looks like this:
6092
6093 @c Keep this on one line.
6094 @smallexample
6095 (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6096 @end smallexample
6097
6098 @need 1200
6099 @noindent
6100 This is code in which you figure out what happens by discovering how the
6101 functions are embedded in parentheses. It is easier to read if you
6102 reformat it with each expression indented more deeply than its
6103 enclosing expression:
6104
6105 @smallexample
6106 @group
6107 (/
6108 (+ 10
6109 (*
6110 (buffer-size)
6111 (prefix-numeric-value arg)))
6112 10))
6113 @end group
6114 @end smallexample
6115
6116 @need 1200
6117 @noindent
6118 Looking at parentheses, we see that the innermost operation is
6119 @code{(prefix-numeric-value arg)}, which converts the raw argument to a
6120 number. This number is multiplied by the buffer size in the following
6121 expression:
6122
6123 @smallexample
6124 (* (buffer-size) (prefix-numeric-value arg)
6125 @end smallexample
6126
6127 @noindent
6128 This multiplication creates a number that may be larger than the size of
6129 the buffer---seven times larger if the argument is 7, for example. Ten
6130 is then added to this number and finally the large number is divided by
6131 ten to provide a value that is one character larger than the percentage
6132 position in the buffer.
6133
6134 The number that results from all this is passed to @code{goto-char} and
6135 the cursor is moved to that point.
6136
6137 @node beginning-of-buffer complete, , beginning-of-buffer opt arg, beginning-of-buffer
6138 @comment node-name, next, previous, up
6139 @subsection The Complete @code{beginning-of-buffer}
6140
6141 @need 800
6142 Here is the complete text of the @code{beginning-of-buffer} function:
6143
6144 @smallexample
6145 @group
6146 (defun beginning-of-buffer (&optional arg)
6147 "Move point to the beginning of the buffer;
6148 leave mark at previous position.
6149 With arg N, put point N/10 of the way
6150 from the true beginning.
6151 Don't use this in Lisp programs!
6152 \(goto-char (point-min)) is faster
6153 and does not set the mark."
6154 (interactive "P")
6155 (push-mark)
6156 @end group
6157 @group
6158 (goto-char
6159 (if arg
6160 (if (> (buffer-size) 10000)
6161 ;; @r{Avoid overflow for large buffer sizes!}
6162 (* (prefix-numeric-value arg)
6163 (/ (buffer-size) 10))
6164 @end group
6165 @group
6166 (/ (+ 10 (* (buffer-size)
6167 (prefix-numeric-value arg)))
6168 10))
6169 (point-min)))
6170 (if arg (forward-line 1)))
6171 @end group
6172 @end smallexample
6173
6174 @noindent
6175 Except for two small points, the previous discussion shows how this
6176 function works. The first point deals with a detail in the
6177 documentation string, and the second point concerns the last line of
6178 the function.
6179
6180 @need 800
6181 In the documentation string, there is reference to an expression:
6182
6183 @smallexample
6184 \(goto-char (point-min))
6185 @end smallexample
6186
6187 @noindent
6188 A @samp{\} is used before the first parenthesis of this expression.
6189 This @samp{\} tells the Lisp interpreter that the expression should be
6190 printed as shown in the documentation rather than evaluated as a
6191 symbolic expression, which is what it looks like.
6192
6193 @need 1200
6194 Finally, the last line of the @code{beginning-of-buffer} command says to
6195 move point to the beginning of the next line if the command is
6196 invoked with an argument:
6197
6198 @smallexample
6199 (if arg (forward-line 1)))
6200 @end smallexample
6201
6202 @noindent
6203 This puts the cursor at the beginning of the first line after the
6204 appropriate tenths position in the buffer. This is a flourish that
6205 means that the cursor is always located @emph{at least} the requested
6206 tenths of the way through the buffer, which is a nicety that is,
6207 perhaps, not necessary, but which, if it did not occur, would be sure to
6208 draw complaints.
6209
6210 @node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6211 @comment node-name, next, previous, up
6212 @section Review
6213
6214 Here is a brief summary of some of the topics covered in this chapter.
6215
6216 @table @code
6217 @item or
6218 Evaluate each argument in sequence, and return the value of the first
6219 argument that is not @code{nil}; if none return a value that is not
6220 @code{nil}, return @code{nil}. In brief, return the first true value
6221 of the arguments; return a true value if one @emph{or} any of the
6222 other are true.
6223
6224 @item and
6225 Evaluate each argument in sequence, and if any are @code{nil}, return
6226 @code{nil}; if none are @code{nil}, return the value of the last
6227 argument. In brief, return a true value only if all the arguments are
6228 true; return a true value if one @emph{and} each of the others is
6229 true.
6230
6231 @item &optional
6232 A keyword used to indicate that an argument to a function definition
6233 is optional; this means that the function can be evaluated without the
6234 argument, if desired.
6235
6236 @item prefix-numeric-value
6237 Convert the `raw prefix argument' produced by @code{(interactive
6238 "P")} to a numeric value.
6239
6240 @item forward-line
6241 Move point forward to the beginning of the next line, or if the argument
6242 is greater than one, forward that many lines. If it can't move as far
6243 forward as it is supposed to, @code{forward-line} goes forward as far as
6244 it can and then returns a count of the number of additional lines it was
6245 supposed to move but couldn't.
6246
6247 @item erase-buffer
6248 Delete the entire contents of the current buffer.
6249
6250 @item bufferp
6251 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6252 @end table
6253
6254 @node optional Exercise, , Second Buffer Related Review, More Complex
6255 @section @code{optional} Argument Exercise
6256
6257 Write an interactive function with an optional argument that tests
6258 whether its argument, a number, is greater or less than the value of
6259 @code{fill-column}, and tells you which, in a message. However, if you
6260 do not pass an argument to the function, use 56 as a default value.
6261
6262 @node Narrowing & Widening, car cdr & cons, More Complex, Top
6263 @comment node-name, next, previous, up
6264 @chapter Narrowing and Widening
6265 @cindex Focusing attention (narrowing)
6266 @cindex Narrowing
6267 @cindex Widening
6268
6269 Narrowing is a feature of Emacs that makes it possible for you to focus
6270 on a specific part of a buffer, and work without accidentally changing
6271 other parts. Narrowing is normally disabled since it can confuse
6272 novices.
6273
6274 @menu
6275 * Narrowing advantages:: The advantages of narrowing
6276 * save-restriction:: The @code{save-restriction} special form.
6277 * what-line:: The number of the line that point is on.
6278 * narrow Exercise::
6279 @end menu
6280
6281 @node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6282 @ifnottex
6283 @unnumberedsec The Advantages of Narrowing
6284 @end ifnottex
6285
6286 With narrowing, the rest of a buffer is made invisible, as if it weren't
6287 there. This is an advantage if, for example, you want to replace a word
6288 in one part of a buffer but not in another: you narrow to the part you want
6289 and the replacement is carried out only in that section, not in the rest
6290 of the buffer. Searches will only work within a narrowed region, not
6291 outside of one, so if you are fixing a part of a document, you can keep
6292 yourself from accidentally finding parts you do not need to fix by
6293 narrowing just to the region you want.
6294 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6295
6296 However, narrowing does make the rest of the buffer invisible, which
6297 can scare people who inadvertently invoke narrowing and think they
6298 have deleted a part of their file. Moreover, the @code{undo} command
6299 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6300 (nor should it), so people can become quite desperate if they do not
6301 know that they can return the rest of a buffer to visibility with the
6302 @code{widen} command.
6303 (The key binding for @code{widen} is @kbd{C-x n w}.)
6304
6305 Narrowing is just as useful to the Lisp interpreter as to a human.
6306 Often, an Emacs Lisp function is designed to work on just part of a
6307 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6308 buffer that has been narrowed. The @code{what-line} function, for
6309 example, removes the narrowing from a buffer, if it has any narrowing
6310 and when it has finished its job, restores the narrowing to what it was.
6311 On the other hand, the @code{count-lines} function, which is called by
6312 @code{what-line}, uses narrowing to restrict itself to just that portion
6313 of the buffer in which it is interested and then restores the previous
6314 situation.
6315
6316 @node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6317 @comment node-name, next, previous, up
6318 @section The @code{save-restriction} Special Form
6319 @findex save-restriction
6320
6321 In Emacs Lisp, you can use the @code{save-restriction} special form to
6322 keep track of whatever narrowing is in effect, if any. When the Lisp
6323 interpreter meets with @code{save-restriction}, it executes the code
6324 in the body of the @code{save-restriction} expression, and then undoes
6325 any changes to narrowing that the code caused. If, for example, the
6326 buffer is narrowed and the code that follows @code{save-restriction}
6327 gets rid of the narrowing, @code{save-restriction} returns the buffer
6328 to its narrowed region afterwards. In the @code{what-line} command,
6329 any narrowing the buffer may have is undone by the @code{widen}
6330 command that immediately follows the @code{save-restriction} command.
6331 Any original narrowing is restored just before the completion of the
6332 function.
6333
6334 @need 1250
6335 The template for a @code{save-restriction} expression is simple:
6336
6337 @smallexample
6338 @group
6339 (save-restriction
6340 @var{body}@dots{} )
6341 @end group
6342 @end smallexample
6343
6344 @noindent
6345 The body of the @code{save-restriction} is one or more expressions that
6346 will be evaluated in sequence by the Lisp interpreter.
6347
6348 Finally, a point to note: when you use both @code{save-excursion} and
6349 @code{save-restriction}, one right after the other, you should use
6350 @code{save-excursion} outermost. If you write them in reverse order,
6351 you may fail to record narrowing in the buffer to which Emacs switches
6352 after calling @code{save-excursion}. Thus, when written together,
6353 @code{save-excursion} and @code{save-restriction} should be written
6354 like this:
6355
6356 @smallexample
6357 @group
6358 (save-excursion
6359 (save-restriction
6360 @var{body}@dots{}))
6361 @end group
6362 @end smallexample
6363
6364 In other circumstances, when not written together, the
6365 @code{save-excursion} and @code{save-restriction} special forms must
6366 be written in the order appropriate to the function.
6367
6368 @need 1250
6369 For example,
6370
6371 @smallexample
6372 @group
6373 (save-restriction
6374 (widen)
6375 (save-excursion
6376 @var{body}@dots{}))
6377 @end group
6378 @end smallexample
6379
6380 @node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6381 @comment node-name, next, previous, up
6382 @section @code{what-line}
6383 @findex what-line
6384 @cindex Widening, example of
6385
6386 The @code{what-line} command tells you the number of the line in which
6387 the cursor is located. The function illustrates the use of the
6388 @code{save-restriction} and @code{save-excursion} commands. Here is the
6389 text of the function in full:
6390
6391 @smallexample
6392 @group
6393 (defun what-line ()
6394 "Print the current line number (in the buffer) of point."
6395 (interactive)
6396 (save-restriction
6397 (widen)
6398 (save-excursion
6399 (beginning-of-line)
6400 (message "Line %d"
6401 (1+ (count-lines 1 (point)))))))
6402 @end group
6403 @end smallexample
6404
6405 The function has a documentation line and is interactive, as you would
6406 expect. The next two lines use the functions @code{save-restriction} and
6407 @code{widen}.
6408
6409 The @code{save-restriction} special form notes whatever narrowing is in
6410 effect, if any, in the current buffer and restores that narrowing after
6411 the code in the body of the @code{save-restriction} has been evaluated.
6412
6413 The @code{save-restriction} special form is followed by @code{widen}.
6414 This function undoes any narrowing the current buffer may have had
6415 when @code{what-line} was called. (The narrowing that was there is
6416 the narrowing that @code{save-restriction} remembers.) This widening
6417 makes it possible for the line counting commands to count from the
6418 beginning of the buffer. Otherwise, they would have been limited to
6419 counting within the accessible region. Any original narrowing is
6420 restored just before the completion of the function by the
6421 @code{save-restriction} special form.
6422
6423 The call to @code{widen} is followed by @code{save-excursion}, which
6424 saves the location of the cursor (i.e., of point) and of the mark, and
6425 restores them after the code in the body of the @code{save-excursion}
6426 uses the @code{beginning-of-line} function to move point.
6427
6428 (Note that the @code{(widen)} expression comes between the
6429 @code{save-restriction} and @code{save-excursion} special forms. When
6430 you write the two @code{save- @dots{}} expressions in sequence, write
6431 @code{save-excursion} outermost.)
6432
6433 @need 1200
6434 The last two lines of the @code{what-line} function are functions to
6435 count the number of lines in the buffer and then print the number in the
6436 echo area.
6437
6438 @smallexample
6439 @group
6440 (message "Line %d"
6441 (1+ (count-lines 1 (point)))))))
6442 @end group
6443 @end smallexample
6444
6445 The @code{message} function prints a one-line message at the bottom of the
6446 Emacs screen. The first argument is inside of quotation marks and is
6447 printed as a string of characters. However, it may contain @samp{%d},
6448 @samp{%s}, or @samp{%c} to print arguments that follow the string.
6449 @samp{%d} prints the argument as a decimal, so the message will say
6450 something such as @samp{Line 243}.
6451
6452 @need 1200
6453 The number that is printed in place of the @samp{%d} is computed by the
6454 last line of the function:
6455
6456 @smallexample
6457 (1+ (count-lines 1 (point)))
6458 @end smallexample
6459
6460 @noindent
6461 What this does is count the lines from the first position of the
6462 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6463 one to that number. (The @code{1+} function adds one to its
6464 argument.) We add one to it because line 2 has only one line before
6465 it, and @code{count-lines} counts only the lines @emph{before} the
6466 current line.
6467
6468 After @code{count-lines} has done its job, and the message has been
6469 printed in the echo area, the @code{save-excursion} restores point and
6470 mark to their original positions; and @code{save-restriction} restores
6471 the original narrowing, if any.
6472
6473 @node narrow Exercise, , what-line, Narrowing & Widening
6474 @section Exercise with Narrowing
6475
6476 Write a function that will display the first 60 characters of the
6477 current buffer, even if you have narrowed the buffer to its latter
6478 half so that the first line is inaccessible. Restore point, mark,
6479 and narrowing. For this exercise, you need to use
6480 @code{save-restriction}, @code{widen}, @code{goto-char},
6481 @code{point-min}, @code{buffer-substring}, @code{message}, and other
6482 functions, a whole potpourri.
6483
6484 @node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6485 @comment node-name, next, previous, up
6486 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6487 @findex car, @r{introduced}
6488 @findex cdr, @r{introduced}
6489
6490 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6491 functions. The @code{cons} function is used to construct lists, and
6492 the @code{car} and @code{cdr} functions are used to take them apart.
6493
6494 In the walk through of the @code{copy-region-as-kill} function, we
6495 will see @code{cons} as well as two variants on @code{cdr},
6496 namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6497
6498 @menu
6499 * Strange Names:: An historical aside: why the strange names?
6500 * car & cdr:: Functions for extracting part of a list.
6501 * cons:: Constructing a list.
6502 * nthcdr:: Calling @code{cdr} repeatedly.
6503 * nth::
6504 * setcar:: Changing the first element of a list.
6505 * setcdr:: Changing the rest of a list.
6506 * cons Exercise::
6507 @end menu
6508
6509 @node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6510 @ifnottex
6511 @unnumberedsec Strange Names
6512 @end ifnottex
6513
6514 The name of the @code{cons} function is not unreasonable: it is an
6515 abbreviation of the word `construct'. The origins of the names for
6516 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6517 is an acronym from the phrase `Contents of the Address part of the
6518 Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6519 the phrase `Contents of the Decrement part of the Register'. These
6520 phrases refer to specific pieces of hardware on the very early
6521 computer on which the original Lisp was developed. Besides being
6522 obsolete, the phrases have been completely irrelevant for more than 25
6523 years to anyone thinking about Lisp. Nonetheless, although a few
6524 brave scholars have begun to use more reasonable names for these
6525 functions, the old terms are still in use. In particular, since the
6526 terms are used in the Emacs Lisp source code, we will use them in this
6527 introduction.
6528
6529 @node car & cdr, cons, Strange Names, car cdr & cons
6530 @comment node-name, next, previous, up
6531 @section @code{car} and @code{cdr}
6532
6533 The @sc{car} of a list is, quite simply, the first item in the list.
6534 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6535 @code{rose}.
6536
6537 @need 1200
6538 If you are reading this in Info in GNU Emacs, you can see this by
6539 evaluating the following:
6540
6541 @smallexample
6542 (car '(rose violet daisy buttercup))
6543 @end smallexample
6544
6545 @noindent
6546 After evaluating the expression, @code{rose} will appear in the echo
6547 area.
6548
6549 Clearly, a more reasonable name for the @code{car} function would be
6550 @code{first} and this is often suggested.
6551
6552 @code{car} does not remove the first item from the list; it only reports
6553 what it is. After @code{car} has been applied to a list, the list is
6554 still the same as it was. In the jargon, @code{car} is
6555 `non-destructive'. This feature turns out to be important.
6556
6557 The @sc{cdr} of a list is the rest of the list, that is, the
6558 @code{cdr} function returns the part of the list that follows the
6559 first item. Thus, while the @sc{car} of the list @code{'(rose violet
6560 daisy buttercup)} is @code{rose}, the rest of the list, the value
6561 returned by the @code{cdr} function, is @code{(violet daisy
6562 buttercup)}.
6563
6564 @need 1250
6565 You can see this by evaluating the following in the usual way:
6566
6567 @smallexample
6568 (cdr '(rose violet daisy buttercup))
6569 @end smallexample
6570
6571 @noindent
6572 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6573 the echo area.
6574
6575 Like @code{car}, @code{cdr} does not remove any elements from the
6576 list---it just returns a report of what the second and subsequent
6577 elements are.
6578
6579 Incidentally, in the example, the list of flowers is quoted. If it were
6580 not, the Lisp interpreter would try to evaluate the list by calling
6581 @code{rose} as a function. In this example, we do not want to do that.
6582
6583 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6584
6585 (There is a lesson here: when you name new functions, consider very
6586 carefully what you are doing, since you may be stuck with the names
6587 for far longer than you expect. The reason this document perpetuates
6588 these names is that the Emacs Lisp source code uses them, and if I did
6589 not use them, you would have a hard time reading the code; but do,
6590 please, try to avoid using these terms yourself. The people who come
6591 after you will be grateful to you.)
6592
6593 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6594 such as the list @code{(pine fir oak maple)}, the element of the list
6595 returned by the function @code{car} is the symbol @code{pine} without
6596 any parentheses around it. @code{pine} is the first element in the
6597 list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6598 oak maple)}, as you can see by evaluating the following expressions in
6599 the usual way:
6600
6601 @smallexample
6602 @group
6603 (car '(pine fir oak maple))
6604
6605 (cdr '(pine fir oak maple))
6606 @end group
6607 @end smallexample
6608
6609 On the other hand, in a list of lists, the first element is itself a
6610 list. @code{car} returns this first element as a list. For example,
6611 the following list contains three sub-lists, a list of carnivores, a
6612 list of herbivores and a list of sea mammals:
6613
6614 @smallexample
6615 @group
6616 (car '((lion tiger cheetah)
6617 (gazelle antelope zebra)
6618 (whale dolphin seal)))
6619 @end group
6620 @end smallexample
6621
6622 @noindent
6623 In this example, the first element or @sc{car} of the list is the list of
6624 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6625 @code{((gazelle antelope zebra) (whale dolphin seal))}.
6626
6627 @smallexample
6628 @group
6629 (cdr '((lion tiger cheetah)
6630 (gazelle antelope zebra)
6631 (whale dolphin seal)))
6632 @end group
6633 @end smallexample
6634
6635 It is worth saying again that @code{car} and @code{cdr} are
6636 non-destructive---that is, they do not modify or change lists to which
6637 they are applied. This is very important for how they are used.
6638
6639 Also, in the first chapter, in the discussion about atoms, I said that
6640 in Lisp, ``certain kinds of atom, such as an array, can be separated
6641 into parts; but the mechanism for doing this is different from the
6642 mechanism for splitting a list. As far as Lisp is concerned, the
6643 atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
6644 @code{car} and @code{cdr} functions are used for splitting lists and
6645 are considered fundamental to Lisp. Since they cannot split or gain
6646 access to the parts of an array, an array is considered an atom.
6647 Conversely, the other fundamental function, @code{cons}, can put
6648 together or construct a list, but not an array. (Arrays are handled
6649 by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
6650 Emacs Lisp Reference Manual}.)
6651
6652 @node cons, nthcdr, car & cdr, car cdr & cons
6653 @comment node-name, next, previous, up
6654 @section @code{cons}
6655 @findex cons, @r{introduced}
6656
6657 The @code{cons} function constructs lists; it is the inverse of
6658 @code{car} and @code{cdr}. For example, @code{cons} can be used to make
6659 a four element list from the three element list, @code{(fir oak maple)}:
6660
6661 @smallexample
6662 (cons 'pine '(fir oak maple))
6663 @end smallexample
6664
6665 @need 800
6666 @noindent
6667 After evaluating this list, you will see
6668
6669 @smallexample
6670 (pine fir oak maple)
6671 @end smallexample
6672
6673 @noindent
6674 appear in the echo area. @code{cons} puts a new element at the
6675 beginning of a list; it attaches or pushes elements onto the list.
6676
6677 @menu
6678 * Build a list::
6679 * length:: How to find the length of a list.
6680 @end menu
6681
6682 @node Build a list, length, cons, cons
6683 @ifnottex
6684 @unnumberedsubsec Build a list
6685 @end ifnottex
6686
6687 @code{cons} must have a list to attach to.@footnote{Actually, you can
6688 @code{cons} an element to an atom to produce a dotted pair. Dotted
6689 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6690 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
6691 cannot start from absolutely nothing. If you are building a list, you
6692 need to provide at least an empty list at the beginning. Here is a
6693 series of @code{cons} expressions that build up a list of flowers. If
6694 you are reading this in Info in GNU Emacs, you can evaluate each of
6695 the expressions in the usual way; the value is printed in this text
6696 after @samp{@result{}}, which you may read as `evaluates to'.
6697
6698 @smallexample
6699 @group
6700 (cons 'buttercup ())
6701 @result{} (buttercup)
6702 @end group
6703
6704 @group
6705 (cons 'daisy '(buttercup))
6706 @result{} (daisy buttercup)
6707 @end group
6708
6709 @group
6710 (cons 'violet '(daisy buttercup))
6711 @result{} (violet daisy buttercup)
6712 @end group
6713
6714 @group
6715 (cons 'rose '(violet daisy buttercup))
6716 @result{} (rose violet daisy buttercup)
6717 @end group
6718 @end smallexample
6719
6720 @noindent
6721 In the first example, the empty list is shown as @code{()} and a list
6722 made up of @code{buttercup} followed by the empty list is constructed.
6723 As you can see, the empty list is not shown in the list that was
6724 constructed. All that you see is @code{(buttercup)}. The empty list is
6725 not counted as an element of a list because there is nothing in an empty
6726 list. Generally speaking, an empty list is invisible.
6727
6728 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6729 two element list by putting @code{daisy} in front of @code{buttercup};
6730 and the third example constructs a three element list by putting
6731 @code{violet} in front of @code{daisy} and @code{buttercup}.
6732
6733 @node length, , Build a list, cons
6734 @comment node-name, next, previous, up
6735 @subsection Find the Length of a List: @code{length}
6736 @findex length
6737
6738 You can find out how many elements there are in a list by using the Lisp
6739 function @code{length}, as in the following examples:
6740
6741 @smallexample
6742 @group
6743 (length '(buttercup))
6744 @result{} 1
6745 @end group
6746
6747 @group
6748 (length '(daisy buttercup))
6749 @result{} 2
6750 @end group
6751
6752 @group
6753 (length (cons 'violet '(daisy buttercup)))
6754 @result{} 3
6755 @end group
6756 @end smallexample
6757
6758 @noindent
6759 In the third example, the @code{cons} function is used to construct a
6760 three element list which is then passed to the @code{length} function as
6761 its argument.
6762
6763 @need 1200
6764 We can also use @code{length} to count the number of elements in an
6765 empty list:
6766
6767 @smallexample
6768 @group
6769 (length ())
6770 @result{} 0
6771 @end group
6772 @end smallexample
6773
6774 @noindent
6775 As you would expect, the number of elements in an empty list is zero.
6776
6777 An interesting experiment is to find out what happens if you try to find
6778 the length of no list at all; that is, if you try to call @code{length}
6779 without giving it an argument, not even an empty list:
6780
6781 @smallexample
6782 (length )
6783 @end smallexample
6784
6785 @need 800
6786 @noindent
6787 What you see, if you evaluate this, is the error message
6788
6789 @smallexample
6790 Wrong number of arguments: #<subr length>, 0
6791 @end smallexample
6792
6793 @noindent
6794 This means that the function receives the wrong number of
6795 arguments, zero, when it expects some other number of arguments. In
6796 this case, one argument is expected, the argument being a list whose
6797 length the function is measuring. (Note that @emph{one} list is
6798 @emph{one} argument, even if the list has many elements inside it.)
6799
6800 The part of the error message that says @samp{#<subr length>} is the
6801 name of the function. This is written with a special notation,
6802 @samp{#<subr}, that indicates that the function @code{length} is one
6803 of the primitive functions written in C rather than in Emacs Lisp.
6804 (@samp{subr} is an abbreviation for `subroutine'.) @xref{What Is a
6805 Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6806 Manual}, for more about subroutines.
6807
6808 @node nthcdr, nth, cons, car cdr & cons
6809 @comment node-name, next, previous, up
6810 @section @code{nthcdr}
6811 @findex nthcdr
6812
6813 The @code{nthcdr} function is associated with the @code{cdr} function.
6814 What it does is take the @sc{cdr} of a list repeatedly.
6815
6816 If you take the @sc{cdr} of the list @code{(pine fir
6817 oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
6818 repeat this on what was returned, you will be returned the list
6819 @code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
6820 list will just give you the original @sc{cdr} since the function does
6821 not change the list. You need to evaluate the @sc{cdr} of the
6822 @sc{cdr} and so on.) If you continue this, eventually you will be
6823 returned an empty list, which in this case, instead of being shown as
6824 @code{()} is shown as @code{nil}.
6825
6826 @need 1200
6827 For review, here is a series of repeated @sc{cdr}s, the text following
6828 the @samp{@result{}} shows what is returned.
6829
6830 @smallexample
6831 @group
6832 (cdr '(pine fir oak maple))
6833 @result{}(fir oak maple)
6834 @end group
6835
6836 @group
6837 (cdr '(fir oak maple))
6838 @result{} (oak maple)
6839 @end group
6840
6841 @group
6842 (cdr '(oak maple))
6843 @result{}(maple)
6844 @end group
6845
6846 @group
6847 (cdr '(maple))
6848 @result{} nil
6849 @end group
6850
6851 @group
6852 (cdr 'nil)
6853 @result{} nil
6854 @end group
6855
6856 @group
6857 (cdr ())
6858 @result{} nil
6859 @end group
6860 @end smallexample
6861
6862 @need 1200
6863 You can also do several @sc{cdr}s without printing the values in
6864 between, like this:
6865
6866 @smallexample
6867 @group
6868 (cdr (cdr '(pine fir oak maple)))
6869 @result{} (oak maple)
6870 @end group
6871 @end smallexample
6872
6873 @noindent
6874 In this example, the Lisp interpreter evaluates the innermost list first.
6875 The innermost list is quoted, so it just passes the list as it is to the
6876 innermost @code{cdr}. This @code{cdr} passes a list made up of the
6877 second and subsequent elements of the list to the outermost @code{cdr},
6878 which produces a list composed of the third and subsequent elements of
6879 the original list. In this example, the @code{cdr} function is repeated
6880 and returns a list that consists of the original list without its
6881 first two elements.
6882
6883 The @code{nthcdr} function does the same as repeating the call to
6884 @code{cdr}. In the following example, the argument 2 is passed to the
6885 function @code{nthcdr}, along with the list, and the value returned is
6886 the list without its first two items, which is exactly the same
6887 as repeating @code{cdr} twice on the list:
6888
6889 @smallexample
6890 @group
6891 (nthcdr 2 '(pine fir oak maple))
6892 @result{} (oak maple)
6893 @end group
6894 @end smallexample
6895
6896 @need 1200
6897 Using the original four element list, we can see what happens when
6898 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6899 and 5:
6900
6901 @smallexample
6902 @group
6903 ;; @r{Leave the list as it was.}
6904 (nthcdr 0 '(pine fir oak maple))
6905 @result{} (pine fir oak maple)
6906 @end group
6907
6908 @group
6909 ;; @r{Return a copy without the first element.}
6910 (nthcdr 1 '(pine fir oak maple))
6911 @result{} (fir oak maple)
6912 @end group
6913
6914 @group
6915 ;; @r{Return a copy of the list without three elements.}
6916 (nthcdr 3 '(pine fir oak maple))
6917 @result{} (maple)
6918 @end group
6919
6920 @group
6921 ;; @r{Return a copy lacking all four elements.}
6922 (nthcdr 4 '(pine fir oak maple))
6923 @result{} nil
6924 @end group
6925
6926 @group
6927 ;; @r{Return a copy lacking all elements.}
6928 (nthcdr 5 '(pine fir oak maple))
6929 @result{} nil
6930 @end group
6931 @end smallexample
6932
6933 @node nth, setcar, nthcdr, car cdr & cons
6934 @comment node-name, next, previous, up
6935 @section @code{nth}
6936 @findex nth
6937
6938 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6939 The @code{nth} function takes the @sc{car} of the result returned by
6940 @code{nthcdr}. It returns the Nth element of the list.
6941
6942 @need 1500
6943 Thus, if it were not defined in C for speed, the definition of
6944 @code{nth} would be:
6945
6946 @smallexample
6947 @group
6948 (defun nth (n list)
6949 "Returns the Nth element of LIST.
6950 N counts from zero. If LIST is not that long, nil is returned."
6951 (car (nthcdr n list)))
6952 @end group
6953 @end smallexample
6954
6955 @noindent
6956 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6957 but its definition was redone in C in the 1980s.)
6958
6959 The @code{nth} function returns a single element of a list.
6960 This can be very convenient.
6961
6962 Note that the elements are numbered from zero, not one. That is to
6963 say, the first element of a list, its @sc{car} is the zeroth element.
6964 This is called `zero-based' counting and often bothers people who
6965 are accustomed to the first element in a list being number one, which
6966 is `one-based'.
6967
6968 @need 1250
6969 For example:
6970
6971 @smallexample
6972 @group
6973 (nth 0 '("one" "two" "three"))
6974 @result{} "one"
6975
6976 (nth 1 '("one" "two" "three"))
6977 @result{} "two"
6978 @end group
6979 @end smallexample
6980
6981 It is worth mentioning that @code{nth}, like @code{nthcdr} and
6982 @code{cdr}, does not change the original list---the function is
6983 non-destructive. This is in sharp contrast to the @code{setcar} and
6984 @code{setcdr} functions.
6985
6986 @node setcar, setcdr, nth, car cdr & cons
6987 @comment node-name, next, previous, up
6988 @section @code{setcar}
6989 @findex setcar
6990
6991 As you might guess from their names, the @code{setcar} and @code{setcdr}
6992 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
6993 They actually change the original list, unlike @code{car} and @code{cdr}
6994 which leave the original list as it was. One way to find out how this
6995 works is to experiment. We will start with the @code{setcar} function.
6996
6997 @need 1200
6998 First, we can make a list and then set the value of a variable to the
6999 list, using the @code{setq} function. Here is a list of animals:
7000
7001 @smallexample
7002 (setq animals '(antelope giraffe lion tiger))
7003 @end smallexample
7004
7005 @noindent
7006 If you are reading this in Info inside of GNU Emacs, you can evaluate
7007 this expression in the usual fashion, by positioning the cursor after
7008 the expression and typing @kbd{C-x C-e}. (I'm doing this right here as
7009 I write this. This is one of the advantages of having the interpreter
7010 built into the computing environment.)
7011
7012 @need 1200
7013 When we evaluate the variable @code{animals}, we see that it is bound to
7014 the list @code{(antelope giraffe lion tiger)}:
7015
7016 @smallexample
7017 @group
7018 animals
7019 @result{} (antelope giraffe lion tiger)
7020 @end group
7021 @end smallexample
7022
7023 @noindent
7024 Put another way, the variable @code{animals} points to the list
7025 @code{(antelope giraffe lion tiger)}.
7026
7027 Next, evaluate the function @code{setcar} while passing it two
7028 arguments, the variable @code{animals} and the quoted symbol
7029 @code{hippopotamus}; this is done by writing the three element list
7030 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7031 usual fashion:
7032
7033 @smallexample
7034 (setcar animals 'hippopotamus)
7035 @end smallexample
7036
7037 @need 1200
7038 @noindent
7039 After evaluating this expression, evaluate the variable @code{animals}
7040 again. You will see that the list of animals has changed:
7041
7042 @smallexample
7043 @group
7044 animals
7045 @result{} (hippopotamus giraffe lion tiger)
7046 @end group
7047 @end smallexample
7048
7049 @noindent
7050 The first element on the list, @code{antelope} is replaced by
7051 @code{hippopotamus}.
7052
7053 So we can see that @code{setcar} did not add a new element to the list
7054 as @code{cons} would have; it replaced @code{giraffe} with
7055 @code{hippopotamus}; it @emph{changed} the list.
7056
7057 @node setcdr, cons Exercise, setcar, car cdr & cons
7058 @comment node-name, next, previous, up
7059 @section @code{setcdr}
7060 @findex setcdr
7061
7062 The @code{setcdr} function is similar to the @code{setcar} function,
7063 except that the function replaces the second and subsequent elements of
7064 a list rather than the first element.
7065
7066 @need 1200
7067 To see how this works, set the value of the variable to a list of
7068 domesticated animals by evaluating the following expression:
7069
7070 @smallexample
7071 (setq domesticated-animals '(horse cow sheep goat))
7072 @end smallexample
7073
7074 @need 1200
7075 @noindent
7076 If you now evaluate the list, you will be returned the list
7077 @code{(horse cow sheep goat)}:
7078
7079 @smallexample
7080 @group
7081 domesticated-animals
7082 @result{} (horse cow sheep goat)
7083 @end group
7084 @end smallexample
7085
7086 @need 1200
7087 Next, evaluate @code{setcdr} with two arguments, the name of the
7088 variable which has a list as its value, and the list to which the
7089 @sc{cdr} of the first list will be set;
7090
7091 @smallexample
7092 (setcdr domesticated-animals '(cat dog))
7093 @end smallexample
7094
7095 @noindent
7096 If you evaluate this expression, the list @code{(cat dog)} will appear
7097 in the echo area. This is the value returned by the function. The
7098 result we are interested in is the ``side effect'', which we can see by
7099 evaluating the variable @code{domesticated-animals}:
7100
7101 @smallexample
7102 @group
7103 domesticated-animals
7104 @result{} (horse cat dog)
7105 @end group
7106 @end smallexample
7107
7108 @noindent
7109 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7110 @code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7111 @code{(cow sheep goat)} to @code{(cat dog)}.
7112
7113 @node cons Exercise, , setcdr, car cdr & cons
7114 @section Exercise
7115
7116 Construct a list of four birds by evaluating several expressions with
7117 @code{cons}. Find out what happens when you @code{cons} a list onto
7118 itself. Replace the first element of the list of four birds with a
7119 fish. Replace the rest of that list with a list of other fish.
7120 @node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7121 @comment node-name, next, previous, up
7122 @chapter Cutting and Storing Text
7123 @cindex Cutting and storing text
7124 @cindex Storing and cutting text
7125 @cindex Killing text
7126 @cindex Clipping text
7127 @cindex Erasing text
7128 @cindex Deleting text
7129
7130 Whenever you cut or clip text out of a buffer with a `kill' command in
7131 GNU Emacs, it is stored in a list and you can bring it back with a
7132 `yank' command.
7133
7134 (The use of the word `kill' in Emacs for processes which specifically
7135 @emph{do not} destroy the values of the entities is an unfortunate
7136 historical accident. A much more appropriate word would be `clip' since
7137 that is what the kill commands do; they clip text out of a buffer and
7138 put it into storage from which it can be brought back. I have often
7139 been tempted to replace globally all occurrences of `kill' in the Emacs
7140 sources with `clip' and all occurrences of `killed' with `clipped'.)
7141
7142 @menu
7143 * Storing Text:: Text is stored in a list.
7144 * zap-to-char:: Cutting out text up to a character.
7145 * kill-region:: Cutting text out of a region.
7146 * Digression into C:: Minor note on C programming language macros.
7147 * defvar:: How to give a variable an initial value.
7148 * copy-region-as-kill:: A definition for copying text.
7149 * cons & search-fwd Review::
7150 * search Exercises::
7151 @end menu
7152
7153 @node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7154 @ifnottex
7155 @unnumberedsec Storing Text in a List
7156 @end ifnottex
7157
7158 When text is cut out of a buffer, it is stored on a list. Successive
7159 pieces of text are stored on the list successively, so the list might
7160 look like this:
7161
7162 @smallexample
7163 ("a piece of text" "previous piece")
7164 @end smallexample
7165
7166 @need 1200
7167 @noindent
7168 The function @code{cons} can be used to add a piece of text to the list,
7169 like this:
7170
7171 @smallexample
7172 @group
7173 (cons "another piece"
7174 '("a piece of text" "previous piece"))
7175 @end group
7176 @end smallexample
7177
7178 @need 1200
7179 @noindent
7180 If you evaluate this expression, a list of three elements will appear in
7181 the echo area:
7182
7183 @smallexample
7184 ("another piece" "a piece of text" "previous piece")
7185 @end smallexample
7186
7187 With the @code{car} and @code{nthcdr} functions, you can retrieve
7188 whichever piece of text you want. For example, in the following code,
7189 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7190 and the @code{car} returns the first element of that remainder---the
7191 second element of the original list:
7192
7193 @smallexample
7194 @group
7195 (car (nthcdr 1 '("another piece"
7196 "a piece of text"
7197 "previous piece")))
7198 @result{} "a piece of text"
7199 @end group
7200 @end smallexample
7201
7202 The actual functions in Emacs are more complex than this, of course.
7203 The code for cutting and retrieving text has to be written so that
7204 Emacs can figure out which element in the list you want---the first,
7205 second, third, or whatever. In addition, when you get to the end of
7206 the list, Emacs should give you the first element of the list, rather
7207 than nothing at all.
7208
7209 The list that holds the pieces of text is called the @dfn{kill ring}.
7210 This chapter leads up to a description of the kill ring and how it is
7211 used by first tracing how the @code{zap-to-char} function works. This
7212 function uses (or `calls') a function that invokes a function that
7213 manipulates the kill ring. Thus, before reaching the mountains, we
7214 climb the foothills.
7215
7216 A subsequent chapter describes how text that is cut from the buffer is
7217 retrieved. @xref{Yanking, , Yanking Text Back}.
7218
7219 @node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7220 @comment node-name, next, previous, up
7221 @section @code{zap-to-char}
7222 @findex zap-to-char
7223
7224 The @code{zap-to-char} function barely changed between GNU Emacs
7225 version 19 and GNU Emacs version 21. However, @code{zap-to-char}
7226 calls another function, @code{kill-region}, which enjoyed a major rewrite
7227 on the way to version 21.
7228
7229 The @code{kill-region} function in Emacs 19 is complex, but does not
7230 use code that is important at this time. We will skip it.
7231
7232 The @code{kill-region} function in Emacs 21 is easier to read than the
7233 same function in Emacs 19 and introduces a very important concept,
7234 that of error handling. We will walk through the function.
7235
7236 But first, let us look at the interactive @code{zap-to-char} function.
7237
7238 @menu
7239 * Complete zap-to-char:: The complete implementation.
7240 * zap-to-char interactive:: A three part interactive expression.
7241 * zap-to-char body:: A short overview.
7242 * search-forward:: How to search for a string.
7243 * progn:: The @code{progn} special form.
7244 * Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7245 @end menu
7246
7247 @node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7248 @ifnottex
7249 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7250 @end ifnottex
7251
7252 The GNU Emacs version 19 and version 21 implementations of the
7253 @code{zap-to-char} function are nearly identical in form, and they
7254 work alike. The function removes the text in the region between the
7255 location of the cursor (i.e., of point) up to and including the next
7256 occurrence of a specified character. The text that @code{zap-to-char}
7257 removes is put in the kill ring; and it can be retrieved from the kill
7258 ring by typing @kbd{C-y} (@code{yank}). If the command is given an
7259 argument, it removes text through that number of occurrences. Thus,
7260 if the cursor were at the beginning of this sentence and the character
7261 were @samp{s}, @samp{Thus} would be removed. If the argument were
7262 two, @samp{Thus, if the curs} would be removed, up to and including
7263 the @samp{s} in @samp{cursor}.
7264
7265 If the specified character is not found, @code{zap-to-char} will say
7266 ``Search failed'', tell you the character you typed, and not remove
7267 any text.
7268
7269 In order to determine how much text to remove, @code{zap-to-char} uses
7270 a search function. Searches are used extensively in code that
7271 manipulates text, and we will focus attention on them as well as on the
7272 deletion command.
7273
7274 @need 800
7275 Here is the complete text of the version 19 implementation of the function:
7276
7277 @c v 19
7278 @smallexample
7279 @group
7280 (defun zap-to-char (arg char) ; version 19 implementation
7281 "Kill up to and including ARG'th occurrence of CHAR.
7282 Goes backward if ARG is negative; error if CHAR not found."
7283 (interactive "*p\ncZap to char: ")
7284 (kill-region (point)
7285 (progn
7286 (search-forward
7287 (char-to-string char) nil nil arg)
7288 (point))))
7289 @end group
7290 @end smallexample
7291
7292 @node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7293 @comment node-name, next, previous, up
7294 @subsection The @code{interactive} Expression
7295
7296 @need 800
7297 The interactive expression in the @code{zap-to-char} command looks like
7298 this:
7299
7300 @smallexample
7301 (interactive "*p\ncZap to char: ")
7302 @end smallexample
7303
7304 The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7305 three different things. First, and most simply, the asterisk, @samp{*},
7306 causes an error to be signalled if the buffer is read-only. This means that
7307 if you try @code{zap-to-char} in a read-only buffer you will not be able to
7308 remove text, and you will receive a message that says ``Buffer is
7309 read-only''; your terminal may beep at you as well.
7310
7311 The version 21 implementation does not have the asterisk, @samp{*}. The
7312 function works the same as in version 19: in both cases, it cannot
7313 remove text from a read-only buffer but the function does copy the
7314 text that would have been removed to the kill ring. Also, in both
7315 cases, you see an error message.
7316
7317 However, the version 19 implementation copies text from a read-only
7318 buffer only because of a mistake in the implementation of
7319 @code{interactive}. According to the documentation for
7320 @code{interactive}, the asterisk, @samp{*}, should prevent the
7321 @code{zap-to-char} function from doing anything at all when the buffer
7322 is read only. The function should not copy the text to the kill ring.
7323 It is a bug that it does.
7324
7325 In version 21, @code{interactive} is implemented correctly. So the
7326 asterisk, @samp{*}, had to be removed from the interactive
7327 specification. If you insert an @samp{*} and evaluate the function
7328 definition, then the next time you run the @code{zap-to-char} function
7329 on a read-only buffer, you will not copy any text.
7330
7331 That change aside, and a change to the documentation, the two versions
7332 of the @code{zap-to-char} function are identical.
7333
7334 Let us continue with the interactive specification.
7335
7336 The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7337 This part is separated from the next part by a newline, @samp{\n}.
7338 The @samp{p} means that the first argument to the function will be
7339 passed the value of a `processed prefix'. The prefix argument is
7340 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7341 the function is called interactively without a prefix, 1 is passed to
7342 this argument.
7343
7344 The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7345 }. In this part, the lower case @samp{c} indicates that
7346 @code{interactive} expects a prompt and that the argument will be a
7347 character. The prompt follows the @samp{c} and is the string @samp{Zap
7348 to char:@: } (with a space after the colon to make it look good).
7349
7350 What all this does is prepare the arguments to @code{zap-to-char} so they
7351 are of the right type, and give the user a prompt.
7352
7353 @node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7354 @comment node-name, next, previous, up
7355 @subsection The Body of @code{zap-to-char}
7356
7357 The body of the @code{zap-to-char} function contains the code that
7358 kills (that is, removes) the text in the region from the current
7359 position of the cursor up to and including the specified character.
7360 The first part of the code looks like this:
7361
7362 @smallexample
7363 (kill-region (point) @dots{}
7364 @end smallexample
7365
7366 @noindent
7367 @code{(point)} is the current position of the cursor.
7368
7369 The next part of the code is an expression using @code{progn}. The body
7370 of the @code{progn} consists of calls to @code{search-forward} and
7371 @code{point}.
7372
7373 It is easier to understand how @code{progn} works after learning about
7374 @code{search-forward}, so we will look at @code{search-forward} and
7375 then at @code{progn}.
7376
7377 @node search-forward, progn, zap-to-char body, zap-to-char
7378 @comment node-name, next, previous, up
7379 @subsection The @code{search-forward} Function
7380 @findex search-forward
7381
7382 The @code{search-forward} function is used to locate the
7383 zapped-for-character in @code{zap-to-char}. If the search is
7384 successful, @code{search-forward} leaves point immediately after the
7385 last character in the target string. (In @code{zap-to-char}, the
7386 target string is just one character long.) If the search is
7387 backwards, @code{search-forward} leaves point just before the first
7388 character in the target. Also, @code{search-forward} returns @code{t}
7389 for true. (Moving point is therefore a `side effect'.)
7390
7391 @need 1250
7392 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7393
7394 @smallexample
7395 (search-forward (char-to-string char) nil nil arg)
7396 @end smallexample
7397
7398 The @code{search-forward} function takes four arguments:
7399
7400 @enumerate
7401 @item
7402 The first argument is the target, what is searched for. This must be a
7403 string, such as @samp{"z"}.
7404
7405 As it happens, the argument passed to @code{zap-to-char} is a single
7406 character. Because of the way computers are built, the Lisp
7407 interpreter may treat a single character as being different from a
7408 string of characters. Inside the computer, a single character has a
7409 different electronic format than a string of one character. (A single
7410 character can often be recorded in the computer using exactly one
7411 byte; but a string may be longer, and the computer needs to be ready
7412 for this.) Since the @code{search-forward} function searches for a
7413 string, the character that the @code{zap-to-char} function receives as
7414 its argument must be converted inside the computer from one format to
7415 the other; otherwise the @code{search-forward} function will fail.
7416 The @code{char-to-string} function is used to make this conversion.
7417
7418 @item
7419 The second argument bounds the search; it is specified as a position in
7420 the buffer. In this case, the search can go to the end of the buffer,
7421 so no bound is set and the second argument is @code{nil}.
7422
7423 @item
7424 The third argument tells the function what it should do if the search
7425 fails---it can signal an error (and print a message) or it can return
7426 @code{nil}. A @code{nil} as the third argument causes the function to
7427 signal an error when the search fails.
7428
7429 @item
7430 The fourth argument to @code{search-forward} is the repeat count---how
7431 many occurrences of the string to look for. This argument is optional
7432 and if the function is called without a repeat count, this argument is
7433 passed the value 1. If this argument is negative, the search goes
7434 backwards.
7435 @end enumerate
7436
7437 @need 800
7438 In template form, a @code{search-forward} expression looks like this:
7439
7440 @smallexample
7441 @group
7442 (search-forward "@var{target-string}"
7443 @var{limit-of-search}
7444 @var{what-to-do-if-search-fails}
7445 @var{repeat-count})
7446 @end group
7447 @end smallexample
7448
7449 We will look at @code{progn} next.
7450
7451 @node progn, Summing up zap-to-char, search-forward, zap-to-char
7452 @comment node-name, next, previous, up
7453 @subsection The @code{progn} Special Form
7454 @findex progn
7455
7456 @code{progn} is a special form that causes each of its arguments to be
7457 evaluated in sequence and then returns the value of the last one. The
7458 preceding expressions are evaluated only for the side effects they
7459 perform. The values produced by them are discarded.
7460
7461 @need 800
7462 The template for a @code{progn} expression is very simple:
7463
7464 @smallexample
7465 @group
7466 (progn
7467 @var{body}@dots{})
7468 @end group
7469 @end smallexample
7470
7471 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7472 put point in exactly the right position; and return the location of
7473 point so that @code{kill-region} will know how far to kill to.
7474
7475 The first argument to the @code{progn} is @code{search-forward}. When
7476 @code{search-forward} finds the string, the function leaves point
7477 immediately after the last character in the target string. (In this
7478 case the target string is just one character long.) If the search is
7479 backwards, @code{search-forward} leaves point just before the first
7480 character in the target. The movement of point is a side effect.
7481
7482 The second and last argument to @code{progn} is the expression
7483 @code{(point)}. This expression returns the value of point, which in
7484 this case will be the location to which it has been moved by
7485 @code{search-forward}. This value is returned by the @code{progn}
7486 expression and is passed to @code{kill-region} as @code{kill-region}'s
7487 second argument.
7488
7489 @node Summing up zap-to-char, , progn, zap-to-char
7490 @comment node-name, next, previous, up
7491 @subsection Summing up @code{zap-to-char}
7492
7493 Now that we have seen how @code{search-forward} and @code{progn} work,
7494 we can see how the @code{zap-to-char} function works as a whole.
7495
7496 The first argument to @code{kill-region} is the position of the cursor
7497 when the @code{zap-to-char} command is given---the value of point at
7498 that time. Within the @code{progn}, the search function then moves
7499 point to just after the zapped-to-character and @code{point} returns the
7500 value of this location. The @code{kill-region} function puts together
7501 these two values of point, the first one as the beginning of the region
7502 and the second one as the end of the region, and removes the region.
7503
7504 The @code{progn} special form is necessary because the @code{kill-region}
7505 command takes two arguments; and it would fail if @code{search-forward}
7506 and @code{point} expressions were written in sequence as two
7507 additional arguments. The @code{progn} expression is a single argument
7508 to @code{kill-region} and returns the one value that @code{kill-region}
7509 needs for its second argument.
7510
7511 @node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7512 @comment node-name, next, previous, up
7513 @section @code{kill-region}
7514 @findex kill-region
7515
7516 The @code{zap-to-char} function uses the @code{kill-region} function.
7517 This function clips text from a region and copies that text to
7518 the kill ring, from which it may be retrieved.
7519
7520 The Emacs 21 version of that function uses @code{condition-case} and
7521 @code{copy-region-as-kill}, both of which we will explain.
7522 @code{condition-case} is an important special form.
7523
7524 In essence, the @code{kill-region} function calls
7525 @code{condition-case}, which takes three arguments. In this function,
7526 the first argument does nothing. The second argument contains the
7527 code that does the work when all goes well. The third argument
7528 contains the code that is called in the event of an error.
7529
7530 @menu
7531 * Complete kill-region:: The function definition.
7532 * condition-case:: Dealing with a problem.
7533 * delete-and-extract-region:: Doing the work.
7534 @end menu
7535
7536 @node Complete kill-region, condition-case, kill-region, kill-region
7537 @ifnottex
7538 @unnumberedsubsec The Complete @code{kill-region} Definition
7539 @end ifnottex
7540
7541 @need 1200
7542 We will go through the @code{condition-case} code in a moment. First,
7543 let us look at the complete definition of @code{kill-region}, with
7544 comments added:
7545
7546 @c v 21
7547 @smallexample
7548 @group
7549 (defun kill-region (beg end)
7550 "Kill between point and mark.
7551 The text is deleted but saved in the kill ring."
7552 (interactive "r")
7553 @end group
7554
7555 @group
7556 ;; 1. `condition-case' takes three arguments.
7557 ;; If the first argument is nil, as it is here,
7558 ;; information about the error signal is not
7559 ;; stored for use by another function.
7560 (condition-case nil
7561 @end group
7562
7563 @group
7564 ;; 2. The second argument to `condition-case'
7565 ;; tells the Lisp interpreter what to do when all goes well.
7566 @end group
7567
7568 @group
7569 ;; The `delete-and-extract-region' function usually does the
7570 ;; work. If the beginning and ending of the region are both
7571 ;; the same, then the variable `string' will be empty, or nil
7572 (let ((string (delete-and-extract-region beg end)))
7573 @end group
7574
7575 @group
7576 ;; `when' is an `if' clause that cannot take an `else-part'.
7577 ;; Emacs normally sets the value of `last-command' to the
7578 ;; previous command.
7579 @end group
7580 @group
7581 ;; `kill-append' concatenates the new string and the old.
7582 ;; `kill-new' inserts text into a new item in the kill ring.
7583 (when string
7584 (if (eq last-command 'kill-region)
7585 ;; if true, prepend string
7586 (kill-append string (< end beg))
7587 (kill-new string)))
7588 (setq this-command 'kill-region))
7589 @end group
7590
7591 @group
7592 ;; 3. The third argument to `condition-case' tells the interpreter
7593 ;; what to do with an error.
7594 @end group
7595 @group
7596 ;; The third argument has a conditions part and a body part.
7597 ;; If the conditions are met (in this case,
7598 ;; if text or buffer is read-only)
7599 ;; then the body is executed.
7600 @end group
7601 @group
7602 ((buffer-read-only text-read-only) ;; this is the if-part
7603 ;; then...
7604 (copy-region-as-kill beg end)
7605 @end group
7606 @group
7607 (if kill-read-only-ok ;; usually this variable is nil
7608 (message "Read only text copied to kill ring")
7609 ;; or else, signal an error if the buffer is read-only;
7610 (barf-if-buffer-read-only)
7611 ;; and, in any case, signal that the text is read-only.
7612 (signal 'text-read-only (list (current-buffer)))))))
7613 @end group
7614 @end smallexample
7615
7616 @node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7617 @comment node-name, next, previous, up
7618 @subsection @code{condition-case}
7619 @findex condition-case
7620
7621 As we have seen earlier (@pxref{Making Errors, , Generate an Error
7622 Message}), when the Emacs Lisp interpreter has trouble evaluating an
7623 expression, it provides you with help; in the jargon, this is called
7624 ``signaling an error''. Usually, the computer stops the program and
7625 shows you a message.
7626
7627 However, some programs undertake complicated actions. They should not
7628 simply stop on an error. In the @code{kill-region} function, the most
7629 likely error is that you will try to kill text that is read-only and
7630 cannot be removed. So the @code{kill-region} function contains code
7631 to handle this circumstance. This code, which makes up the body of
7632 the @code{kill-region} function, is inside of a @code{condition-case}
7633 special form.
7634
7635 @need 800
7636 The template for @code{condition-case} looks like this:
7637
7638 @smallexample
7639 @group
7640 (condition-case
7641 @var{var}
7642 @var{bodyform}
7643 @var{error-handler}@dots{})
7644 @end group
7645 @end smallexample
7646
7647 The second argument, @var{bodyform}, is straightforward. The
7648 @code{condition-case} special form causes the Lisp interpreter to
7649 evaluate the code in @var{bodyform}. If no error occurs, the special
7650 form returns the code's value and produces the side-effects, if any.
7651
7652 In short, the @var{bodyform} part of a @code{condition-case}
7653 expression determines what should happen when everything works
7654 correctly.
7655
7656 However, if an error occurs, among its other actions, the function
7657 generating the error signal will define one or more error condition
7658 names.
7659
7660 An error handler is the third argument to @code{condition case}.
7661 An error handler has two parts, a @var{condition-name} and a
7662 @var{body}. If the @var{condition-name} part of an error handler
7663 matches a condition name generated by an error, then the @var{body}
7664 part of the error handler is run.
7665
7666 As you will expect, the @var{condition-name} part of an error handler
7667 may be either a single condition name or a list of condition names.
7668
7669 Also, a complete @code{condition-case} expression may contain more
7670 than one error handler. When an error occurs, the first applicable
7671 handler is run.
7672
7673 Lastly, the first argument to the @code{condition-case} expression,
7674 the @var{var} argument, is sometimes bound to a variable that
7675 contains information about the error. However, if that argument is
7676 nil, as is the case in @code{kill-region}, that information is
7677 discarded.
7678
7679 @need 1200
7680 In brief, in the @code{kill-region} function, the code
7681 @code{condition-case} works like this:
7682
7683 @smallexample
7684 @group
7685 @var{If no errors}, @var{run only this code}
7686 @var{but}, @var{if errors}, @var{run this other code}.
7687 @end group
7688 @end smallexample
7689
7690 @node delete-and-extract-region, , condition-case, kill-region
7691 @comment node-name, next, previous, up
7692 @subsection @code{delete-and-extract-region}
7693 @findex delete-and-extract-region
7694
7695 A @code{condition-case} expression has two parts, a part that is
7696 evaluated in the expectation that all will go well, but which may
7697 generate an error; and a part that is evaluated when there is an
7698 error.
7699
7700 First, let us look at the code in @code{kill-region} that is run in
7701 the expectation that all goes well. This is the core of the function.
7702 The code looks like this:
7703
7704 @smallexample
7705 @group
7706 (let ((string (delete-and-extract-region beg end)))
7707 (when string
7708 (if (eq last-command 'kill-region)
7709 (kill-append string (< end beg))
7710 (kill-new string)))
7711 (setq this-command 'kill-region))
7712 @end group
7713 @end smallexample
7714
7715 It looks complicated because we have the new functions
7716 @code{delete-and-extract-region}, @code{kill-append}, and
7717 @code{kill-new} as well as the new variables,
7718 @code{last-command} and @code{this-command}.
7719
7720 The @code{delete-and-extract-region} function is straightforward. It
7721 is a built-in function that deletes the text in a region (a side
7722 effect) and also returns that text. This is the function that
7723 actually removes the text. (And if it cannot do that, it signals the
7724 error.)
7725
7726 In this @code{let} expression, the text that
7727 @code{delete-and-extract-region} returns is placed in the local
7728 variable called @samp{string}. This is the text that is removed from
7729 the buffer. (To be more precise, the variable is set to point to the
7730 address of the extracted text; to say it is `placed in' the variable
7731 is simply a shorthand.)
7732
7733 If the variable @samp{string} does point to text, that text is added
7734 to the kill ring. The variable will have a @code{nil} value if no
7735 text was removed.
7736
7737 The code uses @code{when} to determine whether the variable
7738 @samp{string} points to text. A @code{when} statement is simply a
7739 programmers' convenience. A @code{when} statement is an @code{if}
7740 statement without the possibility of an else clause. In your mind, you
7741 can replace @code{when} with @code{if} and understand what goes on.
7742 That is what the Lisp interpreter does.
7743
7744 @cindex Macro, lisp
7745 @cindex Lisp macro
7746 Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
7747 enables you to define new control constructs and other language
7748 features. It tells the interpreter how to compute another Lisp
7749 expression which will in turn compute the value. In this case, the
7750 `other expression' is an @code{if} expression. For more about Lisp
7751 macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7752 Manual}. The C programming language also provides macros. These are
7753 different, but also useful. We will briefly look at C macros in
7754 @ref{Digression into C, , @code{delete-and-extract-region}:
7755 Digressing into C}.
7756
7757 @need 1200
7758 If the string has content, then another conditional expression is
7759 executed. This is an @code{if} with both a then-part and an else-part.
7760
7761 @smallexample
7762 @group
7763 (if (eq last-command 'kill-region)
7764 (kill-append string (< end beg))
7765 (kill-new string)))
7766 @end group
7767 @end smallexample
7768
7769 The then-part is evaluated if the previous command was another call to
7770 @code{kill-region}; if not, the else-part is evaluated.
7771
7772 @code{last-command} is a variable that comes with Emacs that we have
7773 not seen before. Normally, whenever a function is executed, Emacs
7774 sets the value of @code{last-command} to the previous command.
7775
7776 @need 1200
7777 In this segment of the definition, the @code{if} expression checks
7778 whether the previous command was @code{kill-region}. If it was,
7779
7780 @smallexample
7781 (kill-append string (< end beg))
7782 @end smallexample
7783
7784 @noindent
7785 concatenates a copy of the newly clipped text to the just previously
7786 clipped text in the kill ring. (If the @w{@code{(< end beg))}}
7787 expression is true, @code{kill-append} prepends the string to the just
7788 previously clipped text. For a detailed discussion, see
7789 @ref{kill-append function, , The @code{kill-append} function}.)
7790
7791 If you then yank back the text, i.e., `paste' it, you get both
7792 pieces of text at once. That way, if you delete two words in a row,
7793 and then yank them back, you get both words, in their proper order,
7794 with one yank. (The @w{@code{(< end beg))}} expression makes sure the
7795 order is correct.)
7796
7797 On the other hand, if the previous command is not @code{kill-region},
7798 then the @code{kill-new} function is called, which adds the text to
7799 the kill ring as the latest item, and sets the
7800 @code{kill-ring-yank-pointer} variable to point to it.
7801
7802 @node Digression into C, defvar, kill-region, Cutting & Storing Text
7803 @comment node-name, next, previous, up
7804 @section @code{delete-and-extract-region}: Digressing into C
7805 @findex delete-and-extract-region
7806 @cindex C, a digression into
7807 @cindex Digression into C
7808
7809 The @code{zap-to-char} command uses the
7810 @code{delete-and-extract-region} function, which in turn uses two
7811 other functions, @code{copy-region-as-kill} and
7812 @code{del_range_1}. The @code{copy-region-as-kill} function will be
7813 described in a following section; it puts a copy of the region in the
7814 kill ring so it can be yanked back. (@xref{copy-region-as-kill, ,
7815 @code{copy-region-as-kill}}.)
7816
7817 The @code{delete-and-extract-region} function removes the contents of
7818 a region and you cannot get them back.
7819
7820 Unlike the other code discussed here, @code{delete-and-extract-region}
7821 is not written in Emacs Lisp; it is written in C and is one of the
7822 primitives of the GNU Emacs system. Since it is very simple, I will
7823 digress briefly from Lisp and describe it here.
7824
7825 @need 1500
7826 Like many of the other Emacs primitives,
7827 @code{delete-and-extract-region} is written as an instance of a C
7828 macro, a macro being a template for code. The complete macro looks
7829 like this:
7830
7831 @c /usr/local/src/emacs/src/editfns.c
7832 @smallexample
7833 @group
7834 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7835 Sdelete_and_extract_region, 2, 2, 0,
7836 "Delete the text between START and END and return it.")
7837 (start, end)
7838 Lisp_Object start, end;
7839 @{
7840 validate_region (&start, &end);
7841 return del_range_1 (XINT (start), XINT (end), 1, 1);
7842 @}
7843 @end group
7844 @end smallexample
7845
7846 Without going into the details of the macro writing process, let me
7847 point out that this macro starts with the word @code{DEFUN}. The word
7848 @code{DEFUN} was chosen since the code serves the same purpose as
7849 @code{defun} does in Lisp. The word @code{DEFUN} is followed by seven
7850 parts inside of parentheses:
7851
7852 @itemize @bullet
7853 @item
7854 The first part is the name given to the function in Lisp,
7855 @code{delete-and-extract-region}.
7856
7857 @item
7858 The second part is the name of the function in C,
7859 @code{Fdelete_and_extract_region}. By convention, it starts with
7860 @samp{F}. Since C does not use hyphens in names, underscores are used
7861 instead.
7862
7863 @item
7864 The third part is the name for the C constant structure that records
7865 information on this function for internal use. It is the name of the
7866 function in C but begins with an @samp{S} instead of an @samp{F}.
7867
7868 @item
7869 The fourth and fifth parts specify the minimum and maximum number of
7870 arguments the function can have. This function demands exactly 2
7871 arguments.
7872
7873 @item
7874 The sixth part is nearly like the argument that follows the
7875 @code{interactive} declaration in a function written in Lisp: a letter
7876 followed, perhaps, by a prompt. The only difference from the Lisp is
7877 when the macro is called with no arguments. Then you write a @code{0}
7878 (which is a `null string'), as in this macro.
7879
7880 If you were to specify arguments, you would place them between
7881 quotation marks. The C macro for @code{goto-char} includes
7882 @code{"NGoto char: "} in this position to indicate that the function
7883 expects a raw prefix, in this case, a numerical location in a buffer,
7884 and provides a prompt.
7885
7886 @item
7887 The seventh part is a documentation string, just like the one for a
7888 function written in Emacs Lisp, except that every newline must be
7889 written explicitly as @samp{\n} followed by a backslash and carriage
7890 return.
7891
7892 @need 1000
7893 Thus, the first two lines of documentation for @code{goto-char} are
7894 written like this:
7895
7896 @smallexample
7897 @group
7898 "Set point to POSITION, a number or marker.\n\
7899 Beginning of buffer is position (point-min), end is (point-max).
7900 @end group
7901 @end smallexample
7902 @end itemize
7903
7904 @need 1200
7905 In a C macro, the formal parameters come next, with a statement of
7906 what kind of object they are, followed by what might be called the `body'
7907 of the macro. For @code{delete-and-extract-region} the `body'
7908 consists of the following two lines:
7909
7910 @smallexample
7911 @group
7912 validate_region (&start, &end);
7913 return del_range_1 (XINT (start), XINT (end), 1, 1);
7914 @end group
7915 @end smallexample
7916
7917 The first function, @code{validate_region} checks whether the values
7918 passed as the beginning and end of the region are the proper type and
7919 are within range. The second function, @code{del_range_1}, actually
7920 deletes the text.
7921
7922 @code{del_range_1} is a complex function we will not look into. It
7923 updates the buffer and does other things.
7924
7925 However, it is worth looking at the two arguments passed to
7926 @code{del_range}. These are @w{@code{XINT (start)}} and @w{@code{XINT
7927 (end)}}.
7928
7929 As far as the C language is concerned, @code{start} and @code{end} are
7930 two integers that mark the beginning and end of the region to be
7931 deleted@footnote{More precisely, and requiring more expert knowledge
7932 to understand, the two integers are of type `Lisp_Object', which can
7933 also be a C union instead of an integer type.}.
7934
7935 In early versions of Emacs, these two numbers were thirty-two bits
7936 long, but the code is slowly being generalized to handle other
7937 lengths. Three of the available bits are used to specify the type of
7938 information and a fourth bit is used for handling the computer's
7939 memory; the remaining bits are used as `content'.
7940
7941 @samp{XINT} is a C macro that extracts the relevant number from the
7942 longer collection of bits; the four other bits are discarded.
7943
7944 @need 800
7945 The command in @code{delete-and-extract-region} looks like this:
7946
7947 @smallexample
7948 del_range_1 (XINT (start), XINT (end), 1, 1);
7949 @end smallexample
7950
7951 @noindent
7952 It deletes the region between the beginning position, @code{start},
7953 and the ending position, @code{end}.
7954
7955 From the point of view of the person writing Lisp, Emacs is all very
7956 simple; but hidden underneath is a great deal of complexity to make it
7957 all work.
7958
7959 @node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7960 @comment node-name, next, previous, up
7961 @section Initializing a Variable with @code{defvar}
7962 @findex defvar
7963 @cindex Initializing a variable
7964 @cindex Variable initialization
7965
7966 Unlike the @code{delete-and-extract-region} function, the
7967 @code{copy-region-as-kill} function is written in Emacs Lisp. Two
7968 functions within it, @code{kill-append} and @code{kill-new}, copy a
7969 region in a buffer and save it in a variable called the
7970 @code{kill-ring}. This section describes how the @code{kill-ring}
7971 variable is created and initialized using the @code{defvar} special
7972 form.
7973
7974 (Again we note that the term @code{kill-ring} is a misnomer. The text
7975 that is clipped out of the buffer can be brought back; it is not a ring
7976 of corpses, but a ring of resurrectable text.)
7977
7978 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7979 given an initial value by using the @code{defvar} special form. The
7980 name comes from ``define variable''.
7981
7982 The @code{defvar} special form is similar to @code{setq} in that it sets
7983 the value of a variable. It is unlike @code{setq} in two ways: first,
7984 it only sets the value of the variable if the variable does not already
7985 have a value. If the variable already has a value, @code{defvar} does
7986 not override the existing value. Second, @code{defvar} has a
7987 documentation string.
7988
7989 (Another special form, @code{defcustom}, is designed for variables
7990 that people customize. It has more features than @code{defvar}.
7991 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
7992
7993 @menu
7994 * See variable current value::
7995 * defvar and asterisk:: An old-time convention.
7996 @end menu
7997
7998 @node See variable current value, defvar and asterisk, defvar, defvar
7999 @ifnottex
8000 @unnumberedsubsec Seeing the Current Value of a Variable
8001 @end ifnottex
8002
8003 You can see the current value of a variable, any variable, by using
8004 the @code{describe-variable} function, which is usually invoked by
8005 typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
8006 (followed by @key{RET}) when prompted, you will see what is in your
8007 current kill ring---this may be quite a lot! Conversely, if you have
8008 been doing nothing this Emacs session except read this document, you
8009 may have nothing in it. Also, you will see the documentation for
8010 @code{kill-ring}:
8011
8012 @smallexample
8013 @group
8014 Documentation:
8015 List of killed text sequences.
8016 Since the kill ring is supposed to interact nicely with cut-and-paste
8017 facilities offered by window systems, use of this variable should
8018 @end group
8019 @group
8020 interact nicely with `interprogram-cut-function' and
8021 `interprogram-paste-function'. The functions `kill-new',
8022 `kill-append', and `current-kill' are supposed to implement this
8023 interaction; you may want to use them instead of manipulating the kill
8024 ring directly.
8025 @end group
8026 @end smallexample
8027
8028 @need 800
8029 The kill ring is defined by a @code{defvar} in the following way:
8030
8031 @smallexample
8032 @group
8033 (defvar kill-ring nil
8034 "List of killed text sequences.
8035 @dots{}")
8036 @end group
8037 @end smallexample
8038
8039 @noindent
8040 In this variable definition, the variable is given an initial value of
8041 @code{nil}, which makes sense, since if you have saved nothing, you want
8042 nothing back if you give a @code{yank} command. The documentation
8043 string is written just like the documentation string of a @code{defun}.
8044 As with the documentation string of the @code{defun}, the first line of
8045 the documentation should be a complete sentence, since some commands,
8046 like @code{apropos}, print only the first line of documentation.
8047 Succeeding lines should not be indented; otherwise they look odd when
8048 you use @kbd{C-h v} (@code{describe-variable}).
8049
8050 @node defvar and asterisk, , See variable current value, defvar
8051 @subsection @code{defvar} and an asterisk
8052 @findex defvar @r{for a user customizable variable}
8053 @findex defvar @r{with an asterisk}
8054
8055 In the past, Emacs used the @code{defvar} special form both for
8056 internal variables that you would not expect a user to change and for
8057 variables that you do expect a user to change. Although you can still
8058 use @code{defvar} for user customizable variables, please use
8059 @code{defcustom} instead, since that special form provides a path into
8060 the Customization commands. (@xref{defcustom, , Setting Variables
8061 with @code{defcustom}}.)
8062
8063 When you specified a variable using the @code{defvar} special form,
8064 you could distinguish a readily settable variable from others by
8065 typing an asterisk, @samp{*}, in the first column of its documentation
8066 string. For example:
8067
8068 @smallexample
8069 @group
8070 (defvar shell-command-default-error-buffer nil
8071 "*Buffer name for `shell-command' @dots{} error output.
8072 @dots{} ")
8073 @end group
8074 @end smallexample
8075
8076 @noindent
8077 This means that you could (and still can) use the @code{edit-options}
8078 command to change the value of
8079 @code{shell-command-default-error-buffer} temporarily.
8080
8081 @findex edit-options
8082 However, options set using @code{edit-options} are set only for the
8083 duration of your editing session. The new values are not saved
8084 between sessions. Each time Emacs starts, it reads the original
8085 value, unless you change the value within your @file{.emacs} file,
8086 either by setting it manually or by using @code{customize}.
8087 @xref{Emacs Initialization, , Your @file{.emacs} File}.
8088
8089 For me, the major use of the @code{edit-options} command is to suggest
8090 variables that I might want to set in my @file{.emacs} file. I urge
8091 you to look through the list. (@xref{Edit Options, , Editing Variable
8092 Values, emacs, The GNU Emacs Manual}.)
8093
8094 @node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8095 @comment node-name, next, previous, up
8096 @section @code{copy-region-as-kill}
8097 @findex copy-region-as-kill
8098 @findex nthcdr
8099
8100 The @code{copy-region-as-kill} function copies a region of text from a
8101 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8102 in the @code{kill-ring}.
8103
8104 If you call @code{copy-region-as-kill} immediately after a
8105 @code{kill-region} command, Emacs appends the newly copied text to the
8106 previously copied text. This means that if you yank back the text, you
8107 get it all, from both this and the previous operation. On the other
8108 hand, if some other command precedes the @code{copy-region-as-kill},
8109 the function copies the text into a separate entry in the kill ring.
8110
8111 @menu
8112 * Complete copy-region-as-kill:: The complete function definition.
8113 * copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8114 @end menu
8115
8116 @node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8117 @ifnottex
8118 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8119 @end ifnottex
8120
8121 @need 1200
8122 Here is the complete text of the version 21 @code{copy-region-as-kill}
8123 function:
8124
8125 @smallexample
8126 @group
8127 (defun copy-region-as-kill (beg end)
8128 "Save the region as if killed, but don't kill it.
8129 In Transient Mark mode, deactivate the mark.
8130 If `interprogram-cut-function' is non-nil, also save
8131 the text for a window system cut and paste."
8132 (interactive "r")
8133 @end group
8134 @group
8135 (if (eq last-command 'kill-region)
8136 (kill-append (buffer-substring beg end) (< end beg))
8137 (kill-new (buffer-substring beg end)))
8138 @end group
8139 @group
8140 (if transient-mark-mode
8141 (setq deactivate-mark t))
8142 nil)
8143 @end group
8144 @end smallexample
8145
8146 @need 800
8147 As usual, this function can be divided into its component parts:
8148
8149 @smallexample
8150 @group
8151 (defun copy-region-as-kill (@var{argument-list})
8152 "@var{documentation}@dots{}"
8153 (interactive "r")
8154 @var{body}@dots{})
8155 @end group
8156 @end smallexample
8157
8158 The arguments are @code{beg} and @code{end} and the function is
8159 interactive with @code{"r"}, so the two arguments must refer to the
8160 beginning and end of the region. If you have been reading though this
8161 document from the beginning, understanding these parts of a function is
8162 almost becoming routine.
8163
8164 The documentation is somewhat confusing unless you remember that the
8165 word `kill' has a meaning different from its usual meaning. The
8166 `Transient Mark' and @code{interprogram-cut-function} comments explain
8167 certain side-effects.
8168
8169 After you once set a mark, a buffer always contains a region. If you
8170 wish, you can use Transient Mark mode to highlight the region
8171 temporarily. (No one wants to highlight the region all the time, so
8172 Transient Mark mode highlights it only at appropriate times. Many
8173 people turn off Transient Mark mode, so the region is never
8174 highlighted.)
8175
8176 Also, a windowing system allows you to copy, cut, and paste among
8177 different programs. In the X windowing system, for example, the
8178 @code{interprogram-cut-function} function is @code{x-select-text},
8179 which works with the windowing system's equivalent of the Emacs kill
8180 ring.
8181
8182 The body of the @code{copy-region-as-kill} function starts with an
8183 @code{if} clause. What this clause does is distinguish between two
8184 different situations: whether or not this command is executed
8185 immediately after a previous @code{kill-region} command. In the first
8186 case, the new region is appended to the previously copied text.
8187 Otherwise, it is inserted into the beginning of the kill ring as a
8188 separate piece of text from the previous piece.
8189
8190 The last two lines of the function prevent the region from lighting up
8191 if Transient Mark mode is turned on.
8192
8193 The body of @code{copy-region-as-kill} merits discussion in detail.
8194
8195 @node copy-region-as-kill body, , Complete copy-region-as-kill, copy-region-as-kill
8196 @comment node-name, next, previous, up
8197 @subsection The Body of @code{copy-region-as-kill}
8198
8199 The @code{copy-region-as-kill} function works in much the same way as
8200 the @code{kill-region} function (@pxref{kill-region,
8201 ,@code{kill-region}}). Both are written so that two or more kills in
8202 a row combine their text into a single entry. If you yank back the
8203 text from the kill ring, you get it all in one piece. Moreover, kills
8204 that kill forward from the current position of the cursor are added to
8205 the end of the previously copied text and commands that copy text
8206 backwards add it to the beginning of the previously copied text. This
8207 way, the words in the text stay in the proper order.
8208
8209 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8210 use of the @code{last-command} variable that keeps track of the
8211 previous Emacs command.
8212
8213 @menu
8214 * last-command & this-command::
8215 * kill-append function::
8216 * kill-new function::
8217 @end menu
8218
8219 @node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8220 @ifnottex
8221 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8222 @end ifnottex
8223
8224 Normally, whenever a function is executed, Emacs sets the value of
8225 @code{this-command} to the function being executed (which in this case
8226 would be @code{copy-region-as-kill}). At the same time, Emacs sets
8227 the value of @code{last-command} to the previous value of
8228 @code{this-command}.
8229
8230 In the first part of the body of the @code{copy-region-as-kill}
8231 function, an @code{if} expression determines whether the value of
8232 @code{last-command} is @code{kill-region}. If so, the then-part of
8233 the @code{if} expression is evaluated; it uses the @code{kill-append}
8234 function to concatenate the text copied at this call to the function
8235 with the text already in the first element (the @sc{car}) of the kill
8236 ring. On the other hand, if the value of @code{last-command} is not
8237 @code{kill-region}, then the @code{copy-region-as-kill} function
8238 attaches a new element to the kill ring using the @code{kill-new}
8239 function.
8240
8241 @need 1250
8242 The @code{if} expression reads as follows; it uses @code{eq}, which is
8243 a function we have not yet seen:
8244
8245 @smallexample
8246 @group
8247 (if (eq last-command 'kill-region)
8248 ;; @r{then-part}
8249 (kill-append (buffer-substring beg end) (< end beg))
8250 ;; @r{else-part}
8251 (kill-new (buffer-substring beg end)))
8252 @end group
8253 @end smallexample
8254
8255 @findex eq @r{(example of use)}
8256 @noindent
8257 The @code{eq} function tests whether its first argument is the same Lisp
8258 object as its second argument. The @code{eq} function is similar to the
8259 @code{equal} function in that it is used to test for equality, but
8260 differs in that it determines whether two representations are actually
8261 the same object inside the computer, but with different names.
8262 @code{equal} determines whether the structure and contents of two
8263 expressions are the same.
8264
8265 If the previous command was @code{kill-region}, then the Emacs Lisp
8266 interpreter calls the @code{kill-append} function
8267
8268 @node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8269 @unnumberedsubsubsec The @code{kill-append} function
8270 @findex kill-append
8271
8272 @need 800
8273 The @code{kill-append} function looks like this:
8274
8275 @smallexample
8276 @group
8277 (defun kill-append (string before-p)
8278 "Append STRING to the end of the latest kill in the kill ring.
8279 If BEFORE-P is non-nil, prepend STRING to the kill.
8280 If `interprogram-cut-function' is set, pass the resulting kill to
8281 it."
8282 (kill-new (if before-p
8283 (concat string (car kill-ring))
8284 (concat (car kill-ring) string))
8285 t))
8286 @end group
8287 @end smallexample
8288
8289 @noindent
8290 The @code{kill-append} function is fairly straightforward. It uses
8291 the @code{kill-new} function, which we will discuss in more detail in
8292 a moment.
8293
8294 First, let us look at the conditional that is one of the two arguments
8295 to @code{kill-new}. It uses @code{concat} to concatenate the new text
8296 to the @sc{car} of the kill ring. Whether it prepends or appends the
8297 text depends on the results of an @code{if} expression:
8298
8299 @smallexample
8300 @group
8301 (if before-p ; @r{if-part}
8302 (concat string (car kill-ring)) ; @r{then-part}
8303 (concat (car kill-ring) string)) ; @r{else-part}
8304 @end group
8305 @end smallexample
8306
8307 @noindent
8308 If the region being killed is before the region that was killed in the
8309 last command, then it should be prepended before the material that was
8310 saved in the previous kill; and conversely, if the killed text follows
8311 what was just killed, it should be appended after the previous text.
8312 The @code{if} expression depends on the predicate @code{before-p} to
8313 decide whether the newly saved text should be put before or after the
8314 previously saved text.
8315
8316 The symbol @code{before-p} is the name of one of the arguments to
8317 @code{kill-append}. When the @code{kill-append} function is
8318 evaluated, it is bound to the value returned by evaluating the actual
8319 argument. In this case, this is the expression @code{(< end beg)}.
8320 This expression does not directly determine whether the killed text in
8321 this command is located before or after the kill text of the last
8322 command; what is does is determine whether the value of the variable
8323 @code{end} is less than the value of the variable @code{beg}. If it
8324 is, it means that the user is most likely heading towards the
8325 beginning of the buffer. Also, the result of evaluating the predicate
8326 expression, @code{(< end beg)}, will be true and the text will be
8327 prepended before the previous text. On the other hand, if the value of
8328 the variable @code{end} is greater than the value of the variable
8329 @code{beg}, the text will be appended after the previous text.
8330
8331 @need 800
8332 When the newly saved text will be prepended, then the string with the new
8333 text will be concatenated before the old text:
8334
8335 @smallexample
8336 (concat string (car kill-ring))
8337 @end smallexample
8338
8339 @need 1200
8340 @noindent
8341 But if the text will be appended, it will be concatenated
8342 after the old text:
8343
8344 @smallexample
8345 (concat (car kill-ring) string))
8346 @end smallexample
8347
8348 To understand how this works, we first need to review the
8349 @code{concat} function. The @code{concat} function links together or
8350 unites two strings of text. The result is a string. For example:
8351
8352 @smallexample
8353 @group
8354 (concat "abc" "def")
8355 @result{} "abcdef"
8356 @end group
8357
8358 @group
8359 (concat "new "
8360 (car '("first element" "second element")))
8361 @result{} "new first element"
8362
8363 (concat (car
8364 '("first element" "second element")) " modified")
8365 @result{} "first element modified"
8366 @end group
8367 @end smallexample
8368
8369 We can now make sense of @code{kill-append}: it modifies the contents
8370 of the kill ring. The kill ring is a list, each element of which is
8371 saved text. The @code{kill-append} function uses the @code{kill-new}
8372 function which in turn uses the @code{setcar} function.
8373
8374 @node kill-new function, , kill-append function, copy-region-as-kill body
8375 @unnumberedsubsubsec The @code{kill-new} function
8376 @findex kill-new
8377
8378 @need 1200
8379 The @code{kill-new} function looks like this:
8380
8381 @smallexample
8382 @group
8383 (defun kill-new (string &optional replace)
8384 "Make STRING the latest kill in the kill ring.
8385 Set the kill-ring-yank pointer to point to it.
8386 If `interprogram-cut-function' is non-nil, apply it to STRING.
8387 Optional second argument REPLACE non-nil means that STRING will replace
8388 the front of the kill ring, rather than being added to the list."
8389 @end group
8390 @group
8391 (and (fboundp 'menu-bar-update-yank-menu)
8392 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8393 @end group
8394 @group
8395 (if (and replace kill-ring)
8396 (setcar kill-ring string)
8397 (setq kill-ring (cons string kill-ring))
8398 (if (> (length kill-ring) kill-ring-max)
8399 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8400 @end group
8401 @group
8402 (setq kill-ring-yank-pointer kill-ring)
8403 (if interprogram-cut-function
8404 (funcall interprogram-cut-function string (not replace))))
8405 @end group
8406 @end smallexample
8407
8408 As usual, we can look at this function in parts.
8409
8410 @need 1200
8411 The first line of the documentation makes sense:
8412
8413 @smallexample
8414 Make STRING the latest kill in the kill ring.
8415 @end smallexample
8416
8417 @noindent
8418 Let's skip over the rest of the documentation for the moment.
8419
8420 Also, let's skip over the first two lines of code, those involving
8421 @code{menu-bar-update-yank-menu}. We will explain them below.
8422
8423 @need 1200
8424 The critical lines are these:
8425
8426 @smallexample
8427 @group
8428 (if (and replace kill-ring)
8429 ;; @r{then}
8430 (setcar kill-ring string)
8431 @end group
8432 @group
8433 ;; @r{else}
8434 (setq kill-ring (cons string kill-ring))
8435 (if (> (length kill-ring) kill-ring-max)
8436 ;; @r{avoid overly long kill ring}
8437 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8438 @end group
8439 @group
8440 (setq kill-ring-yank-pointer kill-ring)
8441 (if interprogram-cut-function
8442 (funcall interprogram-cut-function string (not replace))))
8443 @end group
8444 @end smallexample
8445
8446 The conditional test is @w{@code{(and replace kill-ring)}}.
8447 This will be true when two conditions are met: the kill ring has
8448 something in it, and the @code{replace} variable is true.
8449
8450 @need 1250
8451 The @code{kill-append} function sets @code{replace} to be true; then,
8452 when the kill ring has at least one item in it, the @code{setcar}
8453 expression is executed:
8454
8455 @smallexample
8456 (setcar kill-ring string)
8457 @end smallexample
8458
8459 The @code{setcar} function actually changes the first element of the
8460 @code{kill-ring} list to the value of @code{string}. It replaces the
8461 first element.
8462
8463 On the other hand, if the kill ring is empty, or replace is false, the
8464 else-part of the condition is executed:
8465
8466 @smallexample
8467 @group
8468 (setq kill-ring (cons string kill-ring))
8469 (if (> (length kill-ring) kill-ring-max)
8470 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8471 @end group
8472 @end smallexample
8473
8474 @noindent
8475 This expression first constructs a new version of the kill ring by
8476 prepending @code{string} to the existing kill ring as a new element.
8477 Then it executes a second @code{if} clause. This second @code{if}
8478 clause keeps the kill ring from growing too long.
8479
8480 Let's look at these two expressions in order.
8481
8482 The @code{setq} line of the else-part sets the new value of the kill
8483 ring to what results from adding the string being killed to the old kill
8484 ring.
8485
8486 @need 800
8487 We can see how this works with an example:
8488
8489 @smallexample
8490 (setq example-list '("here is a clause" "another clause"))
8491 @end smallexample
8492
8493 @need 1200
8494 @noindent
8495 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8496 @code{example-list} and see what it returns:
8497
8498 @smallexample
8499 @group
8500 example-list
8501 @result{} ("here is a clause" "another clause")
8502 @end group
8503 @end smallexample
8504
8505 @need 1200
8506 @noindent
8507 Now, we can add a new element on to this list by evaluating the
8508 following expression:
8509 @findex cons, @r{example}
8510
8511 @smallexample
8512 (setq example-list (cons "a third clause" example-list))
8513 @end smallexample
8514
8515 @need 800
8516 @noindent
8517 When we evaluate @code{example-list}, we find its value is:
8518
8519 @smallexample
8520 @group
8521 example-list
8522 @result{} ("a third clause" "here is a clause" "another clause")
8523 @end group
8524 @end smallexample
8525
8526 @noindent
8527 Thus, the third clause was added to the list by @code{cons}.
8528
8529 @need 1200
8530 This is exactly similar to what the @code{setq} and @code{cons} do in
8531 the function. Here is the line again:
8532
8533 @smallexample
8534 (setq kill-ring (cons string kill-ring))
8535 @end smallexample
8536
8537 @need 1200
8538 Now for the second part of the @code{if} clause. This expression
8539 keeps the kill ring from growing too long. It looks like this:
8540
8541 @smallexample
8542 @group
8543 (if (> (length kill-ring) kill-ring-max)
8544 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8545 @end group
8546 @end smallexample
8547
8548 The code checks whether the length of the kill ring is greater than
8549 the maximum permitted length. This is the value of
8550 @code{kill-ring-max} (which is 60, by default). If the length of the
8551 kill ring is too long, then this code sets the last element of the
8552 kill ring to @code{nil}. It does this by using two functions,
8553 @code{nthcdr} and @code{setcdr}.
8554
8555 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8556 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8557 @sc{car} of a list. In this case, however, @code{setcdr} will not be
8558 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8559 function is used to cause it to set the @sc{cdr} of the next to last
8560 element of the kill ring---this means that since the @sc{cdr} of the
8561 next to last element is the last element of the kill ring, it will set
8562 the last element of the kill ring.
8563
8564 @findex nthcdr, @r{example}
8565 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8566 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8567 @dots{} It does this @var{N} times and returns the results.
8568
8569 @findex setcdr, @r{example}
8570 Thus, if we had a four element list that was supposed to be three
8571 elements long, we could set the @sc{cdr} of the next to last element
8572 to @code{nil}, and thereby shorten the list.
8573
8574 You can see this by evaluating the following three expressions in turn.
8575 First set the value of @code{trees} to @code{(maple oak pine birch)},
8576 then set the @sc{cdr} of its second @sc{cdr} to @code{nil} and then
8577 find the value of @code{trees}:
8578
8579 @smallexample
8580 @group
8581 (setq trees '(maple oak pine birch))
8582 @result{} (maple oak pine birch)
8583 @end group
8584
8585 @group
8586 (setcdr (nthcdr 2 trees) nil)
8587 @result{} nil
8588
8589 trees
8590 @result{} (maple oak pine)
8591 @end group
8592 @end smallexample
8593
8594 @noindent
8595 (The value returned by the @code{setcdr} expression is @code{nil} since
8596 that is what the @sc{cdr} is set to.)
8597
8598 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8599 @sc{cdr} a number of times that is one less than the maximum permitted
8600 size of the kill ring and sets the @sc{cdr} of that element (which
8601 will be the rest of the elements in the kill ring) to @code{nil}.
8602 This prevents the kill ring from growing too long.
8603
8604 @need 800
8605 The next to last expression in the @code{kill-new} function is
8606
8607 @smallexample
8608 (setq kill-ring-yank-pointer kill-ring)
8609 @end smallexample
8610
8611 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8612 the @code{kill-ring}.
8613
8614 Even though the @code{kill-ring-yank-pointer} is called a
8615 @samp{pointer}, it is a variable just like the kill ring. However, the
8616 name has been chosen to help humans understand how the variable is used.
8617 The variable is used in functions such as @code{yank} and
8618 @code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8619
8620 @need 1200
8621 Now, to return to the first two lines in the body of the function:
8622
8623 @smallexample
8624 @group
8625 (and (fboundp 'menu-bar-update-yank-menu)
8626 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8627 @end group
8628 @end smallexample
8629
8630 @noindent
8631 This is an expression whose first element is the function @code{and}.
8632
8633 @findex and, @r{introduced}
8634 The @code{and} special form evaluates each of its arguments until one of
8635 the arguments returns a value of @code{nil}, in which case the
8636 @code{and} expression returns @code{nil}; however, if none of the
8637 arguments returns a value of @code{nil}, the value resulting from
8638 evaluating the last argument is returned. (Since such a value is not
8639 @code{nil}, it is considered true in Emacs Lisp.) In other words, an
8640 @code{and} expression returns a true value only if all its arguments
8641 are true.
8642 @findex and
8643
8644 In this case, the expression tests first to see whether
8645 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8646 calls it. The @code{fboundp} function returns true if the symbol it
8647 is testing has a function definition that `is not void'. If the
8648 symbol's function definition were void, we would receive an error
8649 message, as we did when we created errors intentionally (@pxref{Making
8650 Errors, , Generate an Error Message}).
8651
8652 @need 1200
8653 Essentially, the @code{and} is an @code{if} expression that reads like
8654 this:
8655
8656 @smallexample
8657 @group
8658 if @var{the-menu-bar-function-exists}
8659 then @var{execute-it}
8660 @end group
8661 @end smallexample
8662
8663 @code{menu-bar-update-yank-menu} is one of the functions that make it
8664 possible to use the `Select and Paste' menu in the Edit item of a menu
8665 bar; using a mouse, you can look at the various pieces of text you
8666 have saved and select one piece to paste.
8667
8668 Finally, the last expression in the @code{kill-new} function adds the
8669 newly copied string to whatever facility exists for copying and
8670 pasting among different programs running in a windowing system. In
8671 the X Windowing system, for example, the @code{x-select-text} function
8672 takes the string and stores it in memory operated by X. You can paste
8673 the string in another program, such as an Xterm.
8674
8675 @need 1200
8676 The expression looks like this:
8677
8678 @smallexample
8679 @group
8680 (if interprogram-cut-function
8681 (funcall interprogram-cut-function string (not replace))))
8682 @end group
8683 @end smallexample
8684
8685 If an @code{interprogram-cut-function} exists, then Emacs executes
8686 @code{funcall}, which in turn calls its first argument as a function
8687 and passes the remaining arguments to it. (Incidentally, as far as I
8688 can see, this @code{if} expression could be replaced by an @code{and}
8689 expression similar to the one in the first part of the function.)
8690
8691 We are not going to discuss windowing systems and other programs
8692 further, but merely note that this is a mechanism that enables GNU
8693 Emacs to work easily and well with other programs.
8694
8695 This code for placing text in the kill ring, either concatenated with
8696 an existing element or as a new element, leads us to the code for
8697 bringing back text that has been cut out of the buffer---the yank
8698 commands. However, before discussing the yank commands, it is better
8699 to learn how lists are implemented in a computer. This will make
8700 clear such mysteries as the use of the term `pointer'.
8701
8702 @node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8703 @comment node-name, next, previous, up
8704 @section Review
8705
8706 Here is a brief summary of some recently introduced functions.
8707
8708 @table @code
8709 @item car
8710 @itemx cdr
8711 @code{car} returns the first element of a list; @code{cdr} returns the
8712 second and subsequent elements of a list.
8713
8714 @need 1250
8715 For example:
8716
8717 @smallexample
8718 @group
8719 (car '(1 2 3 4 5 6 7))
8720 @result{} 1
8721 (cdr '(1 2 3 4 5 6 7))
8722 @result{} (2 3 4 5 6 7)
8723 @end group
8724 @end smallexample
8725
8726 @item cons
8727 @code{cons} constructs a list by prepending its first argument to its
8728 second argument.
8729
8730 @need 1250
8731 For example:
8732
8733 @smallexample
8734 @group
8735 (cons 1 '(2 3 4))
8736 @result{} (1 2 3 4)
8737 @end group
8738 @end smallexample
8739
8740 @item nthcdr
8741 Return the result of taking @sc{cdr} `n' times on a list.
8742 @iftex
8743 The
8744 @tex
8745 $n^{th}$
8746 @end tex
8747 @code{cdr}.
8748 @end iftex
8749 The `rest of the rest', as it were.
8750
8751 @need 1250
8752 For example:
8753
8754 @smallexample
8755 @group
8756 (nthcdr 3 '(1 2 3 4 5 6 7))
8757 @result{} (4 5 6 7)
8758 @end group
8759 @end smallexample
8760
8761 @item setcar
8762 @itemx setcdr
8763 @code{setcar} changes the first element of a list; @code{setcdr}
8764 changes the second and subsequent elements of a list.
8765
8766 @need 1250
8767 For example:
8768
8769 @smallexample
8770 @group
8771 (setq triple '(1 2 3))
8772
8773 (setcar triple '37)
8774
8775 triple
8776 @result{} (37 2 3)
8777
8778 (setcdr triple '("foo" "bar"))
8779
8780 triple
8781 @result{} (37 "foo" "bar")
8782 @end group
8783 @end smallexample
8784
8785 @item progn
8786 Evaluate each argument in sequence and then return the value of the
8787 last.
8788
8789 @need 1250
8790 For example:
8791
8792 @smallexample
8793 @group
8794 (progn 1 2 3 4)
8795 @result{} 4
8796 @end group
8797 @end smallexample
8798
8799 @item save-restriction
8800 Record whatever narrowing is in effect in the current buffer, if any,
8801 and restore that narrowing after evaluating the arguments.
8802
8803 @item search-forward
8804 Search for a string, and if the string is found, move point.
8805
8806 @need 1250
8807 @noindent
8808 Takes four arguments:
8809
8810 @enumerate
8811 @item
8812 The string to search for.
8813
8814 @item
8815 Optionally, the limit of the search.
8816
8817 @item
8818 Optionally, what to do if the search fails, return @code{nil} or an
8819 error message.
8820
8821 @item
8822 Optionally, how many times to repeat the search; if negative, the
8823 search goes backwards.
8824 @end enumerate
8825
8826 @item kill-region
8827 @itemx delete-region
8828 @itemx copy-region-as-kill
8829
8830 @code{kill-region} cuts the text between point and mark from the
8831 buffer and stores that text in the kill ring, so you can get it back
8832 by yanking.
8833
8834 @code{delete-and-extract-region} removes the text between point and
8835 mark from the buffer and throws it away. You cannot get it back.
8836
8837 @code{copy-region-as-kill} copies the text between point and mark into
8838 the kill ring, from which you can get it by yanking. The function
8839 does not cut or remove the text from the buffer.
8840 @end table
8841
8842 @need 1500
8843 @node search Exercises, , cons & search-fwd Review, Cutting & Storing Text
8844 @section Searching Exercises
8845
8846 @itemize @bullet
8847 @item
8848 Write an interactive function that searches for a string. If the
8849 search finds the string, leave point after it and display a message
8850 that says ``Found!''. (Do not use @code{search-forward} for the name
8851 of this function; if you do, you will overwrite the existing version of
8852 @code{search-forward} that comes with Emacs. Use a name such as
8853 @code{test-search} instead.)
8854
8855 @item
8856 Write a function that prints the third element of the kill ring in the
8857 echo area, if any; if the kill ring does not contain a third element,
8858 print an appropriate message.
8859 @end itemize
8860
8861 @node List Implementation, Yanking, Cutting & Storing Text, Top
8862 @comment node-name, next, previous, up
8863 @chapter How Lists are Implemented
8864 @cindex Lists in a computer
8865
8866 In Lisp, atoms are recorded in a straightforward fashion; if the
8867 implementation is not straightforward in practice, it is, nonetheless,
8868 straightforward in theory. The atom @samp{rose}, for example, is
8869 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8870 @samp{e}. A list, on the other hand, is kept differently. The mechanism
8871 is equally simple, but it takes a moment to get used to the idea. A
8872 list is kept using a series of pairs of pointers. In the series, the
8873 first pointer in each pair points to an atom or to another list, and the
8874 second pointer in each pair points to the next pair, or to the symbol
8875 @code{nil}, which marks the end of the list.
8876
8877 A pointer itself is quite simply the electronic address of what is
8878 pointed to. Hence, a list is kept as a series of electronic addresses.
8879
8880 @menu
8881 * Lists diagrammed::
8882 * Symbols as Chest:: Exploring a powerful metaphor.
8883 * List Exercise::
8884 @end menu
8885
8886 @node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8887 @ifnottex
8888 @unnumberedsec Lists diagrammed
8889 @end ifnottex
8890
8891 For example, the list @code{(rose violet buttercup)} has three elements,
8892 @samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
8893 electronic address of @samp{rose} is recorded in a segment of computer
8894 memory along with the address that gives the electronic address of where
8895 the atom @samp{violet} is located; and that address (the one that tells
8896 where @samp{violet} is located) is kept along with an address that tells
8897 where the address for the atom @samp{buttercup} is located.
8898
8899 @need 1200
8900 This sounds more complicated than it is and is easier seen in a diagram:
8901
8902 @c clear print-postscript-figures
8903 @c !!! cons-cell-diagram #1
8904 @ifnottex
8905 @smallexample
8906 @group
8907 ___ ___ ___ ___ ___ ___
8908 |___|___|--> |___|___|--> |___|___|--> nil
8909 | | |
8910 | | |
8911 --> rose --> violet --> buttercup
8912 @end group
8913 @end smallexample
8914 @end ifnottex
8915 @ifset print-postscript-figures
8916 @sp 1
8917 @tex
8918 @image{cons-1}
8919 %%%% old method of including an image
8920 % \input /usr/local/lib/tex/inputs/psfig.tex
8921 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8922 % \catcode`\@=0 %
8923 @end tex
8924 @sp 1
8925 @end ifset
8926 @ifclear print-postscript-figures
8927 @iftex
8928 @smallexample
8929 @group
8930 ___ ___ ___ ___ ___ ___
8931 |___|___|--> |___|___|--> |___|___|--> nil
8932 | | |
8933 | | |
8934 --> rose --> violet --> buttercup
8935 @end group
8936 @end smallexample
8937 @end iftex
8938 @end ifclear
8939
8940 @noindent
8941 In the diagram, each box represents a word of computer memory that
8942 holds a Lisp object, usually in the form of a memory address. The boxes,
8943 i.e.@: the addresses, are in pairs. Each arrow points to what the address
8944 is the address of, either an atom or another pair of addresses. The
8945 first box is the electronic address of @samp{rose} and the arrow points
8946 to @samp{rose}; the second box is the address of the next pair of boxes,
8947 the first part of which is the address of @samp{violet} and the second
8948 part of which is the address of the next pair. The very last box
8949 points to the symbol @code{nil}, which marks the end of the list.
8950
8951 @need 1200
8952 When a variable is set to a list with a function such as @code{setq},
8953 it stores the address of the first box in the variable. Thus,
8954 evaluation of the expression
8955
8956 @smallexample
8957 (setq bouquet '(rose violet buttercup))
8958 @end smallexample
8959
8960 @need 1250
8961 @noindent
8962 creates a situation like this:
8963
8964 @c cons-cell-diagram #2
8965 @ifnottex
8966 @smallexample
8967 @group
8968 bouquet
8969 |
8970 | ___ ___ ___ ___ ___ ___
8971 --> |___|___|--> |___|___|--> |___|___|--> nil
8972 | | |
8973 | | |
8974 --> rose --> violet --> buttercup
8975 @end group
8976 @end smallexample
8977 @end ifnottex
8978 @ifset print-postscript-figures
8979 @sp 1
8980 @tex
8981 @image{cons-2}
8982 %%%% old method of including an image
8983 % \input /usr/local/lib/tex/inputs/psfig.tex
8984 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
8985 % \catcode`\@=0 %
8986 @end tex
8987 @sp 1
8988 @end ifset
8989 @ifclear print-postscript-figures
8990 @iftex
8991 @smallexample
8992 @group
8993 bouquet
8994 |
8995 | ___ ___ ___ ___ ___ ___
8996 --> |___|___|--> |___|___|--> |___|___|--> nil
8997 | | |
8998 | | |
8999 --> rose --> violet --> buttercup
9000 @end group
9001 @end smallexample
9002 @end iftex
9003 @end ifclear
9004
9005 @noindent
9006 In this example, the symbol @code{bouquet} holds the address of the first
9007 pair of boxes.
9008
9009 @need 1200
9010 This same list can be illustrated in a different sort of box notation
9011 like this:
9012
9013 @c cons-cell-diagram #2a
9014 @ifnottex
9015 @smallexample
9016 @group
9017 bouquet
9018 |
9019 | -------------- --------------- ----------------
9020 | | car | cdr | | car | cdr | | car | cdr |
9021 -->| rose | o------->| violet | o------->| butter- | nil |
9022 | | | | | | | cup | |
9023 -------------- --------------- ----------------
9024 @end group
9025 @end smallexample
9026 @end ifnottex
9027 @ifset print-postscript-figures
9028 @sp 1
9029 @tex
9030 @image{cons-2a}
9031 %%%% old method of including an image
9032 % \input /usr/local/lib/tex/inputs/psfig.tex
9033 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9034 % \catcode`\@=0 %
9035 @end tex
9036 @sp 1
9037 @end ifset
9038 @ifclear print-postscript-figures
9039 @iftex
9040 @smallexample
9041 @group
9042 bouquet
9043 |
9044 | -------------- --------------- ----------------
9045 | | car | cdr | | car | cdr | | car | cdr |
9046 -->| rose | o------->| violet | o------->| butter- | nil |
9047 | | | | | | | cup | |
9048 -------------- --------------- ----------------
9049 @end group
9050 @end smallexample
9051 @end iftex
9052 @end ifclear
9053
9054 (Symbols consist of more than pairs of addresses, but the structure of
9055 a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9056 consists of a group of address-boxes, one of which is the address of
9057 the printed word @samp{bouquet}, a second of which is the address of a
9058 function definition attached to the symbol, if any, a third of which
9059 is the address of the first pair of address-boxes for the list
9060 @code{(rose violet buttercup)}, and so on. Here we are showing that
9061 the symbol's third address-box points to the first pair of
9062 address-boxes for the list.)
9063
9064 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9065 changed; the symbol simply has an address further down the list. (In
9066 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9067 evaluation of the following expression
9068
9069 @smallexample
9070 (setq flowers (cdr bouquet))
9071 @end smallexample
9072
9073 @need 800
9074 @noindent
9075 produces this:
9076
9077 @c cons-cell-diagram #3
9078 @ifnottex
9079 @sp 1
9080 @smallexample
9081 @group
9082 bouquet flowers
9083 | |
9084 | ___ ___ | ___ ___ ___ ___
9085 --> | | | --> | | | | | |
9086 |___|___|----> |___|___|--> |___|___|--> nil
9087 | | |
9088 | | |
9089 --> rose --> violet --> buttercup
9090 @end group
9091 @end smallexample
9092 @sp 1
9093 @end ifnottex
9094 @ifset print-postscript-figures
9095 @sp 1
9096 @tex
9097 @image{cons-3}
9098 %%%% old method of including an image
9099 % \input /usr/local/lib/tex/inputs/psfig.tex
9100 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9101 % \catcode`\@=0 %
9102 @end tex
9103 @sp 1
9104 @end ifset
9105 @ifclear print-postscript-figures
9106 @iftex
9107 @sp 1
9108 @smallexample
9109 @group
9110 bouquet flowers
9111 | |
9112 | ___ ___ | ___ ___ ___ ___
9113 --> | | | --> | | | | | |
9114 |___|___|----> |___|___|--> |___|___|--> nil
9115 | | |
9116 | | |
9117 --> rose --> violet --> buttercup
9118 @end group
9119 @end smallexample
9120 @sp 1
9121 @end iftex
9122 @end ifclear
9123
9124 @noindent
9125 The value of @code{flowers} is @code{(violet buttercup)}, which is
9126 to say, the symbol @code{flowers} holds the address of the pair of
9127 address-boxes, the first of which holds the address of @code{violet},
9128 and the second of which holds the address of @code{buttercup}.
9129
9130 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9131 pair}. @xref{List Type, , List Type , elisp, The GNU Emacs Lisp
9132 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9133 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9134 information about cons cells and dotted pairs.
9135
9136 @need 1200
9137 The function @code{cons} adds a new pair of addresses to the front of
9138 a series of addresses like that shown above. For example, evaluating
9139 the expression
9140
9141 @smallexample
9142 (setq bouquet (cons 'lily bouquet))
9143 @end smallexample
9144
9145 @need 1500
9146 @noindent
9147 produces:
9148
9149 @c cons-cell-diagram #4
9150 @ifnottex
9151 @sp 1
9152 @smallexample
9153 @group
9154 bouquet flowers
9155 | |
9156 | ___ ___ ___ ___ | ___ ___ ___ ___
9157 --> | | | | | | --> | | | | | |
9158 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9159 | | | |
9160 | | | |
9161 --> lily --> rose --> violet --> buttercup
9162 @end group
9163 @end smallexample
9164 @sp 1
9165 @end ifnottex
9166 @ifset print-postscript-figures
9167 @sp 1
9168 @tex
9169 @image{cons-4}
9170 %%%% old method of including an image
9171 % \input /usr/local/lib/tex/inputs/psfig.tex
9172 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9173 % \catcode`\@=0 %
9174 @end tex
9175 @sp 1
9176 @end ifset
9177 @ifclear print-postscript-figures
9178 @iftex
9179 @sp 1
9180 @smallexample
9181 @group
9182 bouquet flowers
9183 | |
9184 | ___ ___ ___ ___ | ___ ___ ___ ___
9185 --> | | | | | | --> | | | | | |
9186 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9187 | | | |
9188 | | | |
9189 --> lily --> rose --> violet --> buttercup
9190 @end group
9191 @end smallexample
9192 @sp 1
9193 @end iftex
9194 @end ifclear
9195
9196 @need 1200
9197 @noindent
9198 However, this does not change the value of the symbol
9199 @code{flowers}, as you can see by evaluating the following,
9200
9201 @smallexample
9202 (eq (cdr (cdr bouquet)) flowers)
9203 @end smallexample
9204
9205 @noindent
9206 which returns @code{t} for true.
9207
9208 Until it is reset, @code{flowers} still has the value
9209 @code{(violet buttercup)}; that is, it has the address of the cons
9210 cell whose first address is of @code{violet}. Also, this does not
9211 alter any of the pre-existing cons cells; they are all still there.
9212
9213 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9214 of the next cons cell in the series; to get the @sc{car} of a list,
9215 you get the address of the first element of the list; to @code{cons} a
9216 new element on a list, you add a new cons cell to the front of the list.
9217 That is all there is to it! The underlying structure of Lisp is
9218 brilliantly simple!
9219
9220 And what does the last address in a series of cons cells refer to? It
9221 is the address of the empty list, of @code{nil}.
9222
9223 In summary, when a Lisp variable is set to a value, it is provided with
9224 the address of the list to which the variable refers.
9225
9226 @node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9227 @section Symbols as a Chest of Drawers
9228 @cindex Symbols as a Chest of Drawers
9229 @cindex Chest of Drawers, metaphor for a symbol
9230 @cindex Drawers, Chest of, metaphor for a symbol
9231
9232 In an earlier section, I suggested that you might imagine a symbol as
9233 being a chest of drawers. The function definition is put in one
9234 drawer, the value in another, and so on. What is put in the drawer
9235 holding the value can be changed without affecting the contents of the
9236 drawer holding the function definition, and vice-versa.
9237
9238 Actually, what is put in each drawer is the address of the value or
9239 function definition. It is as if you found an old chest in the attic,
9240 and in one of its drawers you found a map giving you directions to
9241 where the buried treasure lies.
9242
9243 (In addition to its name, symbol definition, and variable value, a
9244 symbol has a `drawer' for a @dfn{property list} which can be used to
9245 record other information. Property lists are not discussed here; see
9246 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9247 Reference Manual}.)
9248
9249 @need 1500
9250 Here is a fanciful representation:
9251
9252 @c chest-of-drawers diagram
9253 @ifnottex
9254 @sp 1
9255 @smallexample
9256 @group
9257 Chest of Drawers Contents of Drawers
9258
9259 __ o0O0o __
9260 / \
9261 ---------------------
9262 | directions to | [map to]
9263 | symbol name | bouquet
9264 | |
9265 +---------------------+
9266 | directions to |
9267 | symbol definition | [none]
9268 | |
9269 +---------------------+
9270 | directions to | [map to]
9271 | variable value | (rose violet buttercup)
9272 | |
9273 +---------------------+
9274 | directions to |
9275 | property list | [not described here]
9276 | |
9277 +---------------------+
9278 |/ \|
9279 @end group
9280 @end smallexample
9281 @sp 1
9282 @end ifnottex
9283 @ifset print-postscript-figures
9284 @sp 1
9285 @tex
9286 @image{drawers}
9287 %%%% old method of including an image
9288 % \input /usr/local/lib/tex/inputs/psfig.tex
9289 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9290 % \catcode`\@=0 %
9291 @end tex
9292 @sp 1
9293 @end ifset
9294 @ifclear print-postscript-figures
9295 @iftex
9296 @sp 1
9297 @smallexample
9298 @group
9299 Chest of Drawers Contents of Drawers
9300
9301 __ o0O0o __
9302 / \
9303 ---------------------
9304 | directions to | [map to]
9305 | symbol name | bouquet
9306 | |
9307 +---------------------+
9308 | directions to |
9309 | symbol definition | [none]
9310 | |
9311 +---------------------+
9312 | directions to | [map to]
9313 | variable value | (rose violet buttercup)
9314 | |
9315 +---------------------+
9316 | directions to |
9317 | property list | [not described here]
9318 | |
9319 +---------------------+
9320 |/ \|
9321 @end group
9322 @end smallexample
9323 @sp 1
9324 @end iftex
9325 @end ifclear
9326
9327 @node List Exercise, , Symbols as Chest, List Implementation
9328 @section Exercise
9329
9330 Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
9331 more flowers on to this list and set this new list to
9332 @code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
9333 What does the @code{more-flowers} list now contain?
9334
9335 @node Yanking, Loops & Recursion, List Implementation, Top
9336 @comment node-name, next, previous, up
9337 @chapter Yanking Text Back
9338 @findex yank
9339 @findex rotate-yank-pointer
9340 @cindex Text retrieval
9341 @cindex Retrieving text
9342 @cindex Pasting text
9343
9344 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9345 you can bring it back with a `yank' command. The text that is cut out of
9346 the buffer is put in the kill ring and the yank commands insert the
9347 appropriate contents of the kill ring back into a buffer (not necessarily
9348 the original buffer).
9349
9350 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9351 the kill ring into the current buffer. If the @kbd{C-y} command is
9352 followed immediately by @kbd{M-y}, the first element is replaced by
9353 the second element. Successive @kbd{M-y} commands replace the second
9354 element with the third, fourth, or fifth element, and so on. When the
9355 last element in the kill ring is reached, it is replaced by the first
9356 element and the cycle is repeated. (Thus the kill ring is called a
9357 `ring' rather than just a `list'. However, the actual data structure
9358 that holds the text is a list.
9359 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9360 list is handled as a ring.)
9361
9362 @menu
9363 * Kill Ring Overview:: The kill ring is a list.
9364 * kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
9365 * yank nthcdr Exercises::
9366 @end menu
9367
9368 @node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9369 @comment node-name, next, previous, up
9370 @section Kill Ring Overview
9371 @cindex Kill ring overview
9372
9373 The kill ring is a list of textual strings. This is what it looks like:
9374
9375 @smallexample
9376 ("some text" "a different piece of text" "yet more text")
9377 @end smallexample
9378
9379 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9380 string of characters saying @samp{some text} would be inserted in this
9381 buffer where my cursor is located.
9382
9383 The @code{yank} command is also used for duplicating text by copying it.
9384 The copied text is not cut from the buffer, but a copy of it is put on the
9385 kill ring and is inserted by yanking it back.
9386
9387 Three functions are used for bringing text back from the kill ring:
9388 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9389 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9390 which is used by the two other functions.
9391
9392 These functions refer to the kill ring through a variable called the
9393 @code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
9394 @code{yank} and @code{yank-pop} functions is:
9395
9396 @smallexample
9397 (insert (car kill-ring-yank-pointer))
9398 @end smallexample
9399
9400 To begin to understand how @code{yank} and @code{yank-pop} work, it is
9401 first necessary to look at the @code{kill-ring-yank-pointer} variable
9402 and the @code{rotate-yank-pointer} function.
9403
9404 @node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9405 @comment node-name, next, previous, up
9406 @section The @code{kill-ring-yank-pointer} Variable
9407
9408 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9409 a variable. It points to something by being bound to the value of what
9410 it points to, like any other Lisp variable.
9411
9412 @need 1000
9413 Thus, if the value of the kill ring is:
9414
9415 @smallexample
9416 ("some text" "a different piece of text" "yet more text")
9417 @end smallexample
9418
9419 @need 1250
9420 @noindent
9421 and the @code{kill-ring-yank-pointer} points to the second clause, the
9422 value of @code{kill-ring-yank-pointer} is:
9423
9424 @smallexample
9425 ("a different piece of text" "yet more text")
9426 @end smallexample
9427
9428 As explained in the previous chapter (@pxref{List Implementation}), the
9429 computer does not keep two different copies of the text being pointed to
9430 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
9431 words ``a different piece of text'' and ``yet more text'' are not
9432 duplicated. Instead, the two Lisp variables point to the same pieces of
9433 text. Here is a diagram:
9434
9435 @c cons-cell-diagram #5
9436 @ifnottex
9437 @smallexample
9438 @group
9439 kill-ring kill-ring-yank-pointer
9440 | |
9441 | ___ ___ | ___ ___ ___ ___
9442 ---> | | | --> | | | | | |
9443 |___|___|----> |___|___|--> |___|___|--> nil
9444 | | |
9445 | | |
9446 | | --> "yet more text"
9447 | |
9448 | --> "a different piece of text
9449 |
9450 --> "some text"
9451 @end group
9452 @end smallexample
9453 @sp 1
9454 @end ifnottex
9455 @ifset print-postscript-figures
9456 @sp 1
9457 @tex
9458 @image{cons-5}
9459 %%%% old method of including an image
9460 % \input /usr/local/lib/tex/inputs/psfig.tex
9461 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9462 % \catcode`\@=0 %
9463 @end tex
9464 @sp 1
9465 @end ifset
9466 @ifclear print-postscript-figures
9467 @iftex
9468 @smallexample
9469 @group
9470 kill-ring kill-ring-yank-pointer
9471 | |
9472 | ___ ___ | ___ ___ ___ ___
9473 ---> | | | --> | | | | | |
9474 |___|___|----> |___|___|--> |___|___|--> nil
9475 | | |
9476 | | |
9477 | | --> "yet more text"
9478 | |
9479 | --> "a different piece of text
9480 |
9481 --> "some text"
9482 @end group
9483 @end smallexample
9484 @sp 1
9485 @end iftex
9486 @end ifclear
9487
9488 Both the variable @code{kill-ring} and the variable
9489 @code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
9490 usually described as if it were actually what it is composed of. The
9491 @code{kill-ring} is spoken of as if it were the list rather than that it
9492 points to the list. Conversely, the @code{kill-ring-yank-pointer} is
9493 spoken of as pointing to a list.
9494
9495 These two ways of talking about the same thing sound confusing at first but
9496 make sense on reflection. The kill ring is generally thought of as the
9497 complete structure of data that holds the information of what has recently
9498 been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
9499 on the other hand, serves to indicate---that is, to `point to'---that part
9500 of the kill ring of which the first element (the @sc{car}) will be
9501 inserted.
9502
9503 The @code{rotate-yank-pointer} function changes the element in the
9504 kill ring to which the @code{kill-ring-yank-pointer} points; when the
9505 pointer is set to point to the next element beyond the end of the kill
9506 ring, it automatically sets it to point to the first element of the
9507 kill ring. This is how the list is transformed into a ring. The
9508 @code{rotate-yank-pointer} function itself is not difficult, but
9509 contains many details. It and the much simpler @code{yank} and
9510 @code{yank-pop} functions are described in an appendix.
9511 @xref{Kill Ring, , Handling the Kill Ring}.
9512
9513 @need 1500
9514 @node yank nthcdr Exercises, , kill-ring-yank-pointer, Yanking
9515 @section Exercises with @code{yank} and @code{nthcdr}
9516
9517 @itemize @bullet
9518 @item
9519 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9520 your kill ring. Add several items to your kill ring; look at its
9521 value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
9522 around the kill ring. How many items were in your kill ring? Find
9523 the value of @code{kill-ring-max}. Was your kill ring full, or could
9524 you have kept more blocks of text within it?
9525
9526 @item
9527 Using @code{nthcdr} and @code{car}, construct a series of expressions
9528 to return the first, second, third, and fourth elements of a list.
9529 @end itemize
9530
9531 @node Loops & Recursion, Regexp Search, Yanking, Top
9532 @comment node-name, next, previous, up
9533 @chapter Loops and Recursion
9534 @cindex Loops and recursion
9535 @cindex Recursion and loops
9536 @cindex Repetition (loops)
9537
9538 Emacs Lisp has two primary ways to cause an expression, or a series of
9539 expressions, to be evaluated repeatedly: one uses a @code{while}
9540 loop, and the other uses @dfn{recursion}.
9541
9542 Repetition can be very valuable. For example, to move forward four
9543 sentences, you need only write a program that will move forward one
9544 sentence and then repeat the process four times. Since a computer does
9545 not get bored or tired, such repetitive action does not have the
9546 deleterious effects that excessive or the wrong kinds of repetition can
9547 have on humans.
9548
9549 People mostly write Emacs Lisp functions using @code{while} loops and
9550 their kin; but you can use recursion, which provides a very powerful
9551 way to think about and then to solve problems@footnote{You can write
9552 recursive functions to be frugal or wasteful of mental or computer
9553 resources; as it happens, methods that people find easy---that are
9554 frugal of `mental resources'---sometimes use considerable computer
9555 resources. Emacs was designed to run on machines that we now consider
9556 limited and its default settings are conservative. You may want to
9557 increase the values of @code{max-specpdl-size} and
9558 @code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
9559 15 and 30 times their default value.}.
9560
9561 @menu
9562 * while:: Causing a stretch of code to repeat.
9563 * dolist dotimes::
9564 * Recursion:: Causing a function to call itself.
9565 * Looping exercise::
9566 @end menu
9567
9568 @node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9569 @comment node-name, next, previous, up
9570 @section @code{while}
9571 @cindex Loops
9572 @findex while
9573
9574 The @code{while} special form tests whether the value returned by
9575 evaluating its first argument is true or false. This is similar to what
9576 the Lisp interpreter does with an @code{if}; what the interpreter does
9577 next, however, is different.
9578
9579 In a @code{while} expression, if the value returned by evaluating the
9580 first argument is false, the Lisp interpreter skips the rest of the
9581 expression (the @dfn{body} of the expression) and does not evaluate it.
9582 However, if the value is true, the Lisp interpreter evaluates the body
9583 of the expression and then again tests whether the first argument to
9584 @code{while} is true or false. If the value returned by evaluating the
9585 first argument is again true, the Lisp interpreter again evaluates the
9586 body of the expression.
9587
9588 @need 1200
9589 The template for a @code{while} expression looks like this:
9590
9591 @smallexample
9592 @group
9593 (while @var{true-or-false-test}
9594 @var{body}@dots{})
9595 @end group
9596 @end smallexample
9597
9598 @menu
9599 * Looping with while:: Repeat so long as test returns true.
9600 * Loop Example:: A @code{while} loop that uses a list.
9601 * print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
9602 * Incrementing Loop:: A loop with an incrementing counter.
9603 * Decrementing Loop:: A loop with a decrementing counter.
9604 @end menu
9605
9606 @node Looping with while, Loop Example, while, while
9607 @ifnottex
9608 @unnumberedsubsec Looping with @code{while}
9609 @end ifnottex
9610
9611 So long as the true-or-false-test of the @code{while} expression
9612 returns a true value when it is evaluated, the body is repeatedly
9613 evaluated. This process is called a loop since the Lisp interpreter
9614 repeats the same thing again and again, like an airplane doing a loop.
9615 When the result of evaluating the true-or-false-test is false, the
9616 Lisp interpreter does not evaluate the rest of the @code{while}
9617 expression and `exits the loop'.
9618
9619 Clearly, if the value returned by evaluating the first argument to
9620 @code{while} is always true, the body following will be evaluated
9621 again and again @dots{} and again @dots{} forever. Conversely, if the
9622 value returned is never true, the expressions in the body will never
9623 be evaluated. The craft of writing a @code{while} loop consists of
9624 choosing a mechanism such that the true-or-false-test returns true
9625 just the number of times that you want the subsequent expressions to
9626 be evaluated, and then have the test return false.
9627
9628 The value returned by evaluating a @code{while} is the value of the
9629 true-or-false-test. An interesting consequence of this is that a
9630 @code{while} loop that evaluates without error will return @code{nil}
9631 or false regardless of whether it has looped 1 or 100 times or none at
9632 all. A @code{while} expression that evaluates successfully never
9633 returns a true value! What this means is that @code{while} is always
9634 evaluated for its side effects, which is to say, the consequences of
9635 evaluating the expressions within the body of the @code{while} loop.
9636 This makes sense. It is not the mere act of looping that is desired,
9637 but the consequences of what happens when the expressions in the loop
9638 are repeatedly evaluated.
9639
9640 @node Loop Example, print-elements-of-list, Looping with while, while
9641 @comment node-name, next, previous, up
9642 @subsection A @code{while} Loop and a List
9643
9644 A common way to control a @code{while} loop is to test whether a list
9645 has any elements. If it does, the loop is repeated; but if it does not,
9646 the repetition is ended. Since this is an important technique, we will
9647 create a short example to illustrate it.
9648
9649 A simple way to test whether a list has elements is to evaluate the
9650 list: if it has no elements, it is an empty list and will return the
9651 empty list, @code{()}, which is a synonym for @code{nil} or false. On
9652 the other hand, a list with elements will return those elements when it
9653 is evaluated. Since Emacs Lisp considers as true any value that is not
9654 @code{nil}, a list that returns elements will test true in a
9655 @code{while} loop.
9656
9657 @need 1200
9658 For example, you can set the variable @code{empty-list} to @code{nil} by
9659 evaluating the following @code{setq} expression:
9660
9661 @smallexample
9662 (setq empty-list ())
9663 @end smallexample
9664
9665 @noindent
9666 After evaluating the @code{setq} expression, you can evaluate the
9667 variable @code{empty-list} in the usual way, by placing the cursor after
9668 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9669 echo area:
9670
9671 @smallexample
9672 empty-list
9673 @end smallexample
9674
9675 On the other hand, if you set a variable to be a list with elements, the
9676 list will appear when you evaluate the variable, as you can see by
9677 evaluating the following two expressions:
9678
9679 @smallexample
9680 @group
9681 (setq animals '(gazelle giraffe lion tiger))
9682
9683 animals
9684 @end group
9685 @end smallexample
9686
9687 Thus, to create a @code{while} loop that tests whether there are any
9688 items in the list @code{animals}, the first part of the loop will be
9689 written like this:
9690
9691 @smallexample
9692 @group
9693 (while animals
9694 @dots{}
9695 @end group
9696 @end smallexample
9697
9698 @noindent
9699 When the @code{while} tests its first argument, the variable
9700 @code{animals} is evaluated. It returns a list. So long as the list
9701 has elements, the @code{while} considers the results of the test to be
9702 true; but when the list is empty, it considers the results of the test
9703 to be false.
9704
9705 To prevent the @code{while} loop from running forever, some mechanism
9706 needs to be provided to empty the list eventually. An oft-used
9707 technique is to have one of the subsequent forms in the @code{while}
9708 expression set the value of the list to be the @sc{cdr} of the list.
9709 Each time the @code{cdr} function is evaluated, the list will be made
9710 shorter, until eventually only the empty list will be left. At this
9711 point, the test of the @code{while} loop will return false, and the
9712 arguments to the @code{while} will no longer be evaluated.
9713
9714 For example, the list of animals bound to the variable @code{animals}
9715 can be set to be the @sc{cdr} of the original list with the
9716 following expression:
9717
9718 @smallexample
9719 (setq animals (cdr animals))
9720 @end smallexample
9721
9722 @noindent
9723 If you have evaluated the previous expressions and then evaluate this
9724 expression, you will see @code{(giraffe lion tiger)} appear in the echo
9725 area. If you evaluate the expression again, @code{(lion tiger)} will
9726 appear in the echo area. If you evaluate it again and yet again,
9727 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
9728
9729 A template for a @code{while} loop that uses the @code{cdr} function
9730 repeatedly to cause the true-or-false-test eventually to test false
9731 looks like this:
9732
9733 @smallexample
9734 @group
9735 (while @var{test-whether-list-is-empty}
9736 @var{body}@dots{}
9737 @var{set-list-to-cdr-of-list})
9738 @end group
9739 @end smallexample
9740
9741 This test and use of @code{cdr} can be put together in a function that
9742 goes through a list and prints each element of the list on a line of its
9743 own.
9744
9745 @node print-elements-of-list, Incrementing Loop, Loop Example, while
9746 @subsection An Example: @code{print-elements-of-list}
9747 @findex print-elements-of-list
9748
9749 The @code{print-elements-of-list} function illustrates a @code{while}
9750 loop with a list.
9751
9752 @cindex @file{*scratch*} buffer
9753 The function requires several lines for its output. If you are
9754 reading this in Emacs 21 or a later version, you can evaluate the
9755 following expression inside of Info, as usual.
9756
9757 If you are using an earlier version of Emacs, you need to copy the
9758 necessary expressions to your @file{*scratch*} buffer and evaluate
9759 them there. This is because the echo area had only one line in the
9760 earlier versions.
9761
9762 You can copy the expressions by marking the beginning of the region
9763 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9764 the end of the region and then copying the region using @kbd{M-w}
9765 (@code{copy-region-as-kill}). In the @file{*scratch*} buffer, you can
9766 yank the expressions back by typing @kbd{C-y} (@code{yank}).
9767
9768 After you have copied the expressions to the @file{*scratch*} buffer,
9769 evaluate each expression in turn. Be sure to evaluate the last
9770 expression, @code{(print-elements-of-list animals)}, by typing
9771 @kbd{C-u C-x C-e}, that is, by giving an argument to
9772 @code{eval-last-sexp}. This will cause the result of the evaluation
9773 to be printed in the @file{*scratch*} buffer instead of being printed
9774 in the echo area. (Otherwise you will see something like this in your
9775 echo area: @code{^Jgiraffe^J^Jgazelle^J^Jlion^J^Jtiger^Jnil}, in which
9776 each @samp{^J} stands for a `newline'.)
9777
9778 @need 1500
9779 If you are using Emacs 21 or later, you can evaluate these expressions
9780 directly in the Info buffer, and the echo area will grow to show the
9781 results.
9782
9783 @smallexample
9784 @group
9785 (setq animals '(gazelle giraffe lion tiger))
9786
9787 (defun print-elements-of-list (list)
9788 "Print each element of LIST on a line of its own."
9789 (while list
9790 (print (car list))
9791 (setq list (cdr list))))
9792
9793 (print-elements-of-list animals)
9794 @end group
9795 @end smallexample
9796
9797 @need 1200
9798 @noindent
9799 When you evaluate the three expressions in sequence, you will see
9800 this:
9801
9802 @smallexample
9803 @group
9804 giraffe
9805
9806 gazelle
9807
9808 lion
9809
9810 tiger
9811 nil
9812 @end group
9813 @end smallexample
9814
9815 Each element of the list is printed on a line of its own (that is what
9816 the function @code{print} does) and then the value returned by the
9817 function is printed. Since the last expression in the function is the
9818 @code{while} loop, and since @code{while} loops always return
9819 @code{nil}, a @code{nil} is printed after the last element of the list.
9820
9821 @node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9822 @comment node-name, next, previous, up
9823 @subsection A Loop with an Incrementing Counter
9824
9825 A loop is not useful unless it stops when it ought. Besides
9826 controlling a loop with a list, a common way of stopping a loop is to
9827 write the first argument as a test that returns false when the correct
9828 number of repetitions are complete. This means that the loop must
9829 have a counter---an expression that counts how many times the loop
9830 repeats itself.
9831
9832 The test can be an expression such as @code{(< count desired-number)}
9833 which returns @code{t} for true if the value of @code{count} is less
9834 than the @code{desired-number} of repetitions and @code{nil} for false if
9835 the value of @code{count} is equal to or is greater than the
9836 @code{desired-number}. The expression that increments the count can be
9837 a simple @code{setq} such as @code{(setq count (1+ count))}, where
9838 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
9839 argument. (The expression @code{(1+ count)} has the same result as
9840 @code{(+ count 1)}, but is easier for a human to read.)
9841
9842 @need 1250
9843 The template for a @code{while} loop controlled by an incrementing
9844 counter looks like this:
9845
9846 @smallexample
9847 @group
9848 @var{set-count-to-initial-value}
9849 (while (< count desired-number) ; @r{true-or-false-test}
9850 @var{body}@dots{}
9851 (setq count (1+ count))) ; @r{incrementer}
9852 @end group
9853 @end smallexample
9854
9855 @noindent
9856 Note that you need to set the initial value of @code{count}; usually it
9857 is set to 1.
9858
9859 @menu
9860 * Incrementing Example:: Counting pebbles in a triangle.
9861 * Inc Example parts:: The parts of the function definition.
9862 * Inc Example altogether:: Putting the function definition together.
9863 @end menu
9864
9865 @node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9866 @unnumberedsubsubsec Example with incrementing counter
9867
9868 Suppose you are playing on the beach and decide to make a triangle of
9869 pebbles, putting one pebble in the first row, two in the second row,
9870 three in the third row and so on, like this:
9871
9872 @sp 1
9873 @c pebble diagram
9874 @ifnottex
9875 @smallexample
9876 @group
9877 *
9878 * *
9879 * * *
9880 * * * *
9881 @end group
9882 @end smallexample
9883 @end ifnottex
9884 @iftex
9885 @smallexample
9886 @group
9887 @bullet{}
9888 @bullet{} @bullet{}
9889 @bullet{} @bullet{} @bullet{}
9890 @bullet{} @bullet{} @bullet{} @bullet{}
9891 @end group
9892 @end smallexample
9893 @end iftex
9894 @sp 1
9895
9896 @noindent
9897 (About 2500 years ago, Pythagoras and others developed the beginnings of
9898 number theory by considering questions such as this.)
9899
9900 Suppose you want to know how many pebbles you will need to make a
9901 triangle with 7 rows?
9902
9903 Clearly, what you need to do is add up the numbers from 1 to 7. There
9904 are two ways to do this; start with the smallest number, one, and add up
9905 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9906 number and add the list going down: 7, 6, 5, 4 and so on. Because both
9907 mechanisms illustrate common ways of writing @code{while} loops, we will
9908 create two examples, one counting up and the other counting down. In
9909 this first example, we will start with 1 and add 2, 3, 4 and so on.
9910
9911 If you are just adding up a short list of numbers, the easiest way to do
9912 it is to add up all the numbers at once. However, if you do not know
9913 ahead of time how many numbers your list will have, or if you want to be
9914 prepared for a very long list, then you need to design your addition so
9915 that what you do is repeat a simple process many times instead of doing
9916 a more complex process once.
9917
9918 For example, instead of adding up all the pebbles all at once, what you
9919 can do is add the number of pebbles in the first row, 1, to the number
9920 in the second row, 2, and then add the total of those two rows to the
9921 third row, 3. Then you can add the number in the fourth row, 4, to the
9922 total of the first three rows; and so on.
9923
9924 The critical characteristic of the process is that each repetitive
9925 action is simple. In this case, at each step we add only two numbers,
9926 the number of pebbles in the row and the total already found. This
9927 process of adding two numbers is repeated again and again until the last
9928 row has been added to the total of all the preceding rows. In a more
9929 complex loop the repetitive action might not be so simple, but it will
9930 be simpler than doing everything all at once.
9931
9932 @node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9933 @unnumberedsubsubsec The parts of the function definition
9934
9935 The preceding analysis gives us the bones of our function definition:
9936 first, we will need a variable that we can call @code{total} that will
9937 be the total number of pebbles. This will be the value returned by
9938 the function.
9939
9940 Second, we know that the function will require an argument: this
9941 argument will be the total number of rows in the triangle. It can be
9942 called @code{number-of-rows}.
9943
9944 Finally, we need a variable to use as a counter. We could call this
9945 variable @code{counter}, but a better name is @code{row-number}.
9946 That is because what the counter does is count rows, and a program
9947 should be written to be as understandable as possible.
9948
9949 When the Lisp interpreter first starts evaluating the expressions in the
9950 function, the value of @code{total} should be set to zero, since we have
9951 not added anything to it. Then the function should add the number of
9952 pebbles in the first row to the total, and then add the number of
9953 pebbles in the second to the total, and then add the number of
9954 pebbles in the third row to the total, and so on, until there are no
9955 more rows left to add.
9956
9957 Both @code{total} and @code{row-number} are used only inside the
9958 function, so they can be declared as local variables with @code{let}
9959 and given initial values. Clearly, the initial value for @code{total}
9960 should be 0. The initial value of @code{row-number} should be 1,
9961 since we start with the first row. This means that the @code{let}
9962 statement will look like this:
9963
9964 @smallexample
9965 @group
9966 (let ((total 0)
9967 (row-number 1))
9968 @var{body}@dots{})
9969 @end group
9970 @end smallexample
9971
9972 After the internal variables are declared and bound to their initial
9973 values, we can begin the @code{while} loop. The expression that serves
9974 as the test should return a value of @code{t} for true so long as the
9975 @code{row-number} is less than or equal to the @code{number-of-rows}.
9976 (If the expression tests true only so long as the row number is less
9977 than the number of rows in the triangle, the last row will never be
9978 added to the total; hence the row number has to be either less than or
9979 equal to the number of rows.)
9980
9981 @need 1500
9982 @findex <= @r{(less than or equal)}
9983 Lisp provides the @code{<=} function that returns true if the value of
9984 its first argument is less than or equal to the value of its second
9985 argument and false otherwise. So the expression that the @code{while}
9986 will evaluate as its test should look like this:
9987
9988 @smallexample
9989 (<= row-number number-of-rows)
9990 @end smallexample
9991
9992 The total number of pebbles can be found by repeatedly adding the number
9993 of pebbles in a row to the total already found. Since the number of
9994 pebbles in the row is equal to the row number, the total can be found by
9995 adding the row number to the total. (Clearly, in a more complex
9996 situation, the number of pebbles in the row might be related to the row
9997 number in a more complicated way; if this were the case, the row number
9998 would be replaced by the appropriate expression.)
9999
10000 @smallexample
10001 (setq total (+ total row-number))
10002 @end smallexample
10003
10004 @noindent
10005 What this does is set the new value of @code{total} to be equal to the
10006 sum of adding the number of pebbles in the row to the previous total.
10007
10008 After setting the value of @code{total}, the conditions need to be
10009 established for the next repetition of the loop, if there is one. This
10010 is done by incrementing the value of the @code{row-number} variable,
10011 which serves as a counter. After the @code{row-number} variable has
10012 been incremented, the true-or-false-test at the beginning of the
10013 @code{while} loop tests whether its value is still less than or equal to
10014 the value of the @code{number-of-rows} and if it is, adds the new value
10015 of the @code{row-number} variable to the @code{total} of the previous
10016 repetition of the loop.
10017
10018 @need 1200
10019 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10020 @code{row-number} variable can be incremented with this expression:
10021
10022 @smallexample
10023 (setq row-number (1+ row-number))
10024 @end smallexample
10025
10026 @node Inc Example altogether, , Inc Example parts, Incrementing Loop
10027 @unnumberedsubsubsec Putting the function definition together
10028
10029 We have created the parts for the function definition; now we need to
10030 put them together.
10031
10032 @need 800
10033 First, the contents of the @code{while} expression:
10034
10035 @smallexample
10036 @group
10037 (while (<= row-number number-of-rows) ; @r{true-or-false-test}
10038 (setq total (+ total row-number))
10039 (setq row-number (1+ row-number))) ; @r{incrementer}
10040 @end group
10041 @end smallexample
10042
10043 Along with the @code{let} expression varlist, this very nearly
10044 completes the body of the function definition. However, it requires
10045 one final element, the need for which is somewhat subtle.
10046
10047 The final touch is to place the variable @code{total} on a line by
10048 itself after the @code{while} expression. Otherwise, the value returned
10049 by the whole function is the value of the last expression that is
10050 evaluated in the body of the @code{let}, and this is the value
10051 returned by the @code{while}, which is always @code{nil}.
10052
10053 This may not be evident at first sight. It almost looks as if the
10054 incrementing expression is the last expression of the whole function.
10055 But that expression is part of the body of the @code{while}; it is the
10056 last element of the list that starts with the symbol @code{while}.
10057 Moreover, the whole of the @code{while} loop is a list within the body
10058 of the @code{let}.
10059
10060 @need 1250
10061 In outline, the function will look like this:
10062
10063 @smallexample
10064 @group
10065 (defun @var{name-of-function} (@var{argument-list})
10066 "@var{documentation}@dots{}"
10067 (let (@var{varlist})
10068 (while (@var{true-or-false-test})
10069 @var{body-of-while}@dots{} )
10070 @dots{} ) ; @r{Need final expression here.}
10071 @end group
10072 @end smallexample
10073
10074 The result of evaluating the @code{let} is what is going to be returned
10075 by the @code{defun} since the @code{let} is not embedded within any
10076 containing list, except for the @code{defun} as a whole. However, if
10077 the @code{while} is the last element of the @code{let} expression, the
10078 function will always return @code{nil}. This is not what we want!
10079 Instead, what we want is the value of the variable @code{total}. This
10080 is returned by simply placing the symbol as the last element of the list
10081 starting with @code{let}. It gets evaluated after the preceding
10082 elements of the list are evaluated, which means it gets evaluated after
10083 it has been assigned the correct value for the total.
10084
10085 It may be easier to see this by printing the list starting with
10086 @code{let} all on one line. This format makes it evident that the
10087 @var{varlist} and @code{while} expressions are the second and third
10088 elements of the list starting with @code{let}, and the @code{total} is
10089 the last element:
10090
10091 @smallexample
10092 @group
10093 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10094 @end group
10095 @end smallexample
10096
10097 @need 1200
10098 Putting everything together, the @code{triangle} function definition
10099 looks like this:
10100
10101 @smallexample
10102 @group
10103 (defun triangle (number-of-rows) ; @r{Version with}
10104 ; @r{ incrementing counter.}
10105 "Add up the number of pebbles in a triangle.
10106 The first row has one pebble, the second row two pebbles,
10107 the third row three pebbles, and so on.
10108 The argument is NUMBER-OF-ROWS."
10109 @end group
10110 @group
10111 (let ((total 0)
10112 (row-number 1))
10113 (while (<= row-number number-of-rows)
10114 (setq total (+ total row-number))
10115 (setq row-number (1+ row-number)))
10116 total))
10117 @end group
10118 @end smallexample
10119
10120 @need 1200
10121 After you have installed @code{triangle} by evaluating the function, you
10122 can try it out. Here are two examples:
10123
10124 @smallexample
10125 @group
10126 (triangle 4)
10127
10128 (triangle 7)
10129 @end group
10130 @end smallexample
10131
10132 @noindent
10133 The sum of the first four numbers is 10 and the sum of the first seven
10134 numbers is 28.
10135
10136 @node Decrementing Loop, , Incrementing Loop, while
10137 @comment node-name, next, previous, up
10138 @subsection Loop with a Decrementing Counter
10139
10140 Another common way to write a @code{while} loop is to write the test
10141 so that it determines whether a counter is greater than zero. So long
10142 as the counter is greater than zero, the loop is repeated. But when
10143 the counter is equal to or less than zero, the loop is stopped. For
10144 this to work, the counter has to start out greater than zero and then
10145 be made smaller and smaller by a form that is evaluated
10146 repeatedly.
10147
10148 The test will be an expression such as @code{(> counter 0)} which
10149 returns @code{t} for true if the value of @code{counter} is greater
10150 than zero, and @code{nil} for false if the value of @code{counter} is
10151 equal to or less than zero. The expression that makes the number
10152 smaller and smaller can be a simple @code{setq} such as @code{(setq
10153 counter (1- counter))}, where @code{1-} is a built-in function in
10154 Emacs Lisp that subtracts 1 from its argument.
10155
10156 @need 1250
10157 The template for a decrementing @code{while} loop looks like this:
10158
10159 @smallexample
10160 @group
10161 (while (> counter 0) ; @r{true-or-false-test}
10162 @var{body}@dots{}
10163 (setq counter (1- counter))) ; @r{decrementer}
10164 @end group
10165 @end smallexample
10166
10167 @menu
10168 * Decrementing Example:: More pebbles on the beach.
10169 * Dec Example parts:: The parts of the function definition.
10170 * Dec Example altogether:: Putting the function definition together.
10171 @end menu
10172
10173 @node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10174 @unnumberedsubsubsec Example with decrementing counter
10175
10176 To illustrate a loop with a decrementing counter, we will rewrite the
10177 @code{triangle} function so the counter decreases to zero.
10178
10179 This is the reverse of the earlier version of the function. In this
10180 case, to find out how many pebbles are needed to make a triangle with
10181 3 rows, add the number of pebbles in the third row, 3, to the number
10182 in the preceding row, 2, and then add the total of those two rows to
10183 the row that precedes them, which is 1.
10184
10185 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10186 the number of pebbles in the seventh row, 7, to the number in the
10187 preceding row, which is 6, and then add the total of those two rows to
10188 the row that precedes them, which is 5, and so on. As in the previous
10189 example, each addition only involves adding two numbers, the total of
10190 the rows already added up and the number of pebbles in the row that is
10191 being added to the total. This process of adding two numbers is
10192 repeated again and again until there are no more pebbles to add.
10193
10194 We know how many pebbles to start with: the number of pebbles in the
10195 last row is equal to the number of rows. If the triangle has seven
10196 rows, the number of pebbles in the last row is 7. Likewise, we know how
10197 many pebbles are in the preceding row: it is one less than the number in
10198 the row.
10199
10200 @node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10201 @unnumberedsubsubsec The parts of the function definition
10202
10203 We start with three variables: the total number of rows in the
10204 triangle; the number of pebbles in a row; and the total number of
10205 pebbles, which is what we want to calculate. These variables can be
10206 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10207 @code{total}, respectively.
10208
10209 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10210 inside the function and are declared with @code{let}. The initial
10211 value of @code{total} should, of course, be zero. However, the
10212 initial value of @code{number-of-pebbles-in-row} should be equal to
10213 the number of rows in the triangle, since the addition will start with
10214 the longest row.
10215
10216 @need 1250
10217 This means that the beginning of the @code{let} expression will look
10218 like this:
10219
10220 @smallexample
10221 @group
10222 (let ((total 0)
10223 (number-of-pebbles-in-row number-of-rows))
10224 @var{body}@dots{})
10225 @end group
10226 @end smallexample
10227
10228 The total number of pebbles can be found by repeatedly adding the number
10229 of pebbles in a row to the total already found, that is, by repeatedly
10230 evaluating the following expression:
10231
10232 @smallexample
10233 (setq total (+ total number-of-pebbles-in-row))
10234 @end smallexample
10235
10236 @noindent
10237 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10238 the @code{number-of-pebbles-in-row} should be decremented by one, since
10239 the next time the loop repeats, the preceding row will be
10240 added to the total.
10241
10242 The number of pebbles in a preceding row is one less than the number of
10243 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10244 used to compute the number of pebbles in the preceding row. This can be
10245 done with the following expression:
10246
10247 @smallexample
10248 @group
10249 (setq number-of-pebbles-in-row
10250 (1- number-of-pebbles-in-row))
10251 @end group
10252 @end smallexample
10253
10254 Finally, we know that the @code{while} loop should stop making repeated
10255 additions when there are no pebbles in a row. So the test for
10256 the @code{while} loop is simply:
10257
10258 @smallexample
10259 (while (> number-of-pebbles-in-row 0)
10260 @end smallexample
10261
10262 @node Dec Example altogether, , Dec Example parts, Decrementing Loop
10263 @unnumberedsubsubsec Putting the function definition together
10264
10265 We can put these expressions together to create a function definition
10266 that works. However, on examination, we find that one of the local
10267 variables is unneeded!
10268
10269 @need 1250
10270 The function definition looks like this:
10271
10272 @smallexample
10273 @group
10274 ;;; @r{First subtractive version.}
10275 (defun triangle (number-of-rows)
10276 "Add up the number of pebbles in a triangle."
10277 (let ((total 0)
10278 (number-of-pebbles-in-row number-of-rows))
10279 (while (> number-of-pebbles-in-row 0)
10280 (setq total (+ total number-of-pebbles-in-row))
10281 (setq number-of-pebbles-in-row
10282 (1- number-of-pebbles-in-row)))
10283 total))
10284 @end group
10285 @end smallexample
10286
10287 As written, this function works.
10288
10289 However, we do not need @code{number-of-pebbles-in-row}.
10290
10291 @cindex Argument as local variable
10292 When the @code{triangle} function is evaluated, the symbol
10293 @code{number-of-rows} will be bound to a number, giving it an initial
10294 value. That number can be changed in the body of the function as if
10295 it were a local variable, without any fear that such a change will
10296 effect the value of the variable outside of the function. This is a
10297 very useful characteristic of Lisp; it means that the variable
10298 @code{number-of-rows} can be used anywhere in the function where
10299 @code{number-of-pebbles-in-row} is used.
10300
10301 @need 800
10302 Here is a second version of the function written a bit more cleanly:
10303
10304 @smallexample
10305 @group
10306 (defun triangle (number) ; @r{Second version.}
10307 "Return sum of numbers 1 through NUMBER inclusive."
10308 (let ((total 0))
10309 (while (> number 0)
10310 (setq total (+ total number))
10311 (setq number (1- number)))
10312 total))
10313 @end group
10314 @end smallexample
10315
10316 In brief, a properly written @code{while} loop will consist of three parts:
10317
10318 @enumerate
10319 @item
10320 A test that will return false after the loop has repeated itself the
10321 correct number of times.
10322
10323 @item
10324 An expression the evaluation of which will return the value desired
10325 after being repeatedly evaluated.
10326
10327 @item
10328 An expression to change the value passed to the true-or-false-test so
10329 that the test returns false after the loop has repeated itself the right
10330 number of times.
10331 @end enumerate
10332
10333 @node dolist dotimes, Recursion, while, Loops & Recursion
10334 @comment node-name, next, previous, up
10335 @section Save your time: @code{dolist} and @code{dotimes}
10336
10337 In addition to @code{while}, both @code{dolist} and @code{dotimes}
10338 provide for looping. Sometimes these are quicker to write than the
10339 equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
10340 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10341
10342 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10343 list': @code{dolist} automatically shortens the list each time it
10344 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10345 each shorter version of the list to the first of its arguments.
10346
10347 @code{dotimes} loops a specific number of time: you specify the number.
10348
10349 @menu
10350 * dolist::
10351 * dotimes::
10352 @end menu
10353
10354 @node dolist, dotimes, dolist dotimes, dolist dotimes
10355 @unnumberedsubsubsec The @code{dolist} Macro
10356 @findex dolist
10357
10358 Suppose, for example, you want to reverse a list, so that
10359 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10360
10361 @need 1250
10362 In practice, you would use the @code{reverse} function, like this:
10363
10364 @smallexample
10365 @group
10366 (setq animals '(gazelle giraffe lion tiger))
10367
10368 (reverse animals)
10369 @end group
10370 @end smallexample
10371
10372 @need 800
10373 @noindent
10374 Here is how you could reverse the list using a @code{while} loop:
10375
10376 @smallexample
10377 @group
10378 (setq animals '(gazelle giraffe lion tiger))
10379
10380 (defun reverse-list-with-while (list)
10381 "Using while, reverse the order of LIST."
10382 (let (value) ; make sure list starts empty
10383 (while list
10384 (setq value (cons (car list) value))
10385 (setq list (cdr list)))
10386 value))
10387
10388 (reverse-list-with-while animals)
10389 @end group
10390 @end smallexample
10391
10392 @need 800
10393 @noindent
10394 And here is how you could use the @code{dolist} macro:
10395
10396 @smallexample
10397 @group
10398 (setq animals '(gazelle giraffe lion tiger))
10399
10400 (defun reverse-list-with-dolist (list)
10401 "Using dolist, reverse the order of LIST."
10402 (let (value) ; make sure list starts empty
10403 (dolist (element list value)
10404 (setq value (cons element value)))))
10405
10406 (reverse-list-with-dolist animals)
10407 @end group
10408 @end smallexample
10409
10410 @need 1250
10411 @noindent
10412 In Info, you can place your cursor after the closing parenthesis of
10413 each expression and type @kbd{C-x C-e}; in each case, you should see
10414
10415 @smallexample
10416 (tiger lion giraffe gazelle)
10417 @end smallexample
10418
10419 @noindent
10420 in the echo area.
10421
10422 For this example, the existing @code{reverse} function is obviously best.
10423 The @code{while} loop is just like our first example (@pxref{Loop
10424 Example, , A @code{while} Loop and a List}). The @code{while} first
10425 checks whether the list has elements; if so, it constructs a new list
10426 by adding the first element of the list to the existing list (which in
10427 the first iteration of the loop is @code{nil}). Since the second
10428 element is prepended in front of the first element, and the third
10429 element is prepended in front of the second element, the list is reversed.
10430
10431 In the expression using a @code{while} loop,
10432 the @w{@code{(setq list (cdr list))}}
10433 expression shortens the list, so the @code{while} loop eventually
10434 stops. In addition, it provides the @code{cons} expression with a new
10435 first element by creating a new and shorter list at each repetition of
10436 the loop.
10437
10438 The @code{dolist} expression does very much the same as the
10439 @code{while} expression, except that the @code{dolist} macro does some
10440 of the work you have to do when writing a @code{while} expression.
10441
10442 Like a @code{while} loop, a @code{dolist} loops. What is different is
10443 that it automatically shortens the list each time it loops --- it
10444 `@sc{cdr}s down the list' on its own --- and it automatically binds
10445 the @sc{car} of each shorter version of the list to the first of its
10446 arguments.
10447
10448 In the example, the @sc{car} of each shorter version of the list is
10449 referred to using the symbol @samp{element}, the list itself is called
10450 @samp{list}, and the value returned is called @samp{value}. The
10451 remainder of the @code{dolist} expression is the body.
10452
10453 The @code{dolist} expression binds the @sc{car} of each shorter
10454 version of the list to @code{element} and then evaluates the body of
10455 the expression; and repeats the loop. The result is returned in
10456 @code{value}.
10457
10458 @node dotimes, , dolist, dolist dotimes
10459 @unnumberedsubsubsec The @code{dotimes} Macro
10460 @findex dotimes
10461
10462 The @code{dotimes} macro is similar to @code{dolist}, except that it
10463 loops a specific number of times.
10464
10465 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10466 and so forth each time around the loop, and the value of the third
10467 argument is returned. You need to provide the value of the second
10468 argument, which is how many times the macro loops.
10469
10470 @need 1250
10471 For example, the following binds the numbers from 0 up to, but not
10472 including, the number 3 to the first argument, @var{number}, and then
10473 constructs a list of the three numbers. (The first number is 0, the
10474 second number is 1, and the third number is 2; this makes a total of
10475 three numbers in all, starting with zero as the first number.)
10476
10477 @smallexample
10478 @group
10479 (let (value) ; otherwise a value is a void variable
10480 (dotimes (number 3 value)
10481 (setq value (cons number value))))
10482
10483 @result{} (2 1 0)
10484 @end group
10485 @end smallexample
10486
10487 @noindent
10488 @code{dotimes} returns @code{value}, so the way to use
10489 @code{dotimes} is to operate on some expression @var{number} number of
10490 times and then return the result, either as a list or an atom.
10491
10492 @need 1250
10493 Here is an example of a @code{defun} that uses @code{dotimes} to add
10494 up the number of pebbles in a triangle.
10495
10496 @smallexample
10497 @group
10498 (defun triangle-using-dotimes (number-of-rows)
10499 "Using dotimes, add up the number of pebbles in a triangle."
10500 (let ((total 0)) ; otherwise a total is a void variable
10501 (dotimes (number number-of-rows total)
10502 (setq total (+ total (1+ number))))))
10503
10504 (triangle-using-dotimes 4)
10505 @end group
10506 @end smallexample
10507
10508 @node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10509 @comment node-name, next, previous, up
10510 @section Recursion
10511 @cindex Recursion
10512
10513 A recursive function contains code that tells the Lisp interpreter to
10514 call a program that runs exactly like itself, but with slightly
10515 different arguments. The code runs exactly the same because it has
10516 the same name. However, even though it has the same name, it is not
10517 the same thread of execution. It is different. In the jargon, it is
10518 a different `instance'.
10519
10520 Eventually, if the program is written correctly, the `slightly
10521 different arguments' will become sufficiently different from the first
10522 arguments that the final instance will stop.
10523
10524 @menu
10525 * Building Robots:: Same model, different serial number ...
10526 * Recursive Definition Parts:: Walk until you stop ...
10527 * Recursion with list:: Using a list as the test whether to recurse.
10528 * Recursive triangle function::
10529 * Recursion with cond::
10530 * Recursive Patterns:: Often used templates.
10531 * No Deferment:: Don't store up work ...
10532 * No deferment solution::
10533 @end menu
10534
10535 @node Building Robots, Recursive Definition Parts, Recursion, Recursion
10536 @comment node-name, next, previous, up
10537 @subsection Building Robots: Extending the Metaphor
10538 @cindex Building robots
10539 @cindex Robots, building
10540
10541 It is sometimes helpful to think of a running program as a robot that
10542 does a job. In doing its job, a recursive function calls on a second
10543 robot to help it. The second robot is identical to the first in every
10544 way, except that the second robot helps the first and has been
10545 passed different arguments than the first.
10546
10547 In a recursive function, the second robot may call a third; and the
10548 third may call a fourth, and so on. Each of these is a different
10549 entity; but all are clones.
10550
10551 Since each robot has slightly different instructions---the arguments
10552 will differ from one robot to the next---the last robot should know
10553 when to stop.
10554
10555 Let's expand on the metaphor in which a computer program is a robot.
10556
10557 A function definition provides the blueprints for a robot. When you
10558 install a function definition, that is, when you evaluate a
10559 @code{defun} special form, you install the necessary equipment to
10560 build robots. It is as if you were in a factory, setting up an
10561 assembly line. Robots with the same name are built according to the
10562 same blueprints. So they have, as it were, the same `model number',
10563 but a different `serial number'.
10564
10565 We often say that a recursive function `calls itself'. What we mean
10566 is that the instructions in a recursive function cause the Lisp
10567 interpreter to run a different function that has the same name and
10568 does the same job as the first, but with different arguments.
10569
10570 It is important that the arguments differ from one instance to the
10571 next; otherwise, the process will never stop.
10572
10573 @node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10574 @comment node-name, next, previous, up
10575 @subsection The Parts of a Recursive Definition
10576 @cindex Parts of a Recursive Definition
10577 @cindex Recursive Definition Parts
10578
10579 A recursive function typically contains a conditional expression which
10580 has three parts:
10581
10582 @enumerate
10583 @item
10584 A true-or-false-test that determines whether the function is called
10585 again, here called the @dfn{do-again-test}.
10586
10587 @item
10588 The name of the function. When this name is called, a new instance of
10589 the function---a new robot, as it were---is created and told what to do.
10590
10591 @item
10592 An expression that returns a different value each time the function is
10593 called, here called the @dfn{next-step-expression}. Consequently, the
10594 argument (or arguments) passed to the new instance of the function
10595 will be different from that passed to the previous instance. This
10596 causes the conditional expression, the @dfn{do-again-test}, to test
10597 false after the correct number of repetitions.
10598 @end enumerate
10599
10600 Recursive functions can be much simpler than any other kind of
10601 function. Indeed, when people first start to use them, they often look
10602 so mysteriously simple as to be incomprehensible. Like riding a
10603 bicycle, reading a recursive function definition takes a certain knack
10604 which is hard at first but then seems simple.
10605
10606 @need 1200
10607 There are several different common recursive patterns. A very simple
10608 pattern looks like this:
10609
10610 @smallexample
10611 @group
10612 (defun @var{name-of-recursive-function} (@var{argument-list})
10613 "@var{documentation}@dots{}"
10614 (if @var{do-again-test}
10615 @var{body}@dots{}
10616 (@var{name-of-recursive-function}
10617 @var{next-step-expression})))
10618 @end group
10619 @end smallexample
10620
10621 Each time a recursive function is evaluated, a new instance of it is
10622 created and told what to do. The arguments tell the instance what to do.
10623
10624 An argument is bound to the value of the next-step-expression. Each
10625 instance runs with a different value of the next-step-expression.
10626
10627 The value in the next-step-expression is used in the do-again-test.
10628
10629 The value returned by the next-step-expression is passed to the new
10630 instance of the function, which evaluates it (or some
10631 transmogrification of it) to determine whether to continue or stop.
10632 The next-step-expression is designed so that the do-again-test returns
10633 false when the function should no longer be repeated.
10634
10635 The do-again-test is sometimes called the @dfn{stop condition},
10636 since it stops the repetitions when it tests false.
10637
10638 @node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10639 @comment node-name, next, previous, up
10640 @subsection Recursion with a List
10641
10642 The example of a @code{while} loop that printed the elements of a list
10643 of numbers can be written recursively. Here is the code, including
10644 an expression to set the value of the variable @code{animals} to a list.
10645
10646 If you are using Emacs 20 or before, this example must be copied to
10647 the @file{*scratch*} buffer and each expression must be evaluated
10648 there. Use @kbd{C-u C-x C-e} to evaluate the
10649 @code{(print-elements-recursively animals)} expression so that the
10650 results are printed in the buffer; otherwise the Lisp interpreter will
10651 try to squeeze the results into the one line of the echo area.
10652
10653 Also, place your cursor immediately after the last closing parenthesis
10654 of the @code{print-elements-recursively} function, before the comment.
10655 Otherwise, the Lisp interpreter will try to evaluate the comment.
10656
10657 If you are using Emacs 21 or later, you can evaluate this expression
10658 directly in Info.
10659
10660 @findex print-elements-recursively
10661 @smallexample
10662 @group
10663 (setq animals '(gazelle giraffe lion tiger))
10664
10665 (defun print-elements-recursively (list)
10666 "Print each element of LIST on a line of its own.
10667 Uses recursion."
10668 (if list ; @r{do-again-test}
10669 (progn
10670 (print (car list)) ; @r{body}
10671 (print-elements-recursively ; @r{recursive call}
10672 (cdr list))))) ; @r{next-step-expression}
10673
10674 (print-elements-recursively animals)
10675 @end group
10676 @end smallexample
10677
10678 The @code{print-elements-recursively} function first tests whether
10679 there is any content in the list; if there is, the function prints the
10680 first element of the list, the @sc{car} of the list. Then the
10681 function `invokes itself', but gives itself as its argument, not the
10682 whole list, but the second and subsequent elements of the list, the
10683 @sc{cdr} of the list.
10684
10685 Put another way, if the list is not empty, the function invokes
10686 another instance of code that is similar to the initial code, but is a
10687 different thread of execution, with different arguments than the first
10688 instance.
10689
10690 Put in yet another way, if the list is not empty, the first robot
10691 assemblies a second robot and tells it what to do; the second robot is
10692 a different individual from the first, but is the same model.
10693
10694 When the second evaluation occurs, the @code{if} expression is
10695 evaluated and if true, prints the first element of the list it
10696 receives as its argument (which is the second element of the original
10697 list). Then the function `calls itself' with the @sc{cdr} of the list
10698 it is invoked with, which (the second time around) is the @sc{cdr} of
10699 the @sc{cdr} of the original list.
10700
10701 Note that although we say that the function `calls itself', what we
10702 mean is that the Lisp interpreter assembles and instructs a new
10703 instance of the program. The new instance is a clone of the first,
10704 but is a separate individual.
10705
10706 Each time the function `invokes itself', it invokes itself on a
10707 shorter version of the original list. It creates a new instance that
10708 works on a shorter list.
10709
10710 Eventually, the function invokes itself on an empty list. It creates
10711 a new instance whose argument is @code{nil}. The conditional expression
10712 tests the value of @code{list}. Since the value of @code{list} is
10713 @code{nil}, the @code{if} expression tests false so the then-part is
10714 not evaluated. The function as a whole then returns @code{nil}.
10715
10716 @need 1200
10717 When you evaluate @code{(print-elements-recursively animals)} in the
10718 @file{*scratch*} buffer, you see this result:
10719
10720 @smallexample
10721 @group
10722 giraffe
10723
10724 gazelle
10725
10726 lion
10727
10728 tiger
10729 nil
10730 @end group
10731 @end smallexample
10732
10733 @node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10734 @comment node-name, next, previous, up
10735 @subsection Recursion in Place of a Counter
10736 @findex triangle-recursively
10737
10738 @need 1200
10739 The @code{triangle} function described in a previous section can also
10740 be written recursively. It looks like this:
10741
10742 @smallexample
10743 @group
10744 (defun triangle-recursively (number)
10745 "Return the sum of the numbers 1 through NUMBER inclusive.
10746 Uses recursion."
10747 (if (= number 1) ; @r{do-again-test}
10748 1 ; @r{then-part}
10749 (+ number ; @r{else-part}
10750 (triangle-recursively ; @r{recursive call}
10751 (1- number))))) ; @r{next-step-expression}
10752
10753 (triangle-recursively 7)
10754 @end group
10755 @end smallexample
10756
10757 @noindent
10758 You can install this function by evaluating it and then try it by
10759 evaluating @code{(triangle-recursively 7)}. (Remember to put your
10760 cursor immediately after the last parenthesis of the function
10761 definition, before the comment.) The function evaluates to 28.
10762
10763 To understand how this function works, let's consider what happens in the
10764 various cases when the function is passed 1, 2, 3, or 4 as the value of
10765 its argument.
10766
10767 @menu
10768 * Recursive Example arg of 1 or 2::
10769 * Recursive Example arg of 3 or 4::
10770 @end menu
10771
10772 @node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10773 @ifnottex
10774 @unnumberedsubsubsec An argument of 1 or 2
10775 @end ifnottex
10776
10777 First, what happens if the value of the argument is 1?
10778
10779 The function has an @code{if} expression after the documentation
10780 string. It tests whether the value of @code{number} is equal to 1; if
10781 so, Emacs evaluates the then-part of the @code{if} expression, which
10782 returns the number 1 as the value of the function. (A triangle with
10783 one row has one pebble in it.)
10784
10785 Suppose, however, that the value of the argument is 2. In this case,
10786 Emacs evaluates the else-part of the @code{if} expression.
10787
10788 @need 1200
10789 The else-part consists of an addition, the recursive call to
10790 @code{triangle-recursively} and a decrementing action; and it looks like
10791 this:
10792
10793 @smallexample
10794 (+ number (triangle-recursively (1- number)))
10795 @end smallexample
10796
10797 When Emacs evaluates this expression, the innermost expression is
10798 evaluated first; then the other parts in sequence. Here are the steps
10799 in detail:
10800
10801 @table @i
10802 @item Step 1 @w{ } Evaluate the innermost expression.
10803
10804 The innermost expression is @code{(1- number)} so Emacs decrements the
10805 value of @code{number} from 2 to 1.
10806
10807 @item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
10808
10809 The Lisp interpreter creates an individual instance of
10810 @code{triangle-recursively}. It does not matter that this function is
10811 contained within itself. Emacs passes the result Step 1 as the
10812 argument used by this instance of the @code{triangle-recursively}
10813 function
10814
10815 In this case, Emacs evaluates @code{triangle-recursively} with an
10816 argument of 1. This means that this evaluation of
10817 @code{triangle-recursively} returns 1.
10818
10819 @item Step 3 @w{ } Evaluate the value of @code{number}.
10820
10821 The variable @code{number} is the second element of the list that
10822 starts with @code{+}; its value is 2.
10823
10824 @item Step 4 @w{ } Evaluate the @code{+} expression.
10825
10826 The @code{+} expression receives two arguments, the first
10827 from the evaluation of @code{number} (Step 3) and the second from the
10828 evaluation of @code{triangle-recursively} (Step 2).
10829
10830 The result of the addition is the sum of 2 plus 1, and the number 3 is
10831 returned, which is correct. A triangle with two rows has three
10832 pebbles in it.
10833 @end table
10834
10835 @node Recursive Example arg of 3 or 4, , Recursive Example arg of 1 or 2, Recursive triangle function
10836 @unnumberedsubsubsec An argument of 3 or 4
10837
10838 Suppose that @code{triangle-recursively} is called with an argument of
10839 3.
10840
10841 @table @i
10842 @item Step 1 @w{ } Evaluate the do-again-test.
10843
10844 The @code{if} expression is evaluated first. This is the do-again
10845 test and returns false, so the else-part of the @code{if} expression
10846 is evaluated. (Note that in this example, the do-again-test causes
10847 the function to call itself when it tests false, not when it tests
10848 true.)
10849
10850 @item Step 2 @w{ } Evaluate the innermost expression of the else-part.
10851
10852 The innermost expression of the else-part is evaluated, which decrements
10853 3 to 2. This is the next-step-expression.
10854
10855 @item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
10856
10857 The number 2 is passed to the @code{triangle-recursively} function.
10858
10859 We know what happens when Emacs evaluates @code{triangle-recursively} with
10860 an argument of 2. After going through the sequence of actions described
10861 earlier, it returns a value of 3. So that is what will happen here.
10862
10863 @item Step 4 @w{ } Evaluate the addition.
10864
10865 3 will be passed as an argument to the addition and will be added to the
10866 number with which the function was called, which is 3.
10867 @end table
10868
10869 @noindent
10870 The value returned by the function as a whole will be 6.
10871
10872 Now that we know what will happen when @code{triangle-recursively} is
10873 called with an argument of 3, it is evident what will happen if it is
10874 called with an argument of 4:
10875
10876 @quotation
10877 @need 800
10878 In the recursive call, the evaluation of
10879
10880 @smallexample
10881 (triangle-recursively (1- 4))
10882 @end smallexample
10883
10884 @need 800
10885 @noindent
10886 will return the value of evaluating
10887
10888 @smallexample
10889 (triangle-recursively 3)
10890 @end smallexample
10891
10892 @noindent
10893 which is 6 and this value will be added to 4 by the addition in the
10894 third line.
10895 @end quotation
10896
10897 @noindent
10898 The value returned by the function as a whole will be 10.
10899
10900 Each time @code{triangle-recursively} is evaluated, it evaluates a
10901 version of itself---a different instance of itself---with a smaller
10902 argument, until the argument is small enough so that it does not
10903 evaluate itself.
10904
10905 Note that this particular design for a recursive function
10906 requires that operations be deferred.
10907
10908 Before @code{(triangle-recursively 7)} can calculate its answer, it
10909 must call @code{(triangle-recursively 6)}; and before
10910 @code{(triangle-recursively 6)} can calculate its answer, it must call
10911 @code{(triangle-recursively 5)}; and so on. That is to say, the
10912 calculation that @code{(triangle-recursively 7)} makes must be
10913 deferred until @code{(triangle-recursively 6)} makes its calculation;
10914 and @code{(triangle-recursively 6)} must defer until
10915 @code{(triangle-recursively 5)} completes; and so on.
10916
10917 If each of these instances of @code{triangle-recursively} are thought
10918 of as different robots, the first robot must wait for the second to
10919 complete its job, which must wait until the third completes, and so
10920 on.
10921
10922 There is a way around this kind of waiting, which we will discuss in
10923 @ref{No Deferment, , Recursion without Deferments}.
10924
10925 @node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10926 @comment node-name, next, previous, up
10927 @subsection Recursion Example Using @code{cond}
10928 @findex cond
10929
10930 The version of @code{triangle-recursively} described earlier is written
10931 with the @code{if} special form. It can also be written using another
10932 special form called @code{cond}. The name of the special form
10933 @code{cond} is an abbreviation of the word @samp{conditional}.
10934
10935 Although the @code{cond} special form is not used as often in the
10936 Emacs Lisp sources as @code{if}, it is used often enough to justify
10937 explaining it.
10938
10939 @need 800
10940 The template for a @code{cond} expression looks like this:
10941
10942 @smallexample
10943 @group
10944 (cond
10945 @var{body}@dots{})
10946 @end group
10947 @end smallexample
10948
10949 @noindent
10950 where the @var{body} is a series of lists.
10951
10952 @need 800
10953 Written out more fully, the template looks like this:
10954
10955 @smallexample
10956 @group
10957 (cond
10958 (@var{first-true-or-false-test} @var{first-consequent})
10959 (@var{second-true-or-false-test} @var{second-consequent})
10960 (@var{third-true-or-false-test} @var{third-consequent})
10961 @dots{})
10962 @end group
10963 @end smallexample
10964
10965 When the Lisp interpreter evaluates the @code{cond} expression, it
10966 evaluates the first element (the @sc{car} or true-or-false-test) of
10967 the first expression in a series of expressions within the body of the
10968 @code{cond}.
10969
10970 If the true-or-false-test returns @code{nil} the rest of that
10971 expression, the consequent, is skipped and the true-or-false-test of the
10972 next expression is evaluated. When an expression is found whose
10973 true-or-false-test returns a value that is not @code{nil}, the
10974 consequent of that expression is evaluated. The consequent can be one
10975 or more expressions. If the consequent consists of more than one
10976 expression, the expressions are evaluated in sequence and the value of
10977 the last one is returned. If the expression does not have a consequent,
10978 the value of the true-or-false-test is returned.
10979
10980 If none of the true-or-false-tests test true, the @code{cond} expression
10981 returns @code{nil}.
10982
10983 @need 1250
10984 Written using @code{cond}, the @code{triangle} function looks like this:
10985
10986 @smallexample
10987 @group
10988 (defun triangle-using-cond (number)
10989 (cond ((<= number 0) 0)
10990 ((= number 1) 1)
10991 ((> number 1)
10992 (+ number (triangle-using-cond (1- number))))))
10993 @end group
10994 @end smallexample
10995
10996 @noindent
10997 In this example, the @code{cond} returns 0 if the number is less than or
10998 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
10999 number (triangle-using-cond (1- number)))} if the number is greater than
11000 1.
11001
11002 @node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11003 @comment node-name, next, previous, up
11004 @subsection Recursive Patterns
11005 @cindex Recursive Patterns
11006
11007 Here are three common recursive patterns. Each involves a list.
11008 Recursion does not need to involve lists, but Lisp is designed for lists
11009 and this provides a sense of its primal capabilities.
11010
11011 @menu
11012 * Every::
11013 * Accumulate::
11014 * Keep::
11015 @end menu
11016
11017 @node Every, Accumulate, Recursive Patterns, Recursive Patterns
11018 @comment node-name, next, previous, up
11019 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11020 @cindex Every, type of recursive pattern
11021 @cindex Recursive pattern: every
11022
11023 In the @code{every} recursive pattern, an action is performed on every
11024 element of a list.
11025
11026 @need 1500
11027 The basic pattern is:
11028
11029 @itemize @bullet
11030 @item
11031 If a list be empty, return @code{nil}.
11032 @item
11033 Else, act on the beginning of the list (the @sc{car} of the list)
11034 @itemize @minus
11035 @item
11036 through a recursive call by the function on the rest (the
11037 @sc{cdr}) of the list,
11038 @item
11039 and, optionally, combine the acted-on element, using @code{cons},
11040 with the results of acting on the rest.
11041 @end itemize
11042 @end itemize
11043
11044 @need 1500
11045 Here is example:
11046
11047 @smallexample
11048 @group
11049 (defun square-each (numbers-list)
11050 "Square each of a NUMBERS LIST, recursively."
11051 (if (not numbers-list) ; do-again-test
11052 nil
11053 (cons
11054 (* (car numbers-list) (car numbers-list))
11055 (square-each (cdr numbers-list))))) ; next-step-expression
11056 @end group
11057
11058 @group
11059 (square-each '(1 2 3))
11060 @result{} (1 4 9)
11061 @end group
11062 @end smallexample
11063
11064 @need 1200
11065 @noindent
11066 If @code{numbers-list} is empty, do nothing. But if it has content,
11067 construct a list combining the square of the first number in the list
11068 with the result of the recursive call.
11069
11070 (The example follows the pattern exactly: @code{nil} is returned if
11071 the numbers' list is empty. In practice, you would write the
11072 conditional so it carries out the action when the numbers' list is not
11073 empty.)
11074
11075 The @code{print-elements-recursively} function (@pxref{Recursion with
11076 list, , Recursion with a List}) is another example of an @code{every}
11077 pattern, except in this case, rather than bring the results together
11078 using @code{cons}, we print each element of output.
11079
11080 @need 1250
11081 The @code{print-elements-recursively} function looks like this:
11082
11083 @smallexample
11084 @group
11085 (setq animals '(gazelle giraffe lion tiger))
11086 @end group
11087
11088 @group
11089 (defun print-elements-recursively (list)
11090 "Print each element of LIST on a line of its own.
11091 Uses recursion."
11092 (if list ; @r{do-again-test}
11093 (progn
11094 (print (car list)) ; @r{body}
11095 (print-elements-recursively ; @r{recursive call}
11096 (cdr list))))) ; @r{next-step-expression}
11097
11098 (print-elements-recursively animals)
11099 @end group
11100 @end smallexample
11101
11102 @need 1500
11103 The pattern for @code{print-elements-recursively} is:
11104
11105 @itemize @bullet
11106 @item
11107 If the list be empty, do nothing.
11108 @item
11109 But if the list has at least one element,
11110 @itemize @minus
11111 @item
11112 act on the beginning of the list (the @sc{car} of the list),
11113 @item
11114 and make a recursive call on the rest (the @sc{cdr}) of the list.
11115 @end itemize
11116 @end itemize
11117
11118 @node Accumulate, Keep, Every, Recursive Patterns
11119 @comment node-name, next, previous, up
11120 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11121 @cindex Accumulate, type of recursive pattern
11122 @cindex Recursive pattern: accumulate
11123
11124 Another recursive pattern is called the @code{accumulate} pattern. In
11125 the @code{accumulate} recursive pattern, an action is performed on
11126 every element of a list and the result of that action is accumulated
11127 with the results of performing the action on the other elements.
11128
11129 This is very like the `every' pattern using @code{cons}, except that
11130 @code{cons} is not used, but some other combiner.
11131
11132 @need 1500
11133 The pattern is:
11134
11135 @itemize @bullet
11136 @item
11137 If a list be empty, return zero or some other constant.
11138 @item
11139 Else, act on the beginning of the list (the @sc{car} of the list),
11140 @itemize @minus
11141 @item
11142 and combine that acted-on element, using @code{+} or
11143 some other combining function, with
11144 @item
11145 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11146 @end itemize
11147 @end itemize
11148
11149 @need 1500
11150 Here is an example:
11151
11152 @smallexample
11153 @group
11154 (defun add-elements (numbers-list)
11155 "Add the elements of NUMBERS-LIST together."
11156 (if (not numbers-list)
11157 0
11158 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11159 @end group
11160
11161 @group
11162 (add-elements '(1 2 3 4))
11163 @result{} 10
11164 @end group
11165 @end smallexample
11166
11167 @xref{Files List, , Making a List of Files}, for an example of the
11168 accumulate pattern.
11169
11170 @node Keep, , Accumulate, Recursive Patterns
11171 @comment node-name, next, previous, up
11172 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11173 @cindex Keep, type of recursive pattern
11174 @cindex Recursive pattern: keep
11175
11176 A third recursive pattern is called the @code{keep} pattern.
11177 In the @code{keep} recursive pattern, each element of a list is tested;
11178 the element is acted on and the results are kept only if the element
11179 meets a criterion.
11180
11181 Again, this is very like the `every' pattern, except the element is
11182 skipped unless it meets a criterion.
11183
11184 @need 1500
11185 The pattern has three parts:
11186
11187 @itemize @bullet
11188 @item
11189 If a list be empty, return @code{nil}.
11190 @item
11191 Else, if the beginning of the list (the @sc{car} of the list) passes
11192 a test
11193 @itemize @minus
11194 @item
11195 act on that element and combine it, using @code{cons} with
11196 @item
11197 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11198 @end itemize
11199 @item
11200 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11201 the test
11202 @itemize @minus
11203 @item
11204 skip on that element,
11205 @item
11206 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11207 @end itemize
11208 @end itemize
11209
11210 @need 1500
11211 Here is an example that uses @code{cond}:
11212
11213 @smallexample
11214 @group
11215 (defun keep-three-letter-words (word-list)
11216 "Keep three letter words in WORD-LIST."
11217 (cond
11218 ;; First do-again-test: stop-condition
11219 ((not word-list) nil)
11220
11221 ;; Second do-again-test: when to act
11222 ((eq 3 (length (symbol-name (car word-list))))
11223 ;; combine acted-on element with recursive call on shorter list
11224 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11225
11226 ;; Third do-again-test: when to skip element;
11227 ;; recursively call shorter list with next-step expression
11228 (t (keep-three-letter-words (cdr word-list)))))
11229 @end group
11230
11231 @group
11232 (keep-three-letter-words '(one two three four five six))
11233 @result{} (one two six)
11234 @end group
11235 @end smallexample
11236
11237 It goes without saying that you need not use @code{nil} as the test for
11238 when to stop; and you can, of course, combine these patterns.
11239
11240 @node No Deferment, No deferment solution, Recursive Patterns, Recursion
11241 @subsection Recursion without Deferments
11242 @cindex Deferment in recursion
11243 @cindex Recursion without Deferments
11244
11245 Let's consider again what happens with the @code{triangle-recursively}
11246 function. We will find that the intermediate calculations are
11247 deferred until all can be done.
11248
11249 @need 800
11250 Here is the function definition:
11251
11252 @smallexample
11253 @group
11254 (defun triangle-recursively (number)
11255 "Return the sum of the numbers 1 through NUMBER inclusive.
11256 Uses recursion."
11257 (if (= number 1) ; @r{do-again-test}
11258 1 ; @r{then-part}
11259 (+ number ; @r{else-part}
11260 (triangle-recursively ; @r{recursive call}
11261 (1- number))))) ; @r{next-step-expression}
11262 @end group
11263 @end smallexample
11264
11265 What happens when we call this function with a argument of 7?
11266
11267 The first instance of the @code{triangle-recursively} function adds
11268 the number 7 to the value returned by a second instance of
11269 @code{triangle-recursively}, an instance that has been passed an
11270 argument of 6. That is to say, the first calculation is:
11271
11272 @smallexample
11273 (+ 7 (triangle-recursively 6)
11274 @end smallexample
11275
11276 @noindent
11277 The first instance of @code{triangle-recursively}---you may want to
11278 think of it as a little robot---cannot complete its job. It must hand
11279 off the calculation for @code{(triangle-recursively 6)} to a second
11280 instance of the program, to a second robot. This second individual is
11281 completely different from the first one; it is, in the jargon, a
11282 `different instantiation'. Or, put another way, it is a different
11283 robot. It is the same model as the first; it calculates triangle
11284 numbers recursively; but it has a different serial number.
11285
11286 And what does @code{(triangle-recursively 6)} return? It returns the
11287 number 6 added to the value returned by evaluating
11288 @code{triangle-recursively} with an argument of 5. Using the robot
11289 metaphor, it asks yet another robot to help it.
11290
11291 @need 800
11292 Now the total is:
11293
11294 @smallexample
11295 (+ 7 6 (triangle-recursively 5)
11296 @end smallexample
11297
11298 @need 800
11299 And what happens next?
11300
11301 @smallexample
11302 (+ 7 6 5 (triangle-recursively 4)
11303 @end smallexample
11304
11305 Each time @code{triangle-recursively} is called, except for the last
11306 time, it creates another instance of the program---another robot---and
11307 asks it to make a calculation.
11308
11309 @need 800
11310 Eventually, the full addition is set up and performed:
11311
11312 @smallexample
11313 (+ 7 6 5 4 3 2 1)
11314 @end smallexample
11315
11316 This design for the function defers the calculation of the first step
11317 until the second can be done, and defers that until the third can be
11318 done, and so on. Each deferment means the computer must remember what
11319 is being waited on. This is not a problem when there are only a few
11320 steps, as in this example. But it can be a problem when there are
11321 more steps.
11322
11323 @node No deferment solution, , No Deferment, Recursion
11324 @subsection No Deferment Solution
11325 @cindex No deferment solution
11326 @cindex Defermentless solution
11327 @cindex Solution without deferment
11328
11329 The solution to the problem of deferred operations is to write in a
11330 manner that does not defer operations@footnote{The phrase @dfn{tail
11331 recursive} is used to describe such a process, one that uses
11332 `constant space'.}. This requires
11333 writing to a different pattern, often one that involves writing two
11334 function definitions, an `initialization' function and a `helper'
11335 function.
11336
11337 The `initialization' function sets up the job; the `helper' function
11338 does the work.
11339
11340 @need 1200
11341 Here are the two function definitions for adding up numbers. They are
11342 so simple, I find them hard to understand.
11343
11344 @smallexample
11345 @group
11346 (defun triangle-initialization (number)
11347 "Return the sum of the numbers 1 through NUMBER inclusive.
11348 This is the `initialization' component of a two function
11349 duo that uses recursion."
11350 (triangle-recursive-helper 0 0 number))
11351 @end group
11352 @end smallexample
11353
11354 @smallexample
11355 @group
11356 (defun triangle-recursive-helper (sum counter number)
11357 "Return SUM, using COUNTER, through NUMBER inclusive.
11358 This is the `helper' component of a two function duo
11359 that uses recursion."
11360 (if (> counter number)
11361 sum
11362 (triangle-recursive-helper (+ sum counter) ; @r{sum}
11363 (1+ counter) ; @r{counter}
11364 number))) ; @r{number}
11365 @end group
11366 @end smallexample
11367
11368 @need 1250
11369 Install both function definitions by evaluating them, then call
11370 @code{triangle-initialization} with 2 rows:
11371
11372 @smallexample
11373 @group
11374 (triangle-initialization 2)
11375 @result{} 3
11376 @end group
11377 @end smallexample
11378
11379 The `initialization' function calls the first instance of the `helper'
11380 function with three arguments: zero, zero, and a number which is the
11381 number of rows in the triangle.
11382
11383 The first two arguments passed to the `helper' function are
11384 initialization values. These values are changed when
11385 @code{triangle-recursive-helper} invokes new instances.@footnote{The
11386 jargon is mildly confusing: @code{triangle-recursive-helper} uses a
11387 process that is iterative in a procedure that is recursive. The
11388 process is called iterative because the computer need only record the
11389 three values, @code{sum}, @code{counter}, and @code{number}; the
11390 procedure is recursive because the function `calls itself'. On the
11391 other hand, both the process and the procedure used by
11392 @code{triangle-recursively} are called recursive. The word
11393 `recursive' has different meanings in the two contexts.}
11394
11395 Let's see what happens when we have a triangle that has one row. (This
11396 triangle will have one pebble in it!)
11397
11398 @need 1200
11399 @code{triangle-initialization} will call its helper with
11400 the arguments @w{@code{0 0 1}}. That function will run the conditional
11401 test whether @code{(> counter number)}:
11402
11403 @smallexample
11404 (> 0 1)
11405 @end smallexample
11406
11407 @need 1200
11408 @noindent
11409 and find that the result is false, so it will invoke
11410 the then-part of the @code{if} clause:
11411
11412 @smallexample
11413 @group
11414 (triangle-recursive-helper
11415 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11416 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11417 number) ; @r{number stays the same}
11418 @end group
11419 @end smallexample
11420
11421 @need 800
11422 @noindent
11423 which will first compute:
11424
11425 @smallexample
11426 @group
11427 (triangle-recursive-helper (+ 0 0) ; @r{sum}
11428 (1+ 0) ; @r{counter}
11429 1) ; @r{number}
11430 @exdent which is:
11431
11432 (triangle-recursive-helper 0 1 1)
11433 @end group
11434 @end smallexample
11435
11436 Again, @code{(> counter number)} will be false, so again, the Lisp
11437 interpreter will evaluate @code{triangle-recursive-helper}, creating a
11438 new instance with new arguments.
11439
11440 @need 800
11441 This new instance will be;
11442
11443 @smallexample
11444 @group
11445 (triangle-recursive-helper
11446 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11447 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11448 number) ; @r{number stays the same}
11449
11450 @exdent which is:
11451
11452 (triangle-recursive-helper 1 2 1)
11453 @end group
11454 @end smallexample
11455
11456 In this case, the @code{(> counter number)} test will be true! So the
11457 instance will return the value of the sum, which will be 1, as
11458 expected.
11459
11460 Now, let's pass @code{triangle-initialization} an argument
11461 of 2, to find out how many pebbles there are in a triangle with two rows.
11462
11463 That function calls @code{(triangle-recursive-helper 0 0 2)}.
11464
11465 @need 800
11466 In stages, the instances called will be:
11467
11468 @smallexample
11469 @group
11470 @r{sum counter number}
11471 (triangle-recursive-helper 0 1 2)
11472
11473 (triangle-recursive-helper 1 2 2)
11474
11475 (triangle-recursive-helper 3 3 2)
11476 @end group
11477 @end smallexample
11478
11479 When the last instance is called, the @code{(> counter number)} test
11480 will be true, so the instance will return the value of @code{sum},
11481 which will be 3.
11482
11483 This kind of pattern helps when you are writing functions that can use
11484 many resources in a computer.
11485
11486 @need 1500
11487 @node Looping exercise, , Recursion, Loops & Recursion
11488 @section Looping Exercise
11489
11490 @itemize @bullet
11491 @item
11492 Write a function similar to @code{triangle} in which each row has a
11493 value which is the square of the row number. Use a @code{while} loop.
11494
11495 @item
11496 Write a function similar to @code{triangle} that multiplies instead of
11497 adds the values.
11498
11499 @item
11500 Rewrite these two functions recursively. Rewrite these functions
11501 using @code{cond}.
11502
11503 @c comma in printed title causes problem in Info cross reference
11504 @item
11505 Write a function for Texinfo mode that creates an index entry at the
11506 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
11507 (In a Texinfo file, @samp{@@dfn} marks a definition. For more
11508 information, see
11509 @ifinfo
11510 @ref{Indicating, , Indicating Definitions, texinfo}.)
11511 @end ifinfo
11512 @ifhtml
11513 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}.)
11514 @end ifhtml
11515 @iftex
11516 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
11517 Documentation Format}.)
11518 @end iftex
11519 @end itemize
11520
11521 @node Regexp Search, Counting Words, Loops & Recursion, Top
11522 @comment node-name, next, previous, up
11523 @chapter Regular Expression Searches
11524 @cindex Searches, illustrating
11525 @cindex Regular expression searches
11526 @cindex Patterns, searching for
11527 @cindex Motion by sentence and paragraph
11528 @cindex Sentences, movement by
11529 @cindex Paragraphs, movement by
11530
11531 Regular expression searches are used extensively in GNU Emacs. The
11532 two functions, @code{forward-sentence} and @code{forward-paragraph},
11533 illustrate these searches well. They use regular expressions to find
11534 where to move point. The phrase `regular expression' is often written
11535 as `regexp'.
11536
11537 Regular expression searches are described in @ref{Regexp Search, ,
11538 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11539 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11540 Manual}. In writing this chapter, I am presuming that you have at
11541 least a mild acquaintance with them. The major point to remember is
11542 that regular expressions permit you to search for patterns as well as
11543 for literal strings of characters. For example, the code in
11544 @code{forward-sentence} searches for the pattern of possible
11545 characters that could mark the end of a sentence, and moves point to
11546 that spot.
11547
11548 Before looking at the code for the @code{forward-sentence} function, it
11549 is worth considering what the pattern that marks the end of a sentence
11550 must be. The pattern is discussed in the next section; following that
11551 is a description of the regular expression search function,
11552 @code{re-search-forward}. The @code{forward-sentence} function
11553 is described in the section following. Finally, the
11554 @code{forward-paragraph} function is described in the last section of
11555 this chapter. @code{forward-paragraph} is a complex function that
11556 introduces several new features.
11557
11558 @menu
11559 * sentence-end:: The regular expression for @code{sentence-end}.
11560 * re-search-forward:: Very similar to @code{search-forward}.
11561 * forward-sentence:: A straightforward example of regexp search.
11562 * forward-paragraph:: A somewhat complex example.
11563 * etags:: How to create your own @file{TAGS} table.
11564 * Regexp Review::
11565 * re-search Exercises::
11566 @end menu
11567
11568 @node sentence-end, re-search-forward, Regexp Search, Regexp Search
11569 @comment node-name, next, previous, up
11570 @section The Regular Expression for @code{sentence-end}
11571 @findex sentence-end
11572
11573 The symbol @code{sentence-end} is bound to the pattern that marks the
11574 end of a sentence. What should this regular expression be?
11575
11576 Clearly, a sentence may be ended by a period, a question mark, or an
11577 exclamation mark. Indeed, only clauses that end with one of those three
11578 characters should be considered the end of a sentence. This means that
11579 the pattern should include the character set:
11580
11581 @smallexample
11582 [.?!]
11583 @end smallexample
11584
11585 However, we do not want @code{forward-sentence} merely to jump to a
11586 period, a question mark, or an exclamation mark, because such a character
11587 might be used in the middle of a sentence. A period, for example, is
11588 used after abbreviations. So other information is needed.
11589
11590 According to convention, you type two spaces after every sentence, but
11591 only one space after a period, a question mark, or an exclamation mark in
11592 the body of a sentence. So a period, a question mark, or an exclamation
11593 mark followed by two spaces is a good indicator of an end of sentence.
11594 However, in a file, the two spaces may instead be a tab or the end of a
11595 line. This means that the regular expression should include these three
11596 items as alternatives.
11597
11598 @need 800
11599 This group of alternatives will look like this:
11600
11601 @smallexample
11602 @group
11603 \\($\\| \\| \\)
11604 ^ ^^
11605 TAB SPC
11606 @end group
11607 @end smallexample
11608
11609 @noindent
11610 Here, @samp{$} indicates the end of the line, and I have pointed out
11611 where the tab and two spaces are inserted in the expression. Both are
11612 inserted by putting the actual characters into the expression.
11613
11614 Two backslashes, @samp{\\}, are required before the parentheses and
11615 vertical bars: the first backslash quotes the following backslash in
11616 Emacs; and the second indicates that the following character, the
11617 parenthesis or the vertical bar, is special.
11618
11619 @need 1000
11620 Also, a sentence may be followed by one or more carriage returns, like
11621 this:
11622
11623 @smallexample
11624 @group
11625 [
11626 ]*
11627 @end group
11628 @end smallexample
11629
11630 @noindent
11631 Like tabs and spaces, a carriage return is inserted into a regular
11632 expression by inserting it literally. The asterisk indicates that the
11633 @key{RET} is repeated zero or more times.
11634
11635 But a sentence end does not consist only of a period, a question mark or
11636 an exclamation mark followed by appropriate space: a closing quotation
11637 mark or a closing brace of some kind may precede the space. Indeed more
11638 than one such mark or brace may precede the space. These require a
11639 expression that looks like this:
11640
11641 @smallexample
11642 []\"')@}]*
11643 @end smallexample
11644
11645 In this expression, the first @samp{]} is the first character in the
11646 expression; the second character is @samp{"}, which is preceded by a
11647 @samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
11648 three characters are @samp{'}, @samp{)}, and @samp{@}}.
11649
11650 All this suggests what the regular expression pattern for matching the
11651 end of a sentence should be; and, indeed, if we evaluate
11652 @code{sentence-end} we find that it returns the following value:
11653
11654 @smallexample
11655 @group
11656 sentence-end
11657 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
11658 ]*"
11659 @end group
11660 @end smallexample
11661
11662 @ignore
11663
11664 @noindent
11665 (Note that here the @key{TAB}, two spaces, and @key{RET} are shown
11666 literally in the pattern.)
11667
11668 This regular expression can be decyphered as follows:
11669
11670 @table @code
11671 @item [.?!]
11672 The first part of the pattern is the three characters, a period, a question
11673 mark and an exclamation mark, within square brackets. The pattern must
11674 begin with one or other of these characters.
11675
11676 @item []\"')@}]*
11677 The second part of the pattern is the group of closing braces and
11678 quotation marks, which can appear zero or more times. These may follow
11679 the period, question mark or exclamation mark. In a regular expression,
11680 the backslash, @samp{\}, followed by the double quotation mark,
11681 @samp{"}, indicates the class of string-quote characters. Usually, the
11682 double quotation mark is the only character in this class. The
11683 asterisk, @samp{*}, indicates that the items in the previous group (the
11684 group surrounded by square brackets, @samp{[]}) may be repeated zero or
11685 more times.
11686
11687 @item \\($\\| \\| \\)
11688 The third part of the pattern is one or other of: either the end of a
11689 line, or two blank spaces, or a tab. The double back-slashes are used
11690 to prevent Emacs from reading the parentheses and vertical bars as part
11691 of the search pattern; the parentheses are used to mark the group and
11692 the vertical bars are used to indicated that the patterns to either side
11693 of them are alternatives. The dollar sign is used to indicate the end
11694 of a line and both the two spaces and the tab are each inserted as is to
11695 indicate what they are.
11696
11697 @item [@key{RET}]*
11698 Finally, the last part of the pattern indicates that the end of the line
11699 or the whitespace following the period, question mark or exclamation
11700 mark may, but need not, be followed by one or more carriage returns. In
11701 the pattern, the carriage return is inserted as an actual carriage
11702 return between square brackets but here it is shown as @key{RET}.
11703 @end table
11704
11705 @end ignore
11706
11707 @node re-search-forward, forward-sentence, sentence-end, Regexp Search
11708 @comment node-name, next, previous, up
11709 @section The @code{re-search-forward} Function
11710 @findex re-search-forward
11711
11712 The @code{re-search-forward} function is very like the
11713 @code{search-forward} function. (@xref{search-forward, , The
11714 @code{search-forward} Function}.)
11715
11716 @code{re-search-forward} searches for a regular expression. If the
11717 search is successful, it leaves point immediately after the last
11718 character in the target. If the search is backwards, it leaves point
11719 just before the first character in the target. You may tell
11720 @code{re-search-forward} to return @code{t} for true. (Moving point
11721 is therefore a `side effect'.)
11722
11723 Like @code{search-forward}, the @code{re-search-forward} function takes
11724 four arguments:
11725
11726 @enumerate
11727 @item
11728 The first argument is the regular expression that the function searches
11729 for. The regular expression will be a string between quotations marks.
11730
11731 @item
11732 The optional second argument limits how far the function will search; it is a
11733 bound, which is specified as a position in the buffer.
11734
11735 @item
11736 The optional third argument specifies how the function responds to
11737 failure: @code{nil} as the third argument causes the function to
11738 signal an error (and print a message) when the search fails; any other
11739 value causes it to return @code{nil} if the search fails and @code{t}
11740 if the search succeeds.
11741
11742 @item
11743 The optional fourth argument is the repeat count. A negative repeat
11744 count causes @code{re-search-forward} to search backwards.
11745 @end enumerate
11746
11747 @need 800
11748 The template for @code{re-search-forward} looks like this:
11749
11750 @smallexample
11751 @group
11752 (re-search-forward "@var{regular-expression}"
11753 @var{limit-of-search}
11754 @var{what-to-do-if-search-fails}
11755 @var{repeat-count})
11756 @end group
11757 @end smallexample
11758
11759 The second, third, and fourth arguments are optional. However, if you
11760 want to pass a value to either or both of the last two arguments, you
11761 must also pass a value to all the preceding arguments. Otherwise, the
11762 Lisp interpreter will mistake which argument you are passing the value
11763 to.
11764
11765 @need 1200
11766 In the @code{forward-sentence} function, the regular expression will be
11767 the value of the variable @code{sentence-end}, namely:
11768
11769 @smallexample
11770 @group
11771 "[.?!][]\"')@}]*\\($\\| \\| \\)[
11772 ]*"
11773 @end group
11774 @end smallexample
11775
11776 @noindent
11777 The limit of the search will be the end of the paragraph (since a
11778 sentence cannot go beyond a paragraph). If the search fails, the
11779 function will return @code{nil}; and the repeat count will be provided
11780 by the argument to the @code{forward-sentence} function.
11781
11782 @node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11783 @comment node-name, next, previous, up
11784 @section @code{forward-sentence}
11785 @findex forward-sentence
11786
11787 The command to move the cursor forward a sentence is a straightforward
11788 illustration of how to use regular expression searches in Emacs Lisp.
11789 Indeed, the function looks longer and more complicated than it is; this
11790 is because the function is designed to go backwards as well as forwards;
11791 and, optionally, over more than one sentence. The function is usually
11792 bound to the key command @kbd{M-e}.
11793
11794 @menu
11795 * Complete forward-sentence::
11796 * fwd-sentence while loops:: Two @code{while} loops.
11797 * fwd-sentence re-search:: A regular expression search.
11798 @end menu
11799
11800 @node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11801 @ifnottex
11802 @unnumberedsubsec Complete @code{forward-sentence} function definition
11803 @end ifnottex
11804
11805 @need 1250
11806 Here is the code for @code{forward-sentence}:
11807
11808 @smallexample
11809 @group
11810 (defun forward-sentence (&optional arg)
11811 "Move forward to next sentence-end. With argument, repeat.
11812 With negative argument, move backward repeatedly to sentence-beginning.
11813 Sentence ends are identified by the value of sentence-end
11814 treated as a regular expression. Also, every paragraph boundary
11815 terminates sentences as well."
11816 @end group
11817 @group
11818 (interactive "p")
11819 (or arg (setq arg 1))
11820 (while (< arg 0)
11821 (let ((par-beg
11822 (save-excursion (start-of-paragraph-text) (point))))
11823 (if (re-search-backward
11824 (concat sentence-end "[^ \t\n]") par-beg t)
11825 (goto-char (1- (match-end 0)))
11826 (goto-char par-beg)))
11827 (setq arg (1+ arg)))
11828 (while (> arg 0)
11829 (let ((par-end
11830 (save-excursion (end-of-paragraph-text) (point))))
11831 (if (re-search-forward sentence-end par-end t)
11832 (skip-chars-backward " \t\n")
11833 (goto-char par-end)))
11834 (setq arg (1- arg))))
11835 @end group
11836 @end smallexample
11837
11838 The function looks long at first sight and it is best to look at its
11839 skeleton first, and then its muscle. The way to see the skeleton is to
11840 look at the expressions that start in the left-most columns:
11841
11842 @smallexample
11843 @group
11844 (defun forward-sentence (&optional arg)
11845 "@var{documentation}@dots{}"
11846 (interactive "p")
11847 (or arg (setq arg 1))
11848 (while (< arg 0)
11849 @var{body-of-while-loop}
11850 (while (> arg 0)
11851 @var{body-of-while-loop}
11852 @end group
11853 @end smallexample
11854
11855 This looks much simpler! The function definition consists of
11856 documentation, an @code{interactive} expression, an @code{or}
11857 expression, and @code{while} loops.
11858
11859 Let's look at each of these parts in turn.
11860
11861 We note that the documentation is thorough and understandable.
11862
11863 The function has an @code{interactive "p"} declaration. This means
11864 that the processed prefix argument, if any, is passed to the
11865 function as its argument. (This will be a number.) If the function
11866 is not passed an argument (it is optional) then the argument
11867 @code{arg} will be bound to 1. When @code{forward-sentence} is called
11868 non-interactively without an argument, @code{arg} is bound to
11869 @code{nil}.
11870
11871 The @code{or} expression handles the prefix argument. What it does is
11872 either leave the value of @code{arg} as it is, but only if @code{arg}
11873 is bound to a value; or it sets the value of @code{arg} to 1, in the
11874 case when @code{arg} is bound to @code{nil}.
11875
11876 @node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11877 @unnumberedsubsec The @code{while} loops
11878
11879 Two @code{while} loops follow the @code{or} expression. The first
11880 @code{while} has a true-or-false-test that tests true if the prefix
11881 argument for @code{forward-sentence} is a negative number. This is for
11882 going backwards. The body of this loop is similar to the body of the
11883 second @code{while} clause, but it is not exactly the same. We will
11884 skip this @code{while} loop and concentrate on the second @code{while}
11885 loop.
11886
11887 @need 1500
11888 The second @code{while} loop is for moving point forward. Its skeleton
11889 looks like this:
11890
11891 @smallexample
11892 @group
11893 (while (> arg 0) ; @r{true-or-false-test}
11894 (let @var{varlist}
11895 (if (@var{true-or-false-test})
11896 @var{then-part}
11897 @var{else-part}
11898 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
11899 @end group
11900 @end smallexample
11901
11902 The @code{while} loop is of the decrementing kind.
11903 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
11904 has a true-or-false-test that tests true so long as the counter (in
11905 this case, the variable @code{arg}) is greater than zero; and it has a
11906 decrementer that subtracts 1 from the value of the counter every time
11907 the loop repeats.
11908
11909 If no prefix argument is given to @code{forward-sentence}, which is
11910 the most common way the command is used, this @code{while} loop will
11911 run once, since the value of @code{arg} will be 1.
11912
11913 The body of the @code{while} loop consists of a @code{let} expression,
11914 which creates and binds a local variable, and has, as its body, an
11915 @code{if} expression.
11916
11917 @need 1250
11918 The body of the @code{while} loop looks like this:
11919
11920 @smallexample
11921 @group
11922 (let ((par-end
11923 (save-excursion (end-of-paragraph-text) (point))))
11924 (if (re-search-forward sentence-end par-end t)
11925 (skip-chars-backward " \t\n")
11926 (goto-char par-end)))
11927 @end group
11928 @end smallexample
11929
11930 The @code{let} expression creates and binds the local variable
11931 @code{par-end}. As we shall see, this local variable is designed to
11932 provide a bound or limit to the regular expression search. If the
11933 search fails to find a proper sentence ending in the paragraph, it will
11934 stop on reaching the end of the paragraph.
11935
11936 But first, let us examine how @code{par-end} is bound to the value of
11937 the end of the paragraph. What happens is that the @code{let} sets the
11938 value of @code{par-end} to the value returned when the Lisp interpreter
11939 evaluates the expression
11940
11941 @smallexample
11942 @group
11943 (save-excursion (end-of-paragraph-text) (point))
11944 @end group
11945 @end smallexample
11946
11947 @noindent
11948 In this expression, @code{(end-of-paragraph-text)} moves point to the
11949 end of the paragraph, @code{(point)} returns the value of point, and then
11950 @code{save-excursion} restores point to its original position. Thus,
11951 the @code{let} binds @code{par-end} to the value returned by the
11952 @code{save-excursion} expression, which is the position of the end of
11953 the paragraph. (The @code{(end-of-paragraph-text)} function uses
11954 @code{forward-paragraph}, which we will discuss shortly.)
11955
11956 @need 1200
11957 Emacs next evaluates the body of the @code{let}, which is an @code{if}
11958 expression that looks like this:
11959
11960 @smallexample
11961 @group
11962 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
11963 (skip-chars-backward " \t\n") ; @r{then-part}
11964 (goto-char par-end))) ; @r{else-part}
11965 @end group
11966 @end smallexample
11967
11968 The @code{if} tests whether its first argument is true and if so,
11969 evaluates its then-part; otherwise, the Emacs Lisp interpreter
11970 evaluates the else-part. The true-or-false-test of the @code{if}
11971 expression is the regular expression search.
11972
11973 It may seem odd to have what looks like the `real work' of
11974 the @code{forward-sentence} function buried here, but this is a common
11975 way this kind of operation is carried out in Lisp.
11976
11977 @node fwd-sentence re-search, , fwd-sentence while loops, forward-sentence
11978 @unnumberedsubsec The regular expression search
11979
11980 The @code{re-search-forward} function searches for the end of the
11981 sentence, that is, for the pattern defined by the @code{sentence-end}
11982 regular expression. If the pattern is found---if the end of the sentence is
11983 found---then the @code{re-search-forward} function does two things:
11984
11985 @enumerate
11986 @item
11987 The @code{re-search-forward} function carries out a side effect, which
11988 is to move point to the end of the occurrence found.
11989
11990 @item
11991 The @code{re-search-forward} function returns a value of true. This is
11992 the value received by the @code{if}, and means that the search was
11993 successful.
11994 @end enumerate
11995
11996 @noindent
11997 The side effect, the movement of point, is completed before the
11998 @code{if} function is handed the value returned by the successful
11999 conclusion of the search.
12000
12001 When the @code{if} function receives the value of true from a successful
12002 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12003 which is the expression @code{(skip-chars-backward " \t\n")}. This
12004 expression moves backwards over any blank spaces, tabs or carriage
12005 returns until a printed character is found and then leaves point after
12006 the character. Since point has already been moved to the end of the
12007 pattern that marks the end of the sentence, this action leaves point
12008 right after the closing printed character of the sentence, which is
12009 usually a period.
12010
12011 On the other hand, if the @code{re-search-forward} function fails to
12012 find a pattern marking the end of the sentence, the function returns
12013 false. The false then causes the @code{if} to evaluate its third
12014 argument, which is @code{(goto-char par-end)}: it moves point to the
12015 end of the paragraph.
12016
12017 Regular expression searches are exceptionally useful and the pattern
12018 illustrated by @code{re-search-forward}, in which the search is the
12019 test of an @code{if} expression, is handy. You will see or write code
12020 incorporating this pattern often.
12021
12022 @node forward-paragraph, etags, forward-sentence, Regexp Search
12023 @comment node-name, next, previous, up
12024 @section @code{forward-paragraph}: a Goldmine of Functions
12025 @findex forward-paragraph
12026
12027 The @code{forward-paragraph} function moves point forward to the end
12028 of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12029 number of functions that are important in themselves, including
12030 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12031
12032 The function definition for @code{forward-paragraph} is considerably
12033 longer than the function definition for @code{forward-sentence}
12034 because it works with a paragraph, each line of which may begin with a
12035 fill prefix.
12036
12037 A fill prefix consists of a string of characters that are repeated at
12038 the beginning of each line. For example, in Lisp code, it is a
12039 convention to start each line of a paragraph-long comment with
12040 @samp{;;; }. In Text mode, four blank spaces make up another common
12041 fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
12042 emacs, The GNU Emacs Manual}, for more information about fill
12043 prefixes.)
12044
12045 The existence of a fill prefix means that in addition to being able to
12046 find the end of a paragraph whose lines begin on the left-most
12047 column, the @code{forward-paragraph} function must be able to find the
12048 end of a paragraph when all or many of the lines in the buffer begin
12049 with the fill prefix.
12050
12051 Moreover, it is sometimes practical to ignore a fill prefix that
12052 exists, especially when blank lines separate paragraphs.
12053 This is an added complication.
12054
12055 @menu
12056 * forward-paragraph in brief:: Key parts of the function definition.
12057 * fwd-para let:: The @code{let*} expression.
12058 * fwd-para while:: The forward motion @code{while} loop.
12059 * fwd-para between paragraphs:: Movement between paragraphs.
12060 * fwd-para within paragraph:: Movement within paragraphs.
12061 * fwd-para no fill prefix:: When there is no fill prefix.
12062 * fwd-para with fill prefix:: When there is a fill prefix.
12063 * fwd-para summary:: Summary of @code{forward-paragraph} code.
12064 @end menu
12065
12066 @node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12067 @ifnottex
12068 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
12069 @end ifnottex
12070
12071 Rather than print all of the @code{forward-paragraph} function, we
12072 will only print parts of it. Read without preparation, the function
12073 can be daunting!
12074
12075 @need 800
12076 In outline, the function looks like this:
12077
12078 @smallexample
12079 @group
12080 (defun forward-paragraph (&optional arg)
12081 "@var{documentation}@dots{}"
12082 (interactive "p")
12083 (or arg (setq arg 1))
12084 (let*
12085 @var{varlist}
12086 (while (< arg 0) ; @r{backward-moving-code}
12087 @dots{}
12088 (setq arg (1+ arg)))
12089 (while (> arg 0) ; @r{forward-moving-code}
12090 @dots{}
12091 (setq arg (1- arg)))))
12092 @end group
12093 @end smallexample
12094
12095 The first parts of the function are routine: the function's argument
12096 list consists of one optional argument. Documentation follows.
12097
12098 The lower case @samp{p} in the @code{interactive} declaration means
12099 that the processed prefix argument, if any, is passed to the function.
12100 This will be a number, and is the repeat count of how many paragraphs
12101 point will move. The @code{or} expression in the next line handles
12102 the common case when no argument is passed to the function, which occurs
12103 if the function is called from other code rather than interactively.
12104 This case was described earlier. (@xref{forward-sentence, The
12105 @code{forward-sentence} function}.) Now we reach the end of the
12106 familiar part of this function.
12107
12108 @node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12109 @unnumberedsubsec The @code{let*} expression
12110
12111 The next line of the @code{forward-paragraph} function begins a
12112 @code{let*} expression. This is a different kind of expression than
12113 we have seen so far. The symbol is @code{let*} not @code{let}.
12114
12115 The @code{let*} special form is like @code{let} except that Emacs sets
12116 each variable in sequence, one after another, and variables in the
12117 latter part of the varlist can make use of the values to which Emacs
12118 set variables in the earlier part of the varlist.
12119
12120 In the @code{let*} expression in this function, Emacs binds two
12121 variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12122 The value to which @code{paragraph-separate} is bound depends on the
12123 value of @code{fill-prefix-regexp}.
12124
12125 @need 1200
12126 Let's look at each in turn. The symbol @code{fill-prefix-regexp} is
12127 set to the value returned by evaluating the following list:
12128
12129 @smallexample
12130 @group
12131 (and fill-prefix
12132 (not (equal fill-prefix ""))
12133 (not paragraph-ignore-fill-prefix)
12134 (regexp-quote fill-prefix))
12135 @end group
12136 @end smallexample
12137
12138 @noindent
12139 This is an expression whose first element is the @code{and} special form.
12140
12141 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12142 function}), the @code{and} special form evaluates each of its
12143 arguments until one of the arguments returns a value of @code{nil}, in
12144 which case the @code{and} expression returns @code{nil}; however, if
12145 none of the arguments returns a value of @code{nil}, the value
12146 resulting from evaluating the last argument is returned. (Since such
12147 a value is not @code{nil}, it is considered true in Lisp.) In other
12148 words, an @code{and} expression returns a true value only if all its
12149 arguments are true.
12150 @findex and
12151
12152 In this case, the variable @code{fill-prefix-regexp} is bound to a
12153 non-@code{nil} value only if the following four expressions produce a
12154 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12155 @code{fill-prefix-regexp} is bound to @code{nil}.
12156
12157 @table @code
12158 @item fill-prefix
12159 When this variable is evaluated, the value of the fill prefix, if any,
12160 is returned. If there is no fill prefix, this variable returns
12161 @code{nil}.
12162
12163 @item (not (equal fill-prefix "")
12164 This expression checks whether an existing fill prefix is an empty
12165 string, that is, a string with no characters in it. An empty string is
12166 not a useful fill prefix.
12167
12168 @item (not paragraph-ignore-fill-prefix)
12169 This expression returns @code{nil} if the variable
12170 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12171 true value such as @code{t}.
12172
12173 @item (regexp-quote fill-prefix)
12174 This is the last argument to the @code{and} special form. If all the
12175 arguments to the @code{and} are true, the value resulting from
12176 evaluating this expression will be returned by the @code{and} expression
12177 and bound to the variable @code{fill-prefix-regexp},
12178 @end table
12179
12180 @findex regexp-quote
12181 @noindent
12182 The result of evaluating this @code{and} expression successfully is that
12183 @code{fill-prefix-regexp} will be bound to the value of
12184 @code{fill-prefix} as modified by the @code{regexp-quote} function.
12185 What @code{regexp-quote} does is read a string and return a regular
12186 expression that will exactly match the string and match nothing else.
12187 This means that @code{fill-prefix-regexp} will be set to a value that
12188 will exactly match the fill prefix if the fill prefix exists.
12189 Otherwise, the variable will be set to @code{nil}.
12190
12191 The second local variable in the @code{let*} expression is
12192 @code{paragraph-separate}. It is bound to the value returned by
12193 evaluating the expression:
12194
12195 @smallexample
12196 @group
12197 (if fill-prefix-regexp
12198 (concat paragraph-separate
12199 "\\|^" fill-prefix-regexp "[ \t]*$")
12200 paragraph-separate)))
12201 @end group
12202 @end smallexample
12203
12204 This expression shows why @code{let*} rather than @code{let} was used.
12205 The true-or-false-test for the @code{if} depends on whether the variable
12206 @code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12207
12208 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12209 the else-part of the @code{if} expression and binds
12210 @code{paragraph-separate} to its local value.
12211 (@code{paragraph-separate} is a regular expression that matches what
12212 separates paragraphs.)
12213
12214 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12215 the then-part of the @code{if} expression and binds
12216 @code{paragraph-separate} to a regular expression that includes the
12217 @code{fill-prefix-regexp} as part of the pattern.
12218
12219 Specifically, @code{paragraph-separate} is set to the original value
12220 of the paragraph separate regular expression concatenated with an
12221 alternative expression that consists of the @code{fill-prefix-regexp}
12222 followed by a blank line. The @samp{^} indicates that the
12223 @code{fill-prefix-regexp} must begin a line, and the optional
12224 whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12225 The @samp{\\|} defines this portion of the regexp as an alternative to
12226 @code{paragraph-separate}.
12227
12228 Now we get into the body of the @code{let*}. The first part of the body
12229 of the @code{let*} deals with the case when the function is given a
12230 negative argument and is therefore moving backwards. We will skip this
12231 section.
12232
12233 @node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12234 @unnumberedsubsec The forward motion @code{while} loop
12235
12236 The second part of the body of the @code{let*} deals with forward
12237 motion. It is a @code{while} loop that repeats itself so long as the
12238 value of @code{arg} is greater than zero. In the most common use of
12239 the function, the value of the argument is 1, so the body of the
12240 @code{while} loop is evaluated exactly once, and the cursor moves
12241 forward one paragraph.
12242
12243 This part handles three situations: when point is between paragraphs,
12244 when point is within a paragraph and there is a fill prefix, and
12245 when point is within a paragraph and there is no fill prefix.
12246
12247 @need 800
12248 The @code{while} loop looks like this:
12249
12250 @smallexample
12251 @group
12252 (while (> arg 0)
12253 (beginning-of-line)
12254
12255 ;; @r{between paragraphs}
12256 (while (prog1 (and (not (eobp))
12257 (looking-at paragraph-separate))
12258 (forward-line 1)))
12259 @end group
12260
12261 @group
12262 ;; @r{within paragraphs, with a fill prefix}
12263 (if fill-prefix-regexp
12264 ;; @r{There is a fill prefix; it overrides paragraph-start.}
12265 (while (and (not (eobp))
12266 (not (looking-at paragraph-separate))
12267 (looking-at fill-prefix-regexp))
12268 (forward-line 1))
12269 @end group
12270
12271 @group
12272 ;; @r{within paragraphs, no fill prefix}
12273 (if (re-search-forward paragraph-start nil t)
12274 (goto-char (match-beginning 0))
12275 (goto-char (point-max))))
12276
12277 (setq arg (1- arg)))
12278 @end group
12279 @end smallexample
12280
12281 We can see immediately that this is a decrementing counter @code{while}
12282 loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12283
12284 @need 800
12285 The body of the loop consists of three expressions:
12286
12287 @smallexample
12288 @group
12289 ;; @r{between paragraphs}
12290 (beginning-of-line)
12291 (while
12292 @var{body-of-while})
12293 @end group
12294
12295 @group
12296 ;; @r{within paragraphs, with fill prefix}
12297 (if @var{true-or-false-test}
12298 @var{then-part}
12299 @end group
12300
12301 @group
12302 ;; @r{within paragraphs, no fill prefix}
12303 @var{else-part}
12304 @end group
12305 @end smallexample
12306
12307 @noindent
12308 When the Emacs Lisp interpreter evaluates the body of the
12309 @code{while} loop, the first thing it does is evaluate the
12310 @code{(beginning-of-line)} expression and move point to the beginning
12311 of the line. Then there is an inner @code{while} loop. This
12312 @code{while} loop is designed to move the cursor out of the blank
12313 space between paragraphs, if it should happen to be there. Finally,
12314 there is an @code{if} expression that actually moves point to the end
12315 of the paragraph.
12316
12317 @node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12318 @unnumberedsubsec Between paragraphs
12319
12320 First, let us look at the inner @code{while} loop. This loop handles
12321 the case when point is between paragraphs; it uses three functions
12322 that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12323 @findex prog1
12324 @findex eobp
12325 @findex looking-at
12326
12327 @itemize @bullet
12328 @item
12329 @code{prog1} is similar to the @code{progn} special form,
12330 except that @code{prog1} evaluates its arguments in sequence and then
12331 returns the value of its first argument as the value of the whole
12332 expression. (@code{progn} returns the value of its last argument as the
12333 value of the expression.) The second and subsequent arguments to
12334 @code{prog1} are evaluated only for their side effects.
12335
12336 @item
12337 @code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12338 function that returns true if point is at the end of the buffer.
12339
12340 @item
12341 @code{looking-at} is a function that returns true if the text following
12342 point matches the regular expression passed @code{looking-at} as its
12343 argument.
12344 @end itemize
12345
12346 @need 800
12347 The @code{while} loop we are studying looks like this:
12348
12349 @smallexample
12350 @group
12351 (while (prog1 (and (not (eobp))
12352 (looking-at paragraph-separate))
12353 (forward-line 1)))
12354 @end group
12355 @end smallexample
12356
12357 @need 1200
12358 @noindent
12359 This is a @code{while} loop with no body! The true-or-false-test of the
12360 loop is the expression:
12361
12362 @smallexample
12363 @group
12364 (prog1 (and (not (eobp))
12365 (looking-at paragraph-separate))
12366 (forward-line 1))
12367 @end group
12368 @end smallexample
12369
12370 @noindent
12371 The first argument to the @code{prog1} is the @code{and} expression. It
12372 has within in it a test of whether point is at the end of the buffer and
12373 also a test of whether the pattern following point matches the regular
12374 expression for separating paragraphs.
12375
12376 If the cursor is not at the end of the buffer and if the characters
12377 following the cursor mark the separation between two paragraphs, then
12378 the @code{and} expression is true. After evaluating the @code{and}
12379 expression, the Lisp interpreter evaluates the second argument to
12380 @code{prog1}, which is @code{forward-line}. This moves point forward
12381 one line. The value returned by the @code{prog1} however, is the
12382 value of its first argument, so the @code{while} loop continues so
12383 long as point is not at the end of the buffer and is between
12384 paragraphs. When, finally, point is moved to a paragraph, the
12385 @code{and} expression tests false. Note however, that the
12386 @code{forward-line} command is carried out anyhow. This means that
12387 when point is moved from between paragraphs to a paragraph, it is left
12388 at the beginning of the second line of the paragraph.
12389
12390 @node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12391 @unnumberedsubsec Within paragraphs
12392
12393 The next expression in the outer @code{while} loop is an @code{if}
12394 expression. The Lisp interpreter evaluates the then-part of the
12395 @code{if} when the @code{fill-prefix-regexp} variable has a value other
12396 than @code{nil}, and it evaluates the else-part when the value of
12397 @code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12398 fill prefix.
12399
12400 @node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12401 @unnumberedsubsec No fill prefix
12402
12403 It is simplest to look at the code for the case when there is no fill
12404 prefix first. This code consists of yet another inner @code{if}
12405 expression, and reads as follows:
12406
12407 @smallexample
12408 @group
12409 (if (re-search-forward paragraph-start nil t)
12410 (goto-char (match-beginning 0))
12411 (goto-char (point-max)))
12412 @end group
12413 @end smallexample
12414
12415 @noindent
12416 This expression actually does the work that most people think of as
12417 the primary purpose of the @code{forward-paragraph} command: it causes
12418 a regular expression search to occur that searches forward to the
12419 start of the next paragraph and if it is found, moves point there; but
12420 if the start of another paragraph if not found, it moves point to the
12421 end of the accessible region of the buffer.
12422
12423 The only unfamiliar part of this is the use of @code{match-beginning}.
12424 This is another function that is new to us. The
12425 @code{match-beginning} function returns a number specifying the
12426 location of the start of the text that was matched by the last regular
12427 expression search.
12428
12429 The @code{match-beginning} function is used here because of a
12430 characteristic of a forward search: a successful forward search,
12431 regardless of whether it is a plain search or a regular expression
12432 search, will move point to the end of the text that is found. In this
12433 case, a successful search will move point to the end of the pattern for
12434 @code{paragraph-start}, which will be the beginning of the next
12435 paragraph rather than the end of the current one.
12436
12437 However, we want to put point at the end of the current paragraph, not at
12438 the beginning of the next one. The two positions may be different,
12439 because there may be several blank lines between paragraphs.
12440
12441 @findex match-beginning
12442 When given an argument of 0, @code{match-beginning} returns the position
12443 that is the start of the text that the most recent regular
12444 expression search matched. In this case, the most recent regular
12445 expression search is the one looking for @code{paragraph-start}, so
12446 @code{match-beginning} returns the beginning position of the pattern,
12447 rather than the end of the pattern. The beginning position is the end
12448 of the paragraph.
12449
12450 (Incidentally, when passed a positive number as an argument, the
12451 @code{match-beginning} function will place point at that parenthesized
12452 expression in the last regular expression. It is a useful function.)
12453
12454 @node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12455 @unnumberedsubsec With a fill prefix
12456
12457 The inner @code{if} expression just discussed is the else-part of an enclosing
12458 @code{if} expression which tests whether there is a fill prefix. If
12459 there is a fill prefix, the then-part of this @code{if} is evaluated.
12460 It looks like this:
12461
12462 @smallexample
12463 @group
12464 (while (and (not (eobp))
12465 (not (looking-at paragraph-separate))
12466 (looking-at fill-prefix-regexp))
12467 (forward-line 1))
12468 @end group
12469 @end smallexample
12470
12471 @noindent
12472 What this expression does is move point forward line by line so long
12473 as three conditions are true:
12474
12475 @enumerate
12476 @item
12477 Point is not at the end of the buffer.
12478
12479 @item
12480 The text following point does not separate paragraphs.
12481
12482 @item
12483 The pattern following point is the fill prefix regular expression.
12484 @end enumerate
12485
12486 The last condition may be puzzling, until you remember that point was
12487 moved to the beginning of the line early in the @code{forward-paragraph}
12488 function. This means that if the text has a fill prefix, the
12489 @code{looking-at} function will see it.
12490
12491 @node fwd-para summary, , fwd-para with fill prefix, forward-paragraph
12492 @unnumberedsubsec Summary
12493
12494 In summary, when moving forward, the @code{forward-paragraph} function
12495 does the following:
12496
12497 @itemize @bullet
12498 @item
12499 Move point to the beginning of the line.
12500
12501 @item
12502 Skip over lines between paragraphs.
12503
12504 @item
12505 Check whether there is a fill prefix, and if there is:
12506
12507 @itemize ---
12508
12509 @item
12510 Go forward line by line so long as the line is not a paragraph
12511 separating line.
12512 @end itemize
12513
12514 @item
12515 But if there is no fill prefix,
12516
12517 @itemize ---
12518
12519 @item
12520 Search for the next paragraph start pattern.
12521
12522 @item
12523 Go to the beginning of the paragraph start pattern, which will be the
12524 end of the previous paragraph.
12525
12526 @item
12527 Or else go to the end of the accessible portion of the buffer.
12528 @end itemize
12529 @end itemize
12530
12531 @need 1200
12532 For review, here is the code we have just been discussing, formatted
12533 for clarity:
12534
12535 @smallexample
12536 @group
12537 (interactive "p")
12538 (or arg (setq arg 1))
12539 (let* (
12540 (fill-prefix-regexp
12541 (and fill-prefix (not (equal fill-prefix ""))
12542 (not paragraph-ignore-fill-prefix)
12543 (regexp-quote fill-prefix)))
12544 @end group
12545
12546 @group
12547 (paragraph-separate
12548 (if fill-prefix-regexp
12549 (concat paragraph-separate
12550 "\\|^"
12551 fill-prefix-regexp
12552 "[ \t]*$")
12553 paragraph-separate)))
12554
12555 @var{omitted-backward-moving-code} @dots{}
12556 @end group
12557
12558 @group
12559 (while (> arg 0) ; @r{forward-moving-code}
12560 (beginning-of-line)
12561
12562 (while (prog1 (and (not (eobp))
12563 (looking-at paragraph-separate))
12564 (forward-line 1)))
12565 @end group
12566
12567 @group
12568 (if fill-prefix-regexp
12569 (while (and (not (eobp)) ; @r{then-part}
12570 (not (looking-at paragraph-separate))
12571 (looking-at fill-prefix-regexp))
12572 (forward-line 1))
12573 @end group
12574 @group
12575 ; @r{else-part: the inner-if}
12576 (if (re-search-forward paragraph-start nil t)
12577 (goto-char (match-beginning 0))
12578 (goto-char (point-max))))
12579
12580 (setq arg (1- arg))))) ; @r{decrementer}
12581 @end group
12582 @end smallexample
12583
12584 The full definition for the @code{forward-paragraph} function not only
12585 includes this code for going forwards, but also code for going backwards.
12586
12587 If you are reading this inside of GNU Emacs and you want to see the
12588 whole function, you can type @kbd{C-h f} (@code{describe-function})
12589 and the name of the function. This gives you the function
12590 documentation and the name of the library containing the function's
12591 source. Place point over the name of the library and press the RET
12592 key; you will be taken directly to the source. (Be sure to install
12593 your sources! Without them, you are like a person who tries to drive
12594 a car with his eyes shut!)
12595
12596 @c !!! again, 21.0.100 tags table location in this paragraph
12597 Or -- a good habit to get into -- you can type @kbd{M-.}
12598 (@code{find-tag}) and the name of the function when prompted for it.
12599 This will take you directly to the source. If the @code{find-tag}
12600 function first asks you for the name of a @file{TAGS} table, give it
12601 the name of the @file{TAGS} file such as
12602 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS}. (The exact path to your
12603 @file{TAGS} file depends on how your copy of Emacs was installed.)
12604
12605 You can also create your own @file{TAGS} file for directories that
12606 lack one.
12607 @ifnottex
12608 @xref{etags, , Create Your Own @file{TAGS} File}.
12609 @end ifnottex
12610
12611 @node etags, Regexp Review, forward-paragraph, Regexp Search
12612 @section Create Your Own @file{TAGS} File
12613 @findex etags
12614 @cindex @file{TAGS} file, create own
12615
12616 The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12617 source for a function, variable, node, or other source. The function
12618 depends on tags tables to tell it where to go.
12619
12620 You often need to build and install tags tables yourself. They are
12621 not built automatically. A tags table is called a @file{TAGS} file;
12622 the name is in upper case letters.
12623
12624 You can create a @file{TAGS} file by calling the @code{etags} program
12625 that comes as a part of the Emacs distribution. Usually, @code{etags}
12626 is compiled and installed when Emacs is built. (@code{etags} is not
12627 an Emacs Lisp function or a part of Emacs; it is a C program.)
12628
12629 @need 1250
12630 To create a @file{TAGS} file, first switch to the directory in which
12631 you want to create the file. In Emacs you can do this with the
12632 @kbd{M-x cd} command, or by visiting a file in the directory, or by
12633 listing the directory with @kbd{C-x d} (@code{dired}). Then run the
12634 compile command, with @w{@code{etags *.el}} as the command to execute
12635
12636 @smallexample
12637 M-x compile RET etags *.el RET
12638 @end smallexample
12639
12640 @noindent
12641 to create a @file{TAGS} file.
12642
12643 For example, if you have a large number of files in your
12644 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12645 of which I load 12---you can create a @file{TAGS} file for the Emacs
12646 Lisp files in that directory.
12647
12648 @need 1250
12649 The @code{etags} program takes all the
12650 usual shell `wildcards'. For example, if you have two directories for
12651 which you want a single @file{TAGS file}, type
12652 @w{@code{etags *.el ../elisp/*.el}},
12653 where @file{../elisp/} is the second directory:
12654
12655 @smallexample
12656 M-x compile RET etags *.el ../elisp/*.el RET
12657 @end smallexample
12658
12659 @need 1250
12660 Type
12661
12662 @smallexample
12663 M-x compile RET etags --help RET
12664 @end smallexample
12665
12666 @noindent
12667 to see a list of the options accepted by @code{etags} as well as a
12668 list of supported languages.
12669
12670 The @code{etags} program handles more than 20 languages, including
12671 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12672 Pascal, Perl, Python, Texinfo, makefiles, and most assemblers. The
12673 program has no switches for specifying the language; it recognizes the
12674 language in an input file according to its file name and contents.
12675
12676 @file{etags} is very helpful when you are writing code yourself and
12677 want to refer back to functions you have already written. Just run
12678 @code{etags} again at intervals as you write new functions, so they
12679 become part of the @file{TAGS} file.
12680
12681 If you think an appropriate @file{TAGS} file already exists for what
12682 you want, but do not know where it is, you can use the @code{locate}
12683 program to attempt to find it.
12684
12685 Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12686 full path names of all your @file{TAGS} files. On my system, this
12687 command lists 34 @file{TAGS} files. On the other hand, a `plain
12688 vanilla' system I recently installed did not contain any @file{TAGS}
12689 files.
12690
12691 If the tags table you want has been created, you can use the @code{M-x
12692 visit-tags-table} command to specify it. Otherwise, you will need to
12693 create the tag table yourself and then use @code{M-x
12694 visit-tags-table}.
12695
12696 @subsubheading Building Tags in the Emacs sources
12697 @cindex Building Tags in the Emacs sources
12698 @cindex Tags in the Emacs sources
12699 @findex make tags
12700
12701 The GNU Emacs sources come with a @file{Makefile} that contains a
12702 sophisticated @code{etags} command that creates, collects, and merges
12703 tags tables from all over the Emacs sources and puts the information
12704 into one @file{TAGS} file in the @file{src/} directory below the top
12705 level of your Emacs source directory.
12706
12707 @need 1250
12708 To build this @file{TAGS} file, go to the top level of your Emacs
12709 source directory and run the compile command @code{make tags}:
12710
12711 @smallexample
12712 M-x compile RET make tags RET
12713 @end smallexample
12714
12715 @noindent
12716 (The @code{make tags} command works well with the GNU Emacs sources,
12717 as well as with some other source packages.)
12718
12719 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12720 Manual}.
12721
12722 @node Regexp Review, re-search Exercises, etags, Regexp Search
12723 @comment node-name, next, previous, up
12724 @section Review
12725
12726 Here is a brief summary of some recently introduced functions.
12727
12728 @table @code
12729 @item while
12730 Repeatedly evaluate the body of the expression so long as the first
12731 element of the body tests true. Then return @code{nil}. (The
12732 expression is evaluated only for its side effects.)
12733
12734 @need 1250
12735 For example:
12736
12737 @smallexample
12738 @group
12739 (let ((foo 2))
12740 (while (> foo 0)
12741 (insert (format "foo is %d.\n" foo))
12742 (setq foo (1- foo))))
12743
12744 @result{} foo is 2.
12745 foo is 1.
12746 nil
12747 @end group
12748 @end smallexample
12749 @noindent
12750 (The @code{insert} function inserts its arguments at point; the
12751 @code{format} function returns a string formatted from its arguments
12752 the way @code{message} formats its arguments; @code{\n} produces a new
12753 line.)
12754
12755 @item re-search-forward
12756 Search for a pattern, and if the pattern is found, move point to rest
12757 just after it.
12758
12759 @noindent
12760 Takes four arguments, like @code{search-forward}:
12761
12762 @enumerate
12763 @item
12764 A regular expression that specifies the pattern to search for.
12765
12766 @item
12767 Optionally, the limit of the search.
12768
12769 @item
12770 Optionally, what to do if the search fails, return @code{nil} or an
12771 error message.
12772
12773 @item
12774 Optionally, how many times to repeat the search; if negative, the
12775 search goes backwards.
12776 @end enumerate
12777
12778 @item let*
12779 Bind some variables locally to particular values,
12780 and then evaluate the remaining arguments, returning the value of the
12781 last one. While binding the local variables, use the local values of
12782 variables bound earlier, if any.
12783
12784 @need 1250
12785 For example:
12786
12787 @smallexample
12788 @group
12789 (let* ((foo 7)
12790 (bar (* 3 foo)))
12791 (message "`bar' is %d." bar))
12792 @result{} `bar' is 21.
12793 @end group
12794 @end smallexample
12795
12796 @item match-beginning
12797 Return the position of the start of the text found by the last regular
12798 expression search.
12799
12800 @item looking-at
12801 Return @code{t} for true if the text after point matches the argument,
12802 which should be a regular expression.
12803
12804 @item eobp
12805 Return @code{t} for true if point is at the end of the accessible part
12806 of a buffer. The end of the accessible part is the end of the buffer
12807 if the buffer is not narrowed; it is the end of the narrowed part if
12808 the buffer is narrowed.
12809
12810 @item prog1
12811 Evaluate each argument in sequence and then return the value of the
12812 @emph{first}.
12813
12814 @need 1250
12815 For example:
12816
12817 @smallexample
12818 @group
12819 (prog1 1 2 3 4)
12820 @result{} 1
12821 @end group
12822 @end smallexample
12823 @end table
12824
12825 @need 1500
12826 @node re-search Exercises, , Regexp Review, Regexp Search
12827 @section Exercises with @code{re-search-forward}
12828
12829 @itemize @bullet
12830 @item
12831 Write a function to search for a regular expression that matches two
12832 or more blank lines in sequence.
12833
12834 @item
12835 Write a function to search for duplicated words, such as `the the'.
12836 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12837 Manual}, for information on how to write a regexp (a regular
12838 expression) to match a string that is composed of two identical
12839 halves. You can devise several regexps; some are better than others.
12840 The function I use is described in an appendix, along with several
12841 regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
12842 @end itemize
12843
12844 @node Counting Words, Words in a defun, Regexp Search, Top
12845 @chapter Counting: Repetition and Regexps
12846 @cindex Repetition for word counting
12847 @cindex Regular expressions for word counting
12848
12849 Repetition and regular expression searches are powerful tools that you
12850 often use when you write code in Emacs Lisp. This chapter illustrates
12851 the use of regular expression searches through the construction of
12852 word count commands using @code{while} loops and recursion.
12853
12854 @menu
12855 * Why Count Words::
12856 * count-words-region:: Use a regexp, but find a problem.
12857 * recursive-count-words:: Start with case of no words in region.
12858 * Counting Exercise::
12859 @end menu
12860
12861 @node Why Count Words, count-words-region, Counting Words, Counting Words
12862 @ifnottex
12863 @unnumberedsec Counting words
12864 @end ifnottex
12865
12866 The standard Emacs distribution contains a function for counting the
12867 number of lines within a region. However, there is no corresponding
12868 function for counting words.
12869
12870 Certain types of writing ask you to count words. Thus, if you write
12871 an essay, you may be limited to 800 words; if you write a novel, you
12872 may discipline yourself to write 1000 words a day. It seems odd to me
12873 that Emacs lacks a word count command. Perhaps people use Emacs
12874 mostly for code or types of documentation that do not require word
12875 counts; or perhaps they restrict themselves to the operating system
12876 word count command, @code{wc}. Alternatively, people may follow
12877 the publishers' convention and compute a word count by dividing the
12878 number of characters in a document by five. In any event, here are
12879 commands to count words.
12880
12881 @node count-words-region, recursive-count-words, Why Count Words, Counting Words
12882 @comment node-name, next, previous, up
12883 @section The @code{count-words-region} Function
12884 @findex count-words-region
12885
12886 A word count command could count words in a line, paragraph, region,
12887 or buffer. What should the command cover? You could design the
12888 command to count the number of words in a complete buffer. However,
12889 the Emacs tradition encourages flexibility---you may want to count
12890 words in just a section, rather than all of a buffer. So it makes
12891 more sense to design the command to count the number of words in a
12892 region. Once you have a @code{count-words-region} command, you can,
12893 if you wish, count words in a whole buffer by marking it with @kbd{C-x
12894 h} (@code{mark-whole-buffer}).
12895
12896 Clearly, counting words is a repetitive act: starting from the
12897 beginning of the region, you count the first word, then the second
12898 word, then the third word, and so on, until you reach the end of the
12899 region. This means that word counting is ideally suited to recursion
12900 or to a @code{while} loop.
12901
12902 @menu
12903 * Design count-words-region:: The definition using a @code{while} loop.
12904 * Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
12905 @end menu
12906
12907 @node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12908 @ifnottex
12909 @unnumberedsubsec Designing @code{count-words-region}
12910 @end ifnottex
12911
12912 First, we will implement the word count command with a @code{while}
12913 loop, then with recursion. The command will, of course, be
12914 interactive.
12915
12916 @need 800
12917 The template for an interactive function definition is, as always:
12918
12919 @smallexample
12920 @group
12921 (defun @var{name-of-function} (@var{argument-list})
12922 "@var{documentation}@dots{}"
12923 (@var{interactive-expression}@dots{})
12924 @var{body}@dots{})
12925 @end group
12926 @end smallexample
12927
12928 What we need to do is fill in the slots.
12929
12930 The name of the function should be self-explanatory and similar to the
12931 existing @code{count-lines-region} name. This makes the name easier
12932 to remember. @code{count-words-region} is a good choice.
12933
12934 The function counts words within a region. This means that the
12935 argument list must contain symbols that are bound to the two
12936 positions, the beginning and end of the region. These two positions
12937 can be called @samp{beginning} and @samp{end} respectively. The first
12938 line of the documentation should be a single sentence, since that is
12939 all that is printed as documentation by a command such as
12940 @code{apropos}. The interactive expression will be of the form
12941 @samp{(interactive "r")}, since that will cause Emacs to pass the
12942 beginning and end of the region to the function's argument list. All
12943 this is routine.
12944
12945 The body of the function needs to be written to do three tasks:
12946 first, to set up conditions under which the @code{while} loop can
12947 count words, second, to run the @code{while} loop, and third, to send
12948 a message to the user.
12949
12950 When a user calls @code{count-words-region}, point may be at the
12951 beginning or the end of the region. However, the counting process
12952 must start at the beginning of the region. This means we will want
12953 to put point there if it is not already there. Executing
12954 @code{(goto-char beginning)} ensures this. Of course, we will want to
12955 return point to its expected position when the function finishes its
12956 work. For this reason, the body must be enclosed in a
12957 @code{save-excursion} expression.
12958
12959 The central part of the body of the function consists of a
12960 @code{while} loop in which one expression jumps point forward word by
12961 word, and another expression counts those jumps. The true-or-false-test
12962 of the @code{while} loop should test true so long as point should jump
12963 forward, and false when point is at the end of the region.
12964
12965 We could use @code{(forward-word 1)} as the expression for moving point
12966 forward word by word, but it is easier to see what Emacs identifies as a
12967 `word' if we use a regular expression search.
12968
12969 A regular expression search that finds the pattern for which it is
12970 searching leaves point after the last character matched. This means
12971 that a succession of successful word searches will move point forward
12972 word by word.
12973
12974 As a practical matter, we want the regular expression search to jump
12975 over whitespace and punctuation between words as well as over the
12976 words themselves. A regexp that refuses to jump over interword
12977 whitespace would never jump more than one word! This means that
12978 the regexp should include the whitespace and punctuation that follows
12979 a word, if any, as well as the word itself. (A word may end a buffer
12980 and not have any following whitespace or punctuation, so that part of
12981 the regexp must be optional.)
12982
12983 Thus, what we want for the regexp is a pattern defining one or more
12984 word constituent characters followed, optionally, by one or more
12985 characters that are not word constituents. The regular expression for
12986 this is:
12987
12988 @smallexample
12989 \w+\W*
12990 @end smallexample
12991
12992 @noindent
12993 The buffer's syntax table determines which characters are and are not
12994 word constituents. (@xref{Syntax, , What Constitutes a Word or
12995 Symbol?}, for more about syntax. Also, see @ref{Syntax, Syntax, The
12996 Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
12997 Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
12998
12999 @need 800
13000 The search expression looks like this:
13001
13002 @smallexample
13003 (re-search-forward "\\w+\\W*")
13004 @end smallexample
13005
13006 @noindent
13007 (Note that paired backslashes precede the @samp{w} and @samp{W}. A
13008 single backslash has special meaning to the Emacs Lisp interpreter. It
13009 indicates that the following character is interpreted differently than
13010 usual. For example, the two characters, @samp{\n}, stand for
13011 @samp{newline}, rather than for a backslash followed by @samp{n}. Two
13012 backslashes in a row stand for an ordinary, `unspecial' backslash.)
13013
13014 We need a counter to count how many words there are; this variable
13015 must first be set to 0 and then incremented each time Emacs goes
13016 around the @code{while} loop. The incrementing expression is simply:
13017
13018 @smallexample
13019 (setq count (1+ count))
13020 @end smallexample
13021
13022 Finally, we want to tell the user how many words there are in the
13023 region. The @code{message} function is intended for presenting this
13024 kind of information to the user. The message has to be phrased so
13025 that it reads properly regardless of how many words there are in the
13026 region: we don't want to say that ``there are 1 words in the region''.
13027 The conflict between singular and plural is ungrammatical. We can
13028 solve this problem by using a conditional expression that evaluates
13029 different messages depending on the number of words in the region.
13030 There are three possibilities: no words in the region, one word in the
13031 region, and more than one word. This means that the @code{cond}
13032 special form is appropriate.
13033
13034 @need 1500
13035 All this leads to the following function definition:
13036
13037 @smallexample
13038 @group
13039 ;;; @r{First version; has bugs!}
13040 (defun count-words-region (beginning end)
13041 "Print number of words in the region.
13042 Words are defined as at least one word-constituent
13043 character followed by at least one character that
13044 is not a word-constituent. The buffer's syntax
13045 table determines which characters these are."
13046 (interactive "r")
13047 (message "Counting words in region ... ")
13048 @end group
13049
13050 @group
13051 ;;; @r{1. Set up appropriate conditions.}
13052 (save-excursion
13053 (goto-char beginning)
13054 (let ((count 0))
13055 @end group
13056
13057 @group
13058 ;;; @r{2. Run the} while @r{loop.}
13059 (while (< (point) end)
13060 (re-search-forward "\\w+\\W*")
13061 (setq count (1+ count)))
13062 @end group
13063
13064 @group
13065 ;;; @r{3. Send a message to the user.}
13066 (cond ((zerop count)
13067 (message
13068 "The region does NOT have any words."))
13069 ((= 1 count)
13070 (message
13071 "The region has 1 word."))
13072 (t
13073 (message
13074 "The region has %d words." count))))))
13075 @end group
13076 @end smallexample
13077
13078 @noindent
13079 As written, the function works, but not in all circumstances.
13080
13081 @node Whitespace Bug, , Design count-words-region, count-words-region
13082 @comment node-name, next, previous, up
13083 @subsection The Whitespace Bug in @code{count-words-region}
13084
13085 The @code{count-words-region} command described in the preceding
13086 section has two bugs, or rather, one bug with two manifestations.
13087 First, if you mark a region containing only whitespace in the middle
13088 of some text, the @code{count-words-region} command tells you that the
13089 region contains one word! Second, if you mark a region containing
13090 only whitespace at the end of the buffer or the accessible portion of
13091 a narrowed buffer, the command displays an error message that looks
13092 like this:
13093
13094 @smallexample
13095 Search failed: "\\w+\\W*"
13096 @end smallexample
13097
13098 If you are reading this in Info in GNU Emacs, you can test for these
13099 bugs yourself.
13100
13101 First, evaluate the function in the usual manner to install it.
13102 @ifinfo
13103 Here is a copy of the definition. Place your cursor after the closing
13104 parenthesis and type @kbd{C-x C-e} to install it.
13105
13106 @smallexample
13107 @group
13108 ;; @r{First version; has bugs!}
13109 (defun count-words-region (beginning end)
13110 "Print number of words in the region.
13111 Words are defined as at least one word-constituent character followed
13112 by at least one character that is not a word-constituent. The buffer's
13113 syntax table determines which characters these are."
13114 @end group
13115 @group
13116 (interactive "r")
13117 (message "Counting words in region ... ")
13118 @end group
13119
13120 @group
13121 ;;; @r{1. Set up appropriate conditions.}
13122 (save-excursion
13123 (goto-char beginning)
13124 (let ((count 0))
13125 @end group
13126
13127 @group
13128 ;;; @r{2. Run the} while @r{loop.}
13129 (while (< (point) end)
13130 (re-search-forward "\\w+\\W*")
13131 (setq count (1+ count)))
13132 @end group
13133
13134 @group
13135 ;;; @r{3. Send a message to the user.}
13136 (cond ((zerop count)
13137 (message "The region does NOT have any words."))
13138 ((= 1 count) (message "The region has 1 word."))
13139 (t (message "The region has %d words." count))))))
13140 @end group
13141 @end smallexample
13142 @end ifinfo
13143
13144 @need 1000
13145 If you wish, you can also install this keybinding by evaluating it:
13146
13147 @smallexample
13148 (global-set-key "\C-c=" 'count-words-region)
13149 @end smallexample
13150
13151 To conduct the first test, set mark and point to the beginning and end
13152 of the following line and then type @kbd{C-c =} (or @kbd{M-x
13153 count-words-region} if you have not bound @kbd{C-c =}):
13154
13155 @smallexample
13156 one two three
13157 @end smallexample
13158
13159 @noindent
13160 Emacs will tell you, correctly, that the region has three words.
13161
13162 Repeat the test, but place mark at the beginning of the line and place
13163 point just @emph{before} the word @samp{one}. Again type the command
13164 @kbd{C-c =} (or @kbd{M-x count-words-region}). Emacs should tell you
13165 that the region has no words, since it is composed only of the
13166 whitespace at the beginning of the line. But instead Emacs tells you
13167 that the region has one word!
13168
13169 For the third test, copy the sample line to the end of the
13170 @file{*scratch*} buffer and then type several spaces at the end of the
13171 line. Place mark right after the word @samp{three} and point at the
13172 end of line. (The end of the line will be the end of the buffer.)
13173 Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13174 Again, Emacs should tell you that the region has no words, since it is
13175 composed only of the whitespace at the end of the line. Instead,
13176 Emacs displays an error message saying @samp{Search failed}.
13177
13178 The two bugs stem from the same problem.
13179
13180 Consider the first manifestation of the bug, in which the command
13181 tells you that the whitespace at the beginning of the line contains
13182 one word. What happens is this: The @code{M-x count-words-region}
13183 command moves point to the beginning of the region. The @code{while}
13184 tests whether the value of point is smaller than the value of
13185 @code{end}, which it is. Consequently, the regular expression search
13186 looks for and finds the first word. It leaves point after the word.
13187 @code{count} is set to one. The @code{while} loop repeats; but this
13188 time the value of point is larger than the value of @code{end}, the
13189 loop is exited; and the function displays a message saying the number
13190 of words in the region is one. In brief, the regular expression
13191 search looks for and finds the word even though it is outside
13192 the marked region.
13193
13194 In the second manifestation of the bug, the region is whitespace at
13195 the end of the buffer. Emacs says @samp{Search failed}. What happens
13196 is that the true-or-false-test in the @code{while} loop tests true, so
13197 the search expression is executed. But since there are no more words
13198 in the buffer, the search fails.
13199
13200 In both manifestations of the bug, the search extends or attempts to
13201 extend outside of the region.
13202
13203 The solution is to limit the search to the region---this is a fairly
13204 simple action, but as you may have come to expect, it is not quite as
13205 simple as you might think.
13206
13207 As we have seen, the @code{re-search-forward} function takes a search
13208 pattern as its first argument. But in addition to this first,
13209 mandatory argument, it accepts three optional arguments. The optional
13210 second argument bounds the search. The optional third argument, if
13211 @code{t}, causes the function to return @code{nil} rather than signal
13212 an error if the search fails. The optional fourth argument is a
13213 repeat count. (In Emacs, you can see a function's documentation by
13214 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13215
13216 In the @code{count-words-region} definition, the value of the end of
13217 the region is held by the variable @code{end} which is passed as an
13218 argument to the function. Thus, we can add @code{end} as an argument
13219 to the regular expression search expression:
13220
13221 @smallexample
13222 (re-search-forward "\\w+\\W*" end)
13223 @end smallexample
13224
13225 However, if you make only this change to the @code{count-words-region}
13226 definition and then test the new version of the definition on a
13227 stretch of whitespace, you will receive an error message saying
13228 @samp{Search failed}.
13229
13230 What happens is this: the search is limited to the region, and fails
13231 as you expect because there are no word-constituent characters in the
13232 region. Since it fails, we receive an error message. But we do not
13233 want to receive an error message in this case; we want to receive the
13234 message that "The region does NOT have any words."
13235
13236 The solution to this problem is to provide @code{re-search-forward}
13237 with a third argument of @code{t}, which causes the function to return
13238 @code{nil} rather than signal an error if the search fails.
13239
13240 However, if you make this change and try it, you will see the message
13241 ``Counting words in region ... '' and @dots{} you will keep on seeing
13242 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13243
13244 Here is what happens: the search is limited to the region, as before,
13245 and it fails because there are no word-constituent characters in the
13246 region, as expected. Consequently, the @code{re-search-forward}
13247 expression returns @code{nil}. It does nothing else. In particular,
13248 it does not move point, which it does as a side effect if it finds the
13249 search target. After the @code{re-search-forward} expression returns
13250 @code{nil}, the next expression in the @code{while} loop is evaluated.
13251 This expression increments the count. Then the loop repeats. The
13252 true-or-false-test tests true because the value of point is still less
13253 than the value of end, since the @code{re-search-forward} expression
13254 did not move point. @dots{} and the cycle repeats @dots{}
13255
13256 The @code{count-words-region} definition requires yet another
13257 modification, to cause the true-or-false-test of the @code{while} loop
13258 to test false if the search fails. Put another way, there are two
13259 conditions that must be satisfied in the true-or-false-test before the
13260 word count variable is incremented: point must still be within the
13261 region and the search expression must have found a word to count.
13262
13263 Since both the first condition and the second condition must be true
13264 together, the two expressions, the region test and the search
13265 expression, can be joined with an @code{and} special form and embedded in
13266 the @code{while} loop as the true-or-false-test, like this:
13267
13268 @smallexample
13269 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13270 @end smallexample
13271
13272 @c colon in printed section title causes problem in Info cross reference
13273 @c also trouble with an overfull hbox
13274 @iftex
13275 @noindent
13276 (For information about @code{and}, see
13277 @ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13278 Functions}.)
13279 @end iftex
13280 @ifinfo
13281 @noindent
13282 (@xref{forward-paragraph}, for information about @code{and}.)
13283 @end ifinfo
13284
13285 The @code{re-search-forward} expression returns @code{t} if the search
13286 succeeds and as a side effect moves point. Consequently, as words are
13287 found, point is moved through the region. When the search
13288 expression fails to find another word, or when point reaches the end
13289 of the region, the true-or-false-test tests false, the @code{while}
13290 loop exists, and the @code{count-words-region} function displays one
13291 or other of its messages.
13292
13293 After incorporating these final changes, the @code{count-words-region}
13294 works without bugs (or at least, without bugs that I have found!).
13295 Here is what it looks like:
13296
13297 @smallexample
13298 @group
13299 ;;; @r{Final version:} @code{while}
13300 (defun count-words-region (beginning end)
13301 "Print number of words in the region."
13302 (interactive "r")
13303 (message "Counting words in region ... ")
13304 @end group
13305
13306 @group
13307 ;;; @r{1. Set up appropriate conditions.}
13308 (save-excursion
13309 (let ((count 0))
13310 (goto-char beginning)
13311 @end group
13312
13313 @group
13314 ;;; @r{2. Run the} while @r{loop.}
13315 (while (and (< (point) end)
13316 (re-search-forward "\\w+\\W*" end t))
13317 (setq count (1+ count)))
13318 @end group
13319
13320 @group
13321 ;;; @r{3. Send a message to the user.}
13322 (cond ((zerop count)
13323 (message
13324 "The region does NOT have any words."))
13325 ((= 1 count)
13326 (message
13327 "The region has 1 word."))
13328 (t
13329 (message
13330 "The region has %d words." count))))))
13331 @end group
13332 @end smallexample
13333
13334 @node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13335 @comment node-name, next, previous, up
13336 @section Count Words Recursively
13337 @cindex Count words recursively
13338 @cindex Recursively counting words
13339 @cindex Words, counted recursively
13340
13341 You can write the function for counting words recursively as well as
13342 with a @code{while} loop. Let's see how this is done.
13343
13344 First, we need to recognize that the @code{count-words-region}
13345 function has three jobs: it sets up the appropriate conditions for
13346 counting to occur; it counts the words in the region; and it sends a
13347 message to the user telling how many words there are.
13348
13349 If we write a single recursive function to do everything, we will
13350 receive a message for every recursive call. If the region contains 13
13351 words, we will receive thirteen messages, one right after the other.
13352 We don't want this! Instead, we must write two functions to do the
13353 job, one of which (the recursive function) will be used inside of the
13354 other. One function will set up the conditions and display the
13355 message; the other will return the word count.
13356
13357 Let us start with the function that causes the message to be displayed.
13358 We can continue to call this @code{count-words-region}.
13359
13360 This is the function that the user will call. It will be interactive.
13361 Indeed, it will be similar to our previous versions of this
13362 function, except that it will call @code{recursive-count-words} to
13363 determine how many words are in the region.
13364
13365 @need 1250
13366 We can readily construct a template for this function, based on our
13367 previous versions:
13368
13369 @smallexample
13370 @group
13371 ;; @r{Recursive version; uses regular expression search}
13372 (defun count-words-region (beginning end)
13373 "@var{documentation}@dots{}"
13374 (@var{interactive-expression}@dots{})
13375 @end group
13376 @group
13377
13378 ;;; @r{1. Set up appropriate conditions.}
13379 (@var{explanatory message})
13380 (@var{set-up functions}@dots{}
13381 @end group
13382 @group
13383
13384 ;;; @r{2. Count the words.}
13385 @var{recursive call}
13386 @end group
13387 @group
13388
13389 ;;; @r{3. Send a message to the user.}
13390 @var{message providing word count}))
13391 @end group
13392 @end smallexample
13393
13394 The definition looks straightforward, except that somehow the count
13395 returned by the recursive call must be passed to the message
13396 displaying the word count. A little thought suggests that this can be
13397 done by making use of a @code{let} expression: we can bind a variable
13398 in the varlist of a @code{let} expression to the number of words in
13399 the region, as returned by the recursive call; and then the
13400 @code{cond} expression, using binding, can display the value to the
13401 user.
13402
13403 Often, one thinks of the binding within a @code{let} expression as
13404 somehow secondary to the `primary' work of a function. But in this
13405 case, what you might consider the `primary' job of the function,
13406 counting words, is done within the @code{let} expression.
13407
13408 @need 1250
13409 Using @code{let}, the function definition looks like this:
13410
13411 @smallexample
13412 @group
13413 (defun count-words-region (beginning end)
13414 "Print number of words in the region."
13415 (interactive "r")
13416 @end group
13417
13418 @group
13419 ;;; @r{1. Set up appropriate conditions.}
13420 (message "Counting words in region ... ")
13421 (save-excursion
13422 (goto-char beginning)
13423 @end group
13424
13425 @group
13426 ;;; @r{2. Count the words.}
13427 (let ((count (recursive-count-words end)))
13428 @end group
13429
13430 @group
13431 ;;; @r{3. Send a message to the user.}
13432 (cond ((zerop count)
13433 (message
13434 "The region does NOT have any words."))
13435 ((= 1 count)
13436 (message
13437 "The region has 1 word."))
13438 (t
13439 (message
13440 "The region has %d words." count))))))
13441 @end group
13442 @end smallexample
13443
13444 Next, we need to write the recursive counting function.
13445
13446 A recursive function has at least three parts: the `do-again-test', the
13447 `next-step-expression', and the recursive call.
13448
13449 The do-again-test determines whether the function will or will not be
13450 called again. Since we are counting words in a region and can use a
13451 function that moves point forward for every word, the do-again-test
13452 can check whether point is still within the region. The do-again-test
13453 should find the value of point and determine whether point is before,
13454 at, or after the value of the end of the region. We can use the
13455 @code{point} function to locate point. Clearly, we must pass the
13456 value of the end of the region to the recursive counting function as an
13457 argument.
13458
13459 In addition, the do-again-test should also test whether the search finds a
13460 word. If it does not, the function should not call itself again.
13461
13462 The next-step-expression changes a value so that when the recursive
13463 function is supposed to stop calling itself, it stops. More
13464 precisely, the next-step-expression changes a value so that at the
13465 right time, the do-again-test stops the recursive function from
13466 calling itself again. In this case, the next-step-expression can be
13467 the expression that moves point forward, word by word.
13468
13469 The third part of a recursive function is the recursive call.
13470
13471 Somewhere, also, we also need a part that does the `work' of the
13472 function, a part that does the counting. A vital part!
13473
13474 @need 1250
13475 But already, we have an outline of the recursive counting function:
13476
13477 @smallexample
13478 @group
13479 (defun recursive-count-words (region-end)
13480 "@var{documentation}@dots{}"
13481 @var{do-again-test}
13482 @var{next-step-expression}
13483 @var{recursive call})
13484 @end group
13485 @end smallexample
13486
13487 Now we need to fill in the slots. Let's start with the simplest cases
13488 first: if point is at or beyond the end of the region, there cannot
13489 be any words in the region, so the function should return zero.
13490 Likewise, if the search fails, there are no words to count, so the
13491 function should return zero.
13492
13493 On the other hand, if point is within the region and the search
13494 succeeds, the function should call itself again.
13495
13496 @need 800
13497 Thus, the do-again-test should look like this:
13498
13499 @smallexample
13500 @group
13501 (and (< (point) region-end)
13502 (re-search-forward "\\w+\\W*" region-end t))
13503 @end group
13504 @end smallexample
13505
13506 Note that the search expression is part of the do-again-test---the
13507 function returns @code{t} if its search succeeds and @code{nil} if it
13508 fails. (@xref{Whitespace Bug, , The Whitespace Bug in
13509 @code{count-words-region}}, for an explanation of how
13510 @code{re-search-forward} works.)
13511
13512 The do-again-test is the true-or-false test of an @code{if} clause.
13513 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13514 clause should call the function again; but if it fails, the else-part
13515 should return zero since either point is outside the region or the
13516 search failed because there were no words to find.
13517
13518 But before considering the recursive call, we need to consider the
13519 next-step-expression. What is it? Interestingly, it is the search
13520 part of the do-again-test.
13521
13522 In addition to returning @code{t} or @code{nil} for the
13523 do-again-test, @code{re-search-forward} moves point forward as a side
13524 effect of a successful search. This is the action that changes the
13525 value of point so that the recursive function stops calling itself
13526 when point completes its movement through the region. Consequently,
13527 the @code{re-search-forward} expression is the next-step-expression.
13528
13529 @need 1200
13530 In outline, then, the body of the @code{recursive-count-words}
13531 function looks like this:
13532
13533 @smallexample
13534 @group
13535 (if @var{do-again-test-and-next-step-combined}
13536 ;; @r{then}
13537 @var{recursive-call-returning-count}
13538 ;; @r{else}
13539 @var{return-zero})
13540 @end group
13541 @end smallexample
13542
13543 How to incorporate the mechanism that counts?
13544
13545 If you are not used to writing recursive functions, a question like
13546 this can be troublesome. But it can and should be approached
13547 systematically.
13548
13549 We know that the counting mechanism should be associated in some way
13550 with the recursive call. Indeed, since the next-step-expression moves
13551 point forward by one word, and since a recursive call is made for
13552 each word, the counting mechanism must be an expression that adds one
13553 to the value returned by a call to @code{recursive-count-words}.
13554
13555 Consider several cases:
13556
13557 @itemize @bullet
13558 @item
13559 If there are two words in the region, the function should return
13560 a value resulting from adding one to the value returned when it counts
13561 the first word, plus the number returned when it counts the remaining
13562 words in the region, which in this case is one.
13563
13564 @item
13565 If there is one word in the region, the function should return
13566 a value resulting from adding one to the value returned when it counts
13567 that word, plus the number returned when it counts the remaining
13568 words in the region, which in this case is zero.
13569
13570 @item
13571 If there are no words in the region, the function should return zero.
13572 @end itemize
13573
13574 From the sketch we can see that the else-part of the @code{if} returns
13575 zero for the case of no words. This means that the then-part of the
13576 @code{if} must return a value resulting from adding one to the value
13577 returned from a count of the remaining words.
13578
13579 @need 1200
13580 The expression will look like this, where @code{1+} is a function that
13581 adds one to its argument.
13582
13583 @smallexample
13584 (1+ (recursive-count-words region-end))
13585 @end smallexample
13586
13587 @need 1200
13588 The whole @code{recursive-count-words} function will then look like
13589 this:
13590
13591 @smallexample
13592 @group
13593 (defun recursive-count-words (region-end)
13594 "@var{documentation}@dots{}"
13595
13596 ;;; @r{1. do-again-test}
13597 (if (and (< (point) region-end)
13598 (re-search-forward "\\w+\\W*" region-end t))
13599 @end group
13600
13601 @group
13602 ;;; @r{2. then-part: the recursive call}
13603 (1+ (recursive-count-words region-end))
13604
13605 ;;; @r{3. else-part}
13606 0))
13607 @end group
13608 @end smallexample
13609
13610 @need 1250
13611 Let's examine how this works:
13612
13613 If there are no words in the region, the else part of the @code{if}
13614 expression is evaluated and consequently the function returns zero.
13615
13616 If there is one word in the region, the value of point is less than
13617 the value of @code{region-end} and the search succeeds. In this case,
13618 the true-or-false-test of the @code{if} expression tests true, and the
13619 then-part of the @code{if} expression is evaluated. The counting
13620 expression is evaluated. This expression returns a value (which will
13621 be the value returned by the whole function) that is the sum of one
13622 added to the value returned by a recursive call.
13623
13624 Meanwhile, the next-step-expression has caused point to jump over the
13625 first (and in this case only) word in the region. This means that
13626 when @code{(recursive-count-words region-end)} is evaluated a second
13627 time, as a result of the recursive call, the value of point will be
13628 equal to or greater than the value of region end. So this time,
13629 @code{recursive-count-words} will return zero. The zero will be added
13630 to one, and the original evaluation of @code{recursive-count-words}
13631 will return one plus zero, which is one, which is the correct amount.
13632
13633 Clearly, if there are two words in the region, the first call to
13634 @code{recursive-count-words} returns one added to the value returned
13635 by calling @code{recursive-count-words} on a region containing the
13636 remaining word---that is, it adds one to one, producing two, which is
13637 the correct amount.
13638
13639 Similarly, if there are three words in the region, the first call to
13640 @code{recursive-count-words} returns one added to the value returned
13641 by calling @code{recursive-count-words} on a region containing the
13642 remaining two words---and so on and so on.
13643
13644 @need 1250
13645 @noindent
13646 With full documentation the two functions look like this:
13647
13648 @need 1250
13649 @noindent
13650 The recursive function:
13651
13652 @findex recursive-count-words
13653 @smallexample
13654 @group
13655 (defun recursive-count-words (region-end)
13656 "Number of words between point and REGION-END."
13657 @end group
13658
13659 @group
13660 ;;; @r{1. do-again-test}
13661 (if (and (< (point) region-end)
13662 (re-search-forward "\\w+\\W*" region-end t))
13663 @end group
13664
13665 @group
13666 ;;; @r{2. then-part: the recursive call}
13667 (1+ (recursive-count-words region-end))
13668
13669 ;;; @r{3. else-part}
13670 0))
13671 @end group
13672 @end smallexample
13673
13674 @need 800
13675 @noindent
13676 The wrapper:
13677
13678 @smallexample
13679 @group
13680 ;;; @r{Recursive version}
13681 (defun count-words-region (beginning end)
13682 "Print number of words in the region.
13683 @end group
13684
13685 @group
13686 Words are defined as at least one word-constituent
13687 character followed by at least one character that is
13688 not a word-constituent. The buffer's syntax table
13689 determines which characters these are."
13690 @end group
13691 @group
13692 (interactive "r")
13693 (message "Counting words in region ... ")
13694 (save-excursion
13695 (goto-char beginning)
13696 (let ((count (recursive-count-words end)))
13697 @end group
13698 @group
13699 (cond ((zerop count)
13700 (message
13701 "The region does NOT have any words."))
13702 @end group
13703 @group
13704 ((= 1 count)
13705 (message "The region has 1 word."))
13706 (t
13707 (message
13708 "The region has %d words." count))))))
13709 @end group
13710 @end smallexample
13711
13712 @node Counting Exercise, , recursive-count-words, Counting Words
13713 @section Exercise: Counting Punctuation
13714
13715 Using a @code{while} loop, write a function to count the number of
13716 punctuation marks in a region---period, comma, semicolon, colon,
13717 exclamation mark, and question mark. Do the same using recursion.
13718
13719 @node Words in a defun, Readying a Graph, Counting Words, Top
13720 @chapter Counting Words in a @code{defun}
13721 @cindex Counting words in a @code{defun}
13722 @cindex Word counting in a @code{defun}
13723
13724 Our next project is to count the number of words in a function
13725 definition. Clearly, this can be done using some variant of
13726 @code{count-word-region}. @xref{Counting Words, , Counting Words:
13727 Repetition and Regexps}. If we are just going to count the words in
13728 one definition, it is easy enough to mark the definition with the
13729 @kbd{C-M-h} (@code{mark-defun}) command, and then call
13730 @code{count-word-region}.
13731
13732 However, I am more ambitious: I want to count the words and symbols in
13733 every definition in the Emacs sources and then print a graph that
13734 shows how many functions there are of each length: how many contain 40
13735 to 49 words or symbols, how many contain 50 to 59 words or symbols,
13736 and so on. I have often been curious how long a typical function is,
13737 and this will tell.
13738
13739 @menu
13740 * Divide and Conquer::
13741 * Words and Symbols:: What to count?
13742 * Syntax:: What constitutes a word or symbol?
13743 * count-words-in-defun:: Very like @code{count-words}.
13744 * Several defuns:: Counting several defuns in a file.
13745 * Find a File:: Do you want to look at a file?
13746 * lengths-list-file:: A list of the lengths of many definitions.
13747 * Several files:: Counting in definitions in different files.
13748 * Several files recursively:: Recursively counting in different files.
13749 * Prepare the data:: Prepare the data for display in a graph.
13750 @end menu
13751
13752 @node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13753 @ifnottex
13754 @unnumberedsec Divide and Conquer
13755 @end ifnottex
13756
13757 Described in one phrase, the histogram project is daunting; but
13758 divided into numerous small steps, each of which we can take one at a
13759 time, the project becomes less fearsome. Let us consider what the
13760 steps must be:
13761
13762 @itemize @bullet
13763 @item
13764 First, write a function to count the words in one definition. This
13765 includes the problem of handling symbols as well as words.
13766
13767 @item
13768 Second, write a function to list the numbers of words in each function
13769 in a file. This function can use the @code{count-words-in-defun}
13770 function.
13771
13772 @item
13773 Third, write a function to list the numbers of words in each function
13774 in each of several files. This entails automatically finding the
13775 various files, switching to them, and counting the words in the
13776 definitions within them.
13777
13778 @item
13779 Fourth, write a function to convert the list of numbers that we
13780 created in step three to a form that will be suitable for printing as
13781 a graph.
13782
13783 @item
13784 Fifth, write a function to print the results as a graph.
13785 @end itemize
13786
13787 This is quite a project! But if we take each step slowly, it will not
13788 be difficult.
13789
13790 @node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13791 @section What to Count?
13792 @cindex Words and symbols in defun
13793
13794 When we first start thinking about how to count the words in a
13795 function definition, the first question is (or ought to be) what are
13796 we going to count? When we speak of `words' with respect to a Lisp
13797 function definition, we are actually speaking, in large part, of
13798 `symbols'. For example, the following @code{multiply-by-seven}
13799 function contains the five symbols @code{defun},
13800 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
13801 addition, in the documentation string, it contains the four words
13802 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
13803 symbol @samp{number} is repeated, so the definition contains a total
13804 of ten words and symbols.
13805
13806 @smallexample
13807 @group
13808 (defun multiply-by-seven (number)
13809 "Multiply NUMBER by seven."
13810 (* 7 number))
13811 @end group
13812 @end smallexample
13813
13814 @noindent
13815 However, if we mark the @code{multiply-by-seven} definition with
13816 @kbd{C-M-h} (@code{mark-defun}), and then call
13817 @code{count-words-region} on it, we will find that
13818 @code{count-words-region} claims the definition has eleven words, not
13819 ten! Something is wrong!
13820
13821 The problem is twofold: @code{count-words-region} does not count the
13822 @samp{*} as a word, and it counts the single symbol,
13823 @code{multiply-by-seven}, as containing three words. The hyphens are
13824 treated as if they were interword spaces rather than intraword
13825 connectors: @samp{multiply-by-seven} is counted as if it were written
13826 @samp{multiply by seven}.
13827
13828 The cause of this confusion is the regular expression search within
13829 the @code{count-words-region} definition that moves point forward word
13830 by word. In the canonical version of @code{count-words-region}, the
13831 regexp is:
13832
13833 @smallexample
13834 "\\w+\\W*"
13835 @end smallexample
13836
13837 @noindent
13838 This regular expression is a pattern defining one or more word
13839 constituent characters possibly followed by one or more characters
13840 that are not word constituents. What is meant by `word constituent
13841 characters' brings us to the issue of syntax, which is worth a section
13842 of its own.
13843
13844 @node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13845 @section What Constitutes a Word or Symbol?
13846 @cindex Syntax categories and tables
13847
13848 Emacs treats different characters as belonging to different
13849 @dfn{syntax categories}. For example, the regular expression,
13850 @samp{\\w+}, is a pattern specifying one or more @emph{word
13851 constituent} characters. Word constituent characters are members of
13852 one syntax category. Other syntax categories include the class of
13853 punctuation characters, such as the period and the comma, and the
13854 class of whitespace characters, such as the blank space and the tab
13855 character. (For more information, see @ref{Syntax, Syntax, The Syntax
13856 Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13857 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13858
13859 Syntax tables specify which characters belong to which categories.
13860 Usually, a hyphen is not specified as a `word constituent character'.
13861 Instead, it is specified as being in the `class of characters that are
13862 part of symbol names but not words.' This means that the
13863 @code{count-words-region} function treats it in the same way it treats
13864 an interword white space, which is why @code{count-words-region}
13865 counts @samp{multiply-by-seven} as three words.
13866
13867 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13868 one symbol: modify the syntax table or modify the regular expression.
13869
13870 We could redefine a hyphen as a word constituent character by
13871 modifying the syntax table that Emacs keeps for each mode. This
13872 action would serve our purpose, except that a hyphen is merely the
13873 most common character within symbols that is not typically a word
13874 constituent character; there are others, too.
13875
13876 Alternatively, we can redefine the regular expression used in the
13877 @code{count-words} definition so as to include symbols. This
13878 procedure has the merit of clarity, but the task is a little tricky.
13879
13880 @need 1200
13881 The first part is simple enough: the pattern must match ``at least one
13882 character that is a word or symbol constituent''. Thus:
13883
13884 @smallexample
13885 "\\(\\w\\|\\s_\\)+"
13886 @end smallexample
13887
13888 @noindent
13889 The @samp{\\(} is the first part of the grouping construct that
13890 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13891 by the @samp{\\|}. The @samp{\\w} matches any word-constituent
13892 character and the @samp{\\s_} matches any character that is part of a
13893 symbol name but not a word-constituent character. The @samp{+}
13894 following the group indicates that the word or symbol constituent
13895 characters must be matched at least once.
13896
13897 However, the second part of the regexp is more difficult to design.
13898 What we want is to follow the first part with ``optionally one or more
13899 characters that are not constituents of a word or symbol''. At first,
13900 I thought I could define this with the following:
13901
13902 @smallexample
13903 "\\(\\W\\|\\S_\\)*"
13904 @end smallexample
13905
13906 @noindent
13907 The upper case @samp{W} and @samp{S} match characters that are
13908 @emph{not} word or symbol constituents. Unfortunately, this
13909 expression matches any character that is either not a word constituent
13910 or not a symbol constituent. This matches any character!
13911
13912 I then noticed that every word or symbol in my test region was
13913 followed by white space (blank space, tab, or newline). So I tried
13914 placing a pattern to match one or more blank spaces after the pattern
13915 for one or more word or symbol constituents. This failed, too. Words
13916 and symbols are often separated by whitespace, but in actual code
13917 parentheses may follow symbols and punctuation may follow words. So
13918 finally, I designed a pattern in which the word or symbol constituents
13919 are followed optionally by characters that are not white space and
13920 then followed optionally by white space.
13921
13922 @need 800
13923 Here is the full regular expression:
13924
13925 @smallexample
13926 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13927 @end smallexample
13928
13929 @node count-words-in-defun, Several defuns, Syntax, Words in a defun
13930 @section The @code{count-words-in-defun} Function
13931 @cindex Counting words in a @code{defun}
13932
13933 We have seen that there are several ways to write a
13934 @code{count-word-region} function. To write a
13935 @code{count-words-in-defun}, we need merely adapt one of these
13936 versions.
13937
13938 The version that uses a @code{while} loop is easy to understand, so I
13939 am going to adapt that. Because @code{count-words-in-defun} will be
13940 part of a more complex program, it need not be interactive and it need
13941 not display a message but just return the count. These considerations
13942 simplify the definition a little.
13943
13944 On the other hand, @code{count-words-in-defun} will be used within a
13945 buffer that contains function definitions. Consequently, it is
13946 reasonable to ask that the function determine whether it is called
13947 when point is within a function definition, and if it is, to return
13948 the count for that definition. This adds complexity to the
13949 definition, but saves us from needing to pass arguments to the
13950 function.
13951
13952 @need 1250
13953 These considerations lead us to prepare the following template:
13954
13955 @smallexample
13956 @group
13957 (defun count-words-in-defun ()
13958 "@var{documentation}@dots{}"
13959 (@var{set up}@dots{}
13960 (@var{while loop}@dots{})
13961 @var{return count})
13962 @end group
13963 @end smallexample
13964
13965 @noindent
13966 As usual, our job is to fill in the slots.
13967
13968 First, the set up.
13969
13970 We are presuming that this function will be called within a buffer
13971 containing function definitions. Point will either be within a
13972 function definition or not. For @code{count-words-in-defun} to work,
13973 point must move to the beginning of the definition, a counter must
13974 start at zero, and the counting loop must stop when point reaches the
13975 end of the definition.
13976
13977 The @code{beginning-of-defun} function searches backwards for an
13978 opening delimiter such as a @samp{(} at the beginning of a line, and
13979 moves point to that position, or else to the limit of the search. In
13980 practice, this means that @code{beginning-of-defun} moves point to the
13981 beginning of an enclosing or preceding function definition, or else to
13982 the beginning of the buffer. We can use @code{beginning-of-defun} to
13983 place point where we wish to start.
13984
13985 The @code{while} loop requires a counter to keep track of the words or
13986 symbols being counted. A @code{let} expression can be used to create
13987 a local variable for this purpose, and bind it to an initial value of zero.
13988
13989 The @code{end-of-defun} function works like @code{beginning-of-defun}
13990 except that it moves point to the end of the definition.
13991 @code{end-of-defun} can be used as part of an expression that
13992 determines the position of the end of the definition.
13993
13994 The set up for @code{count-words-in-defun} takes shape rapidly: first
13995 we move point to the beginning of the definition, then we create a
13996 local variable to hold the count, and finally, we record the position
13997 of the end of the definition so the @code{while} loop will know when to stop
13998 looping.
13999
14000 @need 1250
14001 The code looks like this:
14002
14003 @smallexample
14004 @group
14005 (beginning-of-defun)
14006 (let ((count 0)
14007 (end (save-excursion (end-of-defun) (point))))
14008 @end group
14009 @end smallexample
14010
14011 @noindent
14012 The code is simple. The only slight complication is likely to concern
14013 @code{end}: it is bound to the position of the end of the definition
14014 by a @code{save-excursion} expression that returns the value of point
14015 after @code{end-of-defun} temporarily moves it to the end of the
14016 definition.
14017
14018 The second part of the @code{count-words-in-defun}, after the set up,
14019 is the @code{while} loop.
14020
14021 The loop must contain an expression that jumps point forward word by
14022 word and symbol by symbol, and another expression that counts the
14023 jumps. The true-or-false-test for the @code{while} loop should test
14024 true so long as point should jump forward, and false when point is at
14025 the end of the definition. We have already redefined the regular
14026 expression for this (@pxref{Syntax}), so the loop is straightforward:
14027
14028 @smallexample
14029 @group
14030 (while (and (< (point) end)
14031 (re-search-forward
14032 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14033 (setq count (1+ count)))
14034 @end group
14035 @end smallexample
14036
14037 The third part of the function definition returns the count of words
14038 and symbols. This part is the last expression within the body of the
14039 @code{let} expression, and can be, very simply, the local variable
14040 @code{count}, which when evaluated returns the count.
14041
14042 @need 1250
14043 Put together, the @code{count-words-in-defun} definition looks like this:
14044
14045 @findex count-words-in-defun
14046 @smallexample
14047 @group
14048 (defun count-words-in-defun ()
14049 "Return the number of words and symbols in a defun."
14050 (beginning-of-defun)
14051 (let ((count 0)
14052 (end (save-excursion (end-of-defun) (point))))
14053 @end group
14054 @group
14055 (while
14056 (and (< (point) end)
14057 (re-search-forward
14058 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14059 end t))
14060 (setq count (1+ count)))
14061 count))
14062 @end group
14063 @end smallexample
14064
14065 How to test this? The function is not interactive, but it is easy to
14066 put a wrapper around the function to make it interactive; we can use
14067 almost the same code as for the recursive version of
14068 @code{count-words-region}:
14069
14070 @smallexample
14071 @group
14072 ;;; @r{Interactive version.}
14073 (defun count-words-defun ()
14074 "Number of words and symbols in a function definition."
14075 (interactive)
14076 (message
14077 "Counting words and symbols in function definition ... ")
14078 @end group
14079 @group
14080 (let ((count (count-words-in-defun)))
14081 (cond
14082 ((zerop count)
14083 (message
14084 "The definition does NOT have any words or symbols."))
14085 @end group
14086 @group
14087 ((= 1 count)
14088 (message
14089 "The definition has 1 word or symbol."))
14090 (t
14091 (message
14092 "The definition has %d words or symbols." count)))))
14093 @end group
14094 @end smallexample
14095
14096 @need 800
14097 @noindent
14098 Let's re-use @kbd{C-c =} as a convenient keybinding:
14099
14100 @smallexample
14101 (global-set-key "\C-c=" 'count-words-defun)
14102 @end smallexample
14103
14104 Now we can try out @code{count-words-defun}: install both
14105 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14106 keybinding, and then place the cursor within the following definition:
14107
14108 @smallexample
14109 @group
14110 (defun multiply-by-seven (number)
14111 "Multiply NUMBER by seven."
14112 (* 7 number))
14113 @result{} 10
14114 @end group
14115 @end smallexample
14116
14117 @noindent
14118 Success! The definition has 10 words and symbols.
14119
14120 The next problem is to count the numbers of words and symbols in
14121 several definitions within a single file.
14122
14123 @node Several defuns, Find a File, count-words-in-defun, Words in a defun
14124 @section Count Several @code{defuns} Within a File
14125
14126 A file such as @file{simple.el} may have 80 or more function
14127 definitions within it. Our long term goal is to collect statistics on
14128 many files, but as a first step, our immediate goal is to collect
14129 statistics on one file.
14130
14131 The information will be a series of numbers, each number being the
14132 length of a function definition. We can store the numbers in a list.
14133
14134 We know that we will want to incorporate the information regarding one
14135 file with information about many other files; this means that the
14136 function for counting definition lengths within one file need only
14137 return the list of lengths. It need not and should not display any
14138 messages.
14139
14140 The word count commands contain one expression to jump point forward
14141 word by word and another expression to count the jumps. The function
14142 to return the lengths of definitions can be designed to work the same
14143 way, with one expression to jump point forward definition by
14144 definition and another expression to construct the lengths' list.
14145
14146 This statement of the problem makes it elementary to write the
14147 function definition. Clearly, we will start the count at the
14148 beginning of the file, so the first command will be @code{(goto-char
14149 (point-min))}. Next, we start the @code{while} loop; and the
14150 true-or-false test of the loop can be a regular expression search for
14151 the next function definition---so long as the search succeeds, point
14152 is moved forward and then the body of the loop is evaluated. The body
14153 needs an expression that constructs the lengths' list. @code{cons},
14154 the list construction command, can be used to create the list. That
14155 is almost all there is to it.
14156
14157 @need 800
14158 Here is what this fragment of code looks like:
14159
14160 @smallexample
14161 @group
14162 (goto-char (point-min))
14163 (while (re-search-forward "^(defun" nil t)
14164 (setq lengths-list
14165 (cons (count-words-in-defun) lengths-list)))
14166 @end group
14167 @end smallexample
14168
14169 What we have left out is the mechanism for finding the file that
14170 contains the function definitions.
14171
14172 In previous examples, we either used this, the Info file, or we
14173 switched back and forth to some other buffer, such as the
14174 @file{*scratch*} buffer.
14175
14176 Finding a file is a new process that we have not yet discussed.
14177
14178 @node Find a File, lengths-list-file, Several defuns, Words in a defun
14179 @comment node-name, next, previous, up
14180 @section Find a File
14181 @cindex Find a File
14182
14183 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14184 command. This command is almost, but not quite right for the lengths
14185 problem.
14186
14187 @need 1200
14188 Let's look at the source for @code{find-file} (you can use the
14189 @code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14190 find the source of a function):
14191
14192 @smallexample
14193 @group
14194 (defun find-file (filename)
14195 "Edit file FILENAME.
14196 Switch to a buffer visiting file FILENAME,
14197 creating one if none already exists."
14198 (interactive "FFind file: ")
14199 (switch-to-buffer (find-file-noselect filename)))
14200 @end group
14201 @end smallexample
14202
14203 The definition possesses short but complete documentation and an
14204 interactive specification that prompts you for a file name when you
14205 use the command interactively. The body of the definition contains
14206 two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14207
14208 According to its documentation as shown by @kbd{C-h f} (the
14209 @code{describe-function} command), the @code{find-file-noselect}
14210 function reads the named file into a buffer and returns the buffer.
14211 However, the buffer is not selected. Emacs does not switch its
14212 attention (or yours if you are using @code{find-file-noselect}) to the
14213 named buffer. That is what @code{switch-to-buffer} does: it switches
14214 the buffer to which Emacs attention is directed; and it switches the
14215 buffer displayed in the window to the new buffer. We have discussed
14216 buffer switching elsewhere. (@xref{Switching Buffers}.)
14217
14218 In this histogram project, we do not need to display each file on the
14219 screen as the program determines the length of each definition within
14220 it. Instead of employing @code{switch-to-buffer}, we can work with
14221 @code{set-buffer}, which redirects the attention of the computer
14222 program to a different buffer but does not redisplay it on the screen.
14223 So instead of calling on @code{find-file} to do the job, we must write
14224 our own expression.
14225
14226 The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
14227
14228 @node lengths-list-file, Several files, Find a File, Words in a defun
14229 @section @code{lengths-list-file} in Detail
14230
14231 The core of the @code{lengths-list-file} function is a @code{while}
14232 loop containing a function to move point forward `defun by defun' and
14233 a function to count the number of words and symbols in each defun.
14234 This core must be surrounded by functions that do various other tasks,
14235 including finding the file, and ensuring that point starts out at the
14236 beginning of the file. The function definition looks like this:
14237 @findex lengths-list-file
14238
14239 @smallexample
14240 @group
14241 (defun lengths-list-file (filename)
14242 "Return list of definitions' lengths within FILE.
14243 The returned list is a list of numbers.
14244 Each number is the number of words or
14245 symbols in one function definition."
14246 @end group
14247 @group
14248 (message "Working on `%s' ... " filename)
14249 (save-excursion
14250 (let ((buffer (find-file-noselect filename))
14251 (lengths-list))
14252 (set-buffer buffer)
14253 (setq buffer-read-only t)
14254 (widen)
14255 (goto-char (point-min))
14256 (while (re-search-forward "^(defun" nil t)
14257 (setq lengths-list
14258 (cons (count-words-in-defun) lengths-list)))
14259 (kill-buffer buffer)
14260 lengths-list)))
14261 @end group
14262 @end smallexample
14263
14264 @noindent
14265 The function is passed one argument, the name of the file on which it
14266 will work. It has four lines of documentation, but no interactive
14267 specification. Since people worry that a computer is broken if they
14268 don't see anything going on, the first line of the body is a
14269 message.
14270
14271 The next line contains a @code{save-excursion} that returns Emacs'
14272 attention to the current buffer when the function completes. This is
14273 useful in case you embed this function in another function that
14274 presumes point is restored to the original buffer.
14275
14276 In the varlist of the @code{let} expression, Emacs finds the file and
14277 binds the local variable @code{buffer} to the buffer containing the
14278 file. At the same time, Emacs creates @code{lengths-list} as a local
14279 variable.
14280
14281 Next, Emacs switches its attention to the buffer.
14282
14283 In the following line, Emacs makes the buffer read-only. Ideally,
14284 this line is not necessary. None of the functions for counting words
14285 and symbols in a function definition should change the buffer.
14286 Besides, the buffer is not going to be saved, even if it were changed.
14287 This line is entirely the consequence of great, perhaps excessive,
14288 caution. The reason for the caution is that this function and those
14289 it calls work on the sources for Emacs and it is very inconvenient if
14290 they are inadvertently modified. It goes without saying that I did
14291 not realize a need for this line until an experiment went awry and
14292 started to modify my Emacs source files @dots{}
14293
14294 Next comes a call to widen the buffer if it is narrowed. This
14295 function is usually not needed---Emacs creates a fresh buffer if none
14296 already exists; but if a buffer visiting the file already exists Emacs
14297 returns that one. In this case, the buffer may be narrowed and must
14298 be widened. If we wanted to be fully `user-friendly', we would
14299 arrange to save the restriction and the location of point, but we
14300 won't.
14301
14302 The @code{(goto-char (point-min))} expression moves point to the
14303 beginning of the buffer.
14304
14305 Then comes a @code{while} loop in which the `work' of the function is
14306 carried out. In the loop, Emacs determines the length of each
14307 definition and constructs a lengths' list containing the information.
14308
14309 Emacs kills the buffer after working through it. This is to save
14310 space inside of Emacs. My version of Emacs 19 contained over 300
14311 source files of interest; Emacs 21 contains over 800 source files.
14312 Another function will apply @code{lengths-list-file} to each of the
14313 files.
14314
14315 Finally, the last expression within the @code{let} expression is the
14316 @code{lengths-list} variable; its value is returned as the value of
14317 the whole function.
14318
14319 You can try this function by installing it in the usual fashion. Then
14320 place your cursor after the following expression and type @kbd{C-x
14321 C-e} (@code{eval-last-sexp}).
14322
14323 @c !!! 21.0.100 lisp sources location here
14324 @smallexample
14325 (lengths-list-file
14326 "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14327 @end smallexample
14328
14329 @c was: (lengths-list-file "../lisp/debug.el")
14330 @c !!! as of 21, Info file is in
14331 @c /usr/share/info/emacs-lisp-intro.info.gz
14332 @c but debug.el is in /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14333
14334 @noindent
14335 (You may need to change the pathname of the file; the one here worked
14336 with GNU Emacs version 21.0.100. To change the expression, copy it to
14337 the @file{*scratch*} buffer and edit it.
14338
14339 @need 1200
14340 @noindent
14341 (Also, to see the full length of the list, rather than a truncated
14342 version, you may have to evaluate the following:
14343
14344 @smallexample
14345 (custom-set-variables '(eval-expression-print-length nil))
14346 @end smallexample
14347
14348 @noindent
14349 (@xref{defcustom, , Setting Variables with @code{defcustom}}.
14350 Then evaluate the @code{lengths-list-file} expression.)
14351
14352 @need 1200
14353 The lengths' list for @file{debug.el} takes less than a second to
14354 produce and looks like this:
14355
14356 @smallexample
14357 (77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14358 @end smallexample
14359
14360 @need 1500
14361 (Using my old machine, the version 19 lengths' list for @file{debug.el}
14362 took seven seconds to produce and looked like this:
14363
14364 @smallexample
14365 (75 41 80 62 20 45 44 68 45 12 34 235)
14366 @end smallexample
14367
14368 (The newer version of @file{debug.el} contains more defuns than the
14369 earlier one; and my new machine is much faster than the old one.)
14370
14371 Note that the length of the last definition in the file is first in
14372 the list.
14373
14374 @node Several files, Several files recursively, lengths-list-file, Words in a defun
14375 @section Count Words in @code{defuns} in Different Files
14376
14377 In the previous section, we created a function that returns a list of
14378 the lengths of each definition in a file. Now, we want to define a
14379 function to return a master list of the lengths of the definitions in
14380 a list of files.
14381
14382 Working on each of a list of files is a repetitious act, so we can use
14383 either a @code{while} loop or recursion.
14384
14385 @menu
14386 * lengths-list-many-files:: Return a list of the lengths of defuns.
14387 * append:: Attach one list to another.
14388 @end menu
14389
14390 @node lengths-list-many-files, append, Several files, Several files
14391 @ifnottex
14392 @unnumberedsubsec Determine the lengths of @code{defuns}
14393 @end ifnottex
14394
14395 The design using a @code{while} loop is routine. The argument passed
14396 the function is a list of files. As we saw earlier (@pxref{Loop
14397 Example}), you can write a @code{while} loop so that the body of the
14398 loop is evaluated if such a list contains elements, but to exit the
14399 loop if the list is empty. For this design to work, the body of the
14400 loop must contain an expression that shortens the list each time the
14401 body is evaluated, so that eventually the list is empty. The usual
14402 technique is to set the value of the list to the value of the @sc{cdr}
14403 of the list each time the body is evaluated.
14404
14405 @need 800
14406 The template looks like this:
14407
14408 @smallexample
14409 @group
14410 (while @var{test-whether-list-is-empty}
14411 @var{body}@dots{}
14412 @var{set-list-to-cdr-of-list})
14413 @end group
14414 @end smallexample
14415
14416 Also, we remember that a @code{while} loop returns @code{nil} (the
14417 result of evaluating the true-or-false-test), not the result of any
14418 evaluation within its body. (The evaluations within the body of the
14419 loop are done for their side effects.) However, the expression that
14420 sets the lengths' list is part of the body---and that is the value
14421 that we want returned by the function as a whole. To do this, we
14422 enclose the @code{while} loop within a @code{let} expression, and
14423 arrange that the last element of the @code{let} expression contains
14424 the value of the lengths' list. (@xref{Incrementing Example, , Loop
14425 Example with an Incrementing Counter}.)
14426
14427 @findex lengths-list-many-files
14428 @need 1250
14429 These considerations lead us directly to the function itself:
14430
14431 @smallexample
14432 @group
14433 ;;; @r{Use @code{while} loop.}
14434 (defun lengths-list-many-files (list-of-files)
14435 "Return list of lengths of defuns in LIST-OF-FILES."
14436 @end group
14437 @group
14438 (let (lengths-list)
14439
14440 ;;; @r{true-or-false-test}
14441 (while list-of-files
14442 (setq lengths-list
14443 (append
14444 lengths-list
14445
14446 ;;; @r{Generate a lengths' list.}
14447 (lengths-list-file
14448 (expand-file-name (car list-of-files)))))
14449 @end group
14450
14451 @group
14452 ;;; @r{Make files' list shorter.}
14453 (setq list-of-files (cdr list-of-files)))
14454
14455 ;;; @r{Return final value of lengths' list.}
14456 lengths-list))
14457 @end group
14458 @end smallexample
14459
14460 @code{expand-file-name} is a built-in function that converts a file
14461 name to the absolute, long, path name form of the directory in which
14462 the function is called.
14463
14464 @c !!! 21.0.100 lisp sources location here
14465 @need 1500
14466 Thus, if @code{expand-file-name} is called on @code{debug.el} when
14467 Emacs is visiting the
14468 @file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14469
14470 @smallexample
14471 debug.el
14472 @end smallexample
14473
14474 @need 800
14475 @noindent
14476 becomes
14477
14478 @c !!! 21.0.100 lisp sources location here
14479 @smallexample
14480 /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14481 @end smallexample
14482
14483 The only other new element of this function definition is the as yet
14484 unstudied function @code{append}, which merits a short section for
14485 itself.
14486
14487 @node append, , lengths-list-many-files, Several files
14488 @subsection The @code{append} Function
14489
14490 @need 800
14491 The @code{append} function attaches one list to another. Thus,
14492
14493 @smallexample
14494 (append '(1 2 3 4) '(5 6 7 8))
14495 @end smallexample
14496
14497 @need 800
14498 @noindent
14499 produces the list
14500
14501 @smallexample
14502 (1 2 3 4 5 6 7 8)
14503 @end smallexample
14504
14505 This is exactly how we want to attach two lengths' lists produced by
14506 @code{lengths-list-file} to each other. The results contrast with
14507 @code{cons},
14508
14509 @smallexample
14510 (cons '(1 2 3 4) '(5 6 7 8))
14511 @end smallexample
14512
14513 @need 1250
14514 @noindent
14515 which constructs a new list in which the first argument to @code{cons}
14516 becomes the first element of the new list:
14517
14518 @smallexample
14519 ((1 2 3 4) 5 6 7 8)
14520 @end smallexample
14521
14522 @node Several files recursively, Prepare the data, Several files, Words in a defun
14523 @section Recursively Count Words in Different Files
14524
14525 Besides a @code{while} loop, you can work on each of a list of files
14526 with recursion. A recursive version of @code{lengths-list-many-files}
14527 is short and simple.
14528
14529 The recursive function has the usual parts: the `do-again-test', the
14530 `next-step-expression', and the recursive call. The `do-again-test'
14531 determines whether the function should call itself again, which it
14532 will do if the @code{list-of-files} contains any remaining elements;
14533 the `next-step-expression' resets the @code{list-of-files} to the
14534 @sc{cdr} of itself, so eventually the list will be empty; and the
14535 recursive call calls itself on the shorter list. The complete
14536 function is shorter than this description!
14537 @findex recursive-lengths-list-many-files
14538
14539 @smallexample
14540 @group
14541 (defun recursive-lengths-list-many-files (list-of-files)
14542 "Return list of lengths of each defun in LIST-OF-FILES."
14543 (if list-of-files ; @r{do-again-test}
14544 (append
14545 (lengths-list-file
14546 (expand-file-name (car list-of-files)))
14547 (recursive-lengths-list-many-files
14548 (cdr list-of-files)))))
14549 @end group
14550 @end smallexample
14551
14552 @noindent
14553 In a sentence, the function returns the lengths' list for the first of
14554 the @code{list-of-files} appended to the result of calling itself on
14555 the rest of the @code{list-of-files}.
14556
14557 Here is a test of @code{recursive-lengths-list-many-files}, along with
14558 the results of running @code{lengths-list-file} on each of the files
14559 individually.
14560
14561 Install @code{recursive-lengths-list-many-files} and
14562 @code{lengths-list-file}, if necessary, and then evaluate the
14563 following expressions. You may need to change the files' pathnames;
14564 those here work when this Info file and the Emacs sources are located
14565 in their customary places. To change the expressions, copy them to
14566 the @file{*scratch*} buffer, edit them, and then evaluate them.
14567
14568 The results are shown after the @samp{@result{}}. (These results are
14569 for files from Emacs Version 21.0.100; files from other versions of
14570 Emacs may produce different results.)
14571
14572 @c !!! 21.0.100 lisp sources location here
14573 @smallexample
14574 @group
14575 (cd "/usr/local/share/emacs/21.0.100/")
14576
14577 (lengths-list-file "./lisp/macros.el")
14578 @result{} (273 263 456 90)
14579 @end group
14580
14581 @group
14582 (lengths-list-file "./lisp/mail/mailalias.el")
14583 @result{} (38 32 26 77 174 180 321 198 324)
14584 @end group
14585
14586 @group
14587 (lengths-list-file "./lisp/makesum.el")
14588 @result{} (85 181)
14589 @end group
14590
14591 @group
14592 (recursive-lengths-list-many-files
14593 '("./lisp/macros.el"
14594 "./lisp/mail/mailalias.el"
14595 "./lisp/makesum.el"))
14596 @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14597 @end group
14598 @end smallexample
14599
14600 The @code{recursive-lengths-list-many-files} function produces the
14601 output we want.
14602
14603 The next step is to prepare the data in the list for display in a graph.
14604
14605 @node Prepare the data, , Several files recursively, Words in a defun
14606 @section Prepare the Data for Display in a Graph
14607
14608 The @code{recursive-lengths-list-many-files} function returns a list
14609 of numbers. Each number records the length of a function definition.
14610 What we need to do now is transform this data into a list of numbers
14611 suitable for generating a graph. The new list will tell how many
14612 functions definitions contain less than 10 words and
14613 symbols, how many contain between 10 and 19 words and symbols, how
14614 many contain between 20 and 29 words and symbols, and so on.
14615
14616 In brief, we need to go through the lengths' list produced by the
14617 @code{recursive-lengths-list-many-files} function and count the number
14618 of defuns within each range of lengths, and produce a list of those
14619 numbers.
14620
14621 Based on what we have done before, we can readily foresee that it
14622 should not be too hard to write a function that `@sc{cdr}s' down the
14623 lengths' list, looks at each element, determines which length range it
14624 is in, and increments a counter for that range.
14625
14626 However, before beginning to write such a function, we should consider
14627 the advantages of sorting the lengths' list first, so the numbers are
14628 ordered from smallest to largest. First, sorting will make it easier
14629 to count the numbers in each range, since two adjacent numbers will
14630 either be in the same length range or in adjacent ranges. Second, by
14631 inspecting a sorted list, we can discover the highest and lowest
14632 number, and thereby determine the largest and smallest length range
14633 that we will need.
14634
14635 @menu
14636 * Sorting:: Sorting lists.
14637 * Files List:: Making a list of files.
14638 * Counting function definitions::
14639 @end menu
14640
14641 @node Sorting, Files List, Prepare the data, Prepare the data
14642 @subsection Sorting Lists
14643 @findex sort
14644
14645 Emacs contains a function to sort lists, called (as you might guess)
14646 @code{sort}. The @code{sort} function takes two arguments, the list
14647 to be sorted, and a predicate that determines whether the first of
14648 two list elements is ``less'' than the second.
14649
14650 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14651 Type Object as an Argument}), a predicate is a function that
14652 determines whether some property is true or false. The @code{sort}
14653 function will reorder a list according to whatever property the
14654 predicate uses; this means that @code{sort} can be used to sort
14655 non-numeric lists by non-numeric criteria---it can, for example,
14656 alphabetize a list.
14657
14658 @need 1250
14659 The @code{<} function is used when sorting a numeric list. For example,
14660
14661 @smallexample
14662 (sort '(4 8 21 17 33 7 21 7) '<)
14663 @end smallexample
14664
14665 @need 800
14666 @noindent
14667 produces this:
14668
14669 @smallexample
14670 (4 7 7 8 17 21 21 33)
14671 @end smallexample
14672
14673 @noindent
14674 (Note that in this example, both the arguments are quoted so that the
14675 symbols are not evaluated before being passed to @code{sort} as
14676 arguments.)
14677
14678 Sorting the list returned by the
14679 @code{recursive-lengths-list-many-files} function is straightforward;
14680 it uses the @code{<} function:
14681
14682 @smallexample
14683 @group
14684 (sort
14685 (recursive-lengths-list-many-files
14686 '("../lisp/macros.el"
14687 "../lisp/mailalias.el"
14688 "../lisp/makesum.el"))
14689 '<
14690 @end group
14691 @end smallexample
14692
14693 @need 800
14694 @noindent
14695 which produces:
14696
14697 @smallexample
14698 (85 86 116 122 154 176 179 265)
14699 @end smallexample
14700
14701 @noindent
14702 (Note that in this example, the first argument to @code{sort} is not
14703 quoted, since the expression must be evaluated so as to produce the
14704 list that is passed to @code{sort}.)
14705
14706 @node Files List, Counting function definitions, Sorting, Prepare the data
14707 @subsection Making a List of Files
14708
14709 The @code{recursive-lengths-list-many-files} function requires a list
14710 of files as its argument. For our test examples, we constructed such
14711 a list by hand; but the Emacs Lisp source directory is too large for
14712 us to do for that. Instead, we will write a function to do the job
14713 for us. In this function, we will use both a @code{while} loop and a
14714 recursive call.
14715
14716 @findex directory-files
14717 We did not have to write a function like this for older versions of
14718 GNU Emacs, since they placed all the @samp{.el} files in one
14719 directory. Instead, we were able to use the @code{directory-files}
14720 function, which lists the names of files that match a specified
14721 pattern within a single directory.
14722
14723 However, recent versions of Emacs place Emacs Lisp files in
14724 sub-directories of the top level @file{lisp} directory. This
14725 re-arrangement eases navigation. For example, all the mail related
14726 files are in a @file{lisp} sub-directory called @file{mail}. But at
14727 the same time, this arrangement forces us to create a file listing
14728 function that descends into the sub-directories.
14729
14730 @findex files-in-below-directory
14731 We can create this function, called @code{files-in-below-directory},
14732 using familiar functions such as @code{car}, @code{nthcdr}, and
14733 @code{substring} in conjunction with an existing function called
14734 @code{directory-files-and-attributes}. This latter function not only
14735 lists all the filenames in a directory, including the names
14736 of sub-directories, but also their attributes.
14737
14738 To restate our goal: to create a function that will enable us
14739 to feed filenames to @code{recursive-lengths-list-many-files}
14740 as a list that looks like this (but with more elements):
14741
14742 @smallexample
14743 @group
14744 ("../lisp/macros.el"
14745 "../lisp/mail/rmail.el"
14746 "../lisp/makesum.el")
14747 @end group
14748 @end smallexample
14749
14750 The @code{directory-files-and-attributes} function returns a list of
14751 lists. Each of the lists within the main list consists of 13
14752 elements. The first element is a string that contains the name of the
14753 file -- which, in GNU/Linux, may be a `directory file', that is to
14754 say, a file with the special attributes of a directory. The second
14755 element of the list is @code{t} for a directory, a string
14756 for symbolic link (the string is the name linked to), or @code{nil}.
14757
14758 For example, the first @samp{.el} file in the @file{lisp/} directory
14759 is @file{abbrev.el}. Its name is
14760 @file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14761 directory or a symbolic link.
14762
14763 @need 1000
14764 This is how @code{directory-files-and-attributes} lists that file and
14765 its attributes:
14766
14767 @smallexample
14768 @group
14769 ("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14770 nil
14771 1
14772 1000
14773 100
14774 @end group
14775 @group
14776 (15019 32380)
14777 (14883 48041)
14778 (15214 49336)
14779 11583
14780 "-rw-rw-r--"
14781 @end group
14782 @group
14783 t
14784 341385
14785 776)
14786 @end group
14787 @end smallexample
14788
14789 @need 1200
14790 On the other hand, @file{mail/} is a directory within the @file{lisp/}
14791 directory. The beginning of its listing looks like this:
14792
14793 @smallexample
14794 @group
14795 ("/usr/local/share/emacs/21.0.100/lisp/mail"
14796 t
14797 @dots{}
14798 )
14799 @end group
14800 @end smallexample
14801
14802 (Look at the documentation of @code{file-attributes} to learn about
14803 the different attributes. Bear in mind that the
14804 @code{file-attributes} function does not list the filename, so its
14805 first element is @code{directory-files-and-attributes}'s second
14806 element.)
14807
14808 We will want our new function, @code{files-in-below-directory}, to
14809 list the @samp{.el} files in the directory it is told to check, and in
14810 any directories below that directory.
14811
14812 This gives us a hint on how to construct
14813 @code{files-in-below-directory}: within a directory, the function
14814 should add @samp{.el} filenames to a list; and if, within a directory,
14815 the function comes upon a sub-directory, it should go into that
14816 sub-directory and repeat its actions.
14817
14818 However, we should note that every directory contains a name that
14819 refers to itself, called @file{.}, (``dot'') and a name that refers to
14820 its parent directory, called @file{..} (``double dot''). (In
14821 @file{/}, the root directory, @file{..} refers to itself, since
14822 @file{/} has no parent.) Clearly, we do not want our
14823 @code{files-in-below-directory} function to enter those directories,
14824 since they always lead us, directly or indirectly, to the current
14825 directory.
14826
14827 Consequently, our @code{files-in-below-directory} function must do
14828 several tasks:
14829
14830 @itemize @bullet
14831 @item
14832 Check to see whether it is looking at a filename that ends in
14833 @samp{.el}; and if so, add its name to a list.
14834
14835 @item
14836 Check to see whether it is looking at a filename that is the name of a
14837 directory; and if so,
14838
14839 @itemize @minus
14840 @item
14841 Check to see whether it is looking at @file{.} or @file{..}; and if
14842 so skip it.
14843
14844 @item
14845 Or else, go into that directory and repeat the process.
14846 @end itemize
14847 @end itemize
14848
14849 Let's write a function definition to do these tasks. We will use a
14850 @code{while} loop to move from one filename to another within a
14851 directory, checking what needs to be done; and we will use a recursive
14852 call to repeat the actions on each sub-directory. The recursive
14853 pattern is `accumulate'
14854 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14855 using @code{append} as the combiner.
14856
14857 @ignore
14858 (directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14859 (shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14860 @end ignore
14861
14862 @c /usr/local/share/emacs/21.0.100/lisp/
14863
14864 @need 800
14865 Here is the function:
14866
14867 @smallexample
14868 @group
14869 (defun files-in-below-directory (directory)
14870 "List the .el files in DIRECTORY and in its sub-directories."
14871 ;; Although the function will be used non-interactively,
14872 ;; it will be easier to test if we make it interactive.
14873 ;; The directory will have a name such as
14874 ;; "/usr/local/share/emacs/21.0.100/lisp/"
14875 (interactive "DDirectory name: ")
14876 @end group
14877 @group
14878 (let (el-files-list
14879 (current-directory-list
14880 (directory-files-and-attributes directory t)))
14881 ;; while we are in the current directory
14882 (while current-directory-list
14883 @end group
14884 @group
14885 (cond
14886 ;; check to see whether filename ends in `.el'
14887 ;; and if so, append its name to a list.
14888 ((equal ".el" (substring (car (car current-directory-list)) -3))
14889 (setq el-files-list
14890 (cons (car (car current-directory-list)) el-files-list)))
14891 @end group
14892 @group
14893 ;; check whether filename is that of a directory
14894 ((eq t (car (cdr (car current-directory-list))))
14895 ;; decide whether to skip or recurse
14896 (if
14897 (equal (or "." "..")
14898 (substring (car (car current-directory-list)) -1))
14899 ;; then do nothing if filename is that of
14900 ;; current directory or parent
14901 ()
14902 @end group
14903 @group
14904 ;; else descend into the directory and repeat the process
14905 (setq el-files-list
14906 (append
14907 (files-in-below-directory
14908 (car (car current-directory-list)))
14909 el-files-list)))))
14910 ;; move to the next filename in the list; this also
14911 ;; shortens the list so the while loop eventually comes to an end
14912 (setq current-directory-list (cdr current-directory-list)))
14913 ;; return the filenames
14914 el-files-list))
14915 @end group
14916 @end smallexample
14917
14918 @c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14919
14920 The @code{files-in-below-directory} @code{directory-files} function
14921 takes one argument, the name of a directory.
14922
14923 @need 1250
14924 Thus, on my system,
14925
14926 @c !!! 21.0.100 lisp sources location here
14927 @smallexample
14928 @group
14929 (length
14930 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14931 @end group
14932 @end smallexample
14933
14934 @noindent
14935 tells me that my version 21.0.100 Lisp sources directory contains 754
14936 @samp{.el} files.
14937
14938 @code{files-in-below-directory} returns a list in reverse alphabetical
14939 order. An expression to sort the list in alphabetical order looks
14940 like this:
14941
14942 @smallexample
14943 @group
14944 (sort
14945 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14946 'string-lessp)
14947 @end group
14948 @end smallexample
14949
14950 @ignore
14951 (defun test ()
14952 "Test how long it takes to find lengths of all elisp defuns."
14953 (insert "\n" (current-time-string) "\n")
14954 (sit-for 0)
14955 (sort
14956 (recursive-lengths-list-many-files
14957 '("../lisp/macros.el"
14958 "../lisp/mailalias.el"
14959 "../lisp/makesum.el"))
14960 '<)
14961 (insert (format "%s" (current-time-string))))
14962
14963 @end ignore
14964
14965 @node Counting function definitions, , Files List, Prepare the data
14966 @subsection Counting function definitions
14967
14968 Our immediate goal is to generate a list that tells us how many
14969 function definitions contain fewer than 10 words and symbols, how many
14970 contain between 10 and 19 words and symbols, how many contain between
14971 20 and 29 words and symbols, and so on.
14972
14973 With a sorted list of numbers, this is easy: count how many elements
14974 of the list are smaller than 10, then, after moving past the numbers
14975 just counted, count how many are smaller than 20, then, after moving
14976 past the numbers just counted, count how many are smaller than 30, and
14977 so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
14978 larger than the top of that range. We can call the list of such
14979 numbers the @code{top-of-ranges} list.
14980
14981 @need 1200
14982 If we wished, we could generate this list automatically, but it is
14983 simpler to write a list manually. Here it is:
14984 @vindex top-of-ranges
14985
14986 @smallexample
14987 @group
14988 (defvar top-of-ranges
14989 '(10 20 30 40 50
14990 60 70 80 90 100
14991 110 120 130 140 150
14992 160 170 180 190 200
14993 210 220 230 240 250
14994 260 270 280 290 300)
14995 "List specifying ranges for `defuns-per-range'.")
14996 @end group
14997 @end smallexample
14998
14999 To change the ranges, we edit this list.
15000
15001 Next, we need to write the function that creates the list of the
15002 number of definitions within each range. Clearly, this function must
15003 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15004 as arguments.
15005
15006 The @code{defuns-per-range} function must do two things again and
15007 again: it must count the number of definitions within a range
15008 specified by the current top-of-range value; and it must shift to the
15009 next higher value in the @code{top-of-ranges} list after counting the
15010 number of definitions in the current range. Since each of these
15011 actions is repetitive, we can use @code{while} loops for the job.
15012 One loop counts the number of definitions in the range defined by the
15013 current top-of-range value, and the other loop selects each of the
15014 top-of-range values in turn.
15015
15016 Several entries of the @code{sorted-lengths} list are counted for each
15017 range; this means that the loop for the @code{sorted-lengths} list
15018 will be inside the loop for the @code{top-of-ranges} list, like a
15019 small gear inside a big gear.
15020
15021 The inner loop counts the number of definitions within the range. It
15022 is a simple counting loop of the type we have seen before.
15023 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15024 The true-or-false test of the loop tests whether the value from the
15025 @code{sorted-lengths} list is smaller than the current value of the
15026 top of the range. If it is, the function increments the counter and
15027 tests the next value from the @code{sorted-lengths} list.
15028
15029 @need 1250
15030 The inner loop looks like this:
15031
15032 @smallexample
15033 @group
15034 (while @var{length-element-smaller-than-top-of-range}
15035 (setq number-within-range (1+ number-within-range))
15036 (setq sorted-lengths (cdr sorted-lengths)))
15037 @end group
15038 @end smallexample
15039
15040 The outer loop must start with the lowest value of the
15041 @code{top-of-ranges} list, and then be set to each of the succeeding
15042 higher values in turn. This can be done with a loop like this:
15043
15044 @smallexample
15045 @group
15046 (while top-of-ranges
15047 @var{body-of-loop}@dots{}
15048 (setq top-of-ranges (cdr top-of-ranges)))
15049 @end group
15050 @end smallexample
15051
15052 @need 1200
15053 Put together, the two loops look like this:
15054
15055 @smallexample
15056 @group
15057 (while top-of-ranges
15058
15059 ;; @r{Count the number of elements within the current range.}
15060 (while @var{length-element-smaller-than-top-of-range}
15061 (setq number-within-range (1+ number-within-range))
15062 (setq sorted-lengths (cdr sorted-lengths)))
15063
15064 ;; @r{Move to next range.}
15065 (setq top-of-ranges (cdr top-of-ranges)))
15066 @end group
15067 @end smallexample
15068
15069 In addition, in each circuit of the outer loop, Emacs should record
15070 the number of definitions within that range (the value of
15071 @code{number-within-range}) in a list. We can use @code{cons} for
15072 this purpose. (@xref{cons, , @code{cons}}.)
15073
15074 The @code{cons} function works fine, except that the list it
15075 constructs will contain the number of definitions for the highest
15076 range at its beginning and the number of definitions for the lowest
15077 range at its end. This is because @code{cons} attaches new elements
15078 of the list to the beginning of the list, and since the two loops are
15079 working their way through the lengths' list from the lower end first,
15080 the @code{defuns-per-range-list} will end up largest number first.
15081 But we will want to print our graph with smallest values first and the
15082 larger later. The solution is to reverse the order of the
15083 @code{defuns-per-range-list}. We can do this using the
15084 @code{nreverse} function, which reverses the order of a list.
15085 @findex nreverse
15086
15087 @need 800
15088 For example,
15089
15090 @smallexample
15091 (nreverse '(1 2 3 4))
15092 @end smallexample
15093
15094 @need 800
15095 @noindent
15096 produces:
15097
15098 @smallexample
15099 (4 3 2 1)
15100 @end smallexample
15101
15102 Note that the @code{nreverse} function is ``destructive''---that is,
15103 it changes the list to which it is applied; this contrasts with the
15104 @code{car} and @code{cdr} functions, which are non-destructive. In
15105 this case, we do not want the original @code{defuns-per-range-list},
15106 so it does not matter that it is destroyed. (The @code{reverse}
15107 function provides a reversed copy of a list, leaving the original list
15108 as is.)
15109 @findex reverse
15110
15111 @need 1250
15112 Put all together, the @code{defuns-per-range} looks like this:
15113
15114 @smallexample
15115 @group
15116 (defun defuns-per-range (sorted-lengths top-of-ranges)
15117 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15118 (let ((top-of-range (car top-of-ranges))
15119 (number-within-range 0)
15120 defuns-per-range-list)
15121 @end group
15122
15123 @group
15124 ;; @r{Outer loop.}
15125 (while top-of-ranges
15126 @end group
15127
15128 @group
15129 ;; @r{Inner loop.}
15130 (while (and
15131 ;; @r{Need number for numeric test.}
15132 (car sorted-lengths)
15133 (< (car sorted-lengths) top-of-range))
15134 @end group
15135
15136 @group
15137 ;; @r{Count number of definitions within current range.}
15138 (setq number-within-range (1+ number-within-range))
15139 (setq sorted-lengths (cdr sorted-lengths)))
15140
15141 ;; @r{Exit inner loop but remain within outer loop.}
15142 @end group
15143
15144 @group
15145 (setq defuns-per-range-list
15146 (cons number-within-range defuns-per-range-list))
15147 (setq number-within-range 0) ; @r{Reset count to zero.}
15148 @end group
15149
15150 @group
15151 ;; @r{Move to next range.}
15152 (setq top-of-ranges (cdr top-of-ranges))
15153 ;; @r{Specify next top of range value.}
15154 (setq top-of-range (car top-of-ranges)))
15155 @end group
15156
15157 @group
15158 ;; @r{Exit outer loop and count the number of defuns larger than}
15159 ;; @r{ the largest top-of-range value.}
15160 (setq defuns-per-range-list
15161 (cons
15162 (length sorted-lengths)
15163 defuns-per-range-list))
15164 @end group
15165
15166 @group
15167 ;; @r{Return a list of the number of definitions within each range,}
15168 ;; @r{ smallest to largest.}
15169 (nreverse defuns-per-range-list)))
15170 @end group
15171 @end smallexample
15172
15173 @need 1200
15174 @noindent
15175 The function is straightforward except for one subtle feature. The
15176 true-or-false test of the inner loop looks like this:
15177
15178 @smallexample
15179 @group
15180 (and (car sorted-lengths)
15181 (< (car sorted-lengths) top-of-range))
15182 @end group
15183 @end smallexample
15184
15185 @need 800
15186 @noindent
15187 instead of like this:
15188
15189 @smallexample
15190 (< (car sorted-lengths) top-of-range)
15191 @end smallexample
15192
15193 The purpose of the test is to determine whether the first item in the
15194 @code{sorted-lengths} list is less than the value of the top of the
15195 range.
15196
15197 The simple version of the test works fine unless the
15198 @code{sorted-lengths} list has a @code{nil} value. In that case, the
15199 @code{(car sorted-lengths)} expression function returns
15200 @code{nil}. The @code{<} function cannot compare a number to
15201 @code{nil}, which is an empty list, so Emacs signals an error and
15202 stops the function from attempting to continue to execute.
15203
15204 The @code{sorted-lengths} list always becomes @code{nil} when the
15205 counter reaches the end of the list. This means that any attempt to
15206 use the @code{defuns-per-range} function with the simple version of
15207 the test will fail.
15208
15209 We solve the problem by using the @code{(car sorted-lengths)}
15210 expression in conjunction with the @code{and} expression. The
15211 @code{(car sorted-lengths)} expression returns a non-@code{nil}
15212 value so long as the list has at least one number within it, but
15213 returns @code{nil} if the list is empty. The @code{and} expression
15214 first evaluates the @code{(car sorted-lengths)} expression, and
15215 if it is @code{nil}, returns false @emph{without} evaluating the
15216 @code{<} expression. But if the @code{(car sorted-lengths)}
15217 expression returns a non-@code{nil} value, the @code{and} expression
15218 evaluates the @code{<} expression, and returns that value as the value
15219 of the @code{and} expression.
15220
15221 @c colon in printed section title causes problem in Info cross reference
15222 This way, we avoid an error.
15223 @iftex
15224 @xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15225 Functions}, for more information about @code{and}.
15226 @end iftex
15227 @ifinfo
15228 @xref{forward-paragraph}, for more information about @code{and}.
15229 @end ifinfo
15230
15231 Here is a short test of the @code{defuns-per-range} function. First,
15232 evaluate the expression that binds (a shortened)
15233 @code{top-of-ranges} list to the list of values, then evaluate the
15234 expression for binding the @code{sorted-lengths} list, and then
15235 evaluate the @code{defuns-per-range} function.
15236
15237 @smallexample
15238 @group
15239 ;; @r{(Shorter list than we will use later.)}
15240 (setq top-of-ranges
15241 '(110 120 130 140 150
15242 160 170 180 190 200))
15243
15244 (setq sorted-lengths
15245 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15246
15247 (defuns-per-range sorted-lengths top-of-ranges)
15248 @end group
15249 @end smallexample
15250
15251 @need 800
15252 @noindent
15253 The list returned looks like this:
15254
15255 @smallexample
15256 (2 2 2 0 0 1 0 2 0 0 4)
15257 @end smallexample
15258
15259 @noindent
15260 Indeed, there are two elements of the @code{sorted-lengths} list
15261 smaller than 110, two elements between 110 and 119, two elements
15262 between 120 and 129, and so on. There are four elements with a value
15263 of 200 or larger.
15264
15265 @c The next step is to turn this numbers' list into a graph.
15266
15267 @node Readying a Graph, Emacs Initialization, Words in a defun, Top
15268 @chapter Readying a Graph
15269 @cindex Readying a graph
15270 @cindex Graph prototype
15271 @cindex Prototype graph
15272 @cindex Body of graph
15273
15274 Our goal is to construct a graph showing the numbers of function
15275 definitions of various lengths in the Emacs lisp sources.
15276
15277 As a practical matter, if you were creating a graph, you would
15278 probably use a program such as @code{gnuplot} to do the job.
15279 (@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
15280 however, we create one from scratch, and in the process we will
15281 re-acquaint ourselves with some of what we learned before and learn
15282 more.
15283
15284 In this chapter, we will first write a simple graph printing function.
15285 This first definition will be a @dfn{prototype}, a rapidly written
15286 function that enables us to reconnoiter this unknown graph-making
15287 territory. We will discover dragons, or find that they are myth.
15288 After scouting the terrain, we will feel more confident and enhance
15289 the function to label the axes automatically.
15290
15291 @menu
15292 * Columns of a graph::
15293 * graph-body-print:: How to print the body of a graph.
15294 * recursive-graph-body-print::
15295 * Printed Axes::
15296 * Line Graph Exercise::
15297 @end menu
15298
15299 @node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15300 @ifnottex
15301 @unnumberedsec Printing the Columns of a Graph
15302 @end ifnottex
15303
15304 Since Emacs is designed to be flexible and work with all kinds of
15305 terminals, including character-only terminals, the graph will need to
15306 be made from one of the `typewriter' symbols. An asterisk will do; as
15307 we enhance the graph-printing function, we can make the choice of
15308 symbol a user option.
15309
15310 We can call this function @code{graph-body-print}; it will take a
15311 @code{numbers-list} as its only argument. At this stage, we will not
15312 label the graph, but only print its body.
15313
15314 The @code{graph-body-print} function inserts a vertical column of
15315 asterisks for each element in the @code{numbers-list}. The height of
15316 each line is determined by the value of that element of the
15317 @code{numbers-list}.
15318
15319 Inserting columns is a repetitive act; that means that this function can
15320 be written either with a @code{while} loop or recursively.
15321
15322 Our first challenge is to discover how to print a column of asterisks.
15323 Usually, in Emacs, we print characters onto a screen horizontally,
15324 line by line, by typing. We have two routes we can follow: write our
15325 own column-insertion function or discover whether one exists in Emacs.
15326
15327 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15328 command. This command is like the @kbd{C-h a} (command-apropos)
15329 command, except that the latter finds only those functions that are
15330 commands. The @kbd{M-x apropos} command lists all symbols that match
15331 a regular expression, including functions that are not interactive.
15332 @findex apropos
15333
15334 What we want to look for is some command that prints or inserts
15335 columns. Very likely, the name of the function will contain either
15336 the word `print' or the word `insert' or the word `column'.
15337 Therefore, we can simply type @kbd{M-x apropos RET
15338 print\|insert\|column RET} and look at the result. On my system, this
15339 command takes quite some time, and then produces a list of 79
15340 functions and variables. Scanning down the list, the only function
15341 that looks as if it might do the job is @code{insert-rectangle}.
15342
15343 @need 1200
15344 Indeed, this is the function we want; its documentation says:
15345
15346 @smallexample
15347 @group
15348 insert-rectangle:
15349 Insert text of RECTANGLE with upper left corner at point.
15350 RECTANGLE's first line is inserted at point,
15351 its second line is inserted at a point vertically under point, etc.
15352 RECTANGLE should be a list of strings.
15353 @end group
15354 @end smallexample
15355
15356 We can run a quick test, to make sure it does what we expect of it.
15357
15358 Here is the result of placing the cursor after the
15359 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15360 (@code{eval-last-sexp}). The function inserts the strings
15361 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15362 point. Also the function returns @code{nil}.
15363
15364 @smallexample
15365 @group
15366 (insert-rectangle '("first" "second" "third"))first
15367 second
15368 third
15369 nil
15370 @end group
15371 @end smallexample
15372
15373 @noindent
15374 Of course, we won't be inserting the text of the
15375 @code{insert-rectangle} expression itself into the buffer in which we
15376 are making the graph, but will call the function from our program. We
15377 shall, however, have to make sure that point is in the buffer at the
15378 place where the @code{insert-rectangle} function will insert its
15379 column of strings.
15380
15381 If you are reading this in Info, you can see how this works by
15382 switching to another buffer, such as the @file{*scratch*} buffer,
15383 placing point somewhere in the buffer, typing @kbd{M-:},
15384 typing the @code{insert-rectangle} expression into the minibuffer at
15385 the prompt, and then typing @key{RET}. This causes Emacs to evaluate
15386 the expression in the minibuffer, but to use as the value of point the
15387 position of point in the @file{*scratch*} buffer. (@kbd{M-:}
15388 is the keybinding for @code{eval-expression}.)
15389
15390 We find when we do this that point ends up at the end of the last
15391 inserted line---that is to say, this function moves point as a
15392 side-effect. If we were to repeat the command, with point at this
15393 position, the next insertion would be below and to the right of the
15394 previous insertion. We don't want this! If we are going to make a
15395 bar graph, the columns need to be beside each other.
15396
15397 So we discover that each cycle of the column-inserting @code{while}
15398 loop must reposition point to the place we want it, and that place
15399 will be at the top, not the bottom, of the column. Moreover, we
15400 remember that when we print a graph, we do not expect all the columns
15401 to be the same height. This means that the top of each column may be
15402 at a different height from the previous one. We cannot simply
15403 reposition point to the same line each time, but moved over to the
15404 right---or perhaps we can@dots{}
15405
15406 We are planning to make the columns of the bar graph out of asterisks.
15407 The number of asterisks in the column is the number specified by the
15408 current element of the @code{numbers-list}. We need to construct a
15409 list of asterisks of the right length for each call to
15410 @code{insert-rectangle}. If this list consists solely of the requisite
15411 number of asterisks, then we will have position point the right number
15412 of lines above the base for the graph to print correctly. This could
15413 be difficult.
15414
15415 Alternatively, if we can figure out some way to pass
15416 @code{insert-rectangle} a list of the same length each time, then we
15417 can place point on the same line each time, but move it over one
15418 column to the right for each new column. If we do this, however, some
15419 of the entries in the list passed to @code{insert-rectangle} must be
15420 blanks rather than asterisks. For example, if the maximum height of
15421 the graph is 5, but the height of the column is 3, then
15422 @code{insert-rectangle} requires an argument that looks like this:
15423
15424 @smallexample
15425 (" " " " "*" "*" "*")
15426 @end smallexample
15427
15428 This last proposal is not so difficult, so long as we can determine
15429 the column height. There are two ways for us to specify the column
15430 height: we can arbitrarily state what it will be, which would work
15431 fine for graphs of that height; or we can search through the list of
15432 numbers and use the maximum height of the list as the maximum height
15433 of the graph. If the latter operation were difficult, then the former
15434 procedure would be easiest, but there is a function built into Emacs
15435 that determines the maximum of its arguments. We can use that
15436 function. The function is called @code{max} and it returns the
15437 largest of all its arguments, which must be numbers. Thus, for
15438 example,
15439
15440 @smallexample
15441 (max 3 4 6 5 7 3)
15442 @end smallexample
15443
15444 @noindent
15445 returns 7. (A corresponding function called @code{min} returns the
15446 smallest of all its arguments.)
15447 @findex max
15448 @findex min
15449
15450 However, we cannot simply call @code{max} on the @code{numbers-list};
15451 the @code{max} function expects numbers as its argument, not a list of
15452 numbers. Thus, the following expression,
15453
15454 @smallexample
15455 (max '(3 4 6 5 7 3))
15456 @end smallexample
15457
15458 @need 800
15459 @noindent
15460 produces the following error message;
15461
15462 @smallexample
15463 Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
15464 @end smallexample
15465
15466 @findex apply
15467 We need a function that passes a list of arguments to a function.
15468 This function is @code{apply}. This function `applies' its first
15469 argument (a function) to its remaining arguments, the last of which
15470 may be a list.
15471
15472 @need 1250
15473 For example,
15474
15475 @smallexample
15476 (apply 'max 3 4 7 3 '(4 8 5))
15477 @end smallexample
15478
15479 @noindent
15480 returns 8.
15481
15482 (Incidentally, I don't know how you would learn of this function
15483 without a book such as this. It is possible to discover other
15484 functions, like @code{search-forward} or @code{insert-rectangle}, by
15485 guessing at a part of their names and then using @code{apropos}. Even
15486 though its base in metaphor is clear---`apply' its first argument to
15487 the rest---I doubt a novice would come up with that particular word
15488 when using @code{apropos} or other aid. Of course, I could be wrong;
15489 after all, the function was first named by someone who had to invent
15490 it.)
15491
15492 The second and subsequent arguments to @code{apply} are optional, so
15493 we can use @code{apply} to call a function and pass the elements of a
15494 list to it, like this, which also returns 8:
15495
15496 @smallexample
15497 (apply 'max '(4 8 5))
15498 @end smallexample
15499
15500 This latter way is how we will use @code{apply}. The
15501 @code{recursive-lengths-list-many-files} function returns a numbers'
15502 list to which we can apply @code{max} (we could also apply @code{max} to
15503 the sorted numbers' list; it does not matter whether the list is
15504 sorted or not.)
15505
15506 @need 800
15507 Hence, the operation for finding the maximum height of the graph is this:
15508
15509 @smallexample
15510 (setq max-graph-height (apply 'max numbers-list))
15511 @end smallexample
15512
15513 Now we can return to the question of how to create a list of strings
15514 for a column of the graph. Told the maximum height of the graph
15515 and the number of asterisks that should appear in the column, the
15516 function should return a list of strings for the
15517 @code{insert-rectangle} command to insert.
15518
15519 Each column is made up of asterisks or blanks. Since the function is
15520 passed the value of the height of the column and the number of
15521 asterisks in the column, the number of blanks can be found by
15522 subtracting the number of asterisks from the height of the column.
15523 Given the number of blanks and the number of asterisks, two
15524 @code{while} loops can be used to construct the list:
15525
15526 @smallexample
15527 @group
15528 ;;; @r{First version.}
15529 (defun column-of-graph (max-graph-height actual-height)
15530 "Return list of strings that is one column of a graph."
15531 (let ((insert-list nil)
15532 (number-of-top-blanks
15533 (- max-graph-height actual-height)))
15534 @end group
15535
15536 @group
15537 ;; @r{Fill in asterisks.}
15538 (while (> actual-height 0)
15539 (setq insert-list (cons "*" insert-list))
15540 (setq actual-height (1- actual-height)))
15541 @end group
15542
15543 @group
15544 ;; @r{Fill in blanks.}
15545 (while (> number-of-top-blanks 0)
15546 (setq insert-list (cons " " insert-list))
15547 (setq number-of-top-blanks
15548 (1- number-of-top-blanks)))
15549 @end group
15550
15551 @group
15552 ;; @r{Return whole list.}
15553 insert-list))
15554 @end group
15555 @end smallexample
15556
15557 If you install this function and then evaluate the following
15558 expression you will see that it returns the list as desired:
15559
15560 @smallexample
15561 (column-of-graph 5 3)
15562 @end smallexample
15563
15564 @need 800
15565 @noindent
15566 returns
15567
15568 @smallexample
15569 (" " " " "*" "*" "*")
15570 @end smallexample
15571
15572 As written, @code{column-of-graph} contains a major flaw: the symbols
15573 used for the blank and for the marked entries in the column are
15574 `hard-coded' as a space and asterisk. This is fine for a prototype,
15575 but you, or another user, may wish to use other symbols. For example,
15576 in testing the graph function, you many want to use a period in place
15577 of the space, to make sure the point is being repositioned properly
15578 each time the @code{insert-rectangle} function is called; or you might
15579 want to substitute a @samp{+} sign or other symbol for the asterisk.
15580 You might even want to make a graph-column that is more than one
15581 display column wide. The program should be more flexible. The way to
15582 do that is to replace the blank and the asterisk with two variables
15583 that we can call @code{graph-blank} and @code{graph-symbol} and define
15584 those variables separately.
15585
15586 Also, the documentation is not well written. These considerations
15587 lead us to the second version of the function:
15588
15589 @smallexample
15590 @group
15591 (defvar graph-symbol "*"
15592 "String used as symbol in graph, usually an asterisk.")
15593 @end group
15594
15595 @group
15596 (defvar graph-blank " "
15597 "String used as blank in graph, usually a blank space.
15598 graph-blank must be the same number of columns wide
15599 as graph-symbol.")
15600 @end group
15601 @end smallexample
15602
15603 @noindent
15604 (For an explanation of @code{defvar}, see
15605 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
15606
15607 @smallexample
15608 @group
15609 ;;; @r{Second version.}
15610 (defun column-of-graph (max-graph-height actual-height)
15611 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15612
15613 @end group
15614 @group
15615 The graph-symbols are contiguous entries at the end
15616 of the list.
15617 The list will be inserted as one column of a graph.
15618 The strings are either graph-blank or graph-symbol."
15619 @end group
15620
15621 @group
15622 (let ((insert-list nil)
15623 (number-of-top-blanks
15624 (- max-graph-height actual-height)))
15625 @end group
15626
15627 @group
15628 ;; @r{Fill in @code{graph-symbols}.}
15629 (while (> actual-height 0)
15630 (setq insert-list (cons graph-symbol insert-list))
15631 (setq actual-height (1- actual-height)))
15632 @end group
15633
15634 @group
15635 ;; @r{Fill in @code{graph-blanks}.}
15636 (while (> number-of-top-blanks 0)
15637 (setq insert-list (cons graph-blank insert-list))
15638 (setq number-of-top-blanks
15639 (1- number-of-top-blanks)))
15640
15641 ;; @r{Return whole list.}
15642 insert-list))
15643 @end group
15644 @end smallexample
15645
15646 If we wished, we could rewrite @code{column-of-graph} a third time to
15647 provide optionally for a line graph as well as for a bar graph. This
15648 would not be hard to do. One way to think of a line graph is that it
15649 is no more than a bar graph in which the part of each bar that is
15650 below the top is blank. To construct a column for a line graph, the
15651 function first constructs a list of blanks that is one shorter than
15652 the value, then it uses @code{cons} to attach a graph symbol to the
15653 list; then it uses @code{cons} again to attach the `top blanks' to
15654 the list.
15655
15656 It is easy to see how to write such a function, but since we don't
15657 need it, we will not do it. But the job could be done, and if it were
15658 done, it would be done with @code{column-of-graph}. Even more
15659 important, it is worth noting that few changes would have to be made
15660 anywhere else. The enhancement, if we ever wish to make it, is
15661 simple.
15662
15663 Now, finally, we come to our first actual graph printing function.
15664 This prints the body of a graph, not the labels for the vertical and
15665 horizontal axes, so we can call this @code{graph-body-print}.
15666
15667 @node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15668 @section The @code{graph-body-print} Function
15669 @findex graph-body-print
15670
15671 After our preparation in the preceding section, the
15672 @code{graph-body-print} function is straightforward. The function
15673 will print column after column of asterisks and blanks, using the
15674 elements of a numbers' list to specify the number of asterisks in each
15675 column. This is a repetitive act, which means we can use a
15676 decrementing @code{while} loop or recursive function for the job. In
15677 this section, we will write the definition using a @code{while} loop.
15678
15679 The @code{column-of-graph} function requires the height of the graph
15680 as an argument, so we should determine and record that as a local variable.
15681
15682 This leads us to the following template for the @code{while} loop
15683 version of this function:
15684
15685 @smallexample
15686 @group
15687 (defun graph-body-print (numbers-list)
15688 "@var{documentation}@dots{}"
15689 (let ((height @dots{}
15690 @dots{}))
15691 @end group
15692
15693 @group
15694 (while numbers-list
15695 @var{insert-columns-and-reposition-point}
15696 (setq numbers-list (cdr numbers-list)))))
15697 @end group
15698 @end smallexample
15699
15700 @noindent
15701 We need to fill in the slots of the template.
15702
15703 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15704 determine the height of the graph.
15705
15706 The @code{while} loop will cycle through the @code{numbers-list} one
15707 element at a time. As it is shortened by the @code{(setq numbers-list
15708 (cdr numbers-list))} expression, the @sc{car} of each instance of the
15709 list is the value of the argument for @code{column-of-graph}.
15710
15711 At each cycle of the @code{while} loop, the @code{insert-rectangle}
15712 function inserts the list returned by @code{column-of-graph}. Since
15713 the @code{insert-rectangle} function moves point to the lower right of
15714 the inserted rectangle, we need to save the location of point at the
15715 time the rectangle is inserted, move back to that position after the
15716 rectangle is inserted, and then move horizontally to the next place
15717 from which @code{insert-rectangle} is called.
15718
15719 If the inserted columns are one character wide, as they will be if
15720 single blanks and asterisks are used, the repositioning command is
15721 simply @code{(forward-char 1)}; however, the width of a column may be
15722 greater than one. This means that the repositioning command should be
15723 written @code{(forward-char symbol-width)}. The @code{symbol-width}
15724 itself is the length of a @code{graph-blank} and can be found using
15725 the expression @code{(length graph-blank)}. The best place to bind
15726 the @code{symbol-width} variable to the value of the width of graph
15727 column is in the varlist of the @code{let} expression.
15728
15729 @need 1250
15730 These considerations lead to the following function definition:
15731
15732 @smallexample
15733 @group
15734 (defun graph-body-print (numbers-list)
15735 "Print a bar graph of the NUMBERS-LIST.
15736 The numbers-list consists of the Y-axis values."
15737
15738 (let ((height (apply 'max numbers-list))
15739 (symbol-width (length graph-blank))
15740 from-position)
15741 @end group
15742
15743 @group
15744 (while numbers-list
15745 (setq from-position (point))
15746 (insert-rectangle
15747 (column-of-graph height (car numbers-list)))
15748 (goto-char from-position)
15749 (forward-char symbol-width)
15750 @end group
15751 @group
15752 ;; @r{Draw graph column by column.}
15753 (sit-for 0)
15754 (setq numbers-list (cdr numbers-list)))
15755 @end group
15756 @group
15757 ;; @r{Place point for X axis labels.}
15758 (forward-line height)
15759 (insert "\n")
15760 ))
15761 @end group
15762 @end smallexample
15763
15764 @noindent
15765 The one unexpected expression in this function is the
15766 @w{@code{(sit-for 0)}} expression in the @code{while} loop. This
15767 expression makes the graph printing operation more interesting to
15768 watch than it would be otherwise. The expression causes Emacs to
15769 `sit' or do nothing for a zero length of time and then redraw the
15770 screen. Placed here, it causes Emacs to redraw the screen column by
15771 column. Without it, Emacs would not redraw the screen until the
15772 function exits.
15773
15774 We can test @code{graph-body-print} with a short list of numbers.
15775
15776 @enumerate
15777 @item
15778 Install @code{graph-symbol}, @code{graph-blank},
15779 @code{column-of-graph}, which are in
15780 @ref{Columns of a graph, , Printing the Columns of a Graph},
15781 and @code{graph-body-print}.
15782
15783 @need 800
15784 @item
15785 Copy the following expression:
15786
15787 @smallexample
15788 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15789 @end smallexample
15790
15791 @item
15792 Switch to the @file{*scratch*} buffer and place the cursor where you
15793 want the graph to start.
15794
15795 @item
15796 Type @kbd{M-:} (@code{eval-expression}).
15797
15798 @item
15799 Yank the @code{graph-body-print} expression into the minibuffer
15800 with @kbd{C-y} (@code{yank)}.
15801
15802 @item
15803 Press @key{RET} to evaluate the @code{graph-body-print} expression.
15804 @end enumerate
15805
15806 @need 800
15807 Emacs will print a graph like this:
15808
15809 @smallexample
15810 @group
15811 *
15812 * **
15813 * ****
15814 *** ****
15815 ********* *
15816 ************
15817 *************
15818 @end group
15819 @end smallexample
15820
15821 @node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15822 @section The @code{recursive-graph-body-print} Function
15823 @findex recursive-graph-body-print
15824
15825 The @code{graph-body-print} function may also be written recursively.
15826 The recursive solution is divided into two parts: an outside `wrapper'
15827 that uses a @code{let} expression to determine the values of several
15828 variables that need only be found once, such as the maximum height of
15829 the graph, and an inside function that is called recursively to print
15830 the graph.
15831
15832 @need 1250
15833 The `wrapper' is uncomplicated:
15834
15835 @smallexample
15836 @group
15837 (defun recursive-graph-body-print (numbers-list)
15838 "Print a bar graph of the NUMBERS-LIST.
15839 The numbers-list consists of the Y-axis values."
15840 (let ((height (apply 'max numbers-list))
15841 (symbol-width (length graph-blank))
15842 from-position)
15843 (recursive-graph-body-print-internal
15844 numbers-list
15845 height
15846 symbol-width)))
15847 @end group
15848 @end smallexample
15849
15850 The recursive function is a little more difficult. It has four parts:
15851 the `do-again-test', the printing code, the recursive call, and the
15852 `next-step-expression'. The `do-again-test' is an @code{if}
15853 expression that determines whether the @code{numbers-list} contains
15854 any remaining elements; if it does, the function prints one column of
15855 the graph using the printing code and calls itself again. The
15856 function calls itself again according to the value produced by the
15857 `next-step-expression' which causes the call to act on a shorter
15858 version of the @code{numbers-list}.
15859
15860 @smallexample
15861 @group
15862 (defun recursive-graph-body-print-internal
15863 (numbers-list height symbol-width)
15864 "Print a bar graph.
15865 Used within recursive-graph-body-print function."
15866 @end group
15867
15868 @group
15869 (if numbers-list
15870 (progn
15871 (setq from-position (point))
15872 (insert-rectangle
15873 (column-of-graph height (car numbers-list)))
15874 @end group
15875 @group
15876 (goto-char from-position)
15877 (forward-char symbol-width)
15878 (sit-for 0) ; @r{Draw graph column by column.}
15879 (recursive-graph-body-print-internal
15880 (cdr numbers-list) height symbol-width))))
15881 @end group
15882 @end smallexample
15883
15884 @need 1250
15885 After installation, this expression can be tested; here is a sample:
15886
15887 @smallexample
15888 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15889 @end smallexample
15890
15891 @need 800
15892 Here is what @code{recursive-graph-body-print} produces:
15893
15894 @smallexample
15895 @group
15896 *
15897 ** *
15898 **** *
15899 **** ***
15900 * *********
15901 ************
15902 *************
15903 @end group
15904 @end smallexample
15905
15906 Either of these two functions, @code{graph-body-print} or
15907 @code{recursive-graph-body-print}, create the body of a graph.
15908
15909 @node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15910 @section Need for Printed Axes
15911
15912 A graph needs printed axes, so you can orient yourself. For a do-once
15913 project, it may be reasonable to draw the axes by hand using Emacs'
15914 Picture mode; but a graph drawing function may be used more than once.
15915
15916 For this reason, I have written enhancements to the basic
15917 @code{print-graph-body} function that automatically print labels for
15918 the horizontal and vertical axes. Since the label printing functions
15919 do not contain much new material, I have placed their description in
15920 an appendix. @xref{Full Graph, , A Graph with Labelled Axes}.
15921
15922 @node Line Graph Exercise, , Printed Axes, Readying a Graph
15923 @section Exercise
15924
15925 Write a line graph version of the graph printing functions.
15926
15927 @node Emacs Initialization, Debugging, Readying a Graph, Top
15928 @chapter Your @file{.emacs} File
15929 @cindex @file{.emacs} file
15930 @cindex Customizing your @file{.emacs} file
15931 @cindex Initialization file
15932
15933 ``You don't have to like Emacs to like it'' -- this seemingly
15934 paradoxical statement is the secret of GNU Emacs. The plain, `out of
15935 the box' Emacs is a generic tool. Most people who use it, customize
15936 it to suit themselves.
15937
15938 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15939 expressions in Emacs Lisp you can change or extend Emacs.
15940
15941 @menu
15942 * Default Configuration::
15943 * Site-wide Init:: You can write site-wide init files.
15944 * defcustom:: Emacs will write code for you.
15945 * Beginning a .emacs File:: How to write a @code{.emacs file}.
15946 * Text and Auto-fill:: Automatically wrap lines.
15947 * Mail Aliases:: Use abbreviations for email addresses.
15948 * Indent Tabs Mode:: Don't use tabs with @TeX{}
15949 * Keybindings:: Create some personal keybindings.
15950 * Keymaps:: More about key binding.
15951 * Loading Files:: Load (i.e., evaluate) files automatically.
15952 * Autoload:: Make functions available.
15953 * Simple Extension:: Define a function; bind it to a key.
15954 * X11 Colors:: Colors in version 19 in X.
15955 * Miscellaneous::
15956 * Mode Line:: How to customize your mode line.
15957 @end menu
15958
15959 @node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15960 @ifnottex
15961 @unnumberedsec Emacs' Default Configuration
15962 @end ifnottex
15963
15964 There are those who appreciate Emacs' default configuration. After
15965 all, Emacs starts you in C mode when you edit a C file, starts you in
15966 Fortran mode when you edit a Fortran file, and starts you in
15967 Fundamental mode when you edit an unadorned file. This all makes
15968 sense, if you do not know who is going to use Emacs. Who knows what a
15969 person hopes to do with an unadorned file? Fundamental mode is the
15970 right default for such a file, just as C mode is the right default for
15971 editing C code. But when you do know who is going to use Emacs---you,
15972 yourself---then it makes sense to customize Emacs.
15973
15974 For example, I seldom want Fundamental mode when I edit an
15975 otherwise undistinguished file; I want Text mode. This is why I
15976 customize Emacs: so it suits me.
15977
15978 You can customize and extend Emacs by writing or adapting a
15979 @file{~/.emacs} file. This is your personal initialization file; its
15980 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
15981 may also add @file{.el} to @file{~/.emacs} and call it a
15982 @file{~/.emacs.el} file. In the past, you were forbidden to type the
15983 extra keystrokes that the name @file{~/.emacs.el} requires, but now
15984 you may. The new format is consistent with the Emacs Lisp file
15985 naming conventions; the old format saves typing.}
15986
15987 A @file{~/.emacs} file contains Emacs Lisp code. You can write this
15988 code yourself; or you can use Emacs' @code{customize} feature to write
15989 the code for you. You can combine your own expressions and
15990 auto-written Customize expressions in your @file{.emacs} file.
15991
15992 (I myself prefer to write my own expressions, except for those,
15993 particularly fonts, that I find easier to manipulate using the
15994 @code{customize} command. I combine the two methods.)
15995
15996 Most of this chapter is about writing expressions yourself. It
15997 describes a simple @file{.emacs} file; for more information, see
15998 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
15999 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16000 Manual}.
16001
16002 @node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16003 @section Site-wide Initialization Files
16004
16005 @cindex @file{default.el} init file
16006 @cindex @file{site-init.el} init file
16007 @cindex @file{site-load.el} init file
16008 In addition to your personal initialization file, Emacs automatically
16009 loads various site-wide initialization files, if they exist. These
16010 have the same form as your @file{.emacs} file, but are loaded by
16011 everyone.
16012
16013 Two site-wide initialization files, @file{site-load.el} and
16014 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16015 `dumped' version of Emacs is created, as is most common. (Dumped
16016 copies of Emacs load more quickly. However, once a file is loaded and
16017 dumped, a change to it does not lead to a change in Emacs unless you
16018 load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16019 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16020 @file{INSTALL} file.)
16021
16022 Three other site-wide initialization files are loaded automatically
16023 each time you start Emacs, if they exist. These are
16024 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16025 file, and @file{default.el}, and the terminal type file, which are both
16026 loaded @emph{after} your @file{.emacs} file.
16027
16028 Settings and definitions in your @file{.emacs} file will overwrite
16029 conflicting settings and definitions in a @file{site-start.el} file,
16030 if it exists; but the settings and definitions in a @file{default.el}
16031 or terminal type file will overwrite those in your @file{.emacs} file.
16032 (You can prevent interference from a terminal type file by setting
16033 @code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16034 Simple Extension}.)
16035
16036 @c Rewritten to avoid overfull hbox.
16037 The @file{INSTALL} file that comes in the distribution contains
16038 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16039
16040 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16041 control loading. These files are in the @file{lisp} directory of the
16042 Emacs distribution and are worth perusing.
16043
16044 The @file{loaddefs.el} file contains a good many suggestions as to
16045 what to put into your own @file{.emacs} file, or into a site-wide
16046 initialization file.
16047
16048 @node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16049 @section Specifying Variables using @code{defcustom}
16050 @findex defcustom
16051
16052 You can specify variables using @code{defcustom} so that you and
16053 others can then can use Emacs' @code{customize} feature to set their
16054 values. (You cannot use @code{customize} to write function
16055 definitions; but you can write @code{defuns} in your @file{.emacs}
16056 file. Indeed, you can write any Lisp expression in your @file{.emacs}
16057 file.)
16058
16059 The @code{customize} feature depends on the @code{defcustom} special
16060 form. Although you can use @code{defvar} or @code{setq} for variables
16061 that users set, the @code{defcustom} special form is designed for the
16062 job.
16063
16064 You can use your knowledge of @code{defvar} for writing the
16065 first three arguments for @code{defcustom}. The first argument to
16066 @code{defcustom} is the name of the variable. The second argument is
16067 the variable's initial value, if any; and this value is set only if
16068 the value has not already been set. The third argument is the
16069 documentation.
16070
16071 The fourth and subsequent arguments to @code{defcustom} specify types
16072 and options; these are not featured in @code{defvar}. (These
16073 arguments are optional.)
16074
16075 Each of these arguments consists of a keyword followed by a value.
16076 Each keyword starts with the character @code{:}.
16077
16078 @need 1250
16079 For example, the customizable user option variable
16080 @code{text-mode-hook} looks like this:
16081
16082 @smallexample
16083 @group
16084 (defcustom text-mode-hook nil
16085 "Normal hook run when entering Text mode and many related modes."
16086 :type 'hook
16087 :options '(turn-on-auto-fill flyspell-mode)
16088 :group 'data)
16089 @end group
16090 @end smallexample
16091
16092 @noindent
16093 The name of the variable is @code{text-mode-hook}; it has no default
16094 value; and its documentation string tells you what it does.
16095
16096 The @code{:type} keyword tells Emacs what kind of data
16097 @code{text-mode-hook} should be set to and how to display the value in
16098 a Customization buffer.
16099
16100 The @code{:options} keyword specifies a suggested list of values for
16101 the variable. Currently, you can use @code{:options} only for a hook.
16102 The list is only a suggestion; it is not exclusive; a person who sets
16103 the variable may set it to other values; the list shown following the
16104 @code{:options} keyword is intended to offer convenient choices to a
16105 user.
16106
16107 Finally, the @code{:group} keyword tells the Emacs Customization
16108 command in which group the variable is located. This tells where to
16109 find it.
16110
16111 For more information, see @ref{Customization, , Writing Customization
16112 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16113
16114 Consider @code{text-mode-hook} as an example.
16115
16116 There are two ways to customize this variable. You can use the
16117 customization command or write the appropriate expressions yourself.
16118
16119 @need 800
16120 Using the customization command, you can type:
16121
16122 @smallexample
16123 M-x customize
16124 @end smallexample
16125
16126 @noindent
16127 and find that the group for editing files of data is called `data'.
16128 Enter that group. Text Mode Hook is the first member. You can click
16129 on its various options to set the values. After you click on the
16130 button to
16131
16132 @smallexample
16133 Save for Future Sessions
16134 @end smallexample
16135
16136 @noindent
16137 Emacs will write an expression into your @file{.emacs} file.
16138 It will look like this:
16139
16140 @smallexample
16141 @group
16142 (custom-set-variables
16143 ;; custom-set-variables was added by Custom --
16144 ;; don't edit or cut/paste it!
16145 ;; Your init file should contain only one such instance.
16146 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16147 @end group
16148 @end smallexample
16149
16150 @noindent
16151 (The @code{text-mode-hook-identify} function tells
16152 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16153
16154 In spite of the warning, you certainly may edit, cut, and paste the
16155 expression! I do all time. The purpose of the warning is to scare
16156 those who do not know what they are doing, so they do not
16157 inadvertently generate an error.
16158
16159 The @code{custom-set-variables} works somewhat differently than a
16160 @code{setq}. While I have never learned the differences, I do modify
16161 the @code{custom-set-variables} expressions in my @file{.emacs} file
16162 by hand: I make the changes in what appears to me to be a reasonable
16163 manner and have not had any problems. Others prefer to use the
16164 Customization command and let Emacs do the work for them.
16165
16166 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16167 This function sets the various font faces. Over time, I have set a
16168 considerable number of faces. Some of the time, I re-set them using
16169 @code{customize}; other times, I simply edit the
16170 @code{custom-set-faces} expression in my @file{.emacs} file itself.
16171
16172 The second way to customize your @code{text-mode-hook} is to set it
16173 yourself in your @file{.emacs} file using code that has nothing to do
16174 with the @code{custom-set-@dots{}} functions.
16175
16176 @need 800
16177 When you do this, and later use @code{customize}, you will see a
16178 message that says
16179
16180 @smallexample
16181 this option has been changed outside the customize buffer.
16182 @end smallexample
16183
16184 @need 800
16185 This message is only a warning. If you click on the button to
16186
16187 @smallexample
16188 Save for Future Sessions
16189 @end smallexample
16190
16191 @noindent
16192 Emacs will write a @code{custom-set-@dots{}} expression near the end
16193 of your @file{.emacs} file that will be evaluated after your
16194 hand-written expression. It will, therefore, overrule your
16195 hand-written expression. No harm will be done. When you do this,
16196 however, be careful to remember which expression is active; if you
16197 forget, you may confuse yourself.
16198
16199 So long as you remember where the values are set, you will have no
16200 trouble. In any event, the values are always set in your
16201 initialization file, which is usually called @file{.emacs}.
16202
16203 I myself use @code{customize} for hardly anything. Mostly, I write
16204 expressions myself.
16205
16206 @node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16207 @section Beginning a @file{.emacs} File
16208 @cindex @file{.emacs} file, beginning of
16209
16210 When you start Emacs, it loads your @file{.emacs} file unless you tell
16211 it not to by specifying @samp{-q} on the command line. (The
16212 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16213
16214 A @file{.emacs} file contains Lisp expressions. Often, these are no
16215 more than expressions to set values; sometimes they are function
16216 definitions.
16217
16218 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16219 Manual}, for a short description of initialization files.
16220
16221 This chapter goes over some of the same ground, but is a walk among
16222 extracts from a complete, long-used @file{.emacs} file---my own.
16223
16224 The first part of the file consists of comments: reminders to myself.
16225 By now, of course, I remember these things, but when I started, I did
16226 not.
16227
16228 @smallexample
16229 @group
16230 ;;;; Bob's .emacs file
16231 ; Robert J. Chassell
16232 ; 26 September 1985
16233 @end group
16234 @end smallexample
16235
16236 @noindent
16237 Look at that date! I started this file a long time ago. I have been
16238 adding to it ever since.
16239
16240 @smallexample
16241 @group
16242 ; Each section in this file is introduced by a
16243 ; line beginning with four semicolons; and each
16244 ; entry is introduced by a line beginning with
16245 ; three semicolons.
16246 @end group
16247 @end smallexample
16248
16249 @noindent
16250 This describes the usual conventions for comments in Emacs Lisp.
16251 Everything on a line that follows a semicolon is a comment. Two,
16252 three, and four semicolons are used as section and subsection
16253 markers. (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16254 Manual}, for more about comments.)
16255
16256 @smallexample
16257 @group
16258 ;;;; The Help Key
16259 ; Control-h is the help key;
16260 ; after typing control-h, type a letter to
16261 ; indicate the subject about which you want help.
16262 ; For an explanation of the help facility,
16263 ; type control-h two times in a row.
16264 @end group
16265 @end smallexample
16266
16267 @noindent
16268 Just remember: type @kbd{C-h} two times for help.
16269
16270 @smallexample
16271 @group
16272 ; To find out about any mode, type control-h m
16273 ; while in that mode. For example, to find out
16274 ; about mail mode, enter mail mode and then type
16275 ; control-h m.
16276 @end group
16277 @end smallexample
16278
16279 @noindent
16280 `Mode help', as I call this, is very helpful. Usually, it tells you
16281 all you need to know.
16282
16283 Of course, you don't need to include comments like these in your
16284 @file{.emacs} file. I included them in mine because I kept forgetting
16285 about Mode help or the conventions for comments---but I was able to
16286 remember to look here to remind myself.
16287
16288 @node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16289 @section Text and Auto Fill Mode
16290
16291 Now we come to the part that `turns on' Text mode and
16292 Auto Fill mode.
16293
16294 @smallexample
16295 @group
16296 ;;; Text mode and Auto Fill mode
16297 ; The next three lines put Emacs into Text mode
16298 ; and Auto Fill mode, and are for writers who
16299 ; want to start writing prose rather than code.
16300
16301 (setq default-major-mode 'text-mode)
16302 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16303 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16304 @end group
16305 @end smallexample
16306
16307 Here is the first part of this @file{.emacs} file that does something
16308 besides remind a forgetful human!
16309
16310 The first of the two lines in parentheses tells Emacs to turn on Text
16311 mode when you find a file, @emph{unless} that file should go into some
16312 other mode, such as C mode.
16313
16314 @cindex Per-buffer, local variables list
16315 @cindex Local variables list, per-buffer,
16316 @cindex Automatic mode selection
16317 @cindex Mode selection, automatic
16318 When Emacs reads a file, it looks at the extension to the file name,
16319 if any. (The extension is the part that comes after a @samp{.}.) If
16320 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16321 on C mode. Also, Emacs looks at first nonblank line of the file; if
16322 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
16323 possesses a list of extensions and specifications that it uses
16324 automatically. In addition, Emacs looks near the last page for a
16325 per-buffer, ``local variables list'', if any.
16326
16327 @ifinfo
16328 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16329 Emacs Manual}.
16330
16331 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16332 Manual}.
16333 @end ifinfo
16334 @iftex
16335 See sections ``How Major Modes are Chosen'' and ``Local Variables in
16336 Files'' in @cite{The GNU Emacs Manual}.
16337 @end iftex
16338
16339 Now, back to the @file{.emacs} file.
16340
16341 @need 800
16342 Here is the line again; how does it work?
16343
16344 @cindex Text Mode turned on
16345 @smallexample
16346 (setq default-major-mode 'text-mode)
16347 @end smallexample
16348
16349 @noindent
16350 This line is a short, but complete Emacs Lisp expression.
16351
16352 We are already familiar with @code{setq}. It sets the following variable,
16353 @code{default-major-mode}, to the subsequent value, which is
16354 @code{text-mode}. The single quote mark before @code{text-mode} tells
16355 Emacs to deal directly with the @code{text-mode} variable, not with
16356 whatever it might stand for. @xref{set & setq, , Setting the Value of
16357 a Variable}, for a reminder of how @code{setq} works. The main point
16358 is that there is no difference between the procedure you use to set
16359 a value in your @file{.emacs} file and the procedure you use anywhere
16360 else in Emacs.
16361
16362 @need 800
16363 Here are the next two lines:
16364
16365 @cindex Auto Fill mode turned on
16366 @findex add-hook
16367 @smallexample
16368 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16369 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16370 @end smallexample
16371
16372 @noindent
16373 In these two lines, the @code{add-hook} command first adds
16374 @code{text-mode-hook-identify} to the variable called
16375 @code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16376 variable.
16377
16378 @code{turn-on-auto-fill} is the name of a program, that, you guessed
16379 it!, turns on Auto Fill mode. @code{text-mode-hook-identify} is a
16380 function that tells @code{toggle-text-mode-auto-fill} which buffers
16381 are in Text mode.
16382
16383 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16384 onto Text mode. So every time Emacs turns on Text mode, Emacs also
16385 turns on Auto Fill mode.
16386
16387 In brief, the first line causes Emacs to enter Text mode when you edit
16388 a file, unless the file name extension, first non-blank line, or local
16389 variables tell Emacs otherwise.
16390
16391 Text mode among other actions, sets the syntax table to work
16392 conveniently for writers. In Text mode, Emacs considers an apostrophe
16393 as part of a word like a letter; but Emacs does not consider a period
16394 or a space as part of a word. Thus, @kbd{M-f} moves you over
16395 @samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
16396 the @samp{t} of @samp{it's}.
16397
16398 The second and third lines causes Emacs to turn on Auto Fill mode when
16399 it turns on Text mode. In Auto Fill mode, Emacs automatically breaks
16400 a line that is too wide and brings the excessively wide part of the
16401 line down to the next line. Emacs breaks lines between words, not
16402 within them.
16403
16404 When Auto Fill mode is turned off, lines continue to the right as you
16405 type them. Depending on how you set the value of
16406 @code{truncate-lines}, the words you type either disappear off the
16407 right side of the screen, or else are shown, in a rather ugly and
16408 unreadable manner, as a continuation line on the screen.
16409
16410 @need 1250
16411 In addition, in this part of my @file{.emacs} file, I tell the Emacs
16412 fill commands to insert two spaces after a colon:
16413
16414 @smallexample
16415 (setq colon-double-space t)
16416 @end smallexample
16417
16418 @node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16419 @section Mail Aliases
16420
16421 Here is a @code{setq} that `turns on' mail aliases, along with more
16422 reminders.
16423
16424 @smallexample
16425 @group
16426 ;;; Mail mode
16427 ; To enter mail mode, type `C-x m'
16428 ; To enter RMAIL (for reading mail),
16429 ; type `M-x rmail'
16430
16431 (setq mail-aliases t)
16432 @end group
16433 @end smallexample
16434
16435 @cindex Mail aliases
16436 @noindent
16437 This @code{setq} command sets the value of the variable
16438 @code{mail-aliases} to @code{t}. Since @code{t} means true, the line
16439 says, in effect, ``Yes, use mail aliases.''
16440
16441 Mail aliases are convenient short names for long email addresses or
16442 for lists of email addresses. The file where you keep your `aliases'
16443 is @file{~/.mailrc}. You write an alias like this:
16444
16445 @smallexample
16446 alias geo george@@foobar.wiz.edu
16447 @end smallexample
16448
16449 @noindent
16450 When you write a message to George, address it to @samp{geo}; the
16451 mailer will automatically expand @samp{geo} to the full address.
16452
16453 @node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16454 @section Indent Tabs Mode
16455 @cindex Tabs, preventing
16456 @findex indent-tabs-mode
16457
16458 By default, Emacs inserts tabs in place of multiple spaces when it
16459 formats a region. (For example, you might indent many lines of text
16460 all at once with the @code{indent-region} command.) Tabs look fine on
16461 a terminal or with ordinary printing, but they produce badly indented
16462 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16463
16464 @need 1250
16465 The following turns off Indent Tabs mode:
16466
16467 @smallexample
16468 @group
16469 ;;; Prevent Extraneous Tabs
16470 (setq-default indent-tabs-mode nil)
16471 @end group
16472 @end smallexample
16473
16474 Note that this line uses @code{setq-default} rather than the
16475 @code{setq} command that we have seen before. The @code{setq-default}
16476 command sets values only in buffers that do not have their own local
16477 values for the variable.
16478
16479 @ifinfo
16480 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16481
16482 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16483 Manual}.
16484 @end ifinfo
16485 @iftex
16486 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16487 Files'' in @cite{The GNU Emacs Manual}.
16488 @end iftex
16489
16490 @node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16491 @section Some Keybindings
16492
16493 Now for some personal keybindings:
16494
16495 @smallexample
16496 @group
16497 ;;; Compare windows
16498 (global-set-key "\C-cw" 'compare-windows)
16499 @end group
16500 @end smallexample
16501
16502 @findex compare-windows
16503 @code{compare-windows} is a nifty command that compares the text in
16504 your current window with text in the next window. It makes the
16505 comparison by starting at point in each window, moving over text in
16506 each window as far as they match. I use this command all the time.
16507
16508 This also shows how to set a key globally, for all modes.
16509
16510 @cindex Setting a key globally
16511 @cindex Global set key
16512 @cindex Key setting globally
16513 @findex global-set-key
16514 The command is @code{global-set-key}. It is followed by the
16515 keybinding. In a @file{.emacs} file, the keybinding is written as
16516 shown: @code{\C-c} stands for `control-c', which means `press the
16517 control key and the @kbd{c} key at the same time'. The @code{w} means
16518 `press the @kbd{w} key'. The keybinding is surrounded by double
16519 quotation marks. In documentation, you would write this as @kbd{C-c
16520 w}. (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16521 than a @key{CTL} key, you would write @code{\M-c}. @xref{Init
16522 Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16523 Manual}, for details.)
16524
16525 The command invoked by the keys is @code{compare-windows}. Note that
16526 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
16527 would first try to evaluate the symbol to determine its value.
16528
16529 These three things, the double quotation marks, the backslash before
16530 the @samp{C}, and the single quote mark are necessary parts of
16531 keybinding that I tend to forget. Fortunately, I have come to
16532 remember that I should look at my existing @file{.emacs} file, and
16533 adapt what is there.
16534
16535 As for the keybinding itself: @kbd{C-c w}. This combines the prefix
16536 key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
16537 set of keys, @kbd{C-c} followed by a single character, is strictly
16538 reserved for individuals' own use. (I call these `own' keys, since
16539 these are for my own use.) You should always be able to create such a
16540 keybinding for your own use without stomping on someone else's
16541 keybinding. If you ever write an extension to Emacs, please avoid
16542 taking any of these keys for public use. Create a key like @kbd{C-c
16543 C-w} instead. Otherwise, we will run out of `own' keys.
16544
16545 @need 1250
16546 Here is another keybinding, with a comment:
16547
16548 @smallexample
16549 @group
16550 ;;; Keybinding for `occur'
16551 ; I use occur a lot, so let's bind it to a key:
16552 (global-set-key "\C-co" 'occur)
16553 @end group
16554 @end smallexample
16555
16556 @findex occur
16557 The @code{occur} command shows all the lines in the current buffer
16558 that contain a match for a regular expression. Matching lines are
16559 shown in a buffer called @file{*Occur*}. That buffer serves as a menu
16560 to jump to occurrences.
16561
16562 @findex global-unset-key
16563 @cindex Unbinding key
16564 @cindex Key unbinding
16565 @need 1250
16566 Here is how to unbind a key, so it does not
16567 work:
16568
16569 @smallexample
16570 @group
16571 ;;; Unbind `C-x f'
16572 (global-unset-key "\C-xf")
16573 @end group
16574 @end smallexample
16575
16576 There is a reason for this unbinding: I found I inadvertently typed
16577 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
16578 file, as I intended, I accidentally set the width for filled text,
16579 almost always to a width I did not want. Since I hardly ever reset my
16580 default width, I simply unbound the key.
16581
16582 @findex list-buffers, @r{rebound}
16583 @findex buffer-menu, @r{bound to key}
16584 @need 1250
16585 The following rebinds an existing key:
16586
16587 @smallexample
16588 @group
16589 ;;; Rebind `C-x C-b' for `buffer-menu'
16590 (global-set-key "\C-x\C-b" 'buffer-menu)
16591 @end group
16592 @end smallexample
16593
16594 By default, @kbd{C-x C-b} runs the
16595 @code{list-buffers} command. This command lists
16596 your buffers in @emph{another} window. Since I
16597 almost always want to do something in that
16598 window, I prefer the @code{buffer-menu}
16599 command, which not only lists the buffers,
16600 but moves point into that window.
16601
16602 @node Keymaps, Loading Files, Keybindings, Emacs Initialization
16603 @section Keymaps
16604 @cindex Keymaps
16605 @cindex Rebinding keys
16606
16607 Emacs uses @dfn{keymaps} to record which keys call which commands.
16608 When you use @code{global-set-key} to set the keybinding for a single
16609 command in all parts of Emacs, you are specifying the keybinding in
16610 @code{current-global-map}.
16611
16612 Specific modes, such as C mode or Text mode, have their own keymaps;
16613 the mode-specific keymaps override the global map that is shared by
16614 all buffers.
16615
16616 The @code{global-set-key} function binds, or rebinds, the global
16617 keymap. For example, the following binds the key @kbd{C-x C-b} to the
16618 function @code{buffer-menu}:
16619
16620 @smallexample
16621 (global-set-key "\C-x\C-b" 'buffer-menu)
16622 @end smallexample
16623
16624 Mode-specific keymaps are bound using the @code{define-key} function,
16625 which takes a specific keymap as an argument, as well as the key and
16626 the command. For example, my @file{.emacs} file contains the
16627 following expression to bind the @code{texinfo-insert-@@group} command
16628 to @kbd{C-c C-c g}:
16629
16630 @smallexample
16631 @group
16632 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16633 @end group
16634 @end smallexample
16635
16636 @noindent
16637 The @code{texinfo-insert-@@group} function itself is a little extension
16638 to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
16639 use this command all the time and prefer to type the three strokes
16640 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16641 (@samp{@@group} and its matching @samp{@@end group} are commands that
16642 keep all enclosed text together on one page; many multi-line examples
16643 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16644
16645 @need 1250
16646 Here is the @code{texinfo-insert-@@group} function definition:
16647
16648 @smallexample
16649 @group
16650 (defun texinfo-insert-@@group ()
16651 "Insert the string @@group in a Texinfo buffer."
16652 (interactive)
16653 (beginning-of-line)
16654 (insert "@@group\n"))
16655 @end group
16656 @end smallexample
16657
16658 (Of course, I could have used Abbrev mode to save typing, rather than
16659 write a function to insert a word; but I prefer key strokes consistent
16660 with other Texinfo mode key bindings.)
16661
16662 You will see numerous @code{define-key} expressions in
16663 @file{loaddefs.el} as well as in the various mode libraries, such as
16664 @file{cc-mode.el} and @file{lisp-mode.el}.
16665
16666 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16667 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16668 Reference Manual}, for more information about keymaps.
16669
16670 @node Loading Files, Autoload, Keymaps, Emacs Initialization
16671 @section Loading Files
16672 @cindex Loading files
16673 @c findex load
16674
16675 Many people in the GNU Emacs community have written extensions to
16676 Emacs. As time goes by, these extensions are often included in new
16677 releases. For example, the Calendar and Diary packages are now part
16678 of the standard GNU Emacs.
16679
16680 (Calc, which I consider a vital part of Emacs, would be part of the
16681 standard distribution except that it was so large it was packaged
16682 separately and no one has changed that.)
16683
16684 You can use a @code{load} command to evaluate a complete file and
16685 thereby install all the functions and variables in the file into Emacs.
16686 For example:
16687
16688 @c (auto-compression-mode t)
16689
16690 @smallexample
16691 (load "~/emacs/slowsplit")
16692 @end smallexample
16693
16694 This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16695 exists, the faster, byte compiled @file{slowsplit.elc} file from the
16696 @file{emacs} sub-directory of your home directory. The file contains
16697 the function @code{split-window-quietly}, which John Robinson wrote in
16698 1989.
16699
16700 The @code{split-window-quietly} function splits a window with the
16701 minimum of redisplay. I installed it in 1989 because it worked well
16702 with the slow 1200 baud terminals I was then using. Nowadays, I only
16703 occasionally come across such a slow connection, but I continue to use
16704 the function because I like the way it leaves the bottom half of a
16705 buffer in the lower of the new windows and the top half in the upper
16706 window.
16707
16708 @need 1250
16709 To replace the key binding for the default
16710 @code{split-window-vertically}, you must also unset that key and bind
16711 the keys to @code{split-window-quietly}, like this:
16712
16713 @smallexample
16714 @group
16715 (global-unset-key "\C-x2")
16716 (global-set-key "\C-x2" 'split-window-quietly)
16717 @end group
16718 @end smallexample
16719
16720 @vindex load-path
16721 If you load many extensions, as I do, then instead of specifying the
16722 exact location of the extension file, as shown above, you can specify
16723 that directory as part of Emacs' @code{load-path}. Then, when Emacs
16724 loads a file, it will search that directory as well as its default
16725 list of directories. (The default list is specified in @file{paths.h}
16726 when Emacs is built.)
16727
16728 @need 1250
16729 The following command adds your @file{~/emacs} directory to the
16730 existing load path:
16731
16732 @smallexample
16733 @group
16734 ;;; Emacs Load Path
16735 (setq load-path (cons "~/emacs" load-path))
16736 @end group
16737 @end smallexample
16738
16739 Incidentally, @code{load-library} is an interactive interface to the
16740 @code{load} function. The complete function looks like this:
16741
16742 @findex load-library
16743 @smallexample
16744 @group
16745 (defun load-library (library)
16746 "Load the library named LIBRARY.
16747 This is an interface to the function `load'."
16748 (interactive "sLoad library: ")
16749 (load library))
16750 @end group
16751 @end smallexample
16752
16753 The name of the function, @code{load-library}, comes from the use of
16754 `library' as a conventional synonym for `file'. The source for the
16755 @code{load-library} command is in the @file{files.el} library.
16756
16757 Another interactive command that does a slightly different job is
16758 @code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
16759 Emacs, emacs, The GNU Emacs Manual}, for information on the
16760 distinction between @code{load-library} and this command.
16761
16762 @node Autoload, Simple Extension, Loading Files, Emacs Initialization
16763 @section Autoloading
16764 @findex autoload
16765
16766 Instead of installing a function by loading the file that contains it,
16767 or by evaluating the function definition, you can make the function
16768 available but not actually install it until it is first called. This
16769 is called @dfn{autoloading}.
16770
16771 When you execute an autoloaded function, Emacs automatically evaluates
16772 the file that contains the definition, and then calls the function.
16773
16774 Emacs starts quicker with autoloaded functions, since their libraries
16775 are not loaded right away; but you need to wait a moment when you
16776 first use such a function, while its containing file is evaluated.
16777
16778 Rarely used functions are frequently autoloaded. The
16779 @file{loaddefs.el} library contains hundreds of autoloaded functions,
16780 from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
16781 come to use a `rare' function frequently. When you do, you should
16782 load that function's file with a @code{load} expression in your
16783 @file{.emacs} file.
16784
16785 In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16786 that contain functions that would otherwise be autoloaded. (Actually,
16787 it would have been better to include these files in my `dumped' Emacs
16788 when I built it, but I forgot. @xref{Building Emacs, , Building
16789 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16790 file for more about dumping.)
16791
16792 You may also want to include autoloaded expressions in your @file{.emacs}
16793 file. @code{autoload} is a built-in function that takes up to five
16794 arguments, the final three of which are optional. The first argument
16795 is the name of the function to be autoloaded; the second is the name
16796 of the file to be loaded. The third argument is documentation for the
16797 function, and the fourth tells whether the function can be called
16798 interactively. The fifth argument tells what type of
16799 object---@code{autoload} can handle a keymap or macro as well as a
16800 function (the default is a function).
16801
16802 @need 800
16803 Here is a typical example:
16804
16805 @smallexample
16806 @group
16807 (autoload 'html-helper-mode
16808 "html-helper-mode" "Edit HTML documents" t)
16809 @end group
16810 @end smallexample
16811
16812 @noindent
16813 (@code{html-helper-mode} is an alternative to @code{html-mode}, which
16814 is a standard part of the distribution).
16815
16816 @noindent
16817 This expression autoloads the @code{html-helper-mode} function. It
16818 takes it from the @file{html-helper-mode.el} file (or from the byte
16819 compiled file @file{html-helper-mode.elc}, if it exists.) The file
16820 must be located in a directory specified by @code{load-path}. The
16821 documentation says that this is a mode to help you edit documents
16822 written in the HyperText Markup Language. You can call this mode
16823 interactively by typing @kbd{M-x html-helper-mode}. (You need to
16824 duplicate the function's regular documentation in the autoload
16825 expression because the regular function is not yet loaded, so its
16826 documentation is not available.)
16827
16828 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16829 Manual}, for more information.
16830
16831 @node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16832 @section A Simple Extension: @code{line-to-top-of-window}
16833 @findex line-to-top-of-window
16834 @cindex Simple extension in @file{.emacs} file
16835
16836 Here is a simple extension to Emacs that moves the line point is on to
16837 the top of the window. I use this all the time, to make text easier
16838 to read.
16839
16840 You can put the following code into a separate file and then load it
16841 from your @file{.emacs} file, or you can include it within your
16842 @file{.emacs} file.
16843
16844 @need 1250
16845 Here is the definition:
16846
16847 @smallexample
16848 @group
16849 ;;; Line to top of window;
16850 ;;; replace three keystroke sequence C-u 0 C-l
16851 (defun line-to-top-of-window ()
16852 "Move the line point is on to top of window."
16853 (interactive)
16854 (recenter 0))
16855 @end group
16856 @end smallexample
16857
16858 @need 1250
16859 Now for the keybinding.
16860
16861 Nowadays, function keys as well as mouse button events and
16862 non-@sc{ascii} characters are written within square brackets, without
16863 quotation marks. (In Emacs version 18 and before, you had to write
16864 different function key bindings for each different make of terminal.)
16865
16866 I bind @code{line-to-top-of-window} to my @key{F6} function key like
16867 this:
16868
16869 @smallexample
16870 (global-set-key [f6] 'line-to-top-of-window)
16871 @end smallexample
16872
16873 For more information, see @ref{Init Rebinding, , Rebinding Keys in
16874 Your Init File, emacs, The GNU Emacs Manual}.
16875
16876 @cindex Conditional 'twixt two versions of Emacs
16877 @cindex Version of Emacs, choosing
16878 @cindex Emacs version, choosing
16879 If you run two versions of GNU Emacs, such as versions 20 and 21, and
16880 use one @file{.emacs} file, you can select which code to evaluate with
16881 the following conditional:
16882
16883 @smallexample
16884 @group
16885 (cond
16886 ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16887 ;; evaluate version 20 code
16888 ( @dots{} ))
16889 ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16890 ;; evaluate version 21 code
16891 ( @dots{} )))
16892 @end group
16893 @end smallexample
16894
16895 For example, in contrast to version 20, version 21 blinks its cursor
16896 by default. I hate such blinking, as well as some other features in
16897 version 21, so I placed the following in my @file{.emacs}
16898 file@footnote{When I start instances of Emacs that do not load my
16899 @file{.emacs} file or any site file, I also turn off blinking:
16900
16901 @smallexample
16902 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16903 @end smallexample
16904 }:
16905
16906 @smallexample
16907 @group
16908 (if (string-equal "21" (substring (emacs-version) 10 12))
16909 (progn
16910 (blink-cursor-mode 0)
16911 ;; Insert newline when you press `C-n' (next-line)
16912 ;; at the end of the buffer
16913 (setq next-line-add-newlines t)
16914 @end group
16915 @group
16916 ;; Turn on image viewing
16917 (auto-image-file-mode t)
16918 @end group
16919 @group
16920 ;; Turn on menu bar (this bar has text)
16921 ;; (Use numeric argument to turn on)
16922 (menu-bar-mode 1)
16923 @end group
16924 @group
16925 ;; Turn off tool bar (this bar has icons)
16926 ;; (Use numeric argument to turn on)
16927 (tool-bar-mode nil)
16928 @end group
16929 @group
16930 ;; Turn off tooltip mode for tool bar
16931 ;; (This mode causes icon explanations to pop up)
16932 ;; (Use numeric argument to turn on)
16933 (tooltip-mode nil)
16934 ;; If tooltips turned on, make tips appear promptly
16935 (setq tooltip-delay 0.1) ; default is one second
16936 ))
16937 @end group
16938 @end smallexample
16939
16940 @noindent
16941 (You will note that instead of typing @code{(number-to-string 21)}, I
16942 decided to save typing and wrote `21' as a string, @code{"21"}, rather
16943 than convert it from an integer to a string. In this instance, this
16944 expression is better than the longer, but more general
16945 @code{(number-to-string 21)}. However, if you do not know ahead of
16946 time what type of information will be returned, then the
16947 @code{number-to-string} function will be needed.)
16948
16949 @node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16950 @section X11 Colors
16951
16952 You can specify colors when you use Emacs with the MIT X Windowing
16953 system.
16954
16955 I dislike the default colors and specify my own.
16956
16957 @need 1250
16958 Here are the expressions in my @file{.emacs}
16959 file that set values:
16960
16961 @smallexample
16962 @group
16963 ;; Set cursor color
16964 (set-cursor-color "white")
16965
16966 ;; Set mouse color
16967 (set-mouse-color "white")
16968
16969 ;; Set foreground and background
16970 (set-foreground-color "white")
16971 (set-background-color "darkblue")
16972 @end group
16973
16974 @group
16975 ;;; Set highlighting colors for isearch and drag
16976 (set-face-foreground 'highlight "white")
16977 (set-face-background 'highlight "blue")
16978 @end group
16979
16980 @group
16981 (set-face-foreground 'region "cyan")
16982 (set-face-background 'region "blue")
16983 @end group
16984
16985 @group
16986 (set-face-foreground 'secondary-selection "skyblue")
16987 (set-face-background 'secondary-selection "darkblue")
16988 @end group
16989
16990 @group
16991 ;; Set calendar highlighting colors
16992 (setq calendar-load-hook
16993 '(lambda ()
16994 (set-face-foreground 'diary-face "skyblue")
16995 (set-face-background 'holiday-face "slate blue")
16996 (set-face-foreground 'holiday-face "white")))
16997 @end group
16998 @end smallexample
16999
17000 The various shades of blue soothe my eye and prevent me from seeing
17001 the screen flicker.
17002
17003 Alternatively, I could have set my specifications in various X
17004 initialization files. For example, I could set the foreground,
17005 background, cursor, and pointer (i.e., mouse) colors in my
17006 @file{~/.Xresources} file like this:
17007
17008 @smallexample
17009 @group
17010 Emacs*foreground: white
17011 Emacs*background: darkblue
17012 Emacs*cursorColor: white
17013 Emacs*pointerColor: white
17014 @end group
17015 @end smallexample
17016
17017 In any event, since it is not part of Emacs, I set the root color of
17018 my X window in my @file{~/.xinitrc} file, like this@footnote{I
17019 occasionally run more modern window managers, such as Sawfish with
17020 GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17021 image rather than a plain color.}:
17022
17023 @smallexample
17024 @group
17025 # I use TWM for window manager.
17026 xsetroot -solid Navy -fg white &
17027 @end group
17028 @end smallexample
17029
17030 @node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17031 @section Miscellaneous Settings for a @file{.emacs} File
17032
17033 Here are a few miscellaneous settings:
17034 @sp 1
17035
17036 @itemize @minus
17037 @item
17038 Set the shape and color of the mouse cursor:
17039 @smallexample
17040 @group
17041 ; Cursor shapes are defined in
17042 ; `/usr/include/X11/cursorfont.h';
17043 ; for example, the `target' cursor is number 128;
17044 ; the `top_left_arrow' cursor is number 132.
17045 @end group
17046
17047 @group
17048 (let ((mpointer (x-get-resource "*mpointer"
17049 "*emacs*mpointer")))
17050 ;; If you have not set your mouse pointer
17051 ;; then set it, otherwise leave as is:
17052 (if (eq mpointer nil)
17053 (setq mpointer "132")) ; top_left_arrow
17054 @end group
17055 @group
17056 (setq x-pointer-shape (string-to-int mpointer))
17057 (set-mouse-color "white"))
17058 @end group
17059 @end smallexample
17060 @end itemize
17061
17062 @node Mode Line, , Miscellaneous, Emacs Initialization
17063 @section A Modified Mode Line
17064 @vindex default-mode-line-format
17065 @cindex Mode line format
17066
17067 Finally, a feature I really like: a modified mode line.
17068
17069 When I work over a network, I forget which machine I am using. Also,
17070 I tend to I lose track of where I am, and which line point is on.
17071
17072 So I reset my mode line to look like this:
17073
17074 @smallexample
17075 -:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
17076 @end smallexample
17077
17078 I am visiting a file called @file{foo.texi}, on my machine
17079 @file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
17080 Texinfo mode, and am at the top of the buffer.
17081
17082 @need 1200
17083 My @file{.emacs} file has a section that looks like this:
17084
17085 @smallexample
17086 @group
17087 ;; Set a Mode Line that tells me which machine, which directory,
17088 ;; and which line I am on, plus the other customary information.
17089 (setq default-mode-line-format
17090 (quote
17091 (#("-" 0 1
17092 (help-echo
17093 "mouse-1: select window, mouse-2: delete others ..."))
17094 mode-line-mule-info
17095 mode-line-modified
17096 mode-line-frame-identification
17097 " "
17098 @end group
17099 @group
17100 mode-line-buffer-identification
17101 " "
17102 (:eval (substring
17103 (system-name) 0 (string-match "\\..+" (system-name))))
17104 ":"
17105 default-directory
17106 #(" " 0 1
17107 (help-echo
17108 "mouse-1: select window, mouse-2: delete others ..."))
17109 (line-number-mode " Line %l ")
17110 global-mode-string
17111 @end group
17112 @group
17113 #(" %[(" 0 6
17114 (help-echo
17115 "mouse-1: select window, mouse-2: delete others ..."))
17116 (:eval (mode-line-mode-name))
17117 mode-line-process
17118 minor-mode-alist
17119 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17120 ")%] "
17121 (-3 . "%P")
17122 ;; "-%-"
17123 )))
17124 @end group
17125 @end smallexample
17126
17127 @noindent
17128 Here, I redefine the default mode line. Most of the parts are from
17129 the original; but I make a few changes. I set the @emph{default} mode
17130 line format so as to permit various modes, such as Info, to override
17131 it.
17132
17133 Many elements in the list are self-explanatory:
17134 @code{mode-line-modified} is a variable that tells whether the buffer
17135 has been modified, @code{mode-name} tells the name of the mode, and so
17136 on. However, the format looks complicated because of two features we
17137 have not discussed.
17138
17139 The first string in the mode line is a dash or hyphen, @samp{-}. In
17140 the old days, it would have been specified simply as @code{"-"}. But
17141 nowadays, Emacs can add properties to a string, such as highlighting
17142 or, as in this case, a help feature. If you place your mouse cursor
17143 over the hyphen, some help information appears (By default, you must
17144 wait one second before the information appears. You can change that
17145 timing by changing the value of @code{tooltip-delay}.)
17146
17147 @need 1000
17148 The new string format has a special syntax:
17149
17150 @smallexample
17151 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
17152 @end smallexample
17153
17154 @noindent
17155 The @code{#(} begins a list. The first element of the list is the
17156 string itself, just one @samp{-}. The second and third
17157 elements specify the range over which the fourth element applies. A
17158 range starts @emph{after} a character, so a zero means the range
17159 starts just before the first character; a 1 means that the range ends
17160 just after the first character. The third element is the property for
17161 the range. It consists of a property list, a
17162 property name, in this case, @samp{help-echo}, followed by a value, in this
17163 case, a string. The second, third, and fourth elements of this new
17164 string format can be repeated.
17165
17166 @xref{Text Props and Strings, , Text Properties in String, elisp, The
17167 GNU Emacs Lisp Reference Manual}, and see @ref{Mode Line Format, , Mode
17168 Line Format, elisp, The GNU Emacs Lisp Reference Manual}, for more
17169 information.
17170
17171 @code{mode-line-buffer-identification}
17172 displays the current buffer name. It is a list
17173 beginning @code{(#("%12b" 0 4 @dots{}}.
17174 The @code{#(} begins the list.
17175
17176 The @samp{"%12b"} displays the current buffer name, using the
17177 @code{buffer-name} function with which we are familiar; the `12'
17178 specifies the maximum number of characters that will be displayed.
17179 When a name has fewer characters, whitespace is added to fill out to
17180 this number. (Buffer names can and often should be longer than 12
17181 characters; this length works well in a typical 80 column wide
17182 window.)
17183
17184 @code{:eval} is a new feature in GNU Emacs version 21. It says to
17185 evaluate the following form and use the result as a string to display.
17186 In this case, the expression displays the first component of the full
17187 system name. The end of the first component is a @samp{.} (`period'),
17188 so I use the @code{string-match} function to tell me the length of the
17189 first component. The substring from the zeroth character to that
17190 length is the name of the machine.
17191
17192 @need 1250
17193 This is the expression:
17194
17195 @smallexample
17196 @group
17197 (:eval (substring
17198 (system-name) 0 (string-match "\\..+" (system-name))))
17199 @end group
17200 @end smallexample
17201
17202 @samp{%[} and @samp{%]} cause a pair of square brackets
17203 to appear for each recursive editing level. @samp{%n} says `Narrow'
17204 when narrowing is in effect. @samp{%P} tells you the percentage of
17205 the buffer that is above the bottom of the window, or `Top', `Bottom',
17206 or `All'. (A lower case @samp{p} tell you the percentage above the
17207 @emph{top} of the window.) @samp{%-} inserts enough dashes to fill
17208 out the line.
17209
17210 Remember, ``You don't have to like Emacs to like it'' --- your own
17211 Emacs can have different colors, different commands, and different
17212 keys than a default Emacs.
17213
17214 On the other hand, if you want to bring up a plain `out of the box'
17215 Emacs, with no customization, type:
17216
17217 @smallexample
17218 emacs -q
17219 @end smallexample
17220
17221 @noindent
17222 This will start an Emacs that does @emph{not} load your
17223 @file{~/.emacs} initialization file. A plain, default Emacs. Nothing
17224 more.
17225
17226 @node Debugging, Conclusion, Emacs Initialization, Top
17227 @chapter Debugging
17228 @cindex debugging
17229
17230 GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
17231 first is built into the internals of Emacs and is always with you;
17232 the second requires that you instrument a function before you can use it.
17233
17234 Both debuggers are described extensively in @ref{Debugging, ,
17235 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17236 In this chapter, I will walk through a short example of each.
17237
17238 @menu
17239 * debug:: How to use the built-in debugger.
17240 * debug-on-entry:: Start debugging when you call a function.
17241 * debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
17242 * edebug:: How to use Edebug, a source level debugger.
17243 * Debugging Exercises::
17244 @end menu
17245
17246 @node debug, debug-on-entry, Debugging, Debugging
17247 @section @code{debug}
17248 @findex debug
17249
17250 Suppose you have written a function definition that is intended to
17251 return the sum of the numbers 1 through a given number. (This is the
17252 @code{triangle} function discussed earlier. @xref{Decrementing
17253 Example, , Example with Decrementing Counter}, for a discussion.)
17254 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17255
17256 However, your function definition has a bug. You have mistyped
17257 @samp{1=} for @samp{1-}. Here is the broken definition:
17258
17259 @findex triangle-bugged
17260 @smallexample
17261 @group
17262 (defun triangle-bugged (number)
17263 "Return sum of numbers 1 through NUMBER inclusive."
17264 (let ((total 0))
17265 (while (> number 0)
17266 (setq total (+ total number))
17267 (setq number (1= number))) ; @r{Error here.}
17268 total))
17269 @end group
17270 @end smallexample
17271
17272 If you are reading this in Info, you can evaluate this definition in
17273 the normal fashion. You will see @code{triangle-bugged} appear in the
17274 echo area.
17275
17276 @need 1250
17277 Now evaluate the @code{triangle-bugged} function with an
17278 argument of 4:
17279
17280 @smallexample
17281 (triangle-bugged 4)
17282 @end smallexample
17283
17284 @noindent
17285 In GNU Emacs version 21, you will create and enter a
17286 @file{*Backtrace*} buffer that says:
17287
17288 @noindent
17289 @smallexample
17290 @group
17291 ---------- Buffer: *Backtrace* ----------
17292 Debugger entered--Lisp error: (void-function 1=)
17293 (1= number)
17294 (setq number (1= number))
17295 (while (> number 0) (setq total (+ total number))
17296 (setq number (1= number)))
17297 (let ((total 0)) (while (> number 0) (setq total ...)
17298 (setq number ...)) total)
17299 triangle-bugged(4)
17300 @end group
17301 @group
17302 eval((triangle-bugged 4))
17303 eval-last-sexp-1(nil)
17304 eval-last-sexp(nil)
17305 call-interactively(eval-last-sexp)
17306 ---------- Buffer: *Backtrace* ----------
17307 @end group
17308 @end smallexample
17309
17310 @noindent
17311 (I have reformatted this example slightly; the debugger does not fold
17312 long lines. As usual, you can quit the debugger by typing @kbd{q} in
17313 the @file{*Backtrace*} buffer.)
17314
17315 In practice, for a bug as simple as this, the `Lisp error' line will
17316 tell you what you need to know to correct the definition. The
17317 function @code{1=} is `void'.
17318
17319 @need 800
17320 In GNU Emacs 20 and before, you will see:
17321
17322 @smallexample
17323 Symbol's function definition is void:@: 1=
17324 @end smallexample
17325
17326 @noindent
17327 which has the same meaning as the @file{*Backtrace*} buffer line in
17328 version 21.
17329
17330 However, suppose you are not quite certain what is going on?
17331 You can read the complete backtrace.
17332
17333 In this case, you need to run GNU Emacs 21, which automatically starts
17334 the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17335 you need to start the debugger manually as described below.
17336
17337 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17338 what Emacs did that led to the error. Emacs made an interactive call
17339 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17340 of the @code{triangle-bugged} expression. Each line above tells you
17341 what the Lisp interpreter evaluated next.
17342
17343 @need 1250
17344 The third line from the top of the buffer is
17345
17346 @smallexample
17347 (setq number (1= number))
17348 @end smallexample
17349
17350 @noindent
17351 Emacs tried to evaluate this expression; in order to do so, it tried
17352 to evaluate the inner expression shown on the second line from the
17353 top:
17354
17355 @smallexample
17356 (1= number)
17357 @end smallexample
17358
17359 @need 1250
17360 @noindent
17361 This is where the error occurred; as the top line says:
17362
17363 @smallexample
17364 Debugger entered--Lisp error: (void-function 1=)
17365 @end smallexample
17366
17367 @noindent
17368 You can correct the mistake, re-evaluate the function definition, and
17369 then run your test again.
17370
17371 @node debug-on-entry, debug-on-quit, debug, Debugging
17372 @section @code{debug-on-entry}
17373 @findex debug-on-entry
17374
17375 GNU Emacs 21 starts the debugger automatically when your function has
17376 an error. GNU Emacs version 20 and before did not; it simply
17377 presented you with an error message. You had to start the debugger
17378 manually.
17379
17380 You can start the debugger manually for all versions of Emacs; the
17381 advantage is that the debugger runs even if you do not have a bug in
17382 your code. Sometimes your code will be free of bugs!
17383
17384 You can enter the debugger when you call the function by calling
17385 @code{debug-on-entry}.
17386
17387 @need 1250
17388 @noindent
17389 Type:
17390
17391 @smallexample
17392 M-x debug-on-entry RET triangle-bugged RET
17393 @end smallexample
17394
17395 @need 1250
17396 @noindent
17397 Now, evaluate the following:
17398
17399 @smallexample
17400 (triangle-bugged 5)
17401 @end smallexample
17402
17403 @noindent
17404 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17405 you that it is beginning to evaluate the @code{triangle-bugged}
17406 function:
17407
17408 @smallexample
17409 @group
17410 ---------- Buffer: *Backtrace* ----------
17411 Debugger entered--entering a function:
17412 * triangle-bugged(5)
17413 eval((triangle-bugged 5))
17414 @end group
17415 @group
17416 eval-last-sexp-1(nil)
17417 eval-last-sexp(nil)
17418 call-interactively(eval-last-sexp)
17419 ---------- Buffer: *Backtrace* ----------
17420 @end group
17421 @end smallexample
17422
17423 In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
17424 the first expression in @code{triangle-bugged}; the buffer will look
17425 like this:
17426
17427 @smallexample
17428 @group
17429 ---------- Buffer: *Backtrace* ----------
17430 Debugger entered--beginning evaluation of function call form:
17431 * (let ((total 0)) (while (> number 0) (setq total ...)
17432 (setq number ...)) total)
17433 * triangle-bugged(5)
17434 eval((triangle-bugged 5))
17435 @end group
17436 @group
17437 eval-last-sexp-1(nil)
17438 eval-last-sexp(nil)
17439 call-interactively(eval-last-sexp)
17440 ---------- Buffer: *Backtrace* ----------
17441 @end group
17442 @end smallexample
17443
17444 @noindent
17445 Now, type @kbd{d} again, eight times, slowly. Each time you type
17446 @kbd{d}, Emacs will evaluate another expression in the function
17447 definition.
17448
17449 @need 1750
17450 Eventually, the buffer will look like this:
17451
17452 @smallexample
17453 @group
17454 ---------- Buffer: *Backtrace* ----------
17455 Debugger entered--beginning evaluation of function call form:
17456 * (setq number (1= number))
17457 * (while (> number 0) (setq total (+ total number))
17458 (setq number (1= number)))
17459 @group
17460 @end group
17461 * (let ((total 0)) (while (> number 0) (setq total ...)
17462 (setq number ...)) total)
17463 * triangle-bugged(5)
17464 eval((triangle-bugged 5))
17465 @group
17466 @end group
17467 eval-last-sexp-1(nil)
17468 eval-last-sexp(nil)
17469 call-interactively(eval-last-sexp)
17470 ---------- Buffer: *Backtrace* ----------
17471 @end group
17472 @end smallexample
17473
17474 @noindent
17475 Finally, after you type @kbd{d} two more times, Emacs will reach the
17476 error, and the top two lines of the @file{*Backtrace*} buffer will look
17477 like this:
17478
17479 @smallexample
17480 @group
17481 ---------- Buffer: *Backtrace* ----------
17482 Debugger entered--Lisp error: (void-function 1=)
17483 * (1= number)
17484 @dots{}
17485 ---------- Buffer: *Backtrace* ----------
17486 @end group
17487 @end smallexample
17488
17489 By typing @kbd{d}, you were able to step through the function.
17490
17491 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17492 quits the trace, but does not cancel @code{debug-on-entry}.
17493
17494 @findex cancel-debug-on-entry
17495 To cancel the effect of @code{debug-on-entry}, call
17496 @code{cancel-debug-on-entry} and the name of the function, like this:
17497
17498 @smallexample
17499 M-x cancel-debug-on-entry RET triangle-bugged RET
17500 @end smallexample
17501
17502 @noindent
17503 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
17504
17505 @node debug-on-quit, edebug, debug-on-entry, Debugging
17506 @section @code{debug-on-quit} and @code{(debug)}
17507
17508 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17509 there are two other ways to start @code{debug}.
17510
17511 @findex debug-on-quit
17512 You can start @code{debug} whenever you type @kbd{C-g}
17513 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17514 @code{t}. This is useful for debugging infinite loops.
17515
17516 @need 1500
17517 @cindex @code{(debug)} in code
17518 Or, you can insert a line that says @code{(debug)} into your code
17519 where you want the debugger to start, like this:
17520
17521 @smallexample
17522 @group
17523 (defun triangle-bugged (number)
17524 "Return sum of numbers 1 through NUMBER inclusive."
17525 (let ((total 0))
17526 (while (> number 0)
17527 (setq total (+ total number))
17528 (debug) ; @r{Start debugger.}
17529 (setq number (1= number))) ; @r{Error here.}
17530 total))
17531 @end group
17532 @end smallexample
17533
17534 The @code{debug} function is described in detail in @ref{Debugger, ,
17535 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17536
17537 @node edebug, Debugging Exercises, debug-on-quit, Debugging
17538 @section The @code{edebug} Source Level Debugger
17539 @cindex Source level debugger
17540 @findex edebug
17541
17542 Edebug is a source level debugger. Edebug normally displays the
17543 source of the code you are debugging, with an arrow at the left that
17544 shows which line you are currently executing.
17545
17546 You can walk through the execution of a function, line by line, or run
17547 quickly until reaching a @dfn{breakpoint} where execution stops.
17548
17549 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17550 Lisp Reference Manual}.
17551
17552 Here is a bugged function definition for @code{triangle-recursively}.
17553 @xref{Recursive triangle function, , Recursion in place of a counter},
17554 for a review of it.
17555
17556 @smallexample
17557 @group
17558 (defun triangle-recursively-bugged (number)
17559 "Return sum of numbers 1 through NUMBER inclusive.
17560 Uses recursion."
17561 (if (= number 1)
17562 1
17563 (+ number
17564 (triangle-recursively-bugged
17565 (1= number))))) ; @r{Error here.}
17566 @end group
17567 @end smallexample
17568
17569 @noindent
17570 Normally, you would install this definition by positioning your cursor
17571 after the function's closing parenthesis and typing @kbd{C-x C-e}
17572 (@code{eval-last-sexp}) or else by positioning your cursor within the
17573 definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
17574 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17575 Interactive mode.)
17576
17577 @need 1500
17578 However, to prepare this function definition for Edebug, you must
17579 first @dfn{instrument} the code using a different command. You can do
17580 this by positioning your cursor within the definition and typing
17581
17582 @smallexample
17583 M-x edebug-defun RET
17584 @end smallexample
17585
17586 @noindent
17587 This will cause Emacs to load Edebug automatically if it is not
17588 already loaded, and properly instrument the function.
17589
17590 After instrumenting the function, place your cursor after the
17591 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17592
17593 @smallexample
17594 (triangle-recursively-bugged 3)
17595 @end smallexample
17596
17597 @noindent
17598 You will be jumped back to the source for
17599 @code{triangle-recursively-bugged} and the cursor positioned at the
17600 beginning of the @code{if} line of the function. Also, you will see
17601 an arrowhead at the left hand side of that line. The arrowhead marks
17602 the line where the function is executing. (In the following examples,
17603 we show the arrowhead with @samp{=>}; in a windowing system, you may
17604 see the arrowhead as a solid triangle in the window `fringe'.)
17605
17606 @smallexample
17607 =>@point{}(if (= number 1)
17608 @end smallexample
17609
17610 @noindent
17611 @iftex
17612 In the example, the location of point is displayed with a star,
17613 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17614 @end iftex
17615 @ifnottex
17616 In the example, the location of point is displayed as @samp{@point{}}
17617 (in a printed book, it is displayed with a five pointed star).
17618 @end ifnottex
17619
17620 If you now press @key{SPC}, point will move to the next expression to
17621 be executed; the line will look like this:
17622
17623 @smallexample
17624 =>(if @point{}(= number 1)
17625 @end smallexample
17626
17627 @noindent
17628 As you continue to press @key{SPC}, point will move from expression to
17629 expression. At the same time, whenever an expression returns a value,
17630 that value will be displayed in the echo area. For example, after you
17631 move point past @code{number}, you will see the following:
17632
17633 @smallexample
17634 Result: 3 = C-c
17635 @end smallexample
17636
17637 @noindent
17638 This means the value of @code{number} is 3, which is @sc{ascii}
17639 `control-c' (the third letter of the alphabet).
17640
17641 You can continue moving through the code until you reach the line with
17642 the error. Before evaluation, that line looks like this:
17643
17644 @smallexample
17645 => @point{}(1= number))))) ; @r{Error here.}
17646 @end smallexample
17647
17648 @need 1250
17649 @noindent
17650 When you press @key{SPC} once again, you will produce an error message
17651 that says:
17652
17653 @smallexample
17654 Symbol's function definition is void:@: 1=
17655 @end smallexample
17656
17657 @noindent
17658 This is the bug.
17659
17660 Press @kbd{q} to quit Edebug.
17661
17662 To remove instrumentation from a function definition, simply
17663 re-evaluate it with a command that does not instrument it.
17664 For example, you could place your cursor after the definition's
17665 closing parenthesis and type @kbd{C-x C-e}.
17666
17667 Edebug does a great deal more than walk with you through a function.
17668 You can set it so it races through on its own, stopping only at an
17669 error or at specified stopping points; you can cause it to display the
17670 changing values of various expressions; you can find out how many
17671 times a function is called, and more.
17672
17673 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17674 Lisp Reference Manual}.
17675
17676 @need 1500
17677 @node Debugging Exercises, , edebug, Debugging
17678 @section Debugging Exercises
17679
17680 @itemize @bullet
17681 @item
17682 Install the @code{count-words-region} function and then cause it to
17683 enter the built-in debugger when you call it. Run the command on a
17684 region containing two words. You will need to press @kbd{d} a
17685 remarkable number of times. On your system, is a `hook' called after
17686 the command finishes? (For information on hooks, see @ref{Command
17687 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17688 Manual}.)
17689
17690 @item
17691 Copy @code{count-words-region} into the @file{*scratch*} buffer,
17692 instrument the function for Edebug, and walk through its execution.
17693 The function does not need to have a bug, although you can introduce
17694 one if you wish. If the function lacks a bug, the walk-through
17695 completes without problems.
17696
17697 @item
17698 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17699 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17700 @kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17701 for commands made outside of the Edebug debugging buffer.)
17702
17703 @item
17704 In the Edebug debugging buffer, use the @kbd{p}
17705 (@code{edebug-bounce-point}) command to see where in the region the
17706 @code{count-words-region} is working.
17707
17708 @item
17709 Move point to some spot further down function and then type the
17710 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17711
17712 @item
17713 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17714 walk through the function on its own; use an upper case @kbd{T} for
17715 @code{edebug-Trace-fast-mode}.
17716
17717 @item
17718 Set a breakpoint, then run Edebug in Trace mode until it reaches the
17719 stopping point.
17720 @end itemize
17721
17722 @node Conclusion, the-the, Debugging, Top
17723 @chapter Conclusion
17724
17725 We have now reached the end of this Introduction. You have now
17726 learned enough about programming in Emacs Lisp to set values, to write
17727 simple @file{.emacs} files for yourself and your friends, and write
17728 simple customizations and extensions to Emacs.
17729
17730 This is a place to stop. Or, if you wish, you can now go onward, and
17731 teach yourself.
17732
17733 You have learned some of the basic nuts and bolts of programming. But
17734 only some. There are a great many more brackets and hinges that are
17735 easy to use that we have not touched.
17736
17737 A path you can follow right now lies among the sources to GNU Emacs
17738 and in
17739 @ifnotinfo
17740 @cite{The GNU Emacs Lisp Reference Manual}.
17741 @end ifnotinfo
17742 @ifinfo
17743 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17744 Emacs Lisp Reference Manual}.
17745 @end ifinfo
17746
17747 The Emacs Lisp sources are an adventure. When you read the sources and
17748 come across a function or expression that is unfamiliar, you need to
17749 figure out or find out what it does.
17750
17751 Go to the Reference Manual. It is a thorough, complete, and fairly
17752 easy-to-read description of Emacs Lisp. It is written not only for
17753 experts, but for people who know what you know. (The @cite{Reference
17754 Manual} comes with the standard GNU Emacs distribution. Like this
17755 introduction, it comes as a Texinfo source file, so you can read it
17756 on-line and as a typeset, printed book.)
17757
17758 Go to the other on-line help that is part of GNU Emacs: the on-line
17759 documentation for all functions, and @code{find-tags}, the program
17760 that takes you to sources.
17761
17762 Here is an example of how I explore the sources. Because of its name,
17763 @file{simple.el} is the file I looked at first, a long time ago. As
17764 it happens some of the functions in @file{simple.el} are complicated,
17765 or at least look complicated at first sight. The @code{open-line}
17766 function, for example, looks complicated.
17767
17768 You may want to walk through this function slowly, as we did with the
17769 @code{forward-sentence} function.
17770 @ifnottex
17771 (@xref{forward-sentence}.)
17772 @end ifnottex
17773 @iftex
17774 (@xref{forward-sentence, , @code{forward-sentence}}.)
17775 @end iftex
17776 Or you may want to skip that function and look at another, such as
17777 @code{split-line}. You don't need to read all the functions.
17778 According to @code{count-words-in-defun}, the @code{split-line}
17779 function contains 27 words and symbols.
17780
17781 Even though it is short, @code{split-line} contains four expressions
17782 we have not studied: @code{skip-chars-forward}, @code{indent-to},
17783 @code{current-column} and @samp{?\n}.
17784
17785 Consider the @code{skip-chars-forward} function. (It is part of the
17786 function definition for @code{back-to-indentation}, which is shown in
17787 @ref{Review, , Review}.)
17788
17789 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17790 typing @kbd{C-h f} (@code{describe-function}) and the name of the
17791 function. This gives you the function documentation.
17792
17793 You may be able to guess what is done by a well named function such as
17794 @code{indent-to}; or you can look it up, too. Incidentally, the
17795 @code{describe-function} function itself is in @file{help.el}; it is
17796 one of those long, but decipherable functions. You can look up
17797 @code{describe-function} using the @kbd{C-h f} command!
17798
17799 In this instance, since the code is Lisp, the @file{*Help*} buffer
17800 contains the name of the library containing the function's source.
17801 You can put point over the name of the library and press the RET key,
17802 which in this situation is bound to @code{help-follow}, and be taken
17803 directly to the source, in the same way as @kbd{M-.}
17804 (@code{find-tag}).
17805
17806 The definition for @code{describe-function} illustrates how to
17807 customize the @code{interactive} expression without using the standard
17808 character codes; and it shows how to create a temporary buffer.
17809
17810 (The @code{indent-to} function is written in C rather than Emacs Lisp;
17811 it is a `built-in' function. @code{help-follow} only provides you
17812 with the documentation of a built-in function; it does not take you to
17813 the source. But @code{find-tag} will take you to the source, if
17814 properly set up.)
17815
17816 You can look at a function's source using @code{find-tag}, which is
17817 bound to @kbd{M-.} Finally, you can find out what the Reference
17818 Manual has to say by visiting the manual in Info, and typing @kbd{i}
17819 (@code{Info-index}) and the name of the function, or by looking up
17820 @code{skip-chars-forward} in the index to a printed copy of the
17821 manual.
17822
17823 Similarly, you can find out what is meant by @samp{?\n}. You can try
17824 using @code{Info-index} with @samp{?\n}. It turns out that this
17825 action won't help; but don't give up. If you search the index for
17826 @samp{\n} without the @samp{?}, you will be taken directly to the
17827 relevant section of the manual. (@xref{Character Type, , Character
17828 Type, elisp, The GNU Emacs Lisp Reference Manual}. @samp{?\n} stands
17829 for the newline character.)
17830
17831 Other interesting source files include @file{paragraphs.el},
17832 @file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
17833 file includes short, easily understood functions as well as longer
17834 ones. The @file{loaddefs.el} file contains the many standard
17835 autoloads and many keymaps. I have never looked at it all; only at
17836 parts. @file{loadup.el} is the file that loads the standard parts of
17837 Emacs; it tells you a great deal about how Emacs is built.
17838 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17839 Reference Manual}, for more about building.)
17840
17841 As I said, you have learned some nuts and bolts; however, and very
17842 importantly, we have hardly touched major aspects of programming; I
17843 have said nothing about how to sort information, except to use the
17844 predefined @code{sort} function; I have said nothing about how to store
17845 information, except to use variables and lists; I have said nothing
17846 about how to write programs that write programs. These are topics for
17847 another, and different kind of book, a different kind of learning.
17848
17849 What you have done is learn enough for much practical work with GNU
17850 Emacs. What you have done is get started. This is the end of a
17851 beginning.
17852
17853 @c ================ Appendix ================
17854
17855 @node the-the, Kill Ring, Conclusion, Top
17856 @appendix The @code{the-the} Function
17857 @findex the-the
17858 @cindex Duplicated words function
17859 @cindex Words, duplicated
17860
17861 Sometimes when you you write text, you duplicate words---as with ``you
17862 you'' near the beginning of this sentence. I find that most
17863 frequently, I duplicate ``the'; hence, I call the function for
17864 detecting duplicated words, @code{the-the}.
17865
17866 @need 1250
17867 As a first step, you could use the following regular expression to
17868 search for duplicates:
17869
17870 @smallexample
17871 \\(\\w+[ \t\n]+\\)\\1
17872 @end smallexample
17873
17874 @noindent
17875 This regexp matches one or more word-constituent characters followed
17876 by one or more spaces, tabs, or newlines. However, it does not detect
17877 duplicated words on different lines, since the ending of the first
17878 word, the end of the line, is different from the ending of the second
17879 word, a space. (For more information about regular expressions, see
17880 @ref{Regexp Search, , Regular Expression Searches}, as well as
17881 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
17882 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
17883 The GNU Emacs Lisp Reference Manual}.)
17884
17885 You might try searching just for duplicated word-constituent
17886 characters but that does not work since the pattern detects doubles
17887 such as the two occurrences of `th' in `with the'.
17888
17889 Another possible regexp searches for word-constituent characters
17890 followed by non-word-constituent characters, reduplicated. Here,
17891 @w{@samp{\\w+}} matches one or more word-constituent characters and
17892 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
17893
17894 @smallexample
17895 \\(\\(\\w+\\)\\W*\\)\\1
17896 @end smallexample
17897
17898 @noindent
17899 Again, not useful.
17900
17901 Here is the pattern that I use. It is not perfect, but good enough.
17902 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
17903 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
17904 any characters that are @emph{not} an @@-sign, space, newline, or tab.
17905
17906 @smallexample
17907 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
17908 @end smallexample
17909
17910 One can write more complicated expressions, but I found that this
17911 expression is good enough, so I use it.
17912
17913 Here is the @code{the-the} function, as I include it in my
17914 @file{.emacs} file, along with a handy global key binding:
17915
17916 @smallexample
17917 @group
17918 (defun the-the ()
17919 "Search forward for for a duplicated word."
17920 (interactive)
17921 (message "Searching for for duplicated words ...")
17922 (push-mark)
17923 @end group
17924 @group
17925 ;; This regexp is not perfect
17926 ;; but is fairly good over all:
17927 (if (re-search-forward
17928 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
17929 (message "Found duplicated word.")
17930 (message "End of buffer")))
17931 @end group
17932
17933 @group
17934 ;; Bind `the-the' to C-c \
17935 (global-set-key "\C-c\\" 'the-the)
17936 @end group
17937 @end smallexample
17938
17939 @sp 1
17940 Here is test text:
17941
17942 @smallexample
17943 @group
17944 one two two three four five
17945 five six seven
17946 @end group
17947 @end smallexample
17948
17949 You can substitute the other regular expressions shown above in the
17950 function definition and try each of them on this list.
17951
17952 @node Kill Ring, Full Graph, the-the, Top
17953 @appendix Handling the Kill Ring
17954 @cindex Kill ring handling
17955 @cindex Handling the kill ring
17956 @cindex Ring, making a list like a
17957
17958 The kill ring is a list that is transformed into a ring by the
17959 workings of the @code{rotate-yank-pointer} function. The @code{yank}
17960 and @code{yank-pop} commands use the @code{rotate-yank-pointer}
17961 function. This appendix describes the @code{rotate-yank-pointer}
17962 function as well as both the @code{yank} and the @code{yank-pop}
17963 commands.
17964
17965 @menu
17966 * rotate-yank-pointer:: Move a pointer along a list and around.
17967 * yank:: Paste a copy of a clipped element.
17968 * yank-pop:: Insert first element pointed to.
17969 @end menu
17970
17971 @node rotate-yank-pointer, yank, Kill Ring, Kill Ring
17972 @comment node-name, next, previous, up
17973 @appendixsec The @code{rotate-yank-pointer} Function
17974 @findex rotate-yank-pointer
17975
17976 The @code{rotate-yank-pointer} function changes the element in the kill
17977 ring to which @code{kill-ring-yank-pointer} points. For example, it can
17978 change @code{kill-ring-yank-pointer} from pointing to the second
17979 element to point to the third element.
17980
17981 @need 800
17982 Here is the code for @code{rotate-yank-pointer}:
17983
17984 @smallexample
17985 @group
17986 (defun rotate-yank-pointer (arg)
17987 "Rotate the yanking point in the kill ring."
17988 (interactive "p")
17989 (let ((length (length kill-ring)))
17990 @end group
17991 @group
17992 (if (zerop length)
17993 ;; @r{then-part}
17994 (error "Kill ring is empty")
17995 @end group
17996 @group
17997 ;; @r{else-part}
17998 (setq kill-ring-yank-pointer
17999 (nthcdr (% (+ arg
18000 (- length
18001 (length
18002 kill-ring-yank-pointer)))
18003 length)
18004 kill-ring)))))
18005 @end group
18006 @end smallexample
18007
18008 @menu
18009 * Understanding rotate-yk-ptr::
18010 * rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
18011 @end menu
18012
18013 @node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18014 @ifnottex
18015 @unnumberedsubsec @code{rotate-yank-pointer} in Outline
18016 @end ifnottex
18017
18018 The @code{rotate-yank-pointer} function looks complex, but as usual,
18019 it can be understood by taking it apart piece by piece. First look at
18020 it in skeletal form:
18021
18022 @smallexample
18023 @group
18024 (defun rotate-yank-pointer (arg)
18025 "Rotate the yanking point in the kill ring."
18026 (interactive "p")
18027 (let @var{varlist}
18028 @var{body}@dots{})
18029 @end group
18030 @end smallexample
18031
18032 This function takes one argument, called @code{arg}. It has a brief
18033 documentation string; and it is interactive with a small @samp{p}, which
18034 means that the argument must be a processed prefix passed to the
18035 function as a number.
18036
18037 The body of the function definition is a @code{let} expression, which
18038 itself has a body as well as a @var{varlist}.
18039
18040 The @code{let} expression declares a variable that will be only usable
18041 within the bounds of this function. This variable is called
18042 @code{length} and is bound to a value that is equal to the number of
18043 items in the kill ring. This is done by using the function called
18044 @code{length}. (Note that this function has the same name as the
18045 variable called @code{length}; but one use of the word is to name the
18046 function and the other is to name the variable. The two are quite
18047 distinct. Similarly, an English speaker will distinguish between the
18048 meanings of the word @samp{ship} when he says: "I must ship this package
18049 immediately." and "I must get aboard the ship immediately.")
18050
18051 The function @code{length} tells the number of items there are in a list,
18052 so @code{(length kill-ring)} returns the number of items there are in the
18053 kill ring.
18054
18055 @node rotate-yk-ptr body, , Understanding rotate-yk-ptr, rotate-yank-pointer
18056 @comment node-name, next, previous, up
18057 @appendixsubsec The Body of @code{rotate-yank-pointer}
18058
18059 The body of @code{rotate-yank-pointer} is a @code{let} expression and
18060 the body of the @code{let} expression is an @code{if} expression.
18061
18062 The purpose of the @code{if} expression is to find out whether there is
18063 anything in the kill ring. If the kill ring is empty, the @code{error}
18064 function stops evaluation of the function and prints a message in the
18065 echo area. On the other hand, if the kill ring has something in it, the
18066 work of the function is done.
18067
18068 Here is the if-part and then-part of the @code{if} expression:
18069
18070 @findex zerop
18071 @findex error
18072 @smallexample
18073 @group
18074 (if (zerop length) ; @r{if-part}
18075 (error "Kill ring is empty") ; @r{then-part}
18076 @dots{}
18077 @end group
18078 @end smallexample
18079
18080 @noindent
18081 If there is not anything in the kill ring, its length must be zero and
18082 an error message sent to the user: @samp{Kill ring is empty}. The
18083 @code{if} expression uses the function @code{zerop} which returns true
18084 if the value it is testing is zero. When @code{zerop} tests true, the
18085 then-part of the @code{if} is evaluated. The then-part is a list
18086 starting with the function @code{error}, which is a function that is
18087 similar to the @code{message} function (@pxref{message}), in that it
18088 prints a one-line message in the echo area. However, in addition to
18089 printing a message, @code{error} also stops evaluation of the function
18090 within which it is embedded. This means that the rest of the function
18091 will not be evaluated if the length of the kill ring is zero.
18092
18093 @menu
18094 * Digression concerning error:: How to mislead humans, but not computers.
18095 * rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
18096 * Remainder Function:: The remainder, @code{%}, function.
18097 * rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
18098 * kill-rng-yk-ptr last elt:: Pointing to the last element.
18099 @end menu
18100
18101 @node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18102 @ifnottex
18103 @unnumberedsubsubsec Digression about the word `error'
18104 @end ifnottex
18105
18106 (In my opinion, it is slightly misleading, at least to humans, to use
18107 the term `error' as the name of the @code{error} function. A better
18108 term would be `cancel'. Strictly speaking, of course, you cannot
18109 point to, much less rotate a pointer to a list that has no length, so
18110 from the point of view of the computer, the word `error' is correct.
18111 But a human expects to attempt this sort of thing, if only to find out
18112 whether the kill ring is full or empty. This is an act of
18113 exploration.
18114
18115 (From the human point of view, the act of exploration and discovery is
18116 not necessarily an error, and therefore should not be labelled as one,
18117 even in the bowels of a computer. As it is, the code in Emacs implies
18118 that a human who is acting virtuously, by exploring his or her
18119 environment, is making an error. This is bad. Even though the computer
18120 takes the same steps as it does when there is an `error', a term such as
18121 `cancel' would have a clearer connotation.)
18122
18123 @node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18124 @unnumberedsubsubsec The else-part of the @code{if} expression
18125
18126 The else-part of the @code{if} expression is dedicated to setting the
18127 value of @code{kill-ring-yank-pointer} when the kill ring has something
18128 in it. The code looks like this:
18129
18130 @smallexample
18131 @group
18132 (setq kill-ring-yank-pointer
18133 (nthcdr (% (+ arg
18134 (- length
18135 (length kill-ring-yank-pointer)))
18136 length)
18137 kill-ring)))))
18138 @end group
18139 @end smallexample
18140
18141 This needs some examination. Clearly, @code{kill-ring-yank-pointer}
18142 is being set to be equal to some @sc{cdr} of the kill ring, using the
18143 @code{nthcdr} function that is described in an earlier section.
18144 (@xref{copy-region-as-kill}.) But exactly how does it do this?
18145
18146 Before looking at the details of the code let's first consider the
18147 purpose of the @code{rotate-yank-pointer} function.
18148
18149 The @code{rotate-yank-pointer} function changes what
18150 @code{kill-ring-yank-pointer} points to. If
18151 @code{kill-ring-yank-pointer} starts by pointing to the first element
18152 of a list, a call to @code{rotate-yank-pointer} causes it to point to
18153 the second element; and if @code{kill-ring-yank-pointer} points to the
18154 second element, a call to @code{rotate-yank-pointer} causes it to
18155 point to the third element. (And if @code{rotate-yank-pointer} is
18156 given an argument greater than 1, it jumps the pointer that many
18157 elements.)
18158
18159 The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18160 the @code{kill-ring-yank-pointer} points to. If
18161 @code{kill-ring-yank-pointer} points to the first element of the kill
18162 ring, then, in the simplest case, the @code{rotate-yank-pointer}
18163 function must cause it to point to the second element. Put another
18164 way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18165 to the @sc{cdr} of the kill ring.
18166
18167 @need 1250
18168 That is, under these circumstances,
18169
18170 @smallexample
18171 @group
18172 (setq kill-ring-yank-pointer
18173 ("some text" "a different piece of text" "yet more text"))
18174
18175 (setq kill-ring
18176 ("some text" "a different piece of text" "yet more text"))
18177 @end group
18178 @end smallexample
18179
18180 @need 800
18181 @noindent
18182 the code should do this:
18183
18184 @smallexample
18185 (setq kill-ring-yank-pointer (cdr kill-ring))
18186 @end smallexample
18187
18188 @need 1000
18189 @noindent
18190 As a result, the @code{kill-ring-yank-pointer} will look like this:
18191
18192 @smallexample
18193 @group
18194 kill-ring-yank-pointer
18195 @result{} ("a different piece of text" "yet more text"))
18196 @end group
18197 @end smallexample
18198
18199 The actual @code{setq} expression uses the @code{nthcdr} function to do
18200 the job.
18201
18202 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18203 works by repeatedly taking the @sc{cdr} of a list---it takes the
18204 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18205
18206 @need 800
18207 The two following expressions produce the same result:
18208
18209 @smallexample
18210 @group
18211 (setq kill-ring-yank-pointer (cdr kill-ring))
18212
18213 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18214 @end group
18215 @end smallexample
18216
18217 In the @code{rotate-yank-pointer} function, however, the first
18218 argument to @code{nthcdr} is a rather complex looking expression with
18219 lots of arithmetic inside of it:
18220
18221 @smallexample
18222 @group
18223 (% (+ arg
18224 (- length
18225 (length kill-ring-yank-pointer)))
18226 length)
18227 @end group
18228 @end smallexample
18229
18230 As usual, we need to look at the most deeply embedded expression first
18231 and then work our way towards the light.
18232
18233 The most deeply embedded expression is @code{(length
18234 kill-ring-yank-pointer)}. This finds the length of the current value of
18235 the @code{kill-ring-yank-pointer}. (Remember that the
18236 @code{kill-ring-yank-pointer} is the name of a variable whose value is a
18237 list.)
18238
18239 @need 800
18240 The measurement of the length is inside the expression:
18241
18242 @smallexample
18243 (- length (length kill-ring-yank-pointer))
18244 @end smallexample
18245
18246 @noindent
18247 In this expression, the first @code{length} is the variable that was
18248 assigned the length of the kill ring in the @code{let} statement at the
18249 beginning of the function. (One might think this function would be
18250 clearer if the variable @code{length} were named
18251 @code{length-of-kill-ring} instead; but if you look at the text of the
18252 whole function, you will see that it is so short that naming this
18253 variable @code{length} is not a bother, unless you are pulling the
18254 function apart into very tiny pieces as we are doing here.)
18255
18256 So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18257 difference between the length of the kill ring and the length of the list
18258 whose name is @code{kill-ring-yank-pointer}.
18259
18260 To see how all this fits into the @code{rotate-yank-pointer}
18261 function, let's begin by analyzing the case where
18262 @code{kill-ring-yank-pointer} points to the first element of the kill
18263 ring, just as @code{kill-ring} does, and see what happens when
18264 @code{rotate-yank-pointer} is called with an argument of 1.
18265
18266 The variable @code{length} and the value of the expression
18267 @code{(length kill-ring-yank-pointer)} will be the same since the
18268 variable @code{length} is the length of the kill ring and the
18269 @code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18270 Consequently, the value of
18271
18272 @smallexample
18273 (- length (length kill-ring-yank-pointer))
18274 @end smallexample
18275
18276 @noindent
18277 will be zero. Since the value of @code{arg} will be 1, this will mean
18278 that the value of the whole expression
18279
18280 @smallexample
18281 (+ arg (- length (length kill-ring-yank-pointer)))
18282 @end smallexample
18283
18284 @noindent
18285 will be 1.
18286
18287 Consequently, the argument to @code{nthcdr} will be found as the result of
18288 the expression
18289
18290 @smallexample
18291 (% 1 length)
18292 @end smallexample
18293
18294 @node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18295 @unnumberedsubsubsec The @code{%} remainder function
18296
18297 To understand @code{(% 1 length)}, we need to understand @code{%}.
18298 According to its documentation (which I just found by typing @kbd{C-h
18299 f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18300 its first argument divided by its second argument. For example, the
18301 remainder of 5 divided by 2 is 1. (2 goes into 5 twice with a
18302 remainder of 1.)
18303
18304 What surprises people who don't often do arithmetic is that a smaller
18305 number can be divided by a larger number and have a remainder. In the
18306 example we just used, 5 was divided by 2. We can reverse that and ask,
18307 what is the result of dividing 2 by 5? If you can use fractions, the
18308 answer is obviously 2/5 or .4; but if, as here, you can only use whole
18309 numbers, the result has to be something different. Clearly, 5 can go into
18310 2 zero times, but what of the remainder? To see what the answer is,
18311 consider a case that has to be familiar from childhood:
18312
18313 @itemize @bullet
18314 @item
18315 5 divided by 5 is 1 with a remainder of 0;
18316
18317 @item
18318 6 divided by 5 is 1 with a remainder of 1;
18319
18320 @item
18321 7 divided by 5 is 1 with a remainder of 2.
18322
18323 @item
18324 Similarly, 10 divided by 5 is 2 with a remainder of 0;
18325
18326 @item
18327 11 divided by 5 is 2 with a remainder of 1;
18328
18329 @item
18330 12 divided by 5 is 1 with a remainder of 2.
18331 @end itemize
18332
18333 @need 1250
18334 @noindent
18335 By considering the cases as parallel, we can see that
18336
18337 @itemize @bullet
18338 @item
18339 zero divided by 5 must be zero with a remainder of zero;
18340
18341 @item
18342 1 divided by 5 must be zero with a remainder of 1;
18343
18344 @item
18345 2 divided by 5 must be zero with a remainder of 2;
18346 @end itemize
18347
18348 @noindent
18349 and so on.
18350
18351 @need 1250
18352 So, in this code, if the value of @code{length} is 5, then the result of
18353 evaluating
18354
18355 @smallexample
18356 (% 1 5)
18357 @end smallexample
18358
18359 @noindent
18360 is 1. (I just checked this by placing the cursor after the expression
18361 and typing @kbd{C-x C-e}. Indeed, 1 is printed in the echo area.)
18362
18363 @node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18364 @unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18365
18366 When the @code{kill-ring-yank-pointer} points to the
18367 beginning of the kill ring, and the argument passed to
18368 @code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18369
18370 @smallexample
18371 @group
18372 (- length (length kill-ring-yank-pointer))
18373 @result{} 0
18374 @end group
18375 @end smallexample
18376
18377 @need 1250
18378 @noindent
18379 therefore,
18380
18381 @smallexample
18382 @group
18383 (+ arg (- length (length kill-ring-yank-pointer)))
18384 @result{} 1
18385 @end group
18386 @end smallexample
18387
18388 @need 1250
18389 @noindent
18390 and consequently:
18391
18392 @smallexample
18393 @group
18394 (% (+ arg (- length (length kill-ring-yank-pointer)))
18395 length)
18396 @result{} 1
18397 @end group
18398 @end smallexample
18399
18400 @noindent
18401 regardless of the value of @code{length}.
18402
18403 @need 1250
18404 @noindent
18405 As a result of this, the @code{setq kill-ring-yank-pointer} expression
18406 simplifies to:
18407
18408 @smallexample
18409 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18410 @end smallexample
18411
18412 @noindent
18413 What it does is now easy to understand. Instead of pointing as it did
18414 to the first element of the kill ring, the
18415 @code{kill-ring-yank-pointer} is set to point to the second element.
18416
18417 Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18418 the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18419 and so on for different values of the argument.
18420
18421 Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18422 the second element of the kill ring, its length is shorter than the
18423 length of the kill ring by 1, so the computation of the remainder is
18424 based on the expression @code{(% (+ arg 1) length)}. This means that
18425 the @code{kill-ring-yank-pointer} is moved from the second element of
18426 the kill ring to the third element if the argument passed to
18427 @code{rotate-yank-pointer} is 1.
18428
18429 @node kill-rng-yk-ptr last elt, , rotate-yk-ptr remainder, rotate-yk-ptr body
18430 @unnumberedsubsubsec Pointing to the last element
18431
18432 The final question is, what happens if the @code{kill-ring-yank-pointer}
18433 is set to the @emph{last} element of the kill ring? Will a call to
18434 @code{rotate-yank-pointer} mean that nothing more can be taken from the
18435 kill ring? The answer is no. What happens is different and useful.
18436 The @code{kill-ring-yank-pointer} is set to point to the beginning of
18437 the kill ring instead.
18438
18439 Let's see how this works by looking at the code, assuming the length of the
18440 kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18441 When the @code{kill-ring-yank-pointer} points to the last element of
18442 the kill ring, its length is 1. The code looks like this:
18443
18444 @smallexample
18445 (% (+ arg (- length (length kill-ring-yank-pointer))) length)
18446 @end smallexample
18447
18448 @need 1250
18449 When the variables are replaced by their numeric values, the expression
18450 looks like this:
18451
18452 @smallexample
18453 (% (+ 1 (- 5 1)) 5)
18454 @end smallexample
18455
18456 @noindent
18457 This expression can be evaluated by looking at the most embedded inner
18458 expression first and working outwards: The value of @code{(- 5 1)} is 4;
18459 the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18460 zero. So what @code{rotate-yank-pointer} will do is
18461
18462 @smallexample
18463 (setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18464 @end smallexample
18465
18466 @noindent
18467 which will set the @code{kill-ring-yank-pointer} to point to the beginning
18468 of the kill ring.
18469
18470 So what happens with successive calls to @code{rotate-yank-pointer} is that
18471 it moves the @code{kill-ring-yank-pointer} from element to element in the
18472 kill ring until it reaches the end; then it jumps back to the beginning.
18473 And this is why the kill ring is called a ring, since by jumping back to
18474 the beginning, it is as if the list has no end! (And what is a ring, but
18475 an entity with no end?)
18476
18477 @node yank, yank-pop, rotate-yank-pointer, Kill Ring
18478 @comment node-name, next, previous, up
18479 @appendixsec @code{yank}
18480 @findex yank
18481
18482 After learning about @code{rotate-yank-pointer}, the code for the
18483 @code{yank} function is almost easy. It has only one tricky part, which is
18484 the computation of the argument to be passed to @code{rotate-yank-pointer}.
18485
18486 @need 1250
18487 The code looks like this:
18488
18489 @smallexample
18490 @group
18491 (defun yank (&optional arg)
18492 "Reinsert the last stretch of killed text.
18493 More precisely, reinsert the stretch of killed text most
18494 recently killed OR yanked.
18495 With just C-U as argument, same but put point in front
18496 (and mark at end). With argument n, reinsert the nth
18497 most recently killed stretch of killed text.
18498 See also the command \\[yank-pop]."
18499 @end group
18500 @group
18501
18502 (interactive "*P")
18503 (rotate-yank-pointer (if (listp arg) 0
18504 (if (eq arg '-) -1
18505 (1- arg))))
18506 (push-mark (point))
18507 (insert (car kill-ring-yank-pointer))
18508 (if (consp arg)
18509 (exchange-point-and-mark)))
18510 @end group
18511 @end smallexample
18512
18513 Glancing over this code, we can understand the last few lines readily
18514 enough. The mark is pushed, that is, remembered; then the first element
18515 (the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18516 inserted; and then, if the argument passed the function is a
18517 @code{cons}, point and mark are exchanged so the point is put in the
18518 front of the inserted text rather than at the end. This option is
18519 explained in the documentation. The function itself is interactive with
18520 @code{"*P"}. This means it will not work on a read-only buffer, and that
18521 the unprocessed prefix argument is passed to the function.
18522
18523 @menu
18524 * rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
18525 * rotate-yk-ptr negative arg:: Pass a negative argument.
18526 @end menu
18527
18528 @node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18529 @unnumberedsubsubsec Passing the argument
18530
18531 The hard part of @code{yank} is understanding the computation that
18532 determines the value of the argument passed to
18533 @code{rotate-yank-pointer}. Fortunately, it is not so difficult as it
18534 looks at first sight.
18535
18536 What happens is that the result of evaluating one or both of the
18537 @code{if} expressions will be a number and that number will be the
18538 argument passed to @code{rotate-yank-pointer}.
18539
18540 @need 1250
18541 Laid out with comments, the code looks like this:
18542
18543 @smallexample
18544 @group
18545 (if (listp arg) ; @r{if-part}
18546 0 ; @r{then-part}
18547 (if (eq arg '-) ; @r{else-part, inner if}
18548 -1 ; @r{inner if's then-part}
18549 (1- arg)))) ; @r{inner if's else-part}
18550 @end group
18551 @end smallexample
18552
18553 @noindent
18554 This code consists of two @code{if} expression, one the else-part of
18555 the other.
18556
18557 The first or outer @code{if} expression tests whether the argument
18558 passed to @code{yank} is a list. Oddly enough, this will be true if
18559 @code{yank} is called without an argument---because then it will be
18560 passed the value of @code{nil} for the optional argument and an
18561 evaluation of @code{(listp nil)} returns true! So, if no argument is
18562 passed to @code{yank}, the argument passed to
18563 @code{rotate-yank-pointer} inside of @code{yank} is zero. This means
18564 the pointer is not moved and the first element to which
18565 @code{kill-ring-yank-pointer} points is inserted, as we expect.
18566 Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18567 read as a list, so again, a zero will be passed to
18568 @code{rotate-yank-pointer}. (@kbd{C-u} produces an unprocessed prefix
18569 argument of @code{(4)}, which is a list of one element.) At the same
18570 time, later in the function, this argument will be read as a
18571 @code{cons} so point will be put in the front and mark at the end of
18572 the insertion. (The @code{P} argument to @code{interactive} is
18573 designed to provide these values for the case when an optional
18574 argument is not provided or when it is @kbd{C-u}.)
18575
18576 The then-part of the outer @code{if} expression handles the case when
18577 there is no argument or when it is @kbd{C-u}. The else-part handles the
18578 other situations. The else-part is itself another @code{if} expression.
18579
18580 The inner @code{if} expression tests whether the argument is a minus
18581 sign. (This is done by pressing the @key{META} and @kbd{-} keys at the
18582 same time, or the @key{ESC} key and then the @kbd{-} key). In this
18583 case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18584 argument. This moves the @code{kill-ring-yank-pointer} backwards, which
18585 is what is desired.
18586
18587 If the true-or-false-test of the inner @code{if} expression is false
18588 (that is, if the argument is not a minus sign), the else-part of the
18589 expression is evaluated. This is the expression @code{(1- arg)}.
18590 Because of the two @code{if} expressions, it will only occur when the
18591 argument is a positive number or when it is a negative number (not
18592 just a minus sign on its own). What @code{(1- arg)} does is decrement
18593 the number and return it. (The @code{1-} function subtracts one from
18594 its argument.) This means that if the argument to
18595 @code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18596 the first element to which @code{kill-ring-yank-pointer} points is
18597 yanked back, as you would expect.
18598
18599 @node rotate-yk-ptr negative arg, , rotate-yk-ptr arg, yank
18600 @unnumberedsubsubsec Passing a negative argument
18601
18602 Finally, the question arises, what happens if either the remainder
18603 function, @code{%}, or the @code{nthcdr} function is passed a negative
18604 argument, as they quite well may?
18605
18606 The answers can be found by a quick test. When @code{(% -1 5)} is
18607 evaluated, a negative number is returned; and if @code{nthcdr} is
18608 called with a negative number, it returns the same value as if it were
18609 called with a first argument of zero. This can be seen be evaluating
18610 the following code.
18611
18612 Here the @samp{@result{}} points to the result of evaluating the code
18613 preceding it. This was done by positioning the cursor after the code
18614 and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18615 You can do this if you are reading this in Info inside of GNU Emacs.
18616
18617 @smallexample
18618 @group
18619 (% -1 5)
18620 @result{} -1
18621 @end group
18622
18623 @group
18624 (setq animals '(cats dogs elephants))
18625 @result{} (cats dogs elephants)
18626 @end group
18627
18628 @group
18629 (nthcdr 1 animals)
18630 @result{} (dogs elephants)
18631 @end group
18632
18633 @group
18634 (nthcdr 0 animals)
18635 @result{} (cats dogs elephants)
18636 @end group
18637
18638 @group
18639 (nthcdr -1 animals)
18640 @result{} (cats dogs elephants)
18641 @end group
18642 @end smallexample
18643
18644 So, if a minus sign or a negative number is passed to @code{yank}, the
18645 @code{kill-ring-yank-point} is rotated backwards until it reaches the
18646 beginning of the list. Then it stays there. Unlike the other case,
18647 when it jumps from the end of the list to the beginning of the list,
18648 making a ring, it stops. This makes sense. You often want to get back
18649 to the most recently clipped out piece of text, but you don't usually
18650 want to insert text from as many as thirty kill commands ago. So you
18651 need to work through the ring to get to the end, but won't cycle around
18652 it inadvertently if you are trying to come back to the beginning.
18653
18654 Incidentally, any number passed to @code{yank} with a minus sign
18655 preceding it will be treated as @minus{}1. This is evidently a
18656 simplification for writing the program. You don't need to jump back
18657 towards the beginning of the kill ring more than one place at a time
18658 and doing this is easier than writing a function to determine the
18659 magnitude of the number that follows the minus sign.
18660
18661 @node yank-pop, , yank, Kill Ring
18662 @comment node-name, next, previous, up
18663 @appendixsec @code{yank-pop}
18664 @findex yank-pop
18665
18666 After understanding @code{yank}, the @code{yank-pop} function is easy.
18667 Leaving out the documentation to save space, it looks like this:
18668
18669 @smallexample
18670 @group
18671 (defun yank-pop (arg)
18672 (interactive "*p")
18673 (if (not (eq last-command 'yank))
18674 (error "Previous command was not a yank"))
18675 @end group
18676 @group
18677 (setq this-command 'yank)
18678 (let ((before (< (point) (mark))))
18679 (delete-region (point) (mark))
18680 (rotate-yank-pointer arg)
18681 @end group
18682 @group
18683 (set-mark (point))
18684 (insert (car kill-ring-yank-pointer))
18685 (if before (exchange-point-and-mark))))
18686 @end group
18687 @end smallexample
18688
18689 The function is interactive with a small @samp{p} so the prefix
18690 argument is processed and passed to the function. The command can
18691 only be used after a previous yank; otherwise an error message is
18692 sent. This check uses the variable @code{last-command} which is
18693 discussed elsewhere. (@xref{copy-region-as-kill}.)
18694
18695 The @code{let} clause sets the variable @code{before} to true or false
18696 depending whether point is before or after mark and then the region
18697 between point and mark is deleted. This is the region that was just
18698 inserted by the previous yank and it is this text that will be
18699 replaced. Next the @code{kill-ring-yank-pointer} is rotated so that
18700 the previously inserted text is not reinserted yet again. Mark is set
18701 at the beginning of the place the new text will be inserted and then
18702 the first element to which @code{kill-ring-yank-pointer} points is
18703 inserted. This leaves point after the new text. If in the previous
18704 yank, point was left before the inserted text, point and mark are now
18705 exchanged so point is again left in front of the newly inserted text.
18706 That is all there is to it!
18707
18708 @node Full Graph, GNU Free Documentation License, Kill Ring, Top
18709 @appendix A Graph with Labelled Axes
18710
18711 Printed axes help you understand a graph. They convey scale. In an
18712 earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
18713 wrote the code to print the body of a graph. Here we write the code
18714 for printing and labelling vertical and horizontal axes, along with the
18715 body itself.
18716
18717 @menu
18718 * Labelled Example::
18719 * print-graph Varlist:: @code{let} expression in @code{print-graph}.
18720 * print-Y-axis:: Print a label for the vertical axis.
18721 * print-X-axis:: Print a horizontal label.
18722 * Print Whole Graph:: The function to print a complete graph.
18723 @end menu
18724
18725 @node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18726 @ifnottex
18727 @unnumberedsec Labelled Example Graph
18728 @end ifnottex
18729
18730 Since insertions fill a buffer to the right and below point, the new
18731 graph printing function should first print the Y or vertical axis,
18732 then the body of the graph, and finally the X or horizontal axis.
18733 This sequence lays out for us the contents of the function:
18734
18735 @enumerate
18736 @item
18737 Set up code.
18738
18739 @item
18740 Print Y axis.
18741
18742 @item
18743 Print body of graph.
18744
18745 @item
18746 Print X axis.
18747 @end enumerate
18748
18749 @need 800
18750 Here is an example of how a finished graph should look:
18751
18752 @smallexample
18753 @group
18754 10 -
18755 *
18756 * *
18757 * **
18758 * ***
18759 5 - * *******
18760 * *** *******
18761 *************
18762 ***************
18763 1 - ****************
18764 | | | |
18765 1 5 10 15
18766 @end group
18767 @end smallexample
18768
18769 @noindent
18770 In this graph, both the vertical and the horizontal axes are labelled
18771 with numbers. However, in some graphs, the horizontal axis is time
18772 and would be better labelled with months, like this:
18773
18774 @smallexample
18775 @group
18776 5 - *
18777 * ** *
18778 *******
18779 ********** **
18780 1 - **************
18781 | ^ |
18782 Jan June Jan
18783 @end group
18784 @end smallexample
18785
18786 Indeed, with a little thought, we can easily come up with a variety of
18787 vertical and horizontal labelling schemes. Our task could become
18788 complicated. But complications breed confusion. Rather than permit
18789 this, it is better choose a simple labelling scheme for our first
18790 effort, and to modify or replace it later.
18791
18792 @need 1200
18793 These considerations suggest the following outline for the
18794 @code{print-graph} function:
18795
18796 @smallexample
18797 @group
18798 (defun print-graph (numbers-list)
18799 "@var{documentation}@dots{}"
18800 (let ((height @dots{}
18801 @dots{}))
18802 @end group
18803 @group
18804 (print-Y-axis height @dots{} )
18805 (graph-body-print numbers-list)
18806 (print-X-axis @dots{} )))
18807 @end group
18808 @end smallexample
18809
18810 We can work on each part of the @code{print-graph} function definition
18811 in turn.
18812
18813 @node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18814 @comment node-name, next, previous, up
18815 @appendixsec The @code{print-graph} Varlist
18816 @cindex @code{print-graph} varlist
18817
18818 In writing the @code{print-graph} function, the first task is to write
18819 the varlist in the @code{let} expression. (We will leave aside for the
18820 moment any thoughts about making the function interactive or about the
18821 contents of its documentation string.)
18822
18823 The varlist should set several values. Clearly, the top of the label
18824 for the vertical axis must be at least the height of the graph, which
18825 means that we must obtain this information here. Note that the
18826 @code{print-graph-body} function also requires this information. There
18827 is no reason to calculate the height of the graph in two different
18828 places, so we should change @code{print-graph-body} from the way we
18829 defined it earlier to take advantage of the calculation.
18830
18831 Similarly, both the function for printing the X axis labels and the
18832 @code{print-graph-body} function need to learn the value of the width of
18833 each symbol. We can perform the calculation here and change the
18834 definition for @code{print-graph-body} from the way we defined it in the
18835 previous chapter.
18836
18837 The length of the label for the horizontal axis must be at least as long
18838 as the graph. However, this information is used only in the function
18839 that prints the horizontal axis, so it does not need to be calculated here.
18840
18841 These thoughts lead us directly to the following form for the varlist
18842 in the @code{let} for @code{print-graph}:
18843
18844 @smallexample
18845 @group
18846 (let ((height (apply 'max numbers-list)) ; @r{First version.}
18847 (symbol-width (length graph-blank)))
18848 @end group
18849 @end smallexample
18850
18851 @noindent
18852 As we shall see, this expression is not quite right.
18853
18854 @node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
18855 @comment node-name, next, previous, up
18856 @appendixsec The @code{print-Y-axis} Function
18857 @cindex Axis, print vertical
18858 @cindex Y axis printing
18859 @cindex Vertical axis printing
18860 @cindex Print vertical axis
18861
18862 The job of the @code{print-Y-axis} function is to print a label for
18863 the vertical axis that looks like this:
18864
18865 @smallexample
18866 @group
18867 10 -
18868
18869
18870
18871
18872 5 -
18873
18874
18875
18876 1 -
18877 @end group
18878 @end smallexample
18879
18880 @noindent
18881 The function should be passed the height of the graph, and then should
18882 construct and insert the appropriate numbers and marks.
18883
18884 It is easy enough to see in the figure what the Y axis label should
18885 look like; but to say in words, and then to write a function
18886 definition to do the job is another matter. It is not quite true to
18887 say that we want a number and a tic every five lines: there are only
18888 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
18889 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
18890 and 9). It is better to say that we want a number and a tic mark on
18891 the base line (number 1) and then that we want a number and a tic on
18892 the fifth line from the bottom and on every line that is a multiple of
18893 five.
18894
18895 @menu
18896 * Height of label:: What height for the Y axis?
18897 * Compute a Remainder:: How to compute the remainder of a division.
18898 * Y Axis Element:: Construct a line for the Y axis.
18899 * Y-axis-column:: Generate a list of Y axis labels.
18900 * print-Y-axis Penultimate:: A not quite final version.
18901 @end menu
18902
18903 @node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
18904 @ifnottex
18905 @unnumberedsubsec What height should the label be?
18906 @end ifnottex
18907
18908 The next issue is what height the label should be? Suppose the maximum
18909 height of tallest column of the graph is seven. Should the highest
18910 label on the Y axis be @samp{5 -}, and should the graph stick up above
18911 the label? Or should the highest label be @samp{7 -}, and mark the peak
18912 of the graph? Or should the highest label be @code{10 -}, which is a
18913 multiple of five, and be higher than the topmost value of the graph?
18914
18915 The latter form is preferred. Most graphs are drawn within rectangles
18916 whose sides are an integral number of steps long---5, 10, 15, and so
18917 on for a step distance of five. But as soon as we decide to use a
18918 step height for the vertical axis, we discover that the simple
18919 expression in the varlist for computing the height is wrong. The
18920 expression is @code{(apply 'max numbers-list)}. This returns the
18921 precise height, not the maximum height plus whatever is necessary to
18922 round up to the nearest multiple of five. A more complex expression
18923 is required.
18924
18925 As usual in cases like this, a complex problem becomes simpler if it is
18926 divided into several smaller problems.
18927
18928 First, consider the case when the highest value of the graph is an
18929 integral multiple of five---when it is 5, 10, 15 ,or some higher
18930 multiple of five. We can use this value as the Y axis height.
18931
18932 A fairly simply way to determine whether a number is a multiple of
18933 five is to divide it by five and see if the division results in a
18934 remainder. If there is no remainder, the number is a multiple of
18935 five. Thus, seven divided by five has a remainder of two, and seven
18936 is not an integral multiple of five. Put in slightly different
18937 language, more reminiscent of the classroom, five goes into seven
18938 once, with a remainder of two. However, five goes into ten twice,
18939 with no remainder: ten is an integral multiple of five.
18940
18941 @node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
18942 @appendixsubsec Side Trip: Compute a Remainder
18943
18944 @findex % @r{(remainder function)}
18945 @cindex Remainder function, @code{%}
18946 In Lisp, the function for computing a remainder is @code{%}. The
18947 function returns the remainder of its first argument divided by its
18948 second argument. As it happens, @code{%} is a function in Emacs Lisp
18949 that you cannot discover using @code{apropos}: you find nothing if you
18950 type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
18951 learn of the existence of @code{%} is to read about it in a book such
18952 as this or in the Emacs Lisp sources. The @code{%} function is used
18953 in the code for @code{rotate-yank-pointer}, which is described in an
18954 appendix. (@xref{rotate-yk-ptr body, , The Body of
18955 @code{rotate-yank-pointer}}.)
18956
18957 You can try the @code{%} function by evaluating the following two
18958 expressions:
18959
18960 @smallexample
18961 @group
18962 (% 7 5)
18963
18964 (% 10 5)
18965 @end group
18966 @end smallexample
18967
18968 @noindent
18969 The first expression returns 2 and the second expression returns 0.
18970
18971 To test whether the returned value is zero or some other number, we
18972 can use the @code{zerop} function. This function returns @code{t} if
18973 its argument, which must be a number, is zero.
18974
18975 @smallexample
18976 @group
18977 (zerop (% 7 5))
18978 @result{} nil
18979
18980 (zerop (% 10 5))
18981 @result{} t
18982 @end group
18983 @end smallexample
18984
18985 Thus, the following expression will return @code{t} if the height
18986 of the graph is evenly divisible by five:
18987
18988 @smallexample
18989 (zerop (% height 5))
18990 @end smallexample
18991
18992 @noindent
18993 (The value of @code{height}, of course, can be found from @code{(apply
18994 'max numbers-list)}.)
18995
18996 On the other hand, if the value of @code{height} is not a multiple of
18997 five, we want to reset the value to the next higher multiple of five.
18998 This is straightforward arithmetic using functions with which we are
18999 already familiar. First, we divide the value of @code{height} by five
19000 to determine how many times five goes into the number. Thus, five
19001 goes into twelve twice. If we add one to this quotient and multiply by
19002 five, we will obtain the value of the next multiple of five that is
19003 larger than the height. Five goes into twelve twice. Add one to two,
19004 and multiply by five; the result is fifteen, which is the next multiple
19005 of five that is higher than twelve. The Lisp expression for this is:
19006
19007 @smallexample
19008 (* (1+ (/ height 5)) 5)
19009 @end smallexample
19010
19011 @noindent
19012 For example, if you evaluate the following, the result is 15:
19013
19014 @smallexample
19015 (* (1+ (/ 12 5)) 5)
19016 @end smallexample
19017
19018 All through this discussion, we have been using `five' as the value
19019 for spacing labels on the Y axis; but we may want to use some other
19020 value. For generality, we should replace `five' with a variable to
19021 which we can assign a value. The best name I can think of for this
19022 variable is @code{Y-axis-label-spacing}.
19023
19024 @need 1250
19025 Using this term, and an @code{if} expression, we produce the
19026 following:
19027
19028 @smallexample
19029 @group
19030 (if (zerop (% height Y-axis-label-spacing))
19031 height
19032 ;; @r{else}
19033 (* (1+ (/ height Y-axis-label-spacing))
19034 Y-axis-label-spacing))
19035 @end group
19036 @end smallexample
19037
19038 @noindent
19039 This expression returns the value of @code{height} itself if the height
19040 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19041 else it computes and returns a value of @code{height} that is equal to
19042 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19043
19044 We can now include this expression in the @code{let} expression of the
19045 @code{print-graph} function (after first setting the value of
19046 @code{Y-axis-label-spacing}):
19047 @vindex Y-axis-label-spacing
19048
19049 @smallexample
19050 @group
19051 (defvar Y-axis-label-spacing 5
19052 "Number of lines from one Y axis label to next.")
19053 @end group
19054
19055 @group
19056 @dots{}
19057 (let* ((height (apply 'max numbers-list))
19058 (height-of-top-line
19059 (if (zerop (% height Y-axis-label-spacing))
19060 height
19061 @end group
19062 @group
19063 ;; @r{else}
19064 (* (1+ (/ height Y-axis-label-spacing))
19065 Y-axis-label-spacing)))
19066 (symbol-width (length graph-blank))))
19067 @dots{}
19068 @end group
19069 @end smallexample
19070
19071 @noindent
19072 (Note use of the @code{let*} function: the initial value of height is
19073 computed once by the @code{(apply 'max numbers-list)} expression and
19074 then the resulting value of @code{height} is used to compute its
19075 final value. @xref{fwd-para let, , The @code{let*} expression}, for
19076 more about @code{let*}.)
19077
19078 @node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19079 @appendixsubsec Construct a Y Axis Element
19080
19081 When we print the vertical axis, we want to insert strings such as
19082 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19083 Moreover, we want the numbers and dashes to line up, so shorter
19084 numbers must be padded with leading spaces. If some of the strings
19085 use two digit numbers, the strings with single digit numbers must
19086 include a leading blank space before the number.
19087
19088 @findex number-to-string
19089 To figure out the length of the number, the @code{length} function is
19090 used. But the @code{length} function works only with a string, not with
19091 a number. So the number has to be converted from being a number to
19092 being a string. This is done with the @code{number-to-string} function.
19093 For example,
19094
19095 @smallexample
19096 @group
19097 (length (number-to-string 35))
19098 @result{} 2
19099
19100 (length (number-to-string 100))
19101 @result{} 3
19102 @end group
19103 @end smallexample
19104
19105 @noindent
19106 (@code{number-to-string} is also called @code{int-to-string}; you will
19107 see this alternative name in various sources.)
19108
19109 In addition, in each label, each number is followed by a string such
19110 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19111 This variable is defined with @code{defvar}:
19112
19113 @vindex Y-axis-tic
19114 @smallexample
19115 @group
19116 (defvar Y-axis-tic " - "
19117 "String that follows number in a Y axis label.")
19118 @end group
19119 @end smallexample
19120
19121 The length of the Y label is the sum of the length of the Y axis tic
19122 mark and the length of the number of the top of the graph.
19123
19124 @smallexample
19125 (length (concat (number-to-string height) Y-axis-tic)))
19126 @end smallexample
19127
19128 This value will be calculated by the @code{print-graph} function in
19129 its varlist as @code{full-Y-label-width} and passed on. (Note that we
19130 did not think to include this in the varlist when we first proposed it.)
19131
19132 To make a complete vertical axis label, a tic mark is concatenated
19133 with a number; and the two together may be preceded by one or more
19134 spaces depending on how long the number is. The label consists of
19135 three parts: the (optional) leading spaces, the number, and the tic
19136 mark. The function is passed the value of the number for the specific
19137 row, and the value of the width of the top line, which is calculated
19138 (just once) by @code{print-graph}.
19139
19140 @smallexample
19141 @group
19142 (defun Y-axis-element (number full-Y-label-width)
19143 "Construct a NUMBERed label element.
19144 A numbered element looks like this ` 5 - ',
19145 and is padded as needed so all line up with
19146 the element for the largest number."
19147 @end group
19148 @group
19149 (let* ((leading-spaces
19150 (- full-Y-label-width
19151 (length
19152 (concat (number-to-string number)
19153 Y-axis-tic)))))
19154 @end group
19155 @group
19156 (concat
19157 (make-string leading-spaces ? )
19158 (number-to-string number)
19159 Y-axis-tic)))
19160 @end group
19161 @end smallexample
19162
19163 The @code{Y-axis-element} function concatenates together the leading
19164 spaces, if any; the number, as a string; and the tic mark.
19165
19166 To figure out how many leading spaces the label will need, the
19167 function subtracts the actual length of the label---the length of the
19168 number plus the length of the tic mark---from the desired label width.
19169
19170 @findex make-string
19171 Blank spaces are inserted using the @code{make-string} function. This
19172 function takes two arguments: the first tells it how long the string
19173 will be and the second is a symbol for the character to insert, in a
19174 special format. The format is a question mark followed by a blank
19175 space, like this, @samp{? }. @xref{Character Type, , Character Type,
19176 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19177 syntax for characters.
19178
19179 The @code{number-to-string} function is used in the concatenation
19180 expression, to convert the number to a string that is concatenated
19181 with the leading spaces and the tic mark.
19182
19183 @node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19184 @appendixsubsec Create a Y Axis Column
19185
19186 The preceding functions provide all the tools needed to construct a
19187 function that generates a list of numbered and blank strings to insert
19188 as the label for the vertical axis:
19189
19190 @findex Y-axis-column
19191 @smallexample
19192 @group
19193 (defun Y-axis-column (height width-of-label)
19194 "Construct list of Y axis labels and blank strings.
19195 For HEIGHT of line above base and WIDTH-OF-LABEL."
19196 (let (Y-axis)
19197 @group
19198 @end group
19199 (while (> height 1)
19200 (if (zerop (% height Y-axis-label-spacing))
19201 ;; @r{Insert label.}
19202 (setq Y-axis
19203 (cons
19204 (Y-axis-element height width-of-label)
19205 Y-axis))
19206 @group
19207 @end group
19208 ;; @r{Else, insert blanks.}
19209 (setq Y-axis
19210 (cons
19211 (make-string width-of-label ? )
19212 Y-axis)))
19213 (setq height (1- height)))
19214 ;; @r{Insert base line.}
19215 (setq Y-axis
19216 (cons (Y-axis-element 1 width-of-label) Y-axis))
19217 (nreverse Y-axis)))
19218 @end group
19219 @end smallexample
19220
19221 In this function, we start with the value of @code{height} and
19222 repetitively subtract one from its value. After each subtraction, we
19223 test to see whether the value is an integral multiple of the
19224 @code{Y-axis-label-spacing}. If it is, we construct a numbered label
19225 using the @code{Y-axis-element} function; if not, we construct a
19226 blank label using the @code{make-string} function. The base line
19227 consists of the number one followed by a tic mark.
19228
19229 @node print-Y-axis Penultimate, , Y-axis-column, print-Y-axis
19230 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19231
19232 The list constructed by the @code{Y-axis-column} function is passed to
19233 the @code{print-Y-axis} function, which inserts the list as a column.
19234
19235 @findex print-Y-axis
19236 @smallexample
19237 @group
19238 (defun print-Y-axis (height full-Y-label-width)
19239 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19240 Height must be the maximum height of the graph.
19241 Full width is the width of the highest label element."
19242 ;; Value of height and full-Y-label-width
19243 ;; are passed by `print-graph'.
19244 @end group
19245 @group
19246 (let ((start (point)))
19247 (insert-rectangle
19248 (Y-axis-column height full-Y-label-width))
19249 ;; @r{Place point ready for inserting graph.}
19250 (goto-char start)
19251 ;; @r{Move point forward by value of} full-Y-label-width
19252 (forward-char full-Y-label-width)))
19253 @end group
19254 @end smallexample
19255
19256 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19257 insert the Y axis labels created by the @code{Y-axis-column} function.
19258 In addition, it places point at the correct position for printing the body of
19259 the graph.
19260
19261 You can test @code{print-Y-axis}:
19262
19263 @enumerate
19264 @item
19265 Install
19266
19267 @smallexample
19268 @group
19269 Y-axis-label-spacing
19270 Y-axis-tic
19271 Y-axis-element
19272 Y-axis-column
19273 print-Y-axis
19274 @end group
19275 @end smallexample
19276
19277 @item
19278 Copy the following expression:
19279
19280 @smallexample
19281 (print-Y-axis 12 5)
19282 @end smallexample
19283
19284 @item
19285 Switch to the @file{*scratch*} buffer and place the cursor where you
19286 want the axis labels to start.
19287
19288 @item
19289 Type @kbd{M-:} (@code{eval-expression}).
19290
19291 @item
19292 Yank the @code{graph-body-print} expression into the minibuffer
19293 with @kbd{C-y} (@code{yank)}.
19294
19295 @item
19296 Press @key{RET} to evaluate the expression.
19297 @end enumerate
19298
19299 Emacs will print labels vertically, the top one being
19300 @w{@samp{10 -@w{ }}}. (The @code{print-graph} function
19301 will pass the value of @code{height-of-top-line}, which
19302 in this case would end up as 15.)
19303
19304 @node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19305 @appendixsec The @code{print-X-axis} Function
19306 @cindex Axis, print horizontal
19307 @cindex X axis printing
19308 @cindex Print horizontal axis
19309 @cindex Horizontal axis printing
19310
19311 X axis labels are much like Y axis labels, except that the tics are on a
19312 line above the numbers. Labels should look like this:
19313
19314 @smallexample
19315 @group
19316 | | | |
19317 1 5 10 15
19318 @end group
19319 @end smallexample
19320
19321 The first tic is under the first column of the graph and is preceded by
19322 several blank spaces. These spaces provide room in rows above for the Y
19323 axis labels. The second, third, fourth, and subsequent tics are all
19324 spaced equally, according to the value of @code{X-axis-label-spacing}.
19325
19326 The second row of the X axis consists of numbers, preceded by several
19327 blank spaces and also separated according to the value of the variable
19328 @code{X-axis-label-spacing}.
19329
19330 The value of the variable @code{X-axis-label-spacing} should itself be
19331 measured in units of @code{symbol-width}, since you may want to change
19332 the width of the symbols that you are using to print the body of the
19333 graph without changing the ways the graph is labelled.
19334
19335 @menu
19336 * Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
19337 * X Axis Tic Marks:: Create tic marks for the horizontal axis.
19338 @end menu
19339
19340 @node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19341 @ifnottex
19342 @unnumberedsubsec Similarities and differences
19343 @end ifnottex
19344
19345 The @code{print-X-axis} function is constructed in more or less the
19346 same fashion as the @code{print-Y-axis} function except that it has
19347 two lines: the line of tic marks and the numbers. We will write a
19348 separate function to print each line and then combine them within the
19349 @code{print-X-axis} function.
19350
19351 This is a three step process:
19352
19353 @enumerate
19354 @item
19355 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19356
19357 @item
19358 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19359
19360 @item
19361 Write a function to print both lines, the @code{print-X-axis} function,
19362 using @code{print-X-axis-tic-line} and
19363 @code{print-X-axis-numbered-line}.
19364 @end enumerate
19365
19366 @node X Axis Tic Marks, , Similarities differences, print-X-axis
19367 @appendixsubsec X Axis Tic Marks
19368
19369 The first function should print the X axis tic marks. We must specify
19370 the tic marks themselves and their spacing:
19371
19372 @smallexample
19373 @group
19374 (defvar X-axis-label-spacing
19375 (if (boundp 'graph-blank)
19376 (* 5 (length graph-blank)) 5)
19377 "Number of units from one X axis label to next.")
19378 @end group
19379 @end smallexample
19380
19381 @noindent
19382 (Note that the value of @code{graph-blank} is set by another
19383 @code{defvar}. The @code{boundp} predicate checks whether it has
19384 already been set; @code{boundp} returns @code{nil} if it has not.
19385 If @code{graph-blank} were unbound and we did not use this conditional
19386 construction, in GNU Emacs 21, we would enter the debugger and see an
19387 error message saying
19388 @samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19389
19390 @need 1200
19391 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19392
19393 @smallexample
19394 @group
19395 (defvar X-axis-tic-symbol "|"
19396 "String to insert to point to a column in X axis.")
19397 @end group
19398 @end smallexample
19399
19400 @need 1250
19401 The goal is to make a line that looks like this:
19402
19403 @smallexample
19404 | | | |
19405 @end smallexample
19406
19407 The first tic is indented so that it is under the first column, which is
19408 indented to provide space for the Y axis labels.
19409
19410 A tic element consists of the blank spaces that stretch from one tic to
19411 the next plus a tic symbol. The number of blanks is determined by the
19412 width of the tic symbol and the @code{X-axis-label-spacing}.
19413
19414 @need 1250
19415 The code looks like this:
19416
19417 @smallexample
19418 @group
19419 ;;; X-axis-tic-element
19420 @dots{}
19421 (concat
19422 (make-string
19423 ;; @r{Make a string of blanks.}
19424 (- (* symbol-width X-axis-label-spacing)
19425 (length X-axis-tic-symbol))
19426 ? )
19427 ;; @r{Concatenate blanks with tic symbol.}
19428 X-axis-tic-symbol)
19429 @dots{}
19430 @end group
19431 @end smallexample
19432
19433 Next, we determine how many blanks are needed to indent the first tic
19434 mark to the first column of the graph. This uses the value of
19435 @code{full-Y-label-width} passed it by the @code{print-graph} function.
19436
19437 @need 1250
19438 The code to make @code{X-axis-leading-spaces}
19439 looks like this:
19440
19441 @smallexample
19442 @group
19443 ;; X-axis-leading-spaces
19444 @dots{}
19445 (make-string full-Y-label-width ? )
19446 @dots{}
19447 @end group
19448 @end smallexample
19449
19450 We also need to determine the length of the horizontal axis, which is
19451 the length of the numbers list, and the number of tics in the horizontal
19452 axis:
19453
19454 @smallexample
19455 @group
19456 ;; X-length
19457 @dots{}
19458 (length numbers-list)
19459 @end group
19460
19461 @group
19462 ;; tic-width
19463 @dots{}
19464 (* symbol-width X-axis-label-spacing)
19465 @end group
19466
19467 @group
19468 ;; number-of-X-tics
19469 (if (zerop (% (X-length tic-width)))
19470 (/ (X-length tic-width))
19471 (1+ (/ (X-length tic-width))))
19472 @end group
19473 @end smallexample
19474
19475 @need 1250
19476 All this leads us directly to the function for printing the X axis tic line:
19477
19478 @findex print-X-axis-tic-line
19479 @smallexample
19480 @group
19481 (defun print-X-axis-tic-line
19482 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19483 "Print tics for X axis."
19484 (insert X-axis-leading-spaces)
19485 (insert X-axis-tic-symbol) ; @r{Under first column.}
19486 @end group
19487 @group
19488 ;; @r{Insert second tic in the right spot.}
19489 (insert (concat
19490 (make-string
19491 (- (* symbol-width X-axis-label-spacing)
19492 ;; @r{Insert white space up to second tic symbol.}
19493 (* 2 (length X-axis-tic-symbol)))
19494 ? )
19495 X-axis-tic-symbol))
19496 @end group
19497 @group
19498 ;; @r{Insert remaining tics.}
19499 (while (> number-of-X-tics 1)
19500 (insert X-axis-tic-element)
19501 (setq number-of-X-tics (1- number-of-X-tics))))
19502 @end group
19503 @end smallexample
19504
19505 The line of numbers is equally straightforward:
19506
19507 @need 1250
19508 First, we create a numbered element with blank spaces before each number:
19509
19510 @findex X-axis-element
19511 @smallexample
19512 @group
19513 (defun X-axis-element (number)
19514 "Construct a numbered X axis element."
19515 (let ((leading-spaces
19516 (- (* symbol-width X-axis-label-spacing)
19517 (length (number-to-string number)))))
19518 (concat (make-string leading-spaces ? )
19519 (number-to-string number))))
19520 @end group
19521 @end smallexample
19522
19523 Next, we create the function to print the numbered line, starting with
19524 the number ``1'' under the first column:
19525
19526 @findex print-X-axis-numbered-line
19527 @smallexample
19528 @group
19529 (defun print-X-axis-numbered-line
19530 (number-of-X-tics X-axis-leading-spaces)
19531 "Print line of X-axis numbers"
19532 (let ((number X-axis-label-spacing))
19533 (insert X-axis-leading-spaces)
19534 (insert "1")
19535 @end group
19536 @group
19537 (insert (concat
19538 (make-string
19539 ;; @r{Insert white space up to next number.}
19540 (- (* symbol-width X-axis-label-spacing) 2)
19541 ? )
19542 (number-to-string number)))
19543 @end group
19544 @group
19545 ;; @r{Insert remaining numbers.}
19546 (setq number (+ number X-axis-label-spacing))
19547 (while (> number-of-X-tics 1)
19548 (insert (X-axis-element number))
19549 (setq number (+ number X-axis-label-spacing))
19550 (setq number-of-X-tics (1- number-of-X-tics)))))
19551 @end group
19552 @end smallexample
19553
19554 Finally, we need to write the @code{print-X-axis} that uses
19555 @code{print-X-axis-tic-line} and
19556 @code{print-X-axis-numbered-line}.
19557
19558 The function must determine the local values of the variables used by both
19559 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19560 then it must call them. Also, it must print the carriage return that
19561 separates the two lines.
19562
19563 The function consists of a varlist that specifies five local variables,
19564 and calls to each of the two line printing functions:
19565
19566 @findex print-X-axis
19567 @smallexample
19568 @group
19569 (defun print-X-axis (numbers-list)
19570 "Print X axis labels to length of NUMBERS-LIST."
19571 (let* ((leading-spaces
19572 (make-string full-Y-label-width ? ))
19573 @end group
19574 @group
19575 ;; symbol-width @r{is provided by} graph-body-print
19576 (tic-width (* symbol-width X-axis-label-spacing))
19577 (X-length (length numbers-list))
19578 @end group
19579 @group
19580 (X-tic
19581 (concat
19582 (make-string
19583 @end group
19584 @group
19585 ;; @r{Make a string of blanks.}
19586 (- (* symbol-width X-axis-label-spacing)
19587 (length X-axis-tic-symbol))
19588 ? )
19589 @end group
19590 @group
19591 ;; @r{Concatenate blanks with tic symbol.}
19592 X-axis-tic-symbol))
19593 @end group
19594 @group
19595 (tic-number
19596 (if (zerop (% X-length tic-width))
19597 (/ X-length tic-width)
19598 (1+ (/ X-length tic-width)))))
19599 @end group
19600 @group
19601 (print-X-axis-tic-line tic-number leading-spaces X-tic)
19602 (insert "\n")
19603 (print-X-axis-numbered-line tic-number leading-spaces)))
19604 @end group
19605 @end smallexample
19606
19607 @need 1250
19608 You can test @code{print-X-axis}:
19609
19610 @enumerate
19611 @item
19612 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19613 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19614 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19615
19616 @item
19617 Copy the following expression:
19618
19619 @smallexample
19620 @group
19621 (progn
19622 (let ((full-Y-label-width 5)
19623 (symbol-width 1))
19624 (print-X-axis
19625 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19626 @end group
19627 @end smallexample
19628
19629 @item
19630 Switch to the @file{*scratch*} buffer and place the cursor where you
19631 want the axis labels to start.
19632
19633 @item
19634 Type @kbd{M-:} (@code{eval-expression}).
19635
19636 @item
19637 Yank the test expression into the minibuffer
19638 with @kbd{C-y} (@code{yank)}.
19639
19640 @item
19641 Press @key{RET} to evaluate the expression.
19642 @end enumerate
19643
19644 @need 1250
19645 Emacs will print the horizontal axis like this:
19646
19647 @smallexample
19648 @group
19649 | | | | |
19650 1 5 10 15 20
19651 @end group
19652 @end smallexample
19653
19654 @node Print Whole Graph, , print-X-axis, Full Graph
19655 @appendixsec Printing the Whole Graph
19656 @cindex Printing the whole graph
19657 @cindex Whole graph printing
19658 @cindex Graph, printing all
19659
19660 Now we are nearly ready to print the whole graph.
19661
19662 The function to print the graph with the proper labels follows the
19663 outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19664 Axes}), but with additions.
19665
19666 @need 1250
19667 Here is the outline:
19668
19669 @smallexample
19670 @group
19671 (defun print-graph (numbers-list)
19672 "@var{documentation}@dots{}"
19673 (let ((height @dots{}
19674 @dots{}))
19675 @end group
19676 @group
19677 (print-Y-axis height @dots{} )
19678 (graph-body-print numbers-list)
19679 (print-X-axis @dots{} )))
19680 @end group
19681 @end smallexample
19682
19683 @menu
19684 * The final version:: A few changes.
19685 * Test print-graph:: Run a short test.
19686 * Graphing words in defuns:: Executing the final code.
19687 * lambda:: How to write an anonymous function.
19688 * mapcar:: Apply a function to elements of a list.
19689 * Another Bug:: Yet another bug @dots{} most insidious.
19690 * Final printed graph:: The graph itself!
19691 @end menu
19692
19693 @node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19694 @ifnottex
19695 @unnumberedsubsec Changes for the Final Version
19696 @end ifnottex
19697
19698 The final version is different from what we planned in two ways:
19699 first, it contains additional values calculated once in the varlist;
19700 second, it carries an option to specify the labels' increment per row.
19701 This latter feature turns out to be essential; otherwise, a graph may
19702 have more rows than fit on a display or on a sheet of paper.
19703
19704 @need 1500
19705 This new feature requires a change to the @code{Y-axis-column}
19706 function, to add @code{vertical-step} to it. The function looks like
19707 this:
19708
19709 @findex Y-axis-column @r{Final version.}
19710 @smallexample
19711 @group
19712 ;;; @r{Final version.}
19713 (defun Y-axis-column
19714 (height width-of-label &optional vertical-step)
19715 "Construct list of labels for Y axis.
19716 HEIGHT is maximum height of graph.
19717 WIDTH-OF-LABEL is maximum width of label.
19718 VERTICAL-STEP, an option, is a positive integer
19719 that specifies how much a Y axis label increments
19720 for each line. For example, a step of 5 means
19721 that each line is five units of the graph."
19722 @end group
19723 @group
19724 (let (Y-axis
19725 (number-per-line (or vertical-step 1)))
19726 (while (> height 1)
19727 (if (zerop (% height Y-axis-label-spacing))
19728 @end group
19729 @group
19730 ;; @r{Insert label.}
19731 (setq Y-axis
19732 (cons
19733 (Y-axis-element
19734 (* height number-per-line)
19735 width-of-label)
19736 Y-axis))
19737 @end group
19738 @group
19739 ;; @r{Else, insert blanks.}
19740 (setq Y-axis
19741 (cons
19742 (make-string width-of-label ? )
19743 Y-axis)))
19744 (setq height (1- height)))
19745 @end group
19746 @group
19747 ;; @r{Insert base line.}
19748 (setq Y-axis (cons (Y-axis-element
19749 (or vertical-step 1)
19750 width-of-label)
19751 Y-axis))
19752 (nreverse Y-axis)))
19753 @end group
19754 @end smallexample
19755
19756 The values for the maximum height of graph and the width of a symbol
19757 are computed by @code{print-graph} in its @code{let} expression; so
19758 @code{graph-body-print} must be changed to accept them.
19759
19760 @findex graph-body-print @r{Final version.}
19761 @smallexample
19762 @group
19763 ;;; @r{Final version.}
19764 (defun graph-body-print (numbers-list height symbol-width)
19765 "Print a bar graph of the NUMBERS-LIST.
19766 The numbers-list consists of the Y-axis values.
19767 HEIGHT is maximum height of graph.
19768 SYMBOL-WIDTH is number of each column."
19769 @end group
19770 @group
19771 (let (from-position)
19772 (while numbers-list
19773 (setq from-position (point))
19774 (insert-rectangle
19775 (column-of-graph height (car numbers-list)))
19776 (goto-char from-position)
19777 (forward-char symbol-width)
19778 @end group
19779 @group
19780 ;; @r{Draw graph column by column.}
19781 (sit-for 0)
19782 (setq numbers-list (cdr numbers-list)))
19783 ;; @r{Place point for X axis labels.}
19784 (forward-line height)
19785 (insert "\n")))
19786 @end group
19787 @end smallexample
19788
19789 @need 1250
19790 Finally, the code for the @code{print-graph} function:
19791
19792 @findex print-graph @r{Final version.}
19793 @smallexample
19794 @group
19795 ;;; @r{Final version.}
19796 (defun print-graph
19797 (numbers-list &optional vertical-step)
19798 "Print labelled bar graph of the NUMBERS-LIST.
19799 The numbers-list consists of the Y-axis values.
19800 @end group
19801
19802 @group
19803 Optionally, VERTICAL-STEP, a positive integer,
19804 specifies how much a Y axis label increments for
19805 each line. For example, a step of 5 means that
19806 each row is five units."
19807 @end group
19808 @group
19809 (let* ((symbol-width (length graph-blank))
19810 ;; @code{height} @r{is both the largest number}
19811 ;; @r{and the number with the most digits.}
19812 (height (apply 'max numbers-list))
19813 @end group
19814 @group
19815 (height-of-top-line
19816 (if (zerop (% height Y-axis-label-spacing))
19817 height
19818 ;; @r{else}
19819 (* (1+ (/ height Y-axis-label-spacing))
19820 Y-axis-label-spacing)))
19821 @end group
19822 @group
19823 (vertical-step (or vertical-step 1))
19824 (full-Y-label-width
19825 (length
19826 @end group
19827 @group
19828 (concat
19829 (number-to-string
19830 (* height-of-top-line vertical-step))
19831 Y-axis-tic))))
19832 @end group
19833
19834 @group
19835 (print-Y-axis
19836 height-of-top-line full-Y-label-width vertical-step)
19837 @end group
19838 @group
19839 (graph-body-print
19840 numbers-list height-of-top-line symbol-width)
19841 (print-X-axis numbers-list)))
19842 @end group
19843 @end smallexample
19844
19845 @node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
19846 @appendixsubsec Testing @code{print-graph}
19847
19848 @need 1250
19849 We can test the @code{print-graph} function with a short list of numbers:
19850
19851 @enumerate
19852 @item
19853 Install the final versions of @code{Y-axis-column},
19854 @code{graph-body-print}, and @code{print-graph} (in addition to the
19855 rest of the code.)
19856
19857 @item
19858 Copy the following expression:
19859
19860 @smallexample
19861 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
19862 @end smallexample
19863
19864 @item
19865 Switch to the @file{*scratch*} buffer and place the cursor where you
19866 want the axis labels to start.
19867
19868 @item
19869 Type @kbd{M-:} (@code{eval-expression}).
19870
19871 @item
19872 Yank the test expression into the minibuffer
19873 with @kbd{C-y} (@code{yank)}.
19874
19875 @item
19876 Press @key{RET} to evaluate the expression.
19877 @end enumerate
19878
19879 @need 1250
19880 Emacs will print a graph that looks like this:
19881
19882 @smallexample
19883 @group
19884 10 -
19885
19886
19887 *
19888 ** *
19889 5 - **** *
19890 **** ***
19891 * *********
19892 ************
19893 1 - *************
19894
19895 | | | |
19896 1 5 10 15
19897 @end group
19898 @end smallexample
19899
19900 On the other hand, if you pass @code{print-graph} a
19901 @code{vertical-step} value of 2, by evaluating this expression:
19902
19903 @smallexample
19904 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
19905 @end smallexample
19906
19907 @need 1250
19908 @noindent
19909 The graph looks like this:
19910
19911 @smallexample
19912 @group
19913 20 -
19914
19915
19916 *
19917 ** *
19918 10 - **** *
19919 **** ***
19920 * *********
19921 ************
19922 2 - *************
19923
19924 | | | |
19925 1 5 10 15
19926 @end group
19927 @end smallexample
19928
19929 @noindent
19930 (A question: is the `2' on the bottom of the vertical axis a bug or a
19931 feature? If you think it is a bug, and should be a `1' instead, (or
19932 even a `0'), you can modify the sources.)
19933
19934 @node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
19935 @appendixsubsec Graphing Numbers of Words and Symbols
19936
19937 Now for the graph for which all this code was written: a graph that
19938 shows how many function definitions contain fewer than 10 words and
19939 symbols, how many contain between 10 and 19 words and symbols, how
19940 many contain between 20 and 29 words and symbols, and so on.
19941
19942 This is a multi-step process. First make sure you have loaded all the
19943 requisite code.
19944
19945 @need 1500
19946 It is a good idea to reset the value of @code{top-of-ranges} in case
19947 you have set it to some different value. You can evaluate the
19948 following:
19949
19950 @smallexample
19951 @group
19952 (setq top-of-ranges
19953 '(10 20 30 40 50
19954 60 70 80 90 100
19955 110 120 130 140 150
19956 160 170 180 190 200
19957 210 220 230 240 250
19958 260 270 280 290 300)
19959 @end group
19960 @end smallexample
19961
19962 @noindent
19963 Next create a list of the number of words and symbols in each range.
19964
19965 @need 1500
19966 @noindent
19967 Evaluate the following:
19968
19969 @smallexample
19970 @group
19971 (setq list-for-graph
19972 (defuns-per-range
19973 (sort
19974 (recursive-lengths-list-many-files
19975 (directory-files "/usr/local/emacs/lisp"
19976 t ".+el$"))
19977 '<)
19978 top-of-ranges))
19979 @end group
19980 @end smallexample
19981
19982 @noindent
19983 On my machine, this takes about an hour. It looks though 303 Lisp
19984 files in my copy of Emacs version 19.23. After all that computing,
19985 the @code{list-for-graph} has this value:
19986
19987 @smallexample
19988 @group
19989 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
19990 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
19991 @end group
19992 @end smallexample
19993
19994 @noindent
19995 This means that my copy of Emacs has 537 function definitions with
19996 fewer than 10 words or symbols in them, 1,027 function definitions
19997 with 10 to 19 words or symbols in them, 955 function definitions with
19998 20 to 29 words or symbols in them, and so on.
19999
20000 Clearly, just by looking at this list we can see that most function
20001 definitions contain ten to thirty words and symbols.
20002
20003 Now for printing. We do @emph{not} want to print a graph that is
20004 1,030 lines high @dots{} Instead, we should print a graph that is
20005 fewer than twenty-five lines high. A graph that height can be
20006 displayed on almost any monitor, and easily printed on a sheet of paper.
20007
20008 This means that each value in @code{list-for-graph} must be reduced to
20009 one-fiftieth its present value.
20010
20011 Here is a short function to do just that, using two functions we have
20012 not yet seen, @code{mapcar} and @code{lambda}.
20013
20014 @smallexample
20015 @group
20016 (defun one-fiftieth (full-range)
20017 "Return list, each number one-fiftieth of previous."
20018 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20019 @end group
20020 @end smallexample
20021
20022 @node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20023 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20024 @cindex Anonymous function
20025 @findex lambda
20026
20027 @code{lambda} is the symbol for an anonymous function, a function
20028 without a name. Every time you use an anonymous function, you need to
20029 include its whole body.
20030
20031 @need 1250
20032 @noindent
20033 Thus,
20034
20035 @smallexample
20036 (lambda (arg) (/ arg 50))
20037 @end smallexample
20038
20039 @noindent
20040 is a function definition that says `return the value resulting from
20041 dividing whatever is passed to me as @code{arg} by 50'.
20042
20043 Earlier, for example, we had a function @code{multiply-by-seven}; it
20044 multiplied its argument by 7. This function is similar, except it
20045 divides its argument by 50; and, it has no name. The anonymous
20046 equivalent of @code{multiply-by-seven} is:
20047
20048 @smallexample
20049 (lambda (number) (* 7 number))
20050 @end smallexample
20051
20052 @noindent
20053 (@xref{defun, , The @code{defun} Special Form}.)
20054
20055 @need 1250
20056 @noindent
20057 If we want to multiply 3 by 7, we can write:
20058
20059 @c !!! Clear print-postscript-figures if the computer formatting this
20060 @c document is too small and cannot handle all the diagrams and figures.
20061 @c clear print-postscript-figures
20062 @c set print-postscript-figures
20063 @c lambda example diagram #1
20064 @ifnottex
20065 @smallexample
20066 @group
20067 (multiply-by-seven 3)
20068 \_______________/ ^
20069 | |
20070 function argument
20071 @end group
20072 @end smallexample
20073 @end ifnottex
20074 @ifset print-postscript-figures
20075 @sp 1
20076 @tex
20077 @image{lambda-1}
20078 %%%% old method of including an image
20079 % \input /usr/local/lib/tex/inputs/psfig.tex
20080 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20081 % \catcode`\@=0 %
20082 @end tex
20083 @sp 1
20084 @end ifset
20085 @ifclear print-postscript-figures
20086 @iftex
20087 @smallexample
20088 @group
20089 (multiply-by-seven 3)
20090 \_______________/ ^
20091 | |
20092 function argument
20093 @end group
20094 @end smallexample
20095 @end iftex
20096 @end ifclear
20097
20098 @noindent
20099 This expression returns 21.
20100
20101 @need 1250
20102 @noindent
20103 Similarly, we can write:
20104
20105 @c lambda example diagram #2
20106 @ifnottex
20107 @smallexample
20108 @group
20109 ((lambda (number) (* 7 number)) 3)
20110 \____________________________/ ^
20111 | |
20112 anonymous function argument
20113 @end group
20114 @end smallexample
20115 @end ifnottex
20116 @ifset print-postscript-figures
20117 @sp 1
20118 @tex
20119 @image{lambda-2}
20120 %%%% old method of including an image
20121 % \input /usr/local/lib/tex/inputs/psfig.tex
20122 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20123 % \catcode`\@=0 %
20124 @end tex
20125 @sp 1
20126 @end ifset
20127 @ifclear print-postscript-figures
20128 @iftex
20129 @smallexample
20130 @group
20131 ((lambda (number) (* 7 number)) 3)
20132 \____________________________/ ^
20133 | |
20134 anonymous function argument
20135 @end group
20136 @end smallexample
20137 @end iftex
20138 @end ifclear
20139
20140 @need 1250
20141 @noindent
20142 If we want to divide 100 by 50, we can write:
20143
20144 @c lambda example diagram #3
20145 @ifnottex
20146 @smallexample
20147 @group
20148 ((lambda (arg) (/ arg 50)) 100)
20149 \______________________/ \_/
20150 | |
20151 anonymous function argument
20152 @end group
20153 @end smallexample
20154 @end ifnottex
20155 @ifset print-postscript-figures
20156 @sp 1
20157 @tex
20158 @image{lambda-3}
20159 %%%% old method of including an image
20160 % \input /usr/local/lib/tex/inputs/psfig.tex
20161 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20162 % \catcode`\@=0 %
20163 @end tex
20164 @sp 1
20165 @end ifset
20166 @ifclear print-postscript-figures
20167 @iftex
20168 @smallexample
20169 @group
20170 ((lambda (arg) (/ arg 50)) 100)
20171 \______________________/ \_/
20172 | |
20173 anonymous function argument
20174 @end group
20175 @end smallexample
20176 @end iftex
20177 @end ifclear
20178
20179 @noindent
20180 This expression returns 2. The 100 is passed to the function, which
20181 divides that number by 50.
20182
20183 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20184 Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
20185 expressions derive from the Lambda Calculus.
20186
20187 @node mapcar, Another Bug, lambda, Print Whole Graph
20188 @appendixsubsec The @code{mapcar} Function
20189 @findex mapcar
20190
20191 @code{mapcar} is a function that calls its first argument with each
20192 element of its second argument, in turn. The second argument must be
20193 a sequence.
20194
20195 The @samp{map} part of the name comes from the mathematical phrase,
20196 `mapping over a domain', meaning to apply a function to each of the
20197 elements in a domain. The mathematical phrase is based on the
20198 metaphor of a surveyor walking, one step at a time, over an area he is
20199 mapping. And @samp{car}, of course, comes from the Lisp notion of the
20200 first of a list.
20201
20202 @need 1250
20203 @noindent
20204 For example,
20205
20206 @smallexample
20207 @group
20208 (mapcar '1+ '(2 4 6))
20209 @result{} (3 5 7)
20210 @end group
20211 @end smallexample
20212
20213 @noindent
20214 The function @code{1+} which adds one to its argument, is executed on
20215 @emph{each} element of the list, and a new list is returned.
20216
20217 Contrast this with @code{apply}, which applies its first argument to
20218 all the remaining.
20219 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20220 @code{apply}.)
20221
20222 @need 1250
20223 In the definition of @code{one-fiftieth}, the first argument is the
20224 anonymous function:
20225
20226 @smallexample
20227 (lambda (arg) (/ arg 50))
20228 @end smallexample
20229
20230 @noindent
20231 and the second argument is @code{full-range}, which will be bound to
20232 @code{list-for-graph}.
20233
20234 @need 1250
20235 The whole expression looks like this:
20236
20237 @smallexample
20238 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20239 @end smallexample
20240
20241 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20242 Lisp Reference Manual}, for more about @code{mapcar}.
20243
20244 Using the @code{one-fiftieth} function, we can generate a list in
20245 which each element is one-fiftieth the size of the corresponding
20246 element in @code{list-for-graph}.
20247
20248 @smallexample
20249 @group
20250 (setq fiftieth-list-for-graph
20251 (one-fiftieth list-for-graph))
20252 @end group
20253 @end smallexample
20254
20255 @need 1250
20256 The resulting list looks like this:
20257
20258 @smallexample
20259 @group
20260 (10 20 19 15 11 9 6 5 4 3 3 2 2
20261 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20262 @end group
20263 @end smallexample
20264
20265 @noindent
20266 This, we are almost ready to print! (We also notice the loss of
20267 information: many of the higher ranges are 0, meaning that fewer than
20268 50 defuns had that many words or symbols---but not necessarily meaning
20269 that none had that many words or symbols.)
20270
20271 @node Another Bug, Final printed graph, mapcar, Print Whole Graph
20272 @appendixsubsec Another Bug @dots{} Most Insidious
20273 @cindex Bug, most insidious type
20274 @cindex Insidious type of bug
20275
20276 I said `almost ready to print'! Of course, there is a bug in the
20277 @code{print-graph} function @dots{} It has a @code{vertical-step}
20278 option, but not a @code{horizontal-step} option. The
20279 @code{top-of-range} scale goes from 10 to 300 by tens. But the
20280 @code{print-graph} function will print only by ones.
20281
20282 This is a classic example of what some consider the most insidious
20283 type of bug, the bug of omission. This is not the kind of bug you can
20284 find by studying the code, for it is not in the code; it is an omitted
20285 feature. Your best actions are to try your program early and often;
20286 and try to arrange, as much as you can, to write code that is easy to
20287 understand and easy to change. Try to be aware, whenever you can,
20288 that whatever you have written, @emph{will} be rewritten, if not soon,
20289 eventually. A hard maxim to follow.
20290
20291 It is the @code{print-X-axis-numbered-line} function that needs the
20292 work; and then the @code{print-X-axis} and the @code{print-graph}
20293 functions need to be adapted. Not much needs to be done; there is one
20294 nicety: the numbers ought to line up under the tic marks. This takes
20295 a little thought.
20296
20297 @need 1250
20298 Here is the corrected @code{print-X-axis-numbered-line}:
20299
20300 @smallexample
20301 @group
20302 (defun print-X-axis-numbered-line
20303 (number-of-X-tics X-axis-leading-spaces
20304 &optional horizontal-step)
20305 "Print line of X-axis numbers"
20306 (let ((number X-axis-label-spacing)
20307 (horizontal-step (or horizontal-step 1)))
20308 @end group
20309 @group
20310 (insert X-axis-leading-spaces)
20311 ;; @r{Delete extra leading spaces.}
20312 (delete-char
20313 (- (1-
20314 (length (number-to-string horizontal-step)))))
20315 (insert (concat
20316 (make-string
20317 @end group
20318 @group
20319 ;; @r{Insert white space.}
20320 (- (* symbol-width
20321 X-axis-label-spacing)
20322 (1-
20323 (length
20324 (number-to-string horizontal-step)))
20325 2)
20326 ? )
20327 (number-to-string
20328 (* number horizontal-step))))
20329 @end group
20330 @group
20331 ;; @r{Insert remaining numbers.}
20332 (setq number (+ number X-axis-label-spacing))
20333 (while (> number-of-X-tics 1)
20334 (insert (X-axis-element
20335 (* number horizontal-step)))
20336 (setq number (+ number X-axis-label-spacing))
20337 (setq number-of-X-tics (1- number-of-X-tics)))))
20338 @end group
20339 @end smallexample
20340
20341 @need 1500
20342 If you are reading this in Info, you can see the new versions of
20343 @code{print-X-axis} @code{print-graph} and evaluate them. If you are
20344 reading this in a printed book, you can see the changed lines here
20345 (the full text is too much to print).
20346
20347 @iftex
20348 @smallexample
20349 @group
20350 (defun print-X-axis (numbers-list horizontal-step)
20351 @dots{}
20352 (print-X-axis-numbered-line
20353 tic-number leading-spaces horizontal-step))
20354 @end group
20355 @end smallexample
20356
20357 @smallexample
20358 @group
20359 (defun print-graph
20360 (numbers-list
20361 &optional vertical-step horizontal-step)
20362 @dots{}
20363 (print-X-axis numbers-list horizontal-step))
20364 @end group
20365 @end smallexample
20366 @end iftex
20367
20368 @ifnottex
20369 @smallexample
20370 @group
20371 (defun print-X-axis (numbers-list horizontal-step)
20372 "Print X axis labels to length of NUMBERS-LIST.
20373 Optionally, HORIZONTAL-STEP, a positive integer,
20374 specifies how much an X axis label increments for
20375 each column."
20376 @end group
20377 @group
20378 ;; Value of symbol-width and full-Y-label-width
20379 ;; are passed by `print-graph'.
20380 (let* ((leading-spaces
20381 (make-string full-Y-label-width ? ))
20382 ;; symbol-width @r{is provided by} graph-body-print
20383 (tic-width (* symbol-width X-axis-label-spacing))
20384 (X-length (length numbers-list))
20385 @end group
20386 @group
20387 (X-tic
20388 (concat
20389 (make-string
20390 ;; @r{Make a string of blanks.}
20391 (- (* symbol-width X-axis-label-spacing)
20392 (length X-axis-tic-symbol))
20393 ? )
20394 @end group
20395 @group
20396 ;; @r{Concatenate blanks with tic symbol.}
20397 X-axis-tic-symbol))
20398 (tic-number
20399 (if (zerop (% X-length tic-width))
20400 (/ X-length tic-width)
20401 (1+ (/ X-length tic-width)))))
20402 @end group
20403
20404 @group
20405 (print-X-axis-tic-line
20406 tic-number leading-spaces X-tic)
20407 (insert "\n")
20408 (print-X-axis-numbered-line
20409 tic-number leading-spaces horizontal-step)))
20410 @end group
20411 @end smallexample
20412
20413 @smallexample
20414 @group
20415 (defun print-graph
20416 (numbers-list &optional vertical-step horizontal-step)
20417 "Print labelled bar graph of the NUMBERS-LIST.
20418 The numbers-list consists of the Y-axis values.
20419 @end group
20420
20421 @group
20422 Optionally, VERTICAL-STEP, a positive integer,
20423 specifies how much a Y axis label increments for
20424 each line. For example, a step of 5 means that
20425 each row is five units.
20426 @end group
20427
20428 @group
20429 Optionally, HORIZONTAL-STEP, a positive integer,
20430 specifies how much an X axis label increments for
20431 each column."
20432 (let* ((symbol-width (length graph-blank))
20433 ;; @code{height} @r{is both the largest number}
20434 ;; @r{and the number with the most digits.}
20435 (height (apply 'max numbers-list))
20436 @end group
20437 @group
20438 (height-of-top-line
20439 (if (zerop (% height Y-axis-label-spacing))
20440 height
20441 ;; @r{else}
20442 (* (1+ (/ height Y-axis-label-spacing))
20443 Y-axis-label-spacing)))
20444 @end group
20445 @group
20446 (vertical-step (or vertical-step 1))
20447 (full-Y-label-width
20448 (length
20449 (concat
20450 (number-to-string
20451 (* height-of-top-line vertical-step))
20452 Y-axis-tic))))
20453 @end group
20454 @group
20455 (print-Y-axis
20456 height-of-top-line full-Y-label-width vertical-step)
20457 (graph-body-print
20458 numbers-list height-of-top-line symbol-width)
20459 (print-X-axis numbers-list horizontal-step)))
20460 @end group
20461 @end smallexample
20462 @end ifnottex
20463
20464 @ignore
20465 Graphing Definitions Re-listed
20466
20467 @need 1250
20468 Here are all the graphing definitions in their final form:
20469
20470 @smallexample
20471 @group
20472 (defvar top-of-ranges
20473 '(10 20 30 40 50
20474 60 70 80 90 100
20475 110 120 130 140 150
20476 160 170 180 190 200
20477 210 220 230 240 250)
20478 "List specifying ranges for `defuns-per-range'.")
20479 @end group
20480
20481 @group
20482 (defvar graph-symbol "*"
20483 "String used as symbol in graph, usually an asterisk.")
20484 @end group
20485
20486 @group
20487 (defvar graph-blank " "
20488 "String used as blank in graph, usually a blank space.
20489 graph-blank must be the same number of columns wide
20490 as graph-symbol.")
20491 @end group
20492
20493 @group
20494 (defvar Y-axis-tic " - "
20495 "String that follows number in a Y axis label.")
20496 @end group
20497
20498 @group
20499 (defvar Y-axis-label-spacing 5
20500 "Number of lines from one Y axis label to next.")
20501 @end group
20502
20503 @group
20504 (defvar X-axis-tic-symbol "|"
20505 "String to insert to point to a column in X axis.")
20506 @end group
20507
20508 @group
20509 (defvar X-axis-label-spacing
20510 (if (boundp 'graph-blank)
20511 (* 5 (length graph-blank)) 5)
20512 "Number of units from one X axis label to next.")
20513 @end group
20514 @end smallexample
20515
20516 @smallexample
20517 @group
20518 (defun count-words-in-defun ()
20519 "Return the number of words and symbols in a defun."
20520 (beginning-of-defun)
20521 (let ((count 0)
20522 (end (save-excursion (end-of-defun) (point))))
20523 @end group
20524
20525 @group
20526 (while
20527 (and (< (point) end)
20528 (re-search-forward
20529 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20530 end t))
20531 (setq count (1+ count)))
20532 count))
20533 @end group
20534 @end smallexample
20535
20536 @smallexample
20537 @group
20538 (defun lengths-list-file (filename)
20539 "Return list of definitions' lengths within FILE.
20540 The returned list is a list of numbers.
20541 Each number is the number of words or
20542 symbols in one function definition."
20543 @end group
20544
20545 @group
20546 (message "Working on `%s' ... " filename)
20547 (save-excursion
20548 (let ((buffer (find-file-noselect filename))
20549 (lengths-list))
20550 (set-buffer buffer)
20551 (setq buffer-read-only t)
20552 (widen)
20553 (goto-char (point-min))
20554 @end group
20555
20556 @group
20557 (while (re-search-forward "^(defun" nil t)
20558 (setq lengths-list
20559 (cons (count-words-in-defun) lengths-list)))
20560 (kill-buffer buffer)
20561 lengths-list)))
20562 @end group
20563 @end smallexample
20564
20565 @smallexample
20566 @group
20567 (defun lengths-list-many-files (list-of-files)
20568 "Return list of lengths of defuns in LIST-OF-FILES."
20569 (let (lengths-list)
20570 ;;; @r{true-or-false-test}
20571 (while list-of-files
20572 (setq lengths-list
20573 (append
20574 lengths-list
20575 @end group
20576 @group
20577 ;;; @r{Generate a lengths' list.}
20578 (lengths-list-file
20579 (expand-file-name (car list-of-files)))))
20580 ;;; @r{Make files' list shorter.}
20581 (setq list-of-files (cdr list-of-files)))
20582 ;;; @r{Return final value of lengths' list.}
20583 lengths-list))
20584 @end group
20585 @end smallexample
20586
20587 @smallexample
20588 @group
20589 (defun defuns-per-range (sorted-lengths top-of-ranges)
20590 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20591 (let ((top-of-range (car top-of-ranges))
20592 (number-within-range 0)
20593 defuns-per-range-list)
20594 @end group
20595
20596 @group
20597 ;; @r{Outer loop.}
20598 (while top-of-ranges
20599
20600 ;; @r{Inner loop.}
20601 (while (and
20602 ;; @r{Need number for numeric test.}
20603 (car sorted-lengths)
20604 (< (car sorted-lengths) top-of-range))
20605
20606 ;; @r{Count number of definitions within current range.}
20607 (setq number-within-range (1+ number-within-range))
20608 (setq sorted-lengths (cdr sorted-lengths)))
20609 @end group
20610
20611 @group
20612 ;; @r{Exit inner loop but remain within outer loop.}
20613
20614 (setq defuns-per-range-list
20615 (cons number-within-range defuns-per-range-list))
20616 (setq number-within-range 0) ; @r{Reset count to zero.}
20617
20618 ;; @r{Move to next range.}
20619 (setq top-of-ranges (cdr top-of-ranges))
20620 ;; @r{Specify next top of range value.}
20621 (setq top-of-range (car top-of-ranges)))
20622 @end group
20623
20624 @group
20625 ;; @r{Exit outer loop and count the number of defuns larger than}
20626 ;; @r{ the largest top-of-range value.}
20627 (setq defuns-per-range-list
20628 (cons
20629 (length sorted-lengths)
20630 defuns-per-range-list))
20631
20632 ;; @r{Return a list of the number of definitions within each range,}
20633 ;; @r{ smallest to largest.}
20634 (nreverse defuns-per-range-list)))
20635 @end group
20636 @end smallexample
20637
20638 @smallexample
20639 @group
20640 (defun column-of-graph (max-graph-height actual-height)
20641 "Return list of MAX-GRAPH-HEIGHT strings;
20642 ACTUAL-HEIGHT are graph-symbols.
20643 The graph-symbols are contiguous entries at the end
20644 of the list.
20645 The list will be inserted as one column of a graph.
20646 The strings are either graph-blank or graph-symbol."
20647 @end group
20648
20649 @group
20650 (let ((insert-list nil)
20651 (number-of-top-blanks
20652 (- max-graph-height actual-height)))
20653
20654 ;; @r{Fill in @code{graph-symbols}.}
20655 (while (> actual-height 0)
20656 (setq insert-list (cons graph-symbol insert-list))
20657 (setq actual-height (1- actual-height)))
20658 @end group
20659
20660 @group
20661 ;; @r{Fill in @code{graph-blanks}.}
20662 (while (> number-of-top-blanks 0)
20663 (setq insert-list (cons graph-blank insert-list))
20664 (setq number-of-top-blanks
20665 (1- number-of-top-blanks)))
20666
20667 ;; @r{Return whole list.}
20668 insert-list))
20669 @end group
20670 @end smallexample
20671
20672 @smallexample
20673 @group
20674 (defun Y-axis-element (number full-Y-label-width)
20675 "Construct a NUMBERed label element.
20676 A numbered element looks like this ` 5 - ',
20677 and is padded as needed so all line up with
20678 the element for the largest number."
20679 @end group
20680 @group
20681 (let* ((leading-spaces
20682 (- full-Y-label-width
20683 (length
20684 (concat (number-to-string number)
20685 Y-axis-tic)))))
20686 @end group
20687 @group
20688 (concat
20689 (make-string leading-spaces ? )
20690 (number-to-string number)
20691 Y-axis-tic)))
20692 @end group
20693 @end smallexample
20694
20695 @smallexample
20696 @group
20697 (defun print-Y-axis
20698 (height full-Y-label-width &optional vertical-step)
20699 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20700 Height must be the maximum height of the graph.
20701 Full width is the width of the highest label element.
20702 Optionally, print according to VERTICAL-STEP."
20703 @end group
20704 @group
20705 ;; Value of height and full-Y-label-width
20706 ;; are passed by `print-graph'.
20707 (let ((start (point)))
20708 (insert-rectangle
20709 (Y-axis-column height full-Y-label-width vertical-step))
20710 @end group
20711 @group
20712 ;; @r{Place point ready for inserting graph.}
20713 (goto-char start)
20714 ;; @r{Move point forward by value of} full-Y-label-width
20715 (forward-char full-Y-label-width)))
20716 @end group
20717 @end smallexample
20718
20719 @smallexample
20720 @group
20721 (defun print-X-axis-tic-line
20722 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20723 "Print tics for X axis."
20724 (insert X-axis-leading-spaces)
20725 (insert X-axis-tic-symbol) ; @r{Under first column.}
20726 @end group
20727 @group
20728 ;; @r{Insert second tic in the right spot.}
20729 (insert (concat
20730 (make-string
20731 (- (* symbol-width X-axis-label-spacing)
20732 ;; @r{Insert white space up to second tic symbol.}
20733 (* 2 (length X-axis-tic-symbol)))
20734 ? )
20735 X-axis-tic-symbol))
20736 @end group
20737 @group
20738 ;; @r{Insert remaining tics.}
20739 (while (> number-of-X-tics 1)
20740 (insert X-axis-tic-element)
20741 (setq number-of-X-tics (1- number-of-X-tics))))
20742 @end group
20743 @end smallexample
20744
20745 @smallexample
20746 @group
20747 (defun X-axis-element (number)
20748 "Construct a numbered X axis element."
20749 (let ((leading-spaces
20750 (- (* symbol-width X-axis-label-spacing)
20751 (length (number-to-string number)))))
20752 (concat (make-string leading-spaces ? )
20753 (number-to-string number))))
20754 @end group
20755 @end smallexample
20756
20757 @smallexample
20758 @group
20759 (defun graph-body-print (numbers-list height symbol-width)
20760 "Print a bar graph of the NUMBERS-LIST.
20761 The numbers-list consists of the Y-axis values.
20762 HEIGHT is maximum height of graph.
20763 SYMBOL-WIDTH is number of each column."
20764 @end group
20765 @group
20766 (let (from-position)
20767 (while numbers-list
20768 (setq from-position (point))
20769 (insert-rectangle
20770 (column-of-graph height (car numbers-list)))
20771 (goto-char from-position)
20772 (forward-char symbol-width)
20773 @end group
20774 @group
20775 ;; @r{Draw graph column by column.}
20776 (sit-for 0)
20777 (setq numbers-list (cdr numbers-list)))
20778 ;; @r{Place point for X axis labels.}
20779 (forward-line height)
20780 (insert "\n")))
20781 @end group
20782 @end smallexample
20783
20784 @smallexample
20785 @group
20786 (defun Y-axis-column
20787 (height width-of-label &optional vertical-step)
20788 "Construct list of labels for Y axis.
20789 HEIGHT is maximum height of graph.
20790 WIDTH-OF-LABEL is maximum width of label.
20791 @end group
20792 @group
20793 VERTICAL-STEP, an option, is a positive integer
20794 that specifies how much a Y axis label increments
20795 for each line. For example, a step of 5 means
20796 that each line is five units of the graph."
20797 (let (Y-axis
20798 (number-per-line (or vertical-step 1)))
20799 @end group
20800 @group
20801 (while (> height 1)
20802 (if (zerop (% height Y-axis-label-spacing))
20803 ;; @r{Insert label.}
20804 (setq Y-axis
20805 (cons
20806 (Y-axis-element
20807 (* height number-per-line)
20808 width-of-label)
20809 Y-axis))
20810 @end group
20811 @group
20812 ;; @r{Else, insert blanks.}
20813 (setq Y-axis
20814 (cons
20815 (make-string width-of-label ? )
20816 Y-axis)))
20817 (setq height (1- height)))
20818 @end group
20819 @group
20820 ;; @r{Insert base line.}
20821 (setq Y-axis (cons (Y-axis-element
20822 (or vertical-step 1)
20823 width-of-label)
20824 Y-axis))
20825 (nreverse Y-axis)))
20826 @end group
20827 @end smallexample
20828
20829 @smallexample
20830 @group
20831 (defun print-X-axis-numbered-line
20832 (number-of-X-tics X-axis-leading-spaces
20833 &optional horizontal-step)
20834 "Print line of X-axis numbers"
20835 (let ((number X-axis-label-spacing)
20836 (horizontal-step (or horizontal-step 1)))
20837 @end group
20838 @group
20839 (insert X-axis-leading-spaces)
20840 ;; line up number
20841 (delete-char (- (1- (length (number-to-string horizontal-step)))))
20842 (insert (concat
20843 (make-string
20844 ;; @r{Insert white space up to next number.}
20845 (- (* symbol-width X-axis-label-spacing)
20846 (1- (length (number-to-string horizontal-step)))
20847 2)
20848 ? )
20849 (number-to-string (* number horizontal-step))))
20850 @end group
20851 @group
20852 ;; @r{Insert remaining numbers.}
20853 (setq number (+ number X-axis-label-spacing))
20854 (while (> number-of-X-tics 1)
20855 (insert (X-axis-element (* number horizontal-step)))
20856 (setq number (+ number X-axis-label-spacing))
20857 (setq number-of-X-tics (1- number-of-X-tics)))))
20858 @end group
20859 @end smallexample
20860
20861 @smallexample
20862 @group
20863 (defun print-X-axis (numbers-list horizontal-step)
20864 "Print X axis labels to length of NUMBERS-LIST.
20865 Optionally, HORIZONTAL-STEP, a positive integer,
20866 specifies how much an X axis label increments for
20867 each column."
20868 @end group
20869 @group
20870 ;; Value of symbol-width and full-Y-label-width
20871 ;; are passed by `print-graph'.
20872 (let* ((leading-spaces
20873 (make-string full-Y-label-width ? ))
20874 ;; symbol-width @r{is provided by} graph-body-print
20875 (tic-width (* symbol-width X-axis-label-spacing))
20876 (X-length (length numbers-list))
20877 @end group
20878 @group
20879 (X-tic
20880 (concat
20881 (make-string
20882 ;; @r{Make a string of blanks.}
20883 (- (* symbol-width X-axis-label-spacing)
20884 (length X-axis-tic-symbol))
20885 ? )
20886 @end group
20887 @group
20888 ;; @r{Concatenate blanks with tic symbol.}
20889 X-axis-tic-symbol))
20890 (tic-number
20891 (if (zerop (% X-length tic-width))
20892 (/ X-length tic-width)
20893 (1+ (/ X-length tic-width)))))
20894 @end group
20895
20896 @group
20897 (print-X-axis-tic-line
20898 tic-number leading-spaces X-tic)
20899 (insert "\n")
20900 (print-X-axis-numbered-line
20901 tic-number leading-spaces horizontal-step)))
20902 @end group
20903 @end smallexample
20904
20905 @smallexample
20906 @group
20907 (defun one-fiftieth (full-range)
20908 "Return list, each number of which is 1/50th previous."
20909 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20910 @end group
20911 @end smallexample
20912
20913 @smallexample
20914 @group
20915 (defun print-graph
20916 (numbers-list &optional vertical-step horizontal-step)
20917 "Print labelled bar graph of the NUMBERS-LIST.
20918 The numbers-list consists of the Y-axis values.
20919 @end group
20920
20921 @group
20922 Optionally, VERTICAL-STEP, a positive integer,
20923 specifies how much a Y axis label increments for
20924 each line. For example, a step of 5 means that
20925 each row is five units.
20926 @end group
20927
20928 @group
20929 Optionally, HORIZONTAL-STEP, a positive integer,
20930 specifies how much an X axis label increments for
20931 each column."
20932 (let* ((symbol-width (length graph-blank))
20933 ;; @code{height} @r{is both the largest number}
20934 ;; @r{and the number with the most digits.}
20935 (height (apply 'max numbers-list))
20936 @end group
20937 @group
20938 (height-of-top-line
20939 (if (zerop (% height Y-axis-label-spacing))
20940 height
20941 ;; @r{else}
20942 (* (1+ (/ height Y-axis-label-spacing))
20943 Y-axis-label-spacing)))
20944 @end group
20945 @group
20946 (vertical-step (or vertical-step 1))
20947 (full-Y-label-width
20948 (length
20949 (concat
20950 (number-to-string
20951 (* height-of-top-line vertical-step))
20952 Y-axis-tic))))
20953 @end group
20954 @group
20955
20956 (print-Y-axis
20957 height-of-top-line full-Y-label-width vertical-step)
20958 (graph-body-print
20959 numbers-list height-of-top-line symbol-width)
20960 (print-X-axis numbers-list horizontal-step)))
20961 @end group
20962 @end smallexample
20963 @end ignore
20964
20965 @page
20966 @node Final printed graph, , Another Bug, Print Whole Graph
20967 @appendixsubsec The Printed Graph
20968
20969 When made and installed, you can call the @code{print-graph} command
20970 like this:
20971
20972 @smallexample
20973 @group
20974 (print-graph fiftieth-list-for-graph 50 10)
20975 @end group
20976 @end smallexample
20977
20978 Here is the graph:
20979
20980 @sp 2
20981
20982 @smallexample
20983 @group
20984 1000 - *
20985 **
20986 **
20987 **
20988 **
20989 750 - ***
20990 ***
20991 ***
20992 ***
20993 ****
20994 500 - *****
20995 ******
20996 ******
20997 ******
20998 *******
20999 250 - ********
21000 ********* *
21001 *********** *
21002 ************* *
21003 50 - ***************** * *
21004 | | | | | | | |
21005 10 50 100 150 200 250 300 350
21006 @end group
21007 @end smallexample
21008
21009 @sp 2
21010
21011 The largest group of functions contain 10 -- 19 words and symbols each.
21012
21013 @node GNU Free Documentation License, Index, Full Graph, Top
21014 @appendix GNU Free Documentation License
21015
21016 @cindex FDL, GNU Free Documentation License
21017 @center Version 1.1, March 2000
21018
21019 @display
21020 Copyright @copyright{} 2000 Free Software Foundation, Inc.
21021 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
21022
21023 Everyone is permitted to copy and distribute verbatim copies
21024 of this license document, but changing it is not allowed.
21025 @end display
21026
21027 @enumerate 0
21028 @item
21029 PREAMBLE
21030
21031 The purpose of this License is to make a manual, textbook, or other
21032 written document @dfn{free} in the sense of freedom: to assure everyone
21033 the effective freedom to copy and redistribute it, with or without
21034 modifying it, either commercially or noncommercially. Secondarily,
21035 this License preserves for the author and publisher a way to get
21036 credit for their work, while not being considered responsible for
21037 modifications made by others.
21038
21039 This License is a kind of ``copyleft'', which means that derivative
21040 works of the document must themselves be free in the same sense. It
21041 complements the GNU General Public License, which is a copyleft
21042 license designed for free software.
21043
21044 We have designed this License in order to use it for manuals for free
21045 software, because free software needs free documentation: a free
21046 program should come with manuals providing the same freedoms that the
21047 software does. But this License is not limited to software manuals;
21048 it can be used for any textual work, regardless of subject matter or
21049 whether it is published as a printed book. We recommend this License
21050 principally for works whose purpose is instruction or reference.
21051
21052 @item
21053 APPLICABILITY AND DEFINITIONS
21054
21055 This License applies to any manual or other work that contains a
21056 notice placed by the copyright holder saying it can be distributed
21057 under the terms of this License. The ``Document'', below, refers to any
21058 such manual or work. Any member of the public is a licensee, and is
21059 addressed as ``you''.
21060
21061 A ``Modified Version'' of the Document means any work containing the
21062 Document or a portion of it, either copied verbatim, or with
21063 modifications and/or translated into another language.
21064
21065 A ``Secondary Section'' is a named appendix or a front-matter section of
21066 the Document that deals exclusively with the relationship of the
21067 publishers or authors of the Document to the Document's overall subject
21068 (or to related matters) and contains nothing that could fall directly
21069 within that overall subject. (For example, if the Document is in part a
21070 textbook of mathematics, a Secondary Section may not explain any
21071 mathematics.) The relationship could be a matter of historical
21072 connection with the subject or with related matters, or of legal,
21073 commercial, philosophical, ethical or political position regarding
21074 them.
21075
21076 The ``Invariant Sections'' are certain Secondary Sections whose titles
21077 are designated, as being those of Invariant Sections, in the notice
21078 that says that the Document is released under this License.
21079
21080 The ``Cover Texts'' are certain short passages of text that are listed,
21081 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
21082 the Document is released under this License.
21083
21084 A ``Transparent'' copy of the Document means a machine-readable copy,
21085 represented in a format whose specification is available to the
21086 general public, whose contents can be viewed and edited directly and
21087 straightforwardly with generic text editors or (for images composed of
21088 pixels) generic paint programs or (for drawings) some widely available
21089 drawing editor, and that is suitable for input to text formatters or
21090 for automatic translation to a variety of formats suitable for input
21091 to text formatters. A copy made in an otherwise Transparent file
21092 format whose markup has been designed to thwart or discourage
21093 subsequent modification by readers is not Transparent. A copy that is
21094 not ``Transparent'' is called ``Opaque''.
21095
21096 Examples of suitable formats for Transparent copies include plain
21097 @sc{ascii} without markup, Texinfo input format, La@TeX{} input format,
21098 @acronym{SGML} or @acronym{XML} using a publicly available
21099 @acronym{DTD}, and standard-conforming simple @acronym{HTML} designed
21100 for human modification. Opaque formats include PostScript,
21101 @acronym{PDF}, proprietary formats that can be read and edited only by
21102 proprietary word processors, @acronym{SGML} or @acronym{XML} for which
21103 the @acronym{DTD} and/or processing tools are not generally available,
21104 and the machine-generated @acronym{HTML} produced by some word
21105 processors for output purposes only.
21106
21107 The ``Title Page'' means, for a printed book, the title page itself,
21108 plus such following pages as are needed to hold, legibly, the material
21109 this License requires to appear in the title page. For works in
21110 formats which do not have any title page as such, ``Title Page'' means
21111 the text near the most prominent appearance of the work's title,
21112 preceding the beginning of the body of the text.
21113
21114 @item
21115 VERBATIM COPYING
21116
21117 You may copy and distribute the Document in any medium, either
21118 commercially or noncommercially, provided that this License, the
21119 copyright notices, and the license notice saying this License applies
21120 to the Document are reproduced in all copies, and that you add no other
21121 conditions whatsoever to those of this License. You may not use
21122 technical measures to obstruct or control the reading or further
21123 copying of the copies you make or distribute. However, you may accept
21124 compensation in exchange for copies. If you distribute a large enough
21125 number of copies you must also follow the conditions in section 3.
21126
21127 You may also lend copies, under the same conditions stated above, and
21128 you may publicly display copies.
21129
21130 @item
21131 COPYING IN QUANTITY
21132
21133 If you publish printed copies of the Document numbering more than 100,
21134 and the Document's license notice requires Cover Texts, you must enclose
21135 the copies in covers that carry, clearly and legibly, all these Cover
21136 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21137 the back cover. Both covers must also clearly and legibly identify
21138 you as the publisher of these copies. The front cover must present
21139 the full title with all words of the title equally prominent and
21140 visible. You may add other material on the covers in addition.
21141 Copying with changes limited to the covers, as long as they preserve
21142 the title of the Document and satisfy these conditions, can be treated
21143 as verbatim copying in other respects.
21144
21145 If the required texts for either cover are too voluminous to fit
21146 legibly, you should put the first ones listed (as many as fit
21147 reasonably) on the actual cover, and continue the rest onto adjacent
21148 pages.
21149
21150 If you publish or distribute Opaque copies of the Document numbering
21151 more than 100, you must either include a machine-readable Transparent
21152 copy along with each Opaque copy, or state in or with each Opaque copy
21153 a publicly-accessible computer-network location containing a complete
21154 Transparent copy of the Document, free of added material, which the
21155 general network-using public has access to download anonymously at no
21156 charge using public-standard network protocols. If you use the latter
21157 option, you must take reasonably prudent steps, when you begin
21158 distribution of Opaque copies in quantity, to ensure that this
21159 Transparent copy will remain thus accessible at the stated location
21160 until at least one year after the last time you distribute an Opaque
21161 copy (directly or through your agents or retailers) of that edition to
21162 the public.
21163
21164 It is requested, but not required, that you contact the authors of the
21165 Document well before redistributing any large number of copies, to give
21166 them a chance to provide you with an updated version of the Document.
21167
21168 @item
21169 MODIFICATIONS
21170
21171 You may copy and distribute a Modified Version of the Document under
21172 the conditions of sections 2 and 3 above, provided that you release
21173 the Modified Version under precisely this License, with the Modified
21174 Version filling the role of the Document, thus licensing distribution
21175 and modification of the Modified Version to whoever possesses a copy
21176 of it. In addition, you must do these things in the Modified Version:
21177
21178 @enumerate A
21179 @item
21180 Use in the Title Page (and on the covers, if any) a title distinct
21181 from that of the Document, and from those of previous versions
21182 (which should, if there were any, be listed in the History section
21183 of the Document). You may use the same title as a previous version
21184 if the original publisher of that version gives permission.
21185
21186 @item
21187 List on the Title Page, as authors, one or more persons or entities
21188 responsible for authorship of the modifications in the Modified
21189 Version, together with at least five of the principal authors of the
21190 Document (all of its principal authors, if it has less than five).
21191
21192 @item
21193 State on the Title page the name of the publisher of the
21194 Modified Version, as the publisher.
21195
21196 @item
21197 Preserve all the copyright notices of the Document.
21198
21199 @item
21200 Add an appropriate copyright notice for your modifications
21201 adjacent to the other copyright notices.
21202
21203 @item
21204 Include, immediately after the copyright notices, a license notice
21205 giving the public permission to use the Modified Version under the
21206 terms of this License, in the form shown in the Addendum below.
21207
21208 @item
21209 Preserve in that license notice the full lists of Invariant Sections
21210 and required Cover Texts given in the Document's license notice.
21211
21212 @item
21213 Include an unaltered copy of this License.
21214
21215 @item
21216 Preserve the section entitled ``History'', and its title, and add to
21217 it an item stating at least the title, year, new authors, and
21218 publisher of the Modified Version as given on the Title Page. If
21219 there is no section entitled ``History'' in the Document, create one
21220 stating the title, year, authors, and publisher of the Document as
21221 given on its Title Page, then add an item describing the Modified
21222 Version as stated in the previous sentence.
21223
21224 @item
21225 Preserve the network location, if any, given in the Document for
21226 public access to a Transparent copy of the Document, and likewise
21227 the network locations given in the Document for previous versions
21228 it was based on. These may be placed in the ``History'' section.
21229 You may omit a network location for a work that was published at
21230 least four years before the Document itself, or if the original
21231 publisher of the version it refers to gives permission.
21232
21233 @item
21234 In any section entitled ``Acknowledgments'' or ``Dedications'',
21235 preserve the section's title, and preserve in the section all the
21236 substance and tone of each of the contributor acknowledgments
21237 and/or dedications given therein.
21238
21239 @item
21240 Preserve all the Invariant Sections of the Document,
21241 unaltered in their text and in their titles. Section numbers
21242 or the equivalent are not considered part of the section titles.
21243
21244 @item
21245 Delete any section entitled ``Endorsements''. Such a section
21246 may not be included in the Modified Version.
21247
21248 @item
21249 Do not retitle any existing section as ``Endorsements''
21250 or to conflict in title with any Invariant Section.
21251 @end enumerate
21252
21253 If the Modified Version includes new front-matter sections or
21254 appendices that qualify as Secondary Sections and contain no material
21255 copied from the Document, you may at your option designate some or all
21256 of these sections as invariant. To do this, add their titles to the
21257 list of Invariant Sections in the Modified Version's license notice.
21258 These titles must be distinct from any other section titles.
21259
21260 You may add a section entitled ``Endorsements'', provided it contains
21261 nothing but endorsements of your Modified Version by various
21262 parties---for example, statements of peer review or that the text has
21263 been approved by an organization as the authoritative definition of a
21264 standard.
21265
21266 You may add a passage of up to five words as a Front-Cover Text, and a
21267 passage of up to 25 words as a Back-Cover Text, to the end of the list
21268 of Cover Texts in the Modified Version. Only one passage of
21269 Front-Cover Text and one of Back-Cover Text may be added by (or
21270 through arrangements made by) any one entity. If the Document already
21271 includes a cover text for the same cover, previously added by you or
21272 by arrangement made by the same entity you are acting on behalf of,
21273 you may not add another; but you may replace the old one, on explicit
21274 permission from the previous publisher that added the old one.
21275
21276 The author(s) and publisher(s) of the Document do not by this License
21277 give permission to use their names for publicity for or to assert or
21278 imply endorsement of any Modified Version.
21279
21280 @item
21281 COMBINING DOCUMENTS
21282
21283 You may combine the Document with other documents released under this
21284 License, under the terms defined in section 4 above for modified
21285 versions, provided that you include in the combination all of the
21286 Invariant Sections of all of the original documents, unmodified, and
21287 list them all as Invariant Sections of your combined work in its
21288 license notice.
21289
21290 The combined work need only contain one copy of this License, and
21291 multiple identical Invariant Sections may be replaced with a single
21292 copy. If there are multiple Invariant Sections with the same name but
21293 different contents, make the title of each such section unique by
21294 adding at the end of it, in parentheses, the name of the original
21295 author or publisher of that section if known, or else a unique number.
21296 Make the same adjustment to the section titles in the list of
21297 Invariant Sections in the license notice of the combined work.
21298
21299 In the combination, you must combine any sections entitled ``History''
21300 in the various original documents, forming one section entitled
21301 ``History''; likewise combine any sections entitled ``Acknowledgments'',
21302 and any sections entitled ``Dedications''. You must delete all sections
21303 entitled ``Endorsements.''
21304
21305 @item
21306 COLLECTIONS OF DOCUMENTS
21307
21308 You may make a collection consisting of the Document and other documents
21309 released under this License, and replace the individual copies of this
21310 License in the various documents with a single copy that is included in
21311 the collection, provided that you follow the rules of this License for
21312 verbatim copying of each of the documents in all other respects.
21313
21314 You may extract a single document from such a collection, and distribute
21315 it individually under this License, provided you insert a copy of this
21316 License into the extracted document, and follow this License in all
21317 other respects regarding verbatim copying of that document.
21318
21319 @item
21320 AGGREGATION WITH INDEPENDENT WORKS
21321
21322 A compilation of the Document or its derivatives with other separate
21323 and independent documents or works, in or on a volume of a storage or
21324 distribution medium, does not as a whole count as a Modified Version
21325 of the Document, provided no compilation copyright is claimed for the
21326 compilation. Such a compilation is called an ``aggregate'', and this
21327 License does not apply to the other self-contained works thus compiled
21328 with the Document, on account of their being thus compiled, if they
21329 are not themselves derivative works of the Document.
21330
21331 If the Cover Text requirement of section 3 is applicable to these
21332 copies of the Document, then if the Document is less than one quarter
21333 of the entire aggregate, the Document's Cover Texts may be placed on
21334 covers that surround only the Document within the aggregate.
21335 Otherwise they must appear on covers around the whole aggregate.
21336
21337 @item
21338 TRANSLATION
21339
21340 Translation is considered a kind of modification, so you may
21341 distribute translations of the Document under the terms of section 4.
21342 Replacing Invariant Sections with translations requires special
21343 permission from their copyright holders, but you may include
21344 translations of some or all Invariant Sections in addition to the
21345 original versions of these Invariant Sections. You may include a
21346 translation of this License provided that you also include the
21347 original English version of this License. In case of a disagreement
21348 between the translation and the original English version of this
21349 License, the original English version will prevail.
21350
21351 @item
21352 TERMINATION
21353
21354 You may not copy, modify, sublicense, or distribute the Document except
21355 as expressly provided for under this License. Any other attempt to
21356 copy, modify, sublicense or distribute the Document is void, and will
21357 automatically terminate your rights under this License. However,
21358 parties who have received copies, or rights, from you under this
21359 License will not have their licenses terminated so long as such
21360 parties remain in full compliance.
21361
21362 @item
21363 FUTURE REVISIONS OF THIS LICENSE
21364
21365 The Free Software Foundation may publish new, revised versions
21366 of the GNU Free Documentation License from time to time. Such new
21367 versions will be similar in spirit to the present version, but may
21368 differ in detail to address new problems or concerns. See
21369 @uref{http://www.gnu.org/copyleft/}.
21370
21371 Each version of the License is given a distinguishing version number.
21372 If the Document specifies that a particular numbered version of this
21373 License ``or any later version'' applies to it, you have the option of
21374 following the terms and conditions either of that specified version or
21375 of any later version that has been published (not as a draft) by the
21376 Free Software Foundation. If the Document does not specify a version
21377 number of this License, you may choose any version ever published (not
21378 as a draft) by the Free Software Foundation.
21379 @end enumerate
21380
21381 @node Index, About the Author, GNU Free Documentation License, Top
21382 @comment node-name, next, previous, up
21383 @unnumbered Index
21384
21385 @ifnottex
21386 MENU ENTRY: NODE NAME.
21387 @end ifnottex
21388
21389 @printindex cp
21390
21391 @iftex
21392 @c Place biographical information on right-hand (verso) page
21393
21394 @tex
21395 \ifodd\pageno
21396 \par\vfill\supereject
21397 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21398 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21399 \page\hbox{}\page
21400 \else
21401 \par\vfill\supereject
21402 \par\vfill\supereject
21403 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21404 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21405 \page\hbox{}\page
21406 \page\hbox{}\page
21407 \fi
21408 @end tex
21409
21410 @page
21411 @w{ }
21412
21413 @c ================ Biographical information ================
21414
21415 @w{ }
21416 @sp 8
21417 @center About the Author
21418 @sp 1
21419 @end iftex
21420
21421 @ifnottex
21422 @node About the Author, , Index, Top
21423 @unnumbered About the Author
21424 @end ifnottex
21425
21426 @quotation
21427 Robert J. Chassell has worked with GNU Emacs since 1985. He writes
21428 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21429 world on software freedom. Chassell was a founding Director and
21430 Treasurer of the Free Software Foundation, Inc. He is co-author of
21431 the @cite{Texinfo} manual, and has edited more than a dozen other
21432 books. He graduated from Cambridge University, in England. He has an
21433 abiding interest in social and economic history and flies his own
21434 airplane.
21435 @end quotation
21436
21437 @page
21438 @w{ }
21439
21440 @c Prevent page number on blank verso, so eject it first.
21441 @tex
21442 \par\vfill\supereject
21443 @end tex
21444
21445 @iftex
21446 @headings off
21447 @evenheading @thispage @| @| @thistitle
21448 @oddheading @| @| @thispage
21449 @end iftex
21450
21451 @c Keep T.O.C. short by tightening up.
21452 @ifset largebook
21453 @tex
21454 \global\parskip 2pt plus 1pt
21455 \global\advance\baselineskip by -1pt
21456 @end tex
21457 @end ifset
21458
21459 @shortcontents
21460 @contents
21461
21462 @bye