Add --trace-move.
[bpt/emacs.git] / lispintro / emacs-lisp-intro.texi
CommitLineData
8b096dce
EZ
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 ---------
475dc40a
EZ
12@c <<<< For hard copy printing, this file is now
13@c set for smallbook, which works for all sizes
14@c of paper, and with Postscript figures >>>>
15@smallbook
16@clear largebook
8b096dce 17@set print-postscript-figures
475dc40a
EZ
18@c set largebook
19@c clear print-postscript-figures
8b096dce
EZ
20@c ---------
21
22@comment %**end of header
23
475dc40a
EZ
24@set edition-number 2.02
25@set update-date 2001 Nov 25
8b096dce
EZ
26
27@ignore
28 ## Summary of shell commands to create various output formats:
29
30 ## Info output
31 makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
32
33 ## DVI output
34 texi2dvi emacs-lisp-intro.texi
35
36 ## HTML output
8b096dce
EZ
37 makeinfo --html --no-split --verbose emacs-lisp-intro.texi
38
39 ## Plain text output
40 makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
41 --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
42
43@end ignore
44
45@c ================ Included Figures ================
46
47@c Set print-postscript-figures if you print PostScript figures.
48@c If you clear this, the ten figures will be printed as ASCII diagrams.
49@c (This is not relevant to Info, since Info only handles ASCII.)
50@c Your site may require editing changes to print PostScript; in this
51@c case, search for `print-postscript-figures' and make appropriate changes.
52
53
54@c ================ How to Create an Info file ================
55
56@c If you have `makeinfo' installed, run the following command
57
58@c makeinfo emacs-lisp-intro.texi
59
60@c or, if you want a single, large Info file, and no paragraph indents:
61@c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
62
63@c After creating the Info file, edit your Info `dir' file, if the
0860ed42 64@c `dircategory' section below does not enable your system to
8b096dce
EZ
65@c install the manual automatically.
66@c (The `dir' file is often in the `/usr/local/info/' directory.)
67
68@c ================ How to Create an HTML file ================
69
70@c To convert to HTML format
71@c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
72
73@c ================ How to Print a Book in Various Sizes ================
74
75@c This book can be printed in any of three different sizes.
76@c In the above header, set @-commands appropriately.
77
78@c 7 by 9.25 inches:
79@c @smallbook
80@c @clear largebook
81
82@c 8.5 by 11 inches:
83@c @c smallbook
84@c @set largebook
85
86@c European A4 size paper:
87@c @c smallbook
88@c @afourpaper
89@c @set largebook
90
91@c ================ How to Typeset and Print ================
92
93@c If you do not include PostScript figures, run either of the
94@c following command sequences, or similar commands suited to your
95@c system:
96
97@c texi2dvi emacs-lisp-intro.texi
98@c lpr -d emacs-lisp-intro.dvi
99
100@c or else:
101
102@c tex emacs-lisp-intro.texi
103@c texindex emacs-lisp-intro.??
104@c tex emacs-lisp-intro.texi
105@c lpr -d emacs-lisp-intro.dvi
106
475dc40a
EZ
107@c If you include the PostScript figures, and you have old software,
108@c you may need to convert the .dvi file to a .ps file before
109@c printing. Run either of the following command sequences, or one
110@c similar:
8b096dce
EZ
111@c
112@c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
113@c
114@c or else:
115@c
116@c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
117@c
118
119@c (Note: if you edit the book so as to change the length of the
120@c table of contents, you may have to change the value of `pageno' below.)
121
8b096dce
EZ
122@c ================ End of Formatting Sections ================
123
124@c For next or subsequent edition:
125@c create function using with-output-to-temp-buffer
126@c create a major mode, with keymaps
127@c run an asynchronous process, like grep or diff
128
129@c For smallbook format, use smaller than normal amounts of
130@c whitespace between chapters, sections, and paragraphs.
131@tex
132\global\chapheadingskip = 15pt plus 4pt minus 2pt
133\global\secheadingskip = 12pt plus 3pt minus 2pt
134\global\subsecheadingskip = 9pt plus 2pt minus 2pt \global\parskip 2pt
135plus 1pt
136@end tex
137
138@c For 8.5 by 11 inch format: do not use such a small amount of
139@c whitespace between paragraphs as above:
140@ifset largebook
141@tex
142\global\parskip 6pt plus 1pt
143@end tex
144@end ifset
145
146@c For all sized formats: print within-book cross
147@c reference with ``...'' rather than [...]
148@tex
149% Need following so comma appears after section numbers.
150\global\def\Ysectionnumberandtype{%
151\ifnum\secno=0 \putwordChapter\xreftie\the\chapno, \space %
152\else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno, \space %
153\else \ifnum \subsubsecno=0 %
154\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno, \space %
155\else %
156\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno, \space%
157\fi \fi \fi }
158
159\global\def\Yappendixletterandtype{%
160\ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}, \space%
161\else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno, \space %
162\else \ifnum \subsubsecno=0 %
163\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno, \space %
164\else %
165\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno, \space %
166\fi \fi \fi }
167
168\global\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
169 \def\printedmanual{\ignorespaces #5}%
170 \def\printednodename{\ignorespaces #3}%
171 \setbox1=\hbox{\printedmanual}%
172 \setbox0=\hbox{\printednodename}%
173 \ifdim \wd0 = 0pt
174 % No printed node name was explicitly given.
175 \ifx\SETxref-automatic-section-title\relax %
176 % Use the actual chapter/section title appear inside
177 % the square brackets. Use the real section title if we have it.
178 \ifdim \wd1>0pt%
179 % It is in another manual, so we don't have it.
180 \def\printednodename{\ignorespaces #1}%
181 \else
182 \ifhavexrefs
183 % We know the real title if we have the xref values.
184 \def\printednodename{\refx{#1-title}}%
185 \else
186 % Otherwise just copy the Info node name.
187 \def\printednodename{\ignorespaces #1}%
188 \fi%
189 \fi
190 \def\printednodename{#1-title}%
191 \else
192 % Use the node name inside the square brackets.
193 \def\printednodename{\ignorespaces #1}%
194 \fi
195 \fi
196 %
197 % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not
198 % insert empty discretionaries after hyphens, which means that it will
199 % not find a line break at a hyphen in a node names. Since some manuals
200 % are best written with fairly long node names, containing hyphens, this
201 % is a loss. Therefore, we give the text of the node name again, so it
202 % is as if TeX is seeing it for the first time.
203 \ifdim \wd1 > 0pt
204 \putwordsection{} ``\printednodename'' in \cite{\printedmanual}%
205 \else
206 % _ (for example) has to be the character _ for the purposes of the
207 % control sequence corresponding to the node, but it has to expand
208 % into the usual \leavevmode...\vrule stuff for purposes of
209 % printing. So we \turnoffactive for the \refx-snt, back on for the
210 % printing, back off for the \refx-pg.
211 {\turnoffactive \refx{#1-snt}{}}%
212% \space [\printednodename],\space % <= original
213% \putwordsection{} ``\printednodename'',\space
214 ``\printednodename'',\space
215 \turnoffactive \putwordpage\tie\refx{#1-pg}{}%
216 \fi
217\endgroup}
218@end tex
219
220@c ----------------------------------------------------
221
d586ab6c
EZ
222@dircategory Emacs
223@direntry
224* Emacs Lisp Intro: (eintr).
8b096dce 225 A simple introduction to Emacs Lisp programming.
d586ab6c 226@end direntry
8b096dce
EZ
227
228@ifinfo
229This is an introduction to @cite{Programming in Emacs Lisp}, for
230people who are not programmers.
231
232Edition @value{edition-number}, @value{update-date}
233
234Copyright (C) 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software Foundation, Inc.
235
236Permission is granted to copy, distribute and/or modify this document
237under the terms of the GNU Free Documentation License, Version 1.1 or
238any later version published by the Free Software Foundation; with the
239Invariant Section being the Preface, with the Front-Cover Texts being
240no Front-Cover Texts, and with the Back-Cover Texts being no
241Back-Cover Texts. A copy of the license is included in the section
242entitled ``GNU Free Documentation License''.
243@end ifinfo
244
245@c half title; two lines here, so do not use `shorttitlepage'
246@tex
247{\begingroup%
248 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
249 \endgroup}%
250{\begingroup\hbox{}\vskip 0.25in \chaprm%
251 \centerline{Programming in Emacs Lisp}%
252 \endgroup\page\hbox{}\page}
253@end tex
254
255@titlepage
256@sp 6
257@center @titlefont{An Introduction to}
258@sp 2
259@center @titlefont{Programming in Emacs Lisp}
260@sp 2
261@center Second Edition
262@sp 4
263@center by Robert J. Chassell
264
265@page
266@vskip 0pt plus 1filll
267Copyright @copyright{} 1990, '91, '92, '93, '94, '95, '97, 2001 Free Software Foundation, Inc.
268@sp 2
269
270Published by the Free Software Foundation, Inc.@*
27159 Temple Place, Suite 330@*
272Boston, MA 02111-1307 USA@*
273
274Edition @value{edition-number}, @value{update-date}
275
276@c Printed copies are available for $20 each.@*
277ISBN-1882114-41-8
278
279Permission is granted to copy, distribute and/or modify this document
280under the terms of the GNU Free Documentation License, Version 1.1 or
281any later version published by the Free Software Foundation; with the
282Invariant Section being the Preface, with the Front-Cover Texts being
283no Front-Cover Texts, and with the Back-Cover Texts being no
284Back-Cover Texts. A copy of the license is included in the section
285entitled ``GNU Free Documentation License''.
286@end titlepage
287
288@iftex
289@headings off
290@evenheading @thispage @| @| @thischapter
291@oddheading @thissection @| @| @thispage
292@end iftex
293
475dc40a 294@ifnothtml
8b096dce 295
475dc40a
EZ
296@c Keep T.O.C. short by tightening up.
297@ifset largebook
298@tex
299\global\parskip 2pt plus 1pt
300\global\advance\baselineskip by -1pt
301@end tex
302@end ifset
8b096dce 303
475dc40a
EZ
304@shortcontents
305@contents
306
307@ifset largebook
308@tex
309\global\parskip 6pt plus 1pt
310\global\advance\baselineskip by 1pt
311@end tex
312@end ifset
313
314@end ifnothtml
8b096dce
EZ
315
316@c >>>> Set pageno appropriately <<<<
317
318@c The first page of the Preface is a roman numeral; it is the first
319@c right handed page after the Table of Contents; hence the following
320@c setting must be for an odd negative number.
321
322@c if largebook, there are 8 pages in Table of Contents
323@ifset largebook
324@iftex
325@pageno = -9
326@end iftex
327@end ifset
328
329@c if smallbook, there are 10 pages in Table of Contents
330@ifclear largebook
331@iftex
332@pageno = -11
333@end iftex
334@end ifclear
335
475dc40a
EZ
336@ifnottex
337@node Top, Preface, (dir), (dir)
338@top An Introduction to Programming in Emacs Lisp
339
340This is an introduction to @cite{Programming in Emacs Lisp}, for
341people who are not programmers.
342
343This master menu first lists each chapter and index; then it lists
344every node in every chapter.
345@end ifnottex
346
8b096dce
EZ
347@menu
348* Preface:: What to look for.
349* List Processing:: What is Lisp?
350* Practicing Evaluation:: Running several programs.
351* Writing Defuns:: How to write function definitions.
352* Buffer Walk Through:: Exploring a few buffer-related functions.
353* More Complex:: A few, even more complex functions.
354* Narrowing & Widening:: Restricting your and Emacs attention to
355 a region.
356* car cdr & cons:: Fundamental functions in Lisp.
357* Cutting & Storing Text:: Removing text and saving it.
358* List Implementation:: How lists are implemented in the computer.
359* Yanking:: Pasting stored text.
360* Loops & Recursion:: How to repeat a process.
361* Regexp Search:: Regular expression searches.
362* Counting Words:: A review of repetition and regexps.
363* Words in a defun:: Counting words in a @code{defun}.
364* Readying a Graph:: A prototype graph printing function.
365* Emacs Initialization:: How to write a @file{.emacs} file.
366* Debugging:: How to run the Emacs Lisp debuggers.
367* Conclusion:: Now you have the basics.
368* the-the:: An appendix: how to find reduplicated words.
369* Kill Ring:: An appendix: how the kill ring works.
370* Full Graph:: How to create a graph with labelled axes.
371* GNU Free Documentation License::
372* Index::
373* About the Author::
374
375@detailmenu
376 --- The Detailed Node Listing ---
377
378Preface
379
380* Why:: Why learn Emacs Lisp?
381* On Reading this Text:: Read, gain familiarity, pick up habits....
382* Who You Are:: For whom this is written.
383* Lisp History::
384* Note for Novices:: You can read this as a novice.
385* Thank You::
386
387List Processing
388
389* Lisp Lists:: What are lists?
390* Run a Program:: Any list in Lisp is a program ready to run.
391* Making Errors:: Generating an error message.
392* Names & Definitions:: Names of symbols and function definitions.
393* Lisp Interpreter:: What the Lisp interpreter does.
394* Evaluation:: Running a program.
395* Variables:: Returning a value from a variable.
396* Arguments:: Passing information to a function.
397* set & setq:: Setting the value of a variable.
398* Summary:: The major points.
399* Error Message Exercises::
400
401Lisp Lists
402
403* Numbers Lists:: List have numbers, other lists, in them.
404* Lisp Atoms:: Elemental entities.
405* Whitespace in Lists:: Formating lists to be readable.
406* Typing Lists:: How GNU Emacs helps you type lists.
407
408The Lisp Interpreter
409
410* Complications:: Variables, Special forms, Lists within.
411* Byte Compiling:: Specially processing code for speed.
412
413Evaluation
414
415* Evaluating Inner Lists:: Lists within lists...
416
417Variables
418
419* fill-column Example::
420* Void Function:: The error message for a symbol
421 without a function.
422* Void Variable:: The error message for a symbol without a value.
423
424Arguments
425
426* Data types:: Types of data passed to a function.
427* Args as Variable or List:: An argument can be the value
428 of a variable or list.
429* Variable Number of Arguments:: Some functions may take a
430 variable number of arguments.
431* Wrong Type of Argument:: Passing an argument of the wrong type
432 to a function.
433* message:: A useful function for sending messages.
434
435Setting the Value of a Variable
436
437* Using set:: Setting values.
438* Using setq:: Setting a quoted value.
439* Counting:: Using @code{setq} to count.
440
441Practicing Evaluation
442
443* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
444 causes evaluation.
445* Buffer Names:: Buffers and files are different.
446* Getting Buffers:: Getting a buffer itself, not merely its name.
447* Switching Buffers:: How to change to another buffer.
448* Buffer Size & Locations:: Where point is located and the size of
449 the buffer.
450* Evaluation Exercise::
451
452How To Write Function Definitions
453
454* Primitive Functions::
455* defun:: The @code{defun} special form.
456* Install:: Install a function definition.
457* Interactive:: Making a function interactive.
458* Interactive Options:: Different options for @code{interactive}.
459* Permanent Installation:: Installing code permanently.
460* let:: Creating and initializing local variables.
461* if:: What if?
462* else:: If--then--else expressions.
463* Truth & Falsehood:: What Lisp considers false and true.
464* save-excursion:: Keeping track of point, mark, and buffer.
465* Review::
466* defun Exercises::
467
468Install a Function Definition
469
470* Effect of installation::
471* Change a defun:: How to change a function definition.
472
473Make a Function Interactive
474
475* Interactive multiply-by-seven:: An overview.
476* multiply-by-seven in detail:: The interactive version.
477
478@code{let}
479
480* Prevent confusion::
481* Parts of let Expression::
482* Sample let Expression::
483* Uninitialized let Variables::
484
485The @code{if} Special Form
486
487* if in more detail::
488* type-of-animal in detail:: An example of an @code{if} expression.
489
490Truth and Falsehood in Emacs Lisp
491
492* nil explained:: @code{nil} has two meanings.
493
494@code{save-excursion}
495
496* Point and mark:: A review of various locations.
497* Template for save-excursion::
498
499A Few Buffer--Related Functions
500
501* Finding More:: How to find more information.
502* simplified-beginning-of-buffer:: Shows @code{goto-char},
503 @code{point-min}, and @code{push-mark}.
504* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
505* append-to-buffer:: Uses @code{save-excursion} and
506 @code{insert-buffer-substring}.
507* Buffer Related Review:: Review.
508* Buffer Exercises::
509
510The Definition of @code{mark-whole-buffer}
511
512* mark-whole-buffer overview::
513* Body of mark-whole-buffer:: Only three lines of code.
514
515The Definition of @code{append-to-buffer}
516
517* append-to-buffer overview::
518* append interactive:: A two part interactive expression.
519* append-to-buffer body:: Incorporates a @code{let} expression.
520* append save-excursion:: How the @code{save-excursion} works.
521
522A Few More Complex Functions
523
524* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
525* insert-buffer:: Read-only, and with @code{or}.
526* beginning-of-buffer:: Shows @code{goto-char},
527 @code{point-min}, and @code{push-mark}.
528* Second Buffer Related Review::
529* optional Exercise::
530
531The Definition of @code{insert-buffer}
532
533* insert-buffer code::
534* insert-buffer interactive:: When you can read, but not write.
535* insert-buffer body:: The body has an @code{or} and a @code{let}.
536* if & or:: Using an @code{if} instead of an @code{or}.
537* Insert or:: How the @code{or} expression works.
538* Insert let:: Two @code{save-excursion} expressions.
539
540The Interactive Expression in @code{insert-buffer}
541
542* Read-only buffer:: When a buffer cannot be modified.
543* b for interactive:: An existing buffer or else its name.
544
545Complete Definition of @code{beginning-of-buffer}
546
547* Optional Arguments::
548* beginning-of-buffer opt arg:: Example with optional argument.
549* beginning-of-buffer complete::
550
551@code{beginning-of-buffer} with an Argument
552
553* Disentangle beginning-of-buffer::
554* Large buffer case::
555* Small buffer case::
556
557Narrowing and Widening
558
559* Narrowing advantages:: The advantages of narrowing
560* save-restriction:: The @code{save-restriction} special form.
561* what-line:: The number of the line that point is on.
562* narrow Exercise::
563
564@code{car}, @code{cdr}, @code{cons}: Fundamental Functions
565
566* Strange Names:: An historical aside: why the strange names?
567* car & cdr:: Functions for extracting part of a list.
568* cons:: Constructing a list.
569* nthcdr:: Calling @code{cdr} repeatedly.
570* nth::
571* setcar:: Changing the first element of a list.
572* setcdr:: Changing the rest of a list.
573* cons Exercise::
574
575@code{cons}
576
577* Build a list::
578* length:: How to find the length of a list.
579
580Cutting and Storing Text
581
582* Storing Text:: Text is stored in a list.
583* zap-to-char:: Cutting out text up to a character.
584* kill-region:: Cutting text out of a region.
585* Digression into C:: Minor note on C programming language macros.
586* defvar:: How to give a variable an initial value.
587* copy-region-as-kill:: A definition for copying text.
588* cons & search-fwd Review::
589* search Exercises::
590
591@code{zap-to-char}
592
593* Complete zap-to-char:: The complete implementation.
594* zap-to-char interactive:: A three part interactive expression.
595* zap-to-char body:: A short overview.
596* search-forward:: How to search for a string.
597* progn:: The @code{progn} special form.
598* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
599
600@code{kill-region}
601
602* Complete kill-region:: The function definition.
603* condition-case:: Dealing with a problem.
604* delete-and-extract-region:: Doing the work.
605
606Initializing a Variable with @code{defvar}
607
608* See variable current value::
609* defvar and asterisk:: An old-time convention.
610
611@code{copy-region-as-kill}
612
613* Complete copy-region-as-kill:: The complete function definition.
614* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
615
616The Body of @code{copy-region-as-kill}
617
618* last-command & this-command::
619* kill-append function::
620* kill-new function::
621
622How Lists are Implemented
623
624* Lists diagrammed::
625* Symbols as Chest:: Exploring a powerful metaphor.
626* List Exercise::
627
628Yanking Text Back
629
630* Kill Ring Overview:: The kill ring is a list.
631* kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
632* yank nthcdr Exercises::
633
634Loops and Recursion
635
636* while:: Causing a stretch of code to repeat.
637* dolist dotimes::
638* Recursion:: Causing a function to call itself.
639* Looping exercise::
640
641@code{while}
642
643* Looping with while:: Repeat so long as test returns true.
644* Loop Example:: A @code{while} loop that uses a list.
645* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
646* Incrementing Loop:: A loop with an incrementing counter.
647* Decrementing Loop:: A loop with a decrementing counter.
648
649A Loop with an Incrementing Counter
650
651* Incrementing Example:: Counting pebbles in a triangle.
652* Inc Example parts:: The parts of the function definition.
653* Inc Example altogether:: Putting the function definition together.
654
655Loop with a Decrementing Counter
656
657* Decrementing Example:: More pebbles on the beach.
658* Dec Example parts:: The parts of the function definition.
659* Dec Example altogether:: Putting the function definition together.
660
661Save your time: @code{dolist} and @code{dotimes}
662
663* dolist::
664* dotimes::
665
666Recursion
667
668* Building Robots:: Same model, different serial number ...
669* Recursive Definition Parts:: Walk until you stop ...
670* Recursion with list:: Using a list as the test whether to recurse.
671* Recursive triangle function::
672* Recursion with cond::
673* Recursive Patterns:: Often used templates.
674* No Deferment:: Don't store up work ...
675* No deferment solution::
676
677Recursion in Place of a Counter
678
679* Recursive Example arg of 1 or 2::
680* Recursive Example arg of 3 or 4::
681
682Recursive Patterns
683
684* Every::
685* Accumulate::
686* Keep::
687
688Regular Expression Searches
689
690* sentence-end:: The regular expression for @code{sentence-end}.
691* re-search-forward:: Very similar to @code{search-forward}.
692* forward-sentence:: A straightforward example of regexp search.
693* forward-paragraph:: A somewhat complex example.
694* etags:: How to create your own @file{TAGS} table.
695* Regexp Review::
696* re-search Exercises::
697
698@code{forward-sentence}
699
700* Complete forward-sentence::
701* fwd-sentence while loops:: Two @code{while} loops.
702* fwd-sentence re-search:: A regular expression search.
703
704@code{forward-paragraph}: a Goldmine of Functions
705
706* forward-paragraph in brief:: Key parts of the function definition.
707* fwd-para let:: The @code{let*} expression.
708* fwd-para while:: The forward motion @code{while} loop.
709* fwd-para between paragraphs:: Movement between paragraphs.
710* fwd-para within paragraph:: Movement within paragraphs.
711* fwd-para no fill prefix:: When there is no fill prefix.
712* fwd-para with fill prefix:: When there is a fill prefix.
713* fwd-para summary:: Summary of @code{forward-paragraph} code.
714
715Counting: Repetition and Regexps
716
717* Why Count Words::
718* count-words-region:: Use a regexp, but find a problem.
719* recursive-count-words:: Start with case of no words in region.
720* Counting Exercise::
721
722The @code{count-words-region} Function
723
724* Design count-words-region:: The definition using a @code{while} loop.
725* Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
726
727Counting Words in a @code{defun}
728
729* Divide and Conquer::
730* Words and Symbols:: What to count?
731* Syntax:: What constitutes a word or symbol?
732* count-words-in-defun:: Very like @code{count-words}.
733* Several defuns:: Counting several defuns in a file.
734* Find a File:: Do you want to look at a file?
735* lengths-list-file:: A list of the lengths of many definitions.
736* Several files:: Counting in definitions in different files.
737* Several files recursively:: Recursively counting in different files.
738* Prepare the data:: Prepare the data for display in a graph.
739
740Count Words in @code{defuns} in Different Files
741
742* lengths-list-many-files:: Return a list of the lengths of defuns.
743* append:: Attach one list to another.
744
745Prepare the Data for Display in a Graph
746
747* Sorting:: Sorting lists.
748* Files List:: Making a list of files.
749* Counting function definitions::
750
751Readying a Graph
752
753* Columns of a graph::
754* graph-body-print:: How to print the body of a graph.
755* recursive-graph-body-print::
756* Printed Axes::
757* Line Graph Exercise::
758
759Your @file{.emacs} File
760
761* Default Configuration::
762* Site-wide Init:: You can write site-wide init files.
763* defcustom:: Emacs will write code for you.
764* Beginning a .emacs File:: How to write a @code{.emacs file}.
765* Text and Auto-fill:: Automatically wrap lines.
766* Mail Aliases:: Use abbreviations for email addresses.
767* Indent Tabs Mode:: Don't use tabs with @TeX{}
768* Keybindings:: Create some personal keybindings.
769* Keymaps:: More about key binding.
770* Loading Files:: Load (i.e., evaluate) files automatically.
771* Autoload:: Make functions available.
772* Simple Extension:: Define a function; bind it to a key.
773* X11 Colors:: Colors in version 19 in X.
774* Miscellaneous::
775* Mode Line:: How to customize your mode line.
776
777Debugging
778
779* debug:: How to use the built-in debugger.
780* debug-on-entry:: Start debugging when you call a function.
781* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
782* edebug:: How to use Edebug, a source level debugger.
783* Debugging Exercises::
784
785Handling the Kill Ring
786
787* rotate-yank-pointer:: Move a pointer along a list and around.
788* yank:: Paste a copy of a clipped element.
789* yank-pop:: Insert first element pointed to.
790
791The @code{rotate-yank-pointer} Function
792
793* Understanding rotate-yk-ptr::
794* rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
795
796The Body of @code{rotate-yank-pointer}
797
798* Digression concerning error:: How to mislead humans, but not computers.
799* rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
800* Remainder Function:: The remainder, @code{%}, function.
801* rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
802* kill-rng-yk-ptr last elt:: Pointing to the last element.
803
804@code{yank}
805
806* rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
807* rotate-yk-ptr negative arg:: Pass a negative argument.
808
809A Graph with Labelled Axes
810
811* Labelled Example::
812* print-graph Varlist:: @code{let} expression in @code{print-graph}.
813* print-Y-axis:: Print a label for the vertical axis.
814* print-X-axis:: Print a horizontal label.
815* Print Whole Graph:: The function to print a complete graph.
816
817The @code{print-Y-axis} Function
818
819* Height of label:: What height for the Y axis?
820* Compute a Remainder:: How to compute the remainder of a division.
821* Y Axis Element:: Construct a line for the Y axis.
822* Y-axis-column:: Generate a list of Y axis labels.
823* print-Y-axis Penultimate:: A not quite final version.
824
825The @code{print-X-axis} Function
826
827* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
828* X Axis Tic Marks:: Create tic marks for the horizontal axis.
829
830Printing the Whole Graph
831
832* The final version:: A few changes.
833* Test print-graph:: Run a short test.
834* Graphing words in defuns:: Executing the final code.
835* lambda:: How to write an anonymous function.
836* mapcar:: Apply a function to elements of a list.
837* Another Bug:: Yet another bug @dots{} most insidious.
838* Final printed graph:: The graph itself!
839
840@end detailmenu
841@end menu
842
843@node Preface, List Processing, Top, Top
844@comment node-name, next, previous, up
845@unnumbered Preface
846
847Most of the GNU Emacs integrated environment is written in the programming
848language called Emacs Lisp. The code written in this programming
849language is the software---the sets of instructions---that tell the
850computer what to do when you give it commands. Emacs is designed so
851that you can write new code in Emacs Lisp and easily install it as an
852extension to the editor.
853
854(GNU Emacs is sometimes called an ``extensible editor'', but it does
855much more than provide editing capabilities. It is better to refer to
856Emacs as an ``extensible computing environment''. However, that
857phrase is quite a mouthful. It is easier to refer to Emacs simply as
858an editor. Moreover, everything you do in Emacs---find the Mayan date
859and phases of the moon, simplify polynomials, debug code, manage
860files, read letters, write books---all these activities are kinds of
861editing in the most general sense of the word.)
862
863@menu
864* Why:: Why learn Emacs Lisp?
865* On Reading this Text:: Read, gain familiarity, pick up habits....
866* Who You Are:: For whom this is written.
867* Lisp History::
868* Note for Novices:: You can read this as a novice.
869* Thank You::
870@end menu
871
872@node Why, On Reading this Text, Preface, Preface
873@ifnottex
874@unnumberedsec Why Study Emacs Lisp?
875@end ifnottex
876
877Although Emacs Lisp is usually thought of in association only with Emacs,
878it is a full computer programming language. You can use Emacs Lisp as
879you would any other programming language.
880
881Perhaps you want to understand programming; perhaps you want to extend
882Emacs; or perhaps you want to become a programmer. This introduction to
883Emacs Lisp is designed to get you started: to guide you in learning the
884fundamentals of programming, and more importantly, to show you how you
885can teach yourself to go further.
886
887@node On Reading this Text, Who You Are, Why, Preface
888@comment node-name, next, previous, up
889@unnumberedsec On Reading this Text
890
891All through this document, you will see little sample programs you can
892run inside of Emacs. If you read this document in Info inside of GNU
893Emacs, you can run the programs as they appear. (This is easy to do and
894is explained when the examples are presented.) Alternatively, you can
895read this introduction as a printed book while sitting beside a computer
896running Emacs. (This is what I like to do; I like printed books.) If
897you don't have a running Emacs beside you, you can still read this book,
898but in this case, it is best to treat it as a novel or as a travel guide
899to a country not yet visited: interesting, but not the same as being
900there.
901
902Much of this introduction is dedicated to walk-throughs or guided tours
903of code used in GNU Emacs. These tours are designed for two purposes:
904first, to give you familiarity with real, working code (code you use
905every day); and, second, to give you familiarity with the way Emacs
906works. It is interesting to see how a working environment is
907implemented.
908Also, I
909hope that you will pick up the habit of browsing through source code.
910You can learn from it and mine it for ideas. Having GNU Emacs is like
911having a dragon's cave of treasures.
912
913In addition to learning about Emacs as an editor and Emacs Lisp as a
914programming language, the examples and guided tours will give you an
915opportunity to get acquainted with Emacs as a Lisp programming
916environment. GNU Emacs supports programming and provides tools that
917you will want to become comfortable using, such as @kbd{M-.} (the key
918which invokes the @code{find-tag} command). You will also learn about
919buffers and other objects that are part of the environment.
920Learning about these features of Emacs is like learning new routes
921around your home town.
922
923@ignore
924In addition, I have written several programs as extended examples.
925Although these are examples, the programs are real. I use them.
926Other people use them. You may use them. Beyond the fragments of
927programs used for illustrations, there is very little in here that is
928`just for teaching purposes'; what you see is used. This is a great
929advantage of Emacs Lisp: it is easy to learn to use it for work.
930@end ignore
931
932Finally, I hope to convey some of the skills for using Emacs to
933learn aspects of programming that you don't know. You can often use
934Emacs to help you understand what puzzles you or to find out how to do
935something new. This self-reliance is not only a pleasure, but an
936advantage.
937
938@node Who You Are, Lisp History, On Reading this Text, Preface
939@comment node-name, next, previous, up
940@unnumberedsec For Whom This is Written
941
942This text is written as an elementary introduction for people who are
943not programmers. If you are a programmer, you may not be satisfied with
944this primer. The reason is that you may have become expert at reading
945reference manuals and be put off by the way this text is organized.
946
947An expert programmer who reviewed this text said to me:
948
949@quotation
950@i{I prefer to learn from reference manuals. I ``dive into'' each
951paragraph, and ``come up for air'' between paragraphs.}
952
953@i{When I get to the end of a paragraph, I assume that that subject is
954done, finished, that I know everything I need (with the
955possible exception of the case when the next paragraph starts talking
956about it in more detail). I expect that a well written reference manual
957will not have a lot of redundancy, and that it will have excellent
958pointers to the (one) place where the information I want is.}
959@end quotation
960
961This introduction is not written for this person!
962
963Firstly, I try to say everything at least three times: first, to
964introduce it; second, to show it in context; and third, to show it in a
965different context, or to review it.
966
967Secondly, I hardly ever put all the information about a subject in one
968place, much less in one paragraph. To my way of thinking, that imposes
969too heavy a burden on the reader. Instead I try to explain only what
970you need to know at the time. (Sometimes I include a little extra
971information so you won't be surprised later when the additional
972information is formally introduced.)
973
974When you read this text, you are not expected to learn everything the
975first time. Frequently, you need only make, as it were, a `nodding
976acquaintance' with some of the items mentioned. My hope is that I have
977structured the text and given you enough hints that you will be alert to
978what is important, and concentrate on it.
979
980You will need to ``dive into'' some paragraphs; there is no other way
981to read them. But I have tried to keep down the number of such
982paragraphs. This book is intended as an approachable hill, rather than
983as a daunting mountain.
984
985This introduction to @cite{Programming in Emacs Lisp} has a companion
986document,
987@iftex
988@cite{The GNU Emacs Lisp Reference Manual}.
989@end iftex
990@ifnottex
991@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
992Emacs Lisp Reference Manual}.
993@end ifnottex
994The reference manual has more detail than this introduction. In the
995reference manual, all the information about one topic is concentrated
996in one place. You should turn to it if you are like the programmer
997quoted above. And, of course, after you have read this
998@cite{Introduction}, you will find the @cite{Reference Manual} useful
999when you are writing your own programs.
1000
1001@node Lisp History, Note for Novices, Who You Are, Preface
1002@unnumberedsec Lisp History
1003@cindex Lisp history
1004
1005Lisp was first developed in the late 1950s at the Massachusetts
1006Institute of Technology for research in artificial intelligence. The
1007great power of the Lisp language makes it superior for other purposes as
1008well, such as writing editor commands and integrated environments.
1009
1010@cindex Maclisp
1011@cindex Common Lisp
1012GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1013in the 1960s. It is somewhat inspired by Common Lisp, which became a
1014standard in the 1980s. However, Emacs Lisp is much simpler than Common
1015Lisp. (The standard Emacs distribution contains an optional extensions
1016file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1017
1018@node Note for Novices, Thank You, Lisp History, Preface
1019@comment node-name, next, previous, up
1020@unnumberedsec A Note for Novices
1021
1022If you don't know GNU Emacs, you can still read this document
1023profitably. However, I recommend you learn Emacs, if only to learn to
1024move around your computer screen. You can teach yourself how to use
1025Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1026means you press and release the @key{CTRL} key and the @kbd{h} at the
1027same time, and then press and release @kbd{t}.)
1028
1029Also, I often refer to one of Emacs' standard commands by listing the
1030keys which you press to invoke the command and then giving the name of
1031the command in parentheses, like this: @kbd{M-C-\}
1032(@code{indent-region}). What this means is that the
1033@code{indent-region} command is customarily invoked by typing
1034@kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1035invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1036Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1037@key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1038(On many modern keyboards the @key{META} key is labelled
1039@key{ALT}.)
1040Sometimes a combination like this is called a keychord, since it is
1041similar to the way you play a chord on a piano. If your keyboard does
1042not have a @key{META} key, the @key{ESC} key prefix is used in place
1043of it. In this case, @kbd{M-C-\} means that you press and release your
1044@key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1045the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
1046along with the key that is labelled @key{ALT} and, at the same time,
1047press the @key{\} key.
1048
1049In addition to typing a lone keychord, you can prefix what you type
1050with @kbd{C-u}, which is called the `universal argument'. The
1051@kbd{C-u} keychord passes an argument to the subsequent command.
1052Thus, to indent a region of plain text by 6 spaces, mark the region,
1053and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1054Emacs either passes the number 4 to the command or otherwise runs the
1055command differently than it would otherwise.) @xref{Arguments, ,
1056Numeric Arguments, emacs, The GNU Emacs Manual}.
1057
1058If you are reading this in Info using GNU Emacs, you can read through
1059this whole document just by pressing the space bar, @key{SPC}.
1060(To learn about Info, type @kbd{C-h i} and then select Info.)
1061
1062A note on terminology: when I use the word Lisp alone, I often am
1063referring to the various dialects of Lisp in general, but when I speak
1064of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1065
1066@node Thank You, , Note for Novices, Preface
1067@comment node-name, next, previous, up
1068@unnumberedsec Thank You
1069
1070My thanks to all who helped me with this book. My especial thanks to
1071@r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1072McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1073Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1074@w{Philip Johnson} and @w{David Stampe} for their patient
1075encouragement. My mistakes are my own.
1076
1077@flushright
1078Robert J. Chassell
1079@end flushright
1080
1081@c ================ Beginning of main text ================
1082
1083@c Start main text on right-hand (verso) page
1084
1085@tex
1086\par\vfill\supereject
1087\headings off
1088\ifodd\pageno
1089 \par\vfill\supereject
1090\else
1091 \par\vfill\supereject
1092 \page\hbox{}\page
1093 \par\vfill\supereject
1094\fi
1095@end tex
1096
1097@iftex
1098@headings off
1099@evenheading @thispage @| @| @thischapter
1100@oddheading @thissection @| @| @thispage
1101@pageno = 1
1102@end iftex
1103
1104@node List Processing, Practicing Evaluation, Preface, Top
1105@comment node-name, next, previous, up
1106@chapter List Processing
1107
1108To the untutored eye, Lisp is a strange programming language. In Lisp
1109code there are parentheses everywhere. Some people even claim that the
1110name stands for `Lots of Isolated Silly Parentheses'. But the claim is
1111unwarranted. Lisp stands for LISt Processing, and the programming
1112language handles @emph{lists} (and lists of lists) by putting them
1113between parentheses. The parentheses mark the boundaries of the list.
1114Sometimes a list is preceded by a single apostrophe or quotation mark,
1115@samp{'}. Lists are the basis of Lisp.
1116
1117@menu
1118* Lisp Lists:: What are lists?
1119* Run a Program:: Any list in Lisp is a program ready to run.
1120* Making Errors:: Generating an error message.
1121* Names & Definitions:: Names of symbols and function definitions.
1122* Lisp Interpreter:: What the Lisp interpreter does.
1123* Evaluation:: Running a program.
1124* Variables:: Returning a value from a variable.
1125* Arguments:: Passing information to a function.
1126* set & setq:: Setting the value of a variable.
1127* Summary:: The major points.
1128* Error Message Exercises::
1129@end menu
1130
1131@node Lisp Lists, Run a Program, List Processing, List Processing
1132@comment node-name, next, previous, up
1133@section Lisp Lists
1134@cindex Lisp Lists
1135
1136In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1137This list is preceded by a single apostrophe. It could just as well be
1138written as follows, which looks more like the kind of list you are likely
1139to be familiar with:
1140
1141@smallexample
1142@group
1143'(rose
1144 violet
1145 daisy
1146 buttercup)
1147@end group
1148@end smallexample
1149
1150@noindent
1151The elements of this list are the names of the four different flowers,
1152separated from each other by whitespace and surrounded by parentheses,
1153like flowers in a field with a stone wall around them.
1154@cindex Flowers in a field
1155
1156@menu
1157* Numbers Lists:: List have numbers, other lists, in them.
1158* Lisp Atoms:: Elemental entities.
1159* Whitespace in Lists:: Formating lists to be readable.
1160* Typing Lists:: How GNU Emacs helps you type lists.
1161@end menu
1162
1163@node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1164@ifnottex
1165@unnumberedsubsec Numbers, Lists inside of Lists
1166@end ifnottex
1167
1168Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1169This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1170separated by whitespace.
1171
1172In Lisp, both data and programs are represented the same way; that is,
1173they are both lists of words, numbers, or other lists, separated by
1174whitespace and surrounded by parentheses. (Since a program looks like
1175data, one program may easily serve as data for another; this is a very
1176powerful feature of Lisp.) (Incidentally, these two parenthetical
1177remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1178@samp{.} as punctuation marks.)
1179
1180@need 1200
1181Here is another list, this time with a list inside of it:
1182
1183@smallexample
1184'(this list has (a list inside of it))
1185@end smallexample
1186
1187The components of this list are the words @samp{this}, @samp{list},
1188@samp{has}, and the list @samp{(a list inside of it)}. The interior
1189list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1190@samp{of}, @samp{it}.
1191
1192@node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1193@comment node-name, next, previous, up
1194@subsection Lisp Atoms
1195@cindex Lisp Atoms
1196
1197In Lisp, what we have been calling words are called @dfn{atoms}. This
1198term comes from the historical meaning of the word atom, which means
1199`indivisible'. As far as Lisp is concerned, the words we have been
1200using in the lists cannot be divided into any smaller parts and still
1201mean the same thing as part of a program; likewise with numbers and
1202single character symbols like @samp{+}. On the other hand, unlike an
1203atom, a list can be split into parts. (@xref{car cdr & cons, ,
1204@code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1205
1206In a list, atoms are separated from each other by whitespace. They can be
1207right next to a parenthesis.
1208
1209@cindex @samp{empty list} defined
1210Technically speaking, a list in Lisp consists of parentheses surrounding
1211atoms separated by whitespace or surrounding other lists or surrounding
1212both atoms and other lists. A list can have just one atom in it or
1213have nothing in it at all. A list with nothing in it looks like this:
1214@code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1215empty list is considered both an atom and a list at the same time.
1216
1217@cindex Symbolic expressions, introduced
1218@cindex @samp{expression} defined
1219@cindex @samp{form} defined
1220The printed representation of both atoms and lists are called
1221@dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1222The word @dfn{expression} by itself can refer to either the printed
1223representation, or to the atom or list as it is held internally in the
1224computer. Often, people use the term @dfn{expression}
1225indiscriminately. (Also, in many texts, the word @dfn{form} is used
1226as a synonym for expression.)
1227
1228Incidentally, the atoms that make up our universe were named such when
1229they were thought to be indivisible; but it has been found that physical
1230atoms are not indivisible. Parts can split off an atom or it can
1231fission into two parts of roughly equal size. Physical atoms were named
1232prematurely, before their truer nature was found. In Lisp, certain
1233kinds of atom, such as an array, can be separated into parts; but the
1234mechanism for doing this is different from the mechanism for splitting a
1235list. As far as list operations are concerned, the atoms of a list are
1236unsplittable.
1237
1238As in English, the meanings of the component letters of a Lisp atom
1239are different from the meaning the letters make as a word. For
1240example, the word for the South American sloth, the @samp{ai}, is
1241completely different from the two words, @samp{a}, and @samp{i}.
1242
1243There are many kinds of atom in nature but only a few in Lisp: for
1244example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1245as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1246listed in the examples above are all symbols. In everyday Lisp
1247conversation, the word ``atom'' is not often used, because programmers
1248usually try to be more specific about what kind of atom they are dealing
1249with. Lisp programming is mostly about symbols (and sometimes numbers)
1250within lists. (Incidentally, the preceding three word parenthetical
1251remark is a proper list in Lisp, since it consists of atoms, which in
1252this case are symbols, separated by whitespace and enclosed by
1253parentheses, without any non-Lisp punctuation.)
1254
1255@need 1250
1256In addition, text between double quotation marks---even sentences or
1257paragraphs---is an atom. Here is an example:
1258@cindex Text between double quotation marks
1259
1260@smallexample
1261'(this list includes "text between quotation marks.")
1262@end smallexample
1263
1264@cindex @samp{string} defined
1265@noindent
1266In Lisp, all of the quoted text including the punctuation mark and the
1267blank spaces is a single atom. This kind of atom is called a
1268@dfn{string} (for `string of characters') and is the sort of thing that
1269is used for messages that a computer can print for a human to read.
1270Strings are a different kind of atom than numbers or symbols and are
1271used differently.
1272
1273@node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1274@comment node-name, next, previous, up
1275@subsection Whitespace in Lists
1276@cindex Whitespace in lists
1277
1278@need 1200
1279The amount of whitespace in a list does not matter. From the point of view
1280of the Lisp language,
1281
1282@smallexample
1283@group
1284'(this list
1285 looks like this)
1286@end group
1287@end smallexample
1288
1289@need 800
1290@noindent
1291is exactly the same as this:
1292
1293@smallexample
1294'(this list looks like this)
1295@end smallexample
1296
1297Both examples show what to Lisp is the same list, the list made up of
1298the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1299@samp{this} in that order.
1300
1301Extra whitespace and newlines are designed to make a list more readable
1302by humans. When Lisp reads the expression, it gets rid of all the extra
1303whitespace (but it needs to have at least one space between atoms in
1304order to tell them apart.)
1305
1306Odd as it seems, the examples we have seen cover almost all of what Lisp
1307lists look like! Every other list in Lisp looks more or less like one
1308of these examples, except that the list may be longer and more complex.
1309In brief, a list is between parentheses, a string is between quotation
1310marks, a symbol looks like a word, and a number looks like a number.
1311(For certain situations, square brackets, dots and a few other special
1312characters may be used; however, we will go quite far without them.)
1313
1314@node Typing Lists, , Whitespace in Lists, Lisp Lists
1315@comment node-name, next, previous, up
1316@subsection GNU Emacs Helps You Type Lists
1317@cindex Help typing lists
1318@cindex Formatting help
1319
1320When you type a Lisp expression in GNU Emacs using either Lisp
1321Interaction mode or Emacs Lisp mode, you have available to you several
1322commands to format the Lisp expression so it is easy to read. For
1323example, pressing the @key{TAB} key automatically indents the line the
1324cursor is on by the right amount. A command to properly indent the
1325code in a region is customarily bound to @kbd{M-C-\}. Indentation is
1326designed so that you can see which elements of a list belongs to which
1327list---elements of a sub-list are indented more than the elements of
1328the enclosing list.
1329
1330In addition, when you type a closing parenthesis, Emacs momentarily
1331jumps the cursor back to the matching opening parenthesis, so you can
1332see which one it is. This is very useful, since every list you type
1333in Lisp must have its closing parenthesis match its opening
1334parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1335Manual}, for more information about Emacs' modes.)
1336
1337@node Run a Program, Making Errors, Lisp Lists, List Processing
1338@comment node-name, next, previous, up
1339@section Run a Program
1340@cindex Run a program
1341@cindex Program, running one
1342
1343@cindex @samp{evaluate} defined
1344A list in Lisp---any list---is a program ready to run. If you run it
1345(for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1346of three things: do nothing except return to you the list itself; send
1347you an error message; or, treat the first symbol in the list as a
1348command to do something. (Usually, of course, it is the last of these
1349three things that you really want!)
1350
1351@c use code for the single apostrophe, not samp.
1352The single apostrophe, @code{'}, that I put in front of some of the
1353example lists in preceding sections is called a @dfn{quote}; when it
1354precedes a list, it tells Lisp to do nothing with the list, other than
1355take it as it is written. But if there is no quote preceding a list,
1356the first item of the list is special: it is a command for the computer
1357to obey. (In Lisp, these commands are called @emph{functions}.) The list
1358@code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1359understands that the @code{+} is an instruction to do something with the
1360rest of the list: add the numbers that follow.
1361
1362@need 1250
1363If you are reading this inside of GNU Emacs in Info, here is how you can
1364evaluate such a list: place your cursor immediately after the right
1365hand parenthesis of the following list and then type @kbd{C-x C-e}:
1366
1367@smallexample
1368(+ 2 2)
1369@end smallexample
1370
1371@c use code for the number four, not samp.
1372@noindent
1373You will see the number @code{4} appear in the echo area. (In the
1374jargon, what you have just done is ``evaluate the list.'' The echo area
1375is the line at the bottom of the screen that displays or ``echoes''
1376text.) Now try the same thing with a quoted list: place the cursor
1377right after the following list and type @kbd{C-x C-e}:
1378
1379@smallexample
1380'(this is a quoted list)
1381@end smallexample
1382
1383@noindent
1384You will see @code{(this is a quoted list)} appear in the echo area.
1385
1386@cindex Lisp interpreter, explained
1387@cindex Interpreter, Lisp, explained
1388In both cases, what you are doing is giving a command to the program
1389inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1390interpreter a command to evaluate the expression. The name of the Lisp
1391interpreter comes from the word for the task done by a human who comes
1392up with the meaning of an expression---who ``interprets'' it.
1393
1394You can also evaluate an atom that is not part of a list---one that is
1395not surrounded by parentheses; again, the Lisp interpreter translates
1396from the humanly readable expression to the language of the computer.
1397But before discussing this (@pxref{Variables}), we will discuss what the
1398Lisp interpreter does when you make an error.
1399
1400@node Making Errors, Names & Definitions, Run a Program, List Processing
1401@comment node-name, next, previous, up
1402@section Generate an Error Message
1403@cindex Generate an error message
1404@cindex Error message generation
1405
1406Partly so you won't worry if you do it accidentally, we will now give
1407a command to the Lisp interpreter that generates an error message.
1408This is a harmless activity; and indeed, we will often try to generate
1409error messages intentionally. Once you understand the jargon, error
1410messages can be informative. Instead of being called ``error''
1411messages, they should be called ``help'' messages. They are like
1412signposts to a traveller in a strange country; deciphering them can be
1413hard, but once understood, they can point the way.
1414
1415The error message is generated by a built-in GNU Emacs debugger. We
1416will `enter the debugger'. You get out of the debugger by typing @code{q}.
1417
1418What we will do is evaluate a list that is not quoted and does not
1419have a meaningful command as its first element. Here is a list almost
1420exactly the same as the one we just used, but without the single-quote
1421in front of it. Position the cursor right after it and type @kbd{C-x
1422C-e}:
1423
1424@smallexample
1425(this is an unquoted list)
1426@end smallexample
1427
1428@noindent
1429What you see depends on which version of Emacs you are running. GNU
1430Emacs version 21 provides more information than version 20 and before.
1431First, the more recent result of generating an error; then the
1432earlier, version 20 result.
1433
1434@need 1250
1435@noindent
1436In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1437you will see the following in it:
1438
1439@smallexample
1440@group
1441---------- Buffer: *Backtrace* ----------
1442Debugger entered--Lisp error: (void-function this)
1443 (this is an unquoted list)
1444 eval((this is an unquoted list))
1445 eval-last-sexp-1(nil)
1446 eval-last-sexp(nil)
1447 call-interactively(eval-last-sexp)
1448---------- Buffer: *Backtrace* ----------
1449@end group
1450@end smallexample
1451
1452@need 1200
1453@noindent
1454Your cursor will be in this window (you may have to wait a few seconds
1455before it becomes visible). To quit the debugger and make the
1456debugger window go away, type:
1457
1458@smallexample
1459q
1460@end smallexample
1461
1462@noindent
1463Please type @kbd{q} right now, so you become confident that you can
1464get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1465it.
1466
1467@cindex @samp{function} defined
1468Based on what we already know, we can almost read this error message.
1469
1470You read the @file{*Backtrace*} buffer from the bottom up; it tells
1471you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1472interactive call to the command @code{eval-last-sexp}. @code{eval} is
1473an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1474`symbolic expression'. The command means `evaluate last symbolic
1475expression', which is the expression just before your cursor.
1476
1477Each line above tells you what the Lisp interpreter evaluated next.
1478The most recent action is at the top. The buffer is called the
1479@file{*Backtrace*} buffer because it enables you to track Emacs
1480backwards.
1481
1482@need 800
1483At the top of the @file{*Backtrace*} buffer, you see the line:
1484
1485@smallexample
1486Debugger entered--Lisp error: (void-function this)
1487@end smallexample
1488
1489@noindent
1490The Lisp interpreter tried to evaluate the first atom of the list, the
1491word @samp{this}. It is this action that generated the error message
1492@samp{void-function this}.
1493
1494The message contains the words @samp{void-function} and @samp{this}.
1495
1496@cindex @samp{function} defined
1497The word @samp{function} was mentioned once before. It is a very
1498important word. For our purposes, we can define it by saying that a
1499@dfn{function} is a set of instructions to the computer that tell the
1500computer to do something.
1501
1502Now we can begin to understand the error message: @samp{void-function
1503this}. The function (that is, the word @samp{this}) does not have a
1504definition of any set of instructions for the computer to carry out.
1505
1506The slightly odd word, @samp{void-function}, is designed to cover the
1507way Emacs Lisp is implemented, which is that when a symbol does not
1508have a function definition attached to it, the place that should
1509contain the instructions is `void'.
1510
1511On the other hand, since we were able to add 2 plus 2 successfully, by
1512evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1513have a set of instructions for the computer to obey and those
1514instructions must be to add the numbers that follow the @code{+}.
1515
1516@need 1250
1517In GNU Emacs version 20, and in earlier versions, you will see only
1518one line of error message; it will appear in the echo area and look
1519like this:
1520
1521@smallexample
1522Symbol's function definition is void:@: this
1523@end smallexample
1524
1525@noindent
1526(Also, your terminal may beep at you---some do, some don't; and others
1527blink. This is just a device to get your attention.) The message goes
1528away as soon as you type another key, even just to move the cursor.
1529
1530We know the meaning of the word @samp{Symbol}. It refers to the first
1531atom of the list, the word @samp{this}. The word @samp{function}
1532refers to the instructions that tell the computer what to do.
1533(Technically, the symbol tells the computer where to find the
1534instructions, but this is a complication we can ignore for the
1535moment.)
1536
1537The error message can be understood: @samp{Symbol's function
1538definition is void:@: this}. The symbol (that is, the word
1539@samp{this}) lacks instructions for the computer to carry out.
1540
1541@node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1542@comment node-name, next, previous, up
1543@section Symbol Names and Function Definitions
1544@cindex Symbol names
1545
1546We can articulate another characteristic of Lisp based on what we have
1547discussed so far---an important characteristic: a symbol, like
1548@code{+}, is not itself the set of instructions for the computer to
1549carry out. Instead, the symbol is used, perhaps temporarily, as a way
1550of locating the definition or set of instructions. What we see is the
1551name through which the instructions can be found. Names of people
1552work the same way. I can be referred to as @samp{Bob}; however, I am
1553not the letters @samp{B}, @samp{o}, @samp{b} but am the consciousness
1554consistently associated with a particular life-form. The name is not
1555me, but it can be used to refer to me.
1556
1557In Lisp, one set of instructions can be attached to several names.
1558For example, the computer instructions for adding numbers can be
1559linked to the symbol @code{plus} as well as to the symbol @code{+}
1560(and are in some dialects of Lisp). Among humans, I can be referred
1561to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1562
1563On the other hand, a symbol can have only one function definition
1564attached to it at a time. Otherwise, the computer would be confused as
1565to which definition to use. If this were the case among people, only
1566one person in the world could be named @samp{Bob}. However, the function
1567definition to which the name refers can be changed readily.
1568(@xref{Install, , Install a Function Definition}.)
1569
1570Since Emacs Lisp is large, it is customary to name symbols in a way
1571that identifies the part of Emacs to which the function belongs.
1572Thus, all the names for functions that deal with Texinfo start with
1573@samp{texinfo-} and those for functions that deal with reading mail
1574start with @samp{rmail-}.
1575
1576@node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1577@comment node-name, next, previous, up
1578@section The Lisp Interpreter
1579@cindex Lisp interpreter, what it does
1580@cindex Interpreter, what it does
1581
1582Based on what we have seen, we can now start to figure out what the
1583Lisp interpreter does when we command it to evaluate a list.
1584First, it looks to see whether there is a quote before the list; if
1585there is, the interpreter just gives us the list. On the other
1586hand, if there is no quote, the interpreter looks at the first element
1587in the list and sees whether it has a function definition. If it does,
1588the interpreter carries out the instructions in the function definition.
1589Otherwise, the interpreter prints an error message.
1590
1591This is how Lisp works. Simple. There are added complications which we
1592will get to in a minute, but these are the fundamentals. Of course, to
1593write Lisp programs, you need to know how to write function definitions
1594and attach them to names, and how to do this without confusing either
1595yourself or the computer.
1596
1597@menu
1598* Complications:: Variables, Special forms, Lists within.
1599* Byte Compiling:: Specially processing code for speed.
1600@end menu
1601
1602@node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1603@ifnottex
1604@unnumberedsubsec Complications
1605@end ifnottex
1606
1607Now, for the first complication. In addition to lists, the Lisp
1608interpreter can evaluate a symbol that is not quoted and does not have
1609parentheses around it. The Lisp interpreter will attempt to determine
1610the symbol's value as a @dfn{variable}. This situation is described
1611in the section on variables. (@xref{Variables}.)
1612
1613@cindex Special form
1614The second complication occurs because some functions are unusual and do
1615not work in the usual manner. Those that don't are called @dfn{special
1616forms}. They are used for special jobs, like defining a function, and
1617there are not many of them. In the next few chapters, you will be
1618introduced to several of the more important special forms.
1619
1620The third and final complication is this: if the function that the
1621Lisp interpreter is looking at is not a special form, and if it is part
1622of a list, the Lisp interpreter looks to see whether the list has a list
1623inside of it. If there is an inner list, the Lisp interpreter first
1624figures out what it should do with the inside list, and then it works on
1625the outside list. If there is yet another list embedded inside the
1626inner list, it works on that one first, and so on. It always works on
1627the innermost list first. The interpreter works on the innermost list
1628first, to evaluate the result of that list. The result may be
1629used by the enclosing expression.
1630
1631Otherwise, the interpreter works left to right, from one expression to
1632the next.
1633
1634@node Byte Compiling, , Complications, Lisp Interpreter
1635@subsection Byte Compiling
1636@cindex Byte compiling
1637
1638One other aspect of interpreting: the Lisp interpreter is able to
1639interpret two kinds of entity: humanly readable code, on which we will
1640focus exclusively, and specially processed code, called @dfn{byte
1641compiled} code, which is not humanly readable. Byte compiled code
1642runs faster than humanly readable code.
1643
1644You can transform humanly readable code into byte compiled code by
1645running one of the compile commands such as @code{byte-compile-file}.
1646Byte compiled code is usually stored in a file that ends with a
1647@file{.elc} extension rather than a @file{.el} extension. You will
1648see both kinds of file in the @file{emacs/lisp} directory; the files
1649to read are those with @file{.el} extensions.
1650
1651As a practical matter, for most things you might do to customize or
1652extend Emacs, you do not need to byte compile; and I will not discuss
1653the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1654The GNU Emacs Lisp Reference Manual}, for a full description of byte
1655compilation.
1656
1657@node Evaluation, Variables, Lisp Interpreter, List Processing
1658@comment node-name, next, previous, up
1659@section Evaluation
1660@cindex Evaluation
1661
1662When the Lisp interpreter works on an expression, the term for the
1663activity is called @dfn{evaluation}. We say that the interpreter
1664`evaluates the expression'. I've used this term several times before.
1665The word comes from its use in everyday language, `to ascertain the
1666value or amount of; to appraise', according to @cite{Webster's New
1667Collegiate Dictionary}.
1668
1669After evaluating an expression, the Lisp interpreter will most likely
1670@dfn{return} the value that the computer produces by carrying out the
1671instructions it found in the function definition, or perhaps it will
1672give up on that function and produce an error message. (The interpreter
1673may also find itself tossed, so to speak, to a different function or it
1674may attempt to repeat continually what it is doing for ever and ever in
1675what is called an `infinite loop'. These actions are less common; and
1676we can ignore them.) Most frequently, the interpreter returns a value.
1677
1678@cindex @samp{side effect} defined
1679At the same time the interpreter returns a value, it may do something
1680else as well, such as move a cursor or copy a file; this other kind of
1681action is called a @dfn{side effect}. Actions that we humans think are
1682important, such as printing results, are often ``side effects'' to the
1683Lisp interpreter. The jargon can sound peculiar, but it turns out that
1684it is fairly easy to learn to use side effects.
1685
1686In summary, evaluating a symbolic expression most commonly causes the
1687Lisp interpreter to return a value and perhaps carry out a side effect;
1688or else produce an error.
1689
1690@menu
1691* Evaluating Inner Lists:: Lists within lists...
1692@end menu
1693
1694@node Evaluating Inner Lists, , Evaluation, Evaluation
1695@comment node-name, next, previous, up
1696@subsection Evaluating Inner Lists
1697@cindex Inner list evaluation
1698@cindex Evaluating inner lists
1699
1700If evaluation applies to a list that is inside another list, the outer
1701list may use the value returned by the first evaluation as information
1702when the outer list is evaluated. This explains why inner expressions
1703are evaluated first: the values they return are used by the outer
1704expressions.
1705
1706@need 1250
1707We can investigate this process by evaluating another addition example.
1708Place your cursor after the following expression and type @kbd{C-x C-e}:
1709
1710@smallexample
1711(+ 2 (+ 3 3))
1712@end smallexample
1713
1714@noindent
1715The number 8 will appear in the echo area.
1716
1717What happens is that the Lisp interpreter first evaluates the inner
1718expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1719evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1720returns the value 8. Since there are no more enclosing expressions to
1721evaluate, the interpreter prints that value in the echo area.
1722
1723Now it is easy to understand the name of the command invoked by the
1724keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1725letters @code{sexp} are an abbreviation for `symbolic expression', and
1726@code{eval} is an abbreviation for `evaluate'. The command means
1727`evaluate last symbolic expression'.
1728
1729As an experiment, you can try evaluating the expression by putting the
1730cursor at the beginning of the next line immediately following the
1731expression, or inside the expression.
1732
1733@need 800
1734Here is another copy of the expression:
1735
1736@smallexample
1737(+ 2 (+ 3 3))
1738@end smallexample
1739
1740@noindent
1741If you place the cursor at the beginning of the blank line that
1742immediately follows the expression and type @kbd{C-x C-e}, you will
1743still get the value 8 printed in the echo area. Now try putting the
1744cursor inside the expression. If you put it right after the next to
1745last parenthesis (so it appears to sit on top of the last parenthesis),
1746you will get a 6 printed in the echo area! This is because the command
1747evaluates the expression @code{(+ 3 3)}.
1748
1749Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1750you will get the number itself. In Lisp, if you evaluate a number, you
1751get the number itself---this is how numbers differ from symbols. If you
1752evaluate a list starting with a symbol like @code{+}, you will get a
1753value returned that is the result of the computer carrying out the
1754instructions in the function definition attached to that name. If a
1755symbol by itself is evaluated, something different happens, as we will
1756see in the next section.
1757
1758@node Variables, Arguments, Evaluation, List Processing
1759@comment node-name, next, previous, up
1760@section Variables
1761@cindex Variables
1762
1763In Emacs Lisp, a symbol can have a value attached to it just as it can
1764have a function definition attached to it. The two are different.
1765The function definition is a set of instructions that a computer will
1766obey. A value, on the other hand, is something, such as number or a
1767name, that can vary (which is why such a symbol is called a variable).
1768The value of a symbol can be any expression in Lisp, such as a symbol,
1769number, list, or string. A symbol that has a value is often called a
1770@dfn{variable}.
1771
1772A symbol can have both a function definition and a value attached to
1773it at the same time. Or it can have just one or the other.
1774The two are separate. This is somewhat similar
1775to the way the name Cambridge can refer to the city in Massachusetts
1776and have some information attached to the name as well, such as
1777``great programming center''.
1778
1779@ignore
1780(Incidentally, in Emacs Lisp, a symbol can have two
1781other things attached to it, too: a property list and a documentation
1782string; these are discussed later.)
1783@end ignore
1784
1785Another way to think about this is to imagine a symbol as being a chest
1786of drawers. The function definition is put in one drawer, the value in
1787another, and so on. What is put in the drawer holding the value can be
1788changed without affecting the contents of the drawer holding the
1789function definition, and vice-versa.
1790
1791@menu
1792* fill-column Example::
1793* Void Function:: The error message for a symbol
1794 without a function.
1795* Void Variable:: The error message for a symbol without a value.
1796@end menu
1797
1798@node fill-column Example, Void Function, Variables, Variables
1799@ifnottex
1800@unnumberedsubsec @code{fill-column}, an Example Variable
1801@end ifnottex
1802
1803@findex fill-column, @r{an example variable}
1804@cindex Example variable, @code{fill-column}
1805@cindex Variable, example of, @code{fill-column}
1806The variable @code{fill-column} illustrates a symbol with a value
1807attached to it: in every GNU Emacs buffer, this symbol is set to some
1808value, usually 72 or 70, but sometimes to some other value. To find the
1809value of this symbol, evaluate it by itself. If you are reading this in
1810Info inside of GNU Emacs, you can do this by putting the cursor after
1811the symbol and typing @kbd{C-x C-e}:
1812
1813@smallexample
1814fill-column
1815@end smallexample
1816
1817@noindent
1818After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1819area. This is the value for which @code{fill-column} is set for me as I
1820write this. It may be different for you in your Info buffer. Notice
1821that the value returned as a variable is printed in exactly the same way
1822as the value returned by a function carrying out its instructions. From
1823the point of view of the Lisp interpreter, a value returned is a value
1824returned. What kind of expression it came from ceases to matter once
1825the value is known.
1826
1827A symbol can have any value attached to it or, to use the jargon, we can
1828@dfn{bind} the variable to a value: to a number, such as 72; to a
1829string, @code{"such as this"}; to a list, such as @code{(spruce pine
1830oak)}; we can even bind a variable to a function definition.
1831
1832A symbol can be bound to a value in several ways. @xref{set & setq, ,
1833Setting the Value of a Variable}, for information about one way to do
1834this.
1835
1836@node Void Function, Void Variable, fill-column Example, Variables
1837@comment node-name, next, previous, up
1838@subsection Error Message for a Symbol Without a Function
1839@cindex Symbol without function error
1840@cindex Error for symbol without function
1841
1842When we evaluated @code{fill-column} to find its value as a variable,
1843we did not place parentheses around the word. This is because we did
1844not intend to use it as a function name.
1845
1846If @code{fill-column} were the first or only element of a list, the
1847Lisp interpreter would attempt to find the function definition
1848attached to it. But @code{fill-column} has no function definition.
1849Try evaluating this:
1850
1851@smallexample
1852(fill-column)
1853@end smallexample
1854
1855@need 1250
1856@noindent
1857In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1858that says:
1859
1860@smallexample
1861@group
1862---------- Buffer: *Backtrace* ----------
1863Debugger entered--Lisp error: (void-function fill-column)
1864 (fill-column)
1865 eval((fill-column))
1866 eval-last-sexp-1(nil)
1867 eval-last-sexp(nil)
1868 call-interactively(eval-last-sexp)
1869---------- Buffer: *Backtrace* ----------
1870@end group
1871@end smallexample
1872
1873@noindent
1874(Remember, to quit the debugger and make the debugger window go away,
1875type @kbd{q} in the @file{*Backtrace*} buffer.)
1876
1877@need 800
1878In GNU Emacs 20 and before, you will produce an error message that says:
1879
1880@smallexample
1881Symbol's function definition is void:@: fill-column
1882@end smallexample
1883
1884@noindent
1885(The message will go away away as soon as you move the cursor or type
1886another key.)
1887
1888@node Void Variable, , Void Function, Variables
1889@comment node-name, next, previous, up
1890@subsection Error Message for a Symbol Without a Value
1891@cindex Symbol without value error
1892@cindex Error for symbol without value
1893
1894If you attempt to evaluate a symbol that does not have a value bound to
1895it, you will receive an error message. You can see this by
1896experimenting with our 2 plus 2 addition. In the following expression,
1897put your cursor right after the @code{+}, before the first number 2,
1898type @kbd{C-x C-e}:
1899
1900@smallexample
1901(+ 2 2)
1902@end smallexample
1903
1904@need 1500
1905@noindent
1906In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1907says:
1908
1909@smallexample
1910@group
1911---------- Buffer: *Backtrace* ----------
1912Debugger entered--Lisp error: (void-variable +)
1913 eval(+)
1914 eval-last-sexp-1(nil)
1915 eval-last-sexp(nil)
1916 call-interactively(eval-last-sexp)
1917---------- Buffer: *Backtrace* ----------
1918@end group
1919@end smallexample
1920
1921@noindent
1922(As with the other times we entered the debugger, you can quit by
1923typing @kbd{q} in the @file{*Backtrace*} buffer.)
1924
1925This backtrace is different from the very first error message we saw,
1926which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1927In this case, the function does not have a value as a variable; while
1928in the other error message, the function (the word `this') did not
1929have a definition.
1930
1931In this experiment with the @code{+}, what we did was cause the Lisp
1932interpreter to evaluate the @code{+} and look for the value of the
1933variable instead of the function definition. We did this by placing the
1934cursor right after the symbol rather than after the parenthesis of the
1935enclosing list as we did before. As a consequence, the Lisp interpreter
1936evaluated the preceding s-expression, which in this case was the
1937@code{+} by itself.
1938
1939Since @code{+} does not have a value bound to it, just the function
1940definition, the error message reported that the symbol's value as a
1941variable was void.
1942
1943@need 800
1944In GNU Emacs version 20 and before, your error message will say:
1945
1946@example
1947Symbol's value as variable is void:@: +
1948@end example
1949
1950@noindent
1951The meaning is the same as in GNU Emacs 21.
1952
1953@node Arguments, set & setq, Variables, List Processing
1954@comment node-name, next, previous, up
1955@section Arguments
1956@cindex Arguments
1957@cindex Passing information to functions
1958
1959To see how information is passed to functions, let's look again at
1960our old standby, the addition of two plus two. In Lisp, this is written
1961as follows:
1962
1963@smallexample
1964(+ 2 2)
1965@end smallexample
1966
1967If you evaluate this expression, the number 4 will appear in your echo
1968area. What the Lisp interpreter does is add the numbers that follow
1969the @code{+}.
1970
1971@cindex @samp{argument} defined
1972The numbers added by @code{+} are called the @dfn{arguments} of the
1973function @code{+}. These numbers are the information that is given to
1974or @dfn{passed} to the function.
1975
1976The word `argument' comes from the way it is used in mathematics and
1977does not refer to a disputation between two people; instead it refers to
1978the information presented to the function, in this case, to the
1979@code{+}. In Lisp, the arguments to a function are the atoms or lists
1980that follow the function. The values returned by the evaluation of
1981these atoms or lists are passed to the function. Different functions
1982require different numbers of arguments; some functions require none at
1983all.@footnote{It is curious to track the path by which the word `argument'
1984came to have two different meanings, one in mathematics and the other in
1985everyday English. According to the @cite{Oxford English Dictionary},
1986the word derives from the Latin for @samp{to make clear, prove}; thus it
1987came to mean, by one thread of derivation, `the evidence offered as
1988proof', which is to say, `the information offered', which led to its
1989meaning in Lisp. But in the other thread of derivation, it came to mean
1990`to assert in a manner against which others may make counter
1991assertions', which led to the meaning of the word as a disputation.
1992(Note here that the English word has two different definitions attached
1993to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1994have two different function definitions at the same time.)}
1995
1996@menu
1997* Data types:: Types of data passed to a function.
1998* Args as Variable or List:: An argument can be the value
1999 of a variable or list.
2000* Variable Number of Arguments:: Some functions may take a
2001 variable number of arguments.
2002* Wrong Type of Argument:: Passing an argument of the wrong type
2003 to a function.
2004* message:: A useful function for sending messages.
2005@end menu
2006
2007@node Data types, Args as Variable or List, Arguments, Arguments
2008@comment node-name, next, previous, up
2009@subsection Arguments' Data Types
2010@cindex Data types
2011@cindex Types of data
2012@cindex Arguments' data types
2013
2014The type of data that should be passed to a function depends on what
2015kind of information it uses. The arguments to a function such as
2016@code{+} must have values that are numbers, since @code{+} adds numbers.
2017Other functions use different kinds of data for their arguments.
2018
2019@findex concat
2020For example, the @code{concat} function links together or unites two or
2021more strings of text to produce a string. The arguments are strings.
2022Concatenating the two character strings @code{abc}, @code{def} produces
2023the single string @code{abcdef}. This can be seen by evaluating the
2024following:
2025
2026@smallexample
2027(concat "abc" "def")
2028@end smallexample
2029
2030@noindent
2031The value produced by evaluating this expression is @code{"abcdef"}.
2032
2033A function such as @code{substring} uses both a string and numbers as
2034arguments. The function returns a part of the string, a substring of
2035the first argument. This function takes three arguments. Its first
2036argument is the string of characters, the second and third arguments are
2037numbers that indicate the beginning and end of the substring. The
2038numbers are a count of the number of characters (including spaces and
2039punctuations) from the beginning of the string.
2040
2041@need 800
2042For example, if you evaluate the following:
2043
2044@smallexample
2045(substring "The quick brown fox jumped." 16 19)
2046@end smallexample
2047
2048@noindent
2049you will see @code{"fox"} appear in the echo area. The arguments are the
2050string and the two numbers.
2051
2052Note that the string passed to @code{substring} is a single atom even
2053though it is made up of several words separated by spaces. Lisp counts
2054everything between the two quotation marks as part of the string,
2055including the spaces. You can think of the @code{substring} function as
2056a kind of `atom smasher' since it takes an otherwise indivisible atom
2057and extracts a part. However, @code{substring} is only able to extract
2058a substring from an argument that is a string, not from another type of
2059atom such as a number or symbol.
2060
2061@node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2062@comment node-name, next, previous, up
2063@subsection An Argument as the Value of a Variable or List
2064
2065An argument can be a symbol that returns a value when it is evaluated.
2066For example, when the symbol @code{fill-column} by itself is evaluated,
2067it returns a number. This number can be used in an addition.
2068
2069@need 1250
2070Position the cursor after the following expression and type @kbd{C-x
2071C-e}:
2072
2073@smallexample
2074(+ 2 fill-column)
2075@end smallexample
2076
2077@noindent
2078The value will be a number two more than what you get by evaluating
2079@code{fill-column} alone. For me, this is 74, because the value of
2080@code{fill-column} is 72.
2081
2082As we have just seen, an argument can be a symbol that returns a value
2083when evaluated. In addition, an argument can be a list that returns a
2084value when it is evaluated. For example, in the following expression,
2085the arguments to the function @code{concat} are the strings
2086@w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2087@code{(number-to-string (+ 2 fill-column))}.
2088
2089@c For Emacs 21, need number-to-string
2090@smallexample
2091(concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2092@end smallexample
2093
2094@noindent
2095If you evaluate this expression---and if, as with my Emacs,
2096@code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2097appear in the echo area. (Note that you must put spaces after the
2098word @samp{The} and before the word @samp{red} so they will appear in
2099the final string. The function @code{number-to-string} converts the
2100integer that the addition function returns to a string.
2101@code{number-to-string} is also known as @code{int-to-string}.)
2102
2103@node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2104@comment node-name, next, previous, up
2105@subsection Variable Number of Arguments
2106@cindex Variable number of arguments
2107@cindex Arguments, variable number of
2108
2109Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2110number of arguments. (The @code{*} is the symbol for multiplication.)
2111This can be seen by evaluating each of the following expressions in
2112the usual way. What you will see in the echo area is printed in this
2113text after @samp{@result{}}, which you may read as `evaluates to'.
2114
2115@need 1250
2116In the first set, the functions have no arguments:
2117
2118@smallexample
2119@group
2120(+) @result{} 0
2121
2122(*) @result{} 1
2123@end group
2124@end smallexample
2125
2126@need 1250
2127In this set, the functions have one argument each:
2128
2129@smallexample
2130@group
2131(+ 3) @result{} 3
2132
2133(* 3) @result{} 3
2134@end group
2135@end smallexample
2136
2137@need 1250
2138In this set, the functions have three arguments each:
2139
2140@smallexample
2141@group
2142(+ 3 4 5) @result{} 12
2143
2144(* 3 4 5) @result{} 60
2145@end group
2146@end smallexample
2147
2148@node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2149@comment node-name, next, previous, up
2150@subsection Using the Wrong Type Object as an Argument
2151@cindex Wrong type of argument
2152@cindex Argument, wrong type of
2153
2154When a function is passed an argument of the wrong type, the Lisp
2155interpreter produces an error message. For example, the @code{+}
2156function expects the values of its arguments to be numbers. As an
2157experiment we can pass it the quoted symbol @code{hello} instead of a
2158number. Position the cursor after the following expression and type
2159@kbd{C-x C-e}:
2160
2161@smallexample
2162(+ 2 'hello)
2163@end smallexample
2164
2165@noindent
2166When you do this you will generate an error message. What has happened
2167is that @code{+} has tried to add the 2 to the value returned by
2168@code{'hello}, but the value returned by @code{'hello} is the symbol
2169@code{hello}, not a number. Only numbers can be added. So @code{+}
2170could not carry out its addition.
2171
2172@need 1250
2173In GNU Emacs version 21, you will create and enter a
2174@file{*Backtrace*} buffer that says:
2175
2176@noindent
2177@smallexample
2178@group
2179---------- Buffer: *Backtrace* ----------
2180Debugger entered--Lisp error:
2181 (wrong-type-argument number-or-marker-p hello)
2182 +(2 hello)
2183 eval((+ 2 (quote hello)))
2184 eval-last-sexp-1(nil)
2185 eval-last-sexp(nil)
2186 call-interactively(eval-last-sexp)
2187---------- Buffer: *Backtrace* ----------
2188@end group
2189@end smallexample
2190
2191@need 1250
2192As usual, the error message tries to be helpful and makes sense after you
2193learn how to read it.
2194
2195The first part of the error message is straightforward; it says
2196@samp{wrong type argument}. Next comes the mysterious jargon word
2197@w{@samp{number-or-marker-p}}. This word is trying to tell you what
2198kind of argument the @code{+} expected.
2199
2200The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2201trying to determine whether the information presented it (the value of
2202the argument) is a number or a marker (a special object representing a
2203buffer position). What it does is test to see whether the @code{+} is
2204being given numbers to add. It also tests to see whether the
2205argument is something called a marker, which is a specific feature of
2206Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2207When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2208its position is kept as a marker. The mark can be considered a
2209number---the number of characters the location is from the beginning
2210of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2211numeric value of marker positions as numbers.
2212
2213The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2214practice started in the early days of Lisp programming. The @samp{p}
2215stands for `predicate'. In the jargon used by the early Lisp
2216researchers, a predicate refers to a function to determine whether some
2217property is true or false. So the @samp{p} tells us that
2218@code{number-or-marker-p} is the name of a function that determines
2219whether it is true or false that the argument supplied is a number or
2220a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2221a function that tests whether its argument has the value of zero, and
2222@code{listp}, a function that tests whether its argument is a list.
2223
2224Finally, the last part of the error message is the symbol @code{hello}.
2225This is the value of the argument that was passed to @code{+}. If the
2226addition had been passed the correct type of object, the value passed
2227would have been a number, such as 37, rather than a symbol like
2228@code{hello}. But then you would not have got the error message.
2229
2230@need 1250
2231In GNU Emacs version 20 and before, the echo area displays an error
2232message that says:
2233
2234@smallexample
2235Wrong type argument:@: number-or-marker-p, hello
2236@end smallexample
2237
2238This says, in different words, the same as the top line of the
2239@file{*Backtrace*} buffer.
2240
2241@node message, , Wrong Type of Argument, Arguments
2242@comment node-name, next, previous, up
2243@subsection The @code{message} Function
2244@findex message
2245
2246Like @code{+}, the @code{message} function takes a variable number of
2247arguments. It is used to send messages to the user and is so useful
2248that we will describe it here.
2249
2250@need 1250
2251A message is printed in the echo area. For example, you can print a
2252message in your echo area by evaluating the following list:
2253
2254@smallexample
2255(message "This message appears in the echo area!")
2256@end smallexample
2257
2258The whole string between double quotation marks is a single argument
2259and is printed @i{in toto}. (Note that in this example, the message
2260itself will appear in the echo area within double quotes; that is
2261because you see the value returned by the @code{message} function. In
2262most uses of @code{message} in programs that you write, the text will
2263be printed in the echo area as a side-effect, without the quotes.
2264@xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2265detail}, for an example of this.)
2266
2267However, if there is a @samp{%s} in the quoted string of characters, the
2268@code{message} function does not print the @samp{%s} as such, but looks
2269to the argument that follows the string. It evaluates the second
2270argument and prints the value at the location in the string where the
2271@samp{%s} is.
2272
2273@need 1250
2274You can see this by positioning the cursor after the following
2275expression and typing @kbd{C-x C-e}:
2276
2277@smallexample
2278(message "The name of this buffer is: %s." (buffer-name))
2279@end smallexample
2280
2281@noindent
2282In Info, @code{"The name of this buffer is: *info*."} will appear in the
2283echo area. The function @code{buffer-name} returns the name of the
2284buffer as a string, which the @code{message} function inserts in place
2285of @code{%s}.
2286
2287To print a value as an integer, use @samp{%d} in the same way as
2288@samp{%s}. For example, to print a message in the echo area that
2289states the value of the @code{fill-column}, evaluate the following:
2290
2291@smallexample
2292(message "The value of fill-column is %d." fill-column)
2293@end smallexample
2294
2295@noindent
2296On my system, when I evaluate this list, @code{"The value of
2297fill-column is 72."} appears in my echo area@footnote{Actually, you
2298can use @code{%s} to print a number. It is non-specific. @code{%d}
2299prints only the part of a number left of a decimal point, and not
2300anything that is not a number.}.
2301
2302If there is more than one @samp{%s} in the quoted string, the value of
2303the first argument following the quoted string is printed at the
2304location of the first @samp{%s} and the value of the second argument is
2305printed at the location of the second @samp{%s}, and so on.
2306
2307@need 1250
2308For example, if you evaluate the following,
2309
2310@smallexample
2311@group
2312(message "There are %d %s in the office!"
2313 (- fill-column 14) "pink elephants")
2314@end group
2315@end smallexample
2316
2317@noindent
2318a rather whimsical message will appear in your echo area. On my system
2319it says, @code{"There are 58 pink elephants in the office!"}.
2320
2321The expression @code{(- fill-column 14)} is evaluated and the resulting
2322number is inserted in place of the @samp{%d}; and the string in double
2323quotes, @code{"pink elephants"}, is treated as a single argument and
2324inserted in place of the @samp{%s}. (That is to say, a string between
2325double quotes evaluates to itself, like a number.)
2326
2327Finally, here is a somewhat complex example that not only illustrates
2328the computation of a number, but also shows how you can use an
2329expression within an expression to generate the text that is substituted
2330for @samp{%s}:
2331
2332@smallexample
2333@group
2334(message "He saw %d %s"
2335 (- fill-column 34)
2336 (concat "red "
2337 (substring
2338 "The quick brown foxes jumped." 16 21)
2339 " leaping."))
2340@end group
2341@end smallexample
2342
2343In this example, @code{message} has three arguments: the string,
2344@code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2345the expression beginning with the function @code{concat}. The value
2346resulting from the evaluation of @code{(- fill-column 32)} is inserted
2347in place of the @samp{%d}; and the value returned by the expression
2348beginning with @code{concat} is inserted in place of the @samp{%s}.
2349
2350When I evaluate the expression, the message @code{"He saw 38 red
2351foxes leaping."} appears in my echo area.
2352
2353@node set & setq, Summary, Arguments, List Processing
2354@comment node-name, next, previous, up
2355@section Setting the Value of a Variable
2356@cindex Variable, setting value
2357@cindex Setting value of variable
2358
2359@cindex @samp{bind} defined
2360There are several ways by which a variable can be given a value. One of
2361the ways is to use either the function @code{set} or the function
2362@code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2363jargon for this process is to @dfn{bind} a variable to a value.)
2364
2365The following sections not only describe how @code{set} and @code{setq}
2366work but also illustrate how arguments are passed.
2367
2368@menu
2369* Using set:: Setting values.
2370* Using setq:: Setting a quoted value.
2371* Counting:: Using @code{setq} to count.
2372@end menu
2373
2374@node Using set, Using setq, set & setq, set & setq
2375@comment node-name, next, previous, up
2376@subsection Using @code{set}
2377@findex set
2378
2379To set the value of the symbol @code{flowers} to the list @code{'(rose
2380violet daisy buttercup)}, evaluate the following expression by
2381positioning the cursor after the expression and typing @kbd{C-x C-e}.
2382
2383@smallexample
2384(set 'flowers '(rose violet daisy buttercup))
2385@end smallexample
2386
2387@noindent
2388The list @code{(rose violet daisy buttercup)} will appear in the echo
2389area. This is what is @emph{returned} by the @code{set} function. As a
2390side effect, the symbol @code{flowers} is bound to the list ; that is,
2391the symbol @code{flowers}, which can be viewed as a variable, is given
2392the list as its value. (This process, by the way, illustrates how a
2393side effect to the Lisp interpreter, setting the value, can be the
2394primary effect that we humans are interested in. This is because every
2395Lisp function must return a value if it does not get an error, but it
2396will only have a side effect if it is designed to have one.)
2397
2398After evaluating the @code{set} expression, you can evaluate the symbol
2399@code{flowers} and it will return the value you just set. Here is the
2400symbol. Place your cursor after it and type @kbd{C-x C-e}.
2401
2402@smallexample
2403flowers
2404@end smallexample
2405
2406@noindent
2407When you evaluate @code{flowers}, the list
2408@code{(rose violet daisy buttercup)} appears in the echo area.
2409
2410Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2411in front of it, what you will see in the echo area is the symbol itself,
2412@code{flowers}. Here is the quoted symbol, so you can try this:
2413
2414@smallexample
2415'flowers
2416@end smallexample
2417
2418Note also, that when you use @code{set}, you need to quote both
2419arguments to @code{set}, unless you want them evaluated. Since we do
2420not want either argument evaluated, neither the variable
2421@code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2422are quoted. (When you use @code{set} without quoting its first
2423argument, the first argument is evaluated before anything else is
2424done. If you did this and @code{flowers} did not have a value
2425already, you would get an error message that the @samp{Symbol's value
2426as variable is void}; on the other hand, if @code{flowers} did return
2427a value after it was evaluated, the @code{set} would attempt to set
2428the value that was returned. There are situations where this is the
2429right thing for the function to do; but such situations are rare.)
2430
2431@node Using setq, Counting, Using set, set & setq
2432@comment node-name, next, previous, up
2433@subsection Using @code{setq}
2434@findex setq
2435
2436As a practical matter, you almost always quote the first argument to
2437@code{set}. The combination of @code{set} and a quoted first argument
2438is so common that it has its own name: the special form @code{setq}.
2439This special form is just like @code{set} except that the first argument
2440is quoted automatically, so you don't need to type the quote mark
2441yourself. Also, as an added convenience, @code{setq} permits you to set
2442several different variables to different values, all in one expression.
2443
2444To set the value of the variable @code{carnivores} to the list
2445@code{'(lion tiger leopard)} using @code{setq}, the following expression
2446is used:
2447
2448@smallexample
2449(setq carnivores '(lion tiger leopard))
2450@end smallexample
2451
2452@noindent
2453This is exactly the same as using @code{set} except the first argument
2454is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2455means @code{quote}.)
2456
2457@need 1250
2458With @code{set}, the expression would look like this:
2459
2460@smallexample
2461(set 'carnivores '(lion tiger leopard))
2462@end smallexample
2463
2464Also, @code{setq} can be used to assign different values to
2465different variables. The first argument is bound to the value
2466of the second argument, the third argument is bound to the value of the
2467fourth argument, and so on. For example, you could use the following to
2468assign a list of trees to the symbol @code{trees} and a list of herbivores
2469to the symbol @code{herbivores}:
2470
2471@smallexample
2472@group
2473(setq trees '(pine fir oak maple)
2474 herbivores '(gazelle antelope zebra))
2475@end group
2476@end smallexample
2477
2478@noindent
2479(The expression could just as well have been on one line, but it might
2480not have fit on a page; and humans find it easier to read nicely
2481formatted lists.)
2482
2483Although I have been using the term `assign', there is another way of
2484thinking about the workings of @code{set} and @code{setq}; and that is to
2485say that @code{set} and @code{setq} make the symbol @emph{point} to the
2486list. This latter way of thinking is very common and in forthcoming
2487chapters we shall come upon at least one symbol that has `pointer' as
2488part of its name. The name is chosen because the symbol has a value,
2489specifically a list, attached to it; or, expressed another way,
2490the symbol is set to ``point'' to the list.
2491
2492@node Counting, , Using setq, set & setq
2493@comment node-name, next, previous, up
2494@subsection Counting
2495@cindex Counting
2496
2497Here is an example that shows how to use @code{setq} in a counter. You
2498might use this to count how many times a part of your program repeats
2499itself. First set a variable to zero; then add one to the number each
2500time the program repeats itself. To do this, you need a variable that
2501serves as a counter, and two expressions: an initial @code{setq}
2502expression that sets the counter variable to zero; and a second
2503@code{setq} expression that increments the counter each time it is
2504evaluated.
2505
2506@smallexample
2507@group
2508(setq counter 0) ; @r{Let's call this the initializer.}
2509
2510(setq counter (+ counter 1)) ; @r{This is the incrementer.}
2511
2512counter ; @r{This is the counter.}
2513@end group
2514@end smallexample
2515
2516@noindent
2517(The text following the @samp{;} are comments. @xref{Change a
2518defun, , Change a Function Definition}.)
2519
2520If you evaluate the first of these expressions, the initializer,
2521@code{(setq counter 0)}, and then evaluate the third expression,
2522@code{counter}, the number @code{0} will appear in the echo area. If
2523you then evaluate the second expression, the incrementer, @code{(setq
2524counter (+ counter 1))}, the counter will get the value 1. So if you
2525again evaluate @code{counter}, the number @code{1} will appear in the
2526echo area. Each time you evaluate the second expression, the value of
2527the counter will be incremented.
2528
2529When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2530the Lisp interpreter first evaluates the innermost list; this is the
2531addition. In order to evaluate this list, it must evaluate the variable
2532@code{counter} and the number @code{1}. When it evaluates the variable
2533@code{counter}, it receives its current value. It passes this value and
2534the number @code{1} to the @code{+} which adds them together. The sum
2535is then returned as the value of the inner list and passed to the
2536@code{setq} which sets the variable @code{counter} to this new value.
2537Thus, the value of the variable, @code{counter}, is changed.
2538
2539@node Summary, Error Message Exercises, set & setq, List Processing
2540@comment node-name, next, previous, up
2541@section Summary
2542
2543Learning Lisp is like climbing a hill in which the first part is the
2544steepest. You have now climbed the most difficult part; what remains
2545becomes easier as you progress onwards.
2546
2547In summary,
2548
2549@itemize @bullet
2550
2551@item
2552Lisp programs are made up of expressions, which are lists or single atoms.
2553
2554@item
2555Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2556surrounded by parentheses. A list can be empty.
2557
2558@item
2559Atoms are multi-character symbols, like @code{forward-paragraph}, single
2560character symbols like @code{+}, strings of characters between double
2561quotation marks, or numbers.
2562
2563@item
2564A number evaluates to itself.
2565
2566@item
2567A string between double quotes also evaluates to itself.
2568
2569@item
2570When you evaluate a symbol by itself, its value is returned.
2571
2572@item
2573When you evaluate a list, the Lisp interpreter looks at the first symbol
2574in the list and then at the function definition bound to that symbol.
2575Then the instructions in the function definition are carried out.
2576
2577@item
2578A single-quote, @code{'}, tells the Lisp interpreter that it should
2579return the following expression as written, and not evaluate it as it
2580would if the quote were not there.
2581
2582@item
2583Arguments are the information passed to a function. The arguments to a
2584function are computed by evaluating the rest of the elements of the list
2585of which the function is the first element.
2586
2587@item
2588A function always returns a value when it is evaluated (unless it gets
2589an error); in addition, it may also carry out some action called a
2590``side effect''. In many cases, a function's primary purpose is to
2591create a side effect.
2592@end itemize
2593
2594@node Error Message Exercises, , Summary, List Processing
2595@comment node-name, next, previous, up
2596@section Exercises
2597
2598A few simple exercises:
2599
2600@itemize @bullet
2601@item
2602Generate an error message by evaluating an appropriate symbol that is
2603not within parentheses.
2604
2605@item
2606Generate an error message by evaluating an appropriate symbol that is
2607between parentheses.
2608
2609@item
2610Create a counter that increments by two rather than one.
2611
2612@item
2613Write an expression that prints a message in the echo area when
2614evaluated.
2615@end itemize
2616
2617@node Practicing Evaluation, Writing Defuns, List Processing, Top
2618@comment node-name, next, previous, up
2619@chapter Practicing Evaluation
2620@cindex Practicing evaluation
2621@cindex Evaluation practice
2622
2623Before learning how to write a function definition in Emacs Lisp, it is
2624useful to spend a little time evaluating various expressions that have
2625already been written. These expressions will be lists with the
2626functions as their first (and often only) element. Since some of the
2627functions associated with buffers are both simple and interesting, we
2628will start with those. In this section, we will evaluate a few of
2629these. In another section, we will study the code of several other
2630buffer-related functions, to see how they were written.
2631
2632@menu
2633* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2634 causes evaluation.
2635* Buffer Names:: Buffers and files are different.
2636* Getting Buffers:: Getting a buffer itself, not merely its name.
2637* Switching Buffers:: How to change to another buffer.
2638* Buffer Size & Locations:: Where point is located and the size of
2639 the buffer.
2640* Evaluation Exercise::
2641@end menu
2642
2643@node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2644@ifnottex
2645@unnumberedsec How to Evaluate
2646@end ifnottex
2647
2648@i{Whenever you give an editing command} to Emacs Lisp, such as the
2649command to move the cursor or to scroll the screen, @i{you are evaluating
2650an expression,} the first element of which is a function. @i{This is
2651how Emacs works.}
2652
2653@cindex @samp{interactive function} defined
2654@cindex @samp{command} defined
2655When you type keys, you cause the Lisp interpreter to evaluate an
2656expression and that is how you get your results. Even typing plain text
2657involves evaluating an Emacs Lisp function, in this case, one that uses
2658@code{self-insert-command}, which simply inserts the character you
2659typed. The functions you evaluate by typing keystrokes are called
2660@dfn{interactive} functions, or @dfn{commands}; how you make a function
2661interactive will be illustrated in the chapter on how to write function
2662definitions. @xref{Interactive, , Making a Function Interactive}.
2663
2664In addition to typing keyboard commands, we have seen a second way to
2665evaluate an expression: by positioning the cursor after a list and
2666typing @kbd{C-x C-e}. This is what we will do in the rest of this
2667section. There are other ways to evaluate an expression as well; these
2668will be described as we come to them.
2669
2670Besides being used for practicing evaluation, the functions shown in the
2671next few sections are important in their own right. A study of these
2672functions makes clear the distinction between buffers and files, how to
2673switch to a buffer, and how to determine a location within it.
2674
2675@node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2676@comment node-name, next, previous, up
2677@section Buffer Names
2678@findex buffer-name
2679@findex buffer-file-name
2680
2681The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2682the difference between a file and a buffer. When you evaluate the
2683following expression, @code{(buffer-name)}, the name of the buffer
2684appears in the echo area. When you evaluate @code{(buffer-file-name)},
2685the name of the file to which the buffer refers appears in the echo
2686area. Usually, the name returned by @code{(buffer-name)} is the same as
2687the name of the file to which it refers, and the name returned by
2688@code{(buffer-file-name)} is the full path-name of the file.
2689
2690A file and a buffer are two different entities. A file is information
2691recorded permanently in the computer (unless you delete it). A buffer,
2692on the other hand, is information inside of Emacs that will vanish at
2693the end of the editing session (or when you kill the buffer). Usually,
2694a buffer contains information that you have copied from a file; we say
2695the buffer is @dfn{visiting} that file. This copy is what you work on
2696and modify. Changes to the buffer do not change the file, until you
2697save the buffer. When you save the buffer, the buffer is copied to the file
2698and is thus saved permanently.
2699
2700@need 1250
2701If you are reading this in Info inside of GNU Emacs, you can evaluate
2702each of the following expressions by positioning the cursor after it and
2703typing @kbd{C-x C-e}.
2704
2705@smallexample
2706@group
2707(buffer-name)
2708
2709(buffer-file-name)
2710@end group
2711@end smallexample
2712
2713@noindent
2714When I do this, @file{"introduction.texinfo"} is the value returned by
2715evaluating @code{(buffer-name)}, and
2716@file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2717evaluating @code{(buffer-file-name)}. The former is the name of the
2718buffer and the latter is the name of the file. (In the expressions, the
2719parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2720@code{buffer-file-name} as functions; without the parentheses, the
2721interpreter would attempt to evaluate the symbols as variables.
2722@xref{Variables}.)
2723
2724In spite of the distinction between files and buffers, you will often
2725find that people refer to a file when they mean a buffer and vice-versa.
2726Indeed, most people say, ``I am editing a file,'' rather than saying,
2727``I am editing a buffer which I will soon save to a file.'' It is
2728almost always clear from context what people mean. When dealing with
2729computer programs, however, it is important to keep the distinction in mind,
2730since the computer is not as smart as a person.
2731
2732@cindex Buffer, history of word
2733The word `buffer', by the way, comes from the meaning of the word as a
2734cushion that deadens the force of a collision. In early computers, a
2735buffer cushioned the interaction between files and the computer's
2736central processing unit. The drums or tapes that held a file and the
2737central processing unit were pieces of equipment that were very
2738different from each other, working at their own speeds, in spurts. The
2739buffer made it possible for them to work together effectively.
2740Eventually, the buffer grew from being an intermediary, a temporary
2741holding place, to being the place where work is done. This
2742transformation is rather like that of a small seaport that grew into a
2743great city: once it was merely the place where cargo was warehoused
2744temporarily before being loaded onto ships; then it became a business
2745and cultural center in its own right.
2746
2747Not all buffers are associated with files. For example, when you start
2748an Emacs session by typing the command @code{emacs} alone, without
2749naming any files, Emacs will start with the @file{*scratch*} buffer on
2750the screen. This buffer is not visiting any file. Similarly, a
2751@file{*Help*} buffer is not associated with any file.
2752
2753@cindex @code{nil}, history of word
2754If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2755position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2756expression, the name @code{"*scratch*"} is returned and will appear in
2757the echo area. @code{"*scratch*"} is the name of the buffer. However,
2758if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2759evaluate that, @code{nil} will appear in the echo area. @code{nil} is
2760from the Latin word for `nothing'; in this case, it means that the
2761@file{*scratch*} buffer is not associated with any file. (In Lisp,
2762@code{nil} is also used to mean `false' and is a synonym for the empty
2763list, @code{()}.)
2764
2765Incidentally, if you are in the @file{*scratch*} buffer and want the
2766value returned by an expression to appear in the @file{*scratch*}
2767buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2768instead of @kbd{C-x C-e}. This causes the value returned to appear
2769after the expression. The buffer will look like this:
2770
2771@smallexample
2772(buffer-name)"*scratch*"
2773@end smallexample
2774
2775@noindent
2776You cannot do this in Info since Info is read-only and it will not allow
2777you to change the contents of the buffer. But you can do this in any
2778buffer you can edit; and when you write code or documentation (such as
2779this book), this feature is very useful.
2780
2781@node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2782@comment node-name, next, previous, up
2783@section Getting Buffers
2784@findex current-buffer
2785@findex other-buffer
2786@cindex Getting a buffer
2787
2788The @code{buffer-name} function returns the @emph{name} of the buffer;
2789to get the buffer @emph{itself}, a different function is needed: the
2790@code{current-buffer} function. If you use this function in code, what
2791you get is the buffer itself.
2792
2793A name and the object or entity to which the name refers are different
2794from each other. You are not your name. You are a person to whom
2795others refer by name. If you ask to speak to George and someone hands you
2796a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2797@samp{g}, and @samp{e} written on it, you might be amused, but you would
2798not be satisfied. You do not want to speak to the name, but to the
2799person to whom the name refers. A buffer is similar: the name of the
2800scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2801get a buffer itself, you need to use a function such as
2802@code{current-buffer}.
2803
2804However, there is a slight complication: if you evaluate
2805@code{current-buffer} in an expression on its own, as we will do here,
2806what you see is a printed representation of the name of the buffer
2807without the contents of the buffer. Emacs works this way for two
2808reasons: the buffer may be thousands of lines long---too long to be
2809conveniently displayed; and, another buffer may have the same contents
2810but a different name, and it is important to distinguish between them.
2811
2812@need 800
2813Here is an expression containing the function:
2814
2815@smallexample
2816(current-buffer)
2817@end smallexample
2818
2819@noindent
2820If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2821appears in the echo area. The special format indicates that the
2822buffer itself is being returned, rather than just its name.
2823
2824Incidentally, while you can type a number or symbol into a program, you
2825cannot do that with the printed representation of a buffer: the only way
2826to get a buffer itself is with a function such as @code{current-buffer}.
2827
2828A related function is @code{other-buffer}. This returns the most
2829recently selected buffer other than the one you are in currently. If
2830you have recently switched back and forth from the @file{*scratch*}
2831buffer, @code{other-buffer} will return that buffer.
2832
2833@need 800
2834You can see this by evaluating the expression:
2835
2836@smallexample
2837(other-buffer)
2838@end smallexample
2839
2840@noindent
2841You should see @file{#<buffer *scratch*>} appear in the echo area, or
2842the name of whatever other buffer you switched back from most
2843recently@footnote{Actually, by default, if the buffer from which you
2844just switched is visible to you in another window, @code{other-buffer}
2845will choose the most recent buffer that you cannot see; this is a
2846subtlety that I often forget.}.
2847
2848@node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2849@comment node-name, next, previous, up
2850@section Switching Buffers
2851@findex switch-to-buffer
2852@findex set-buffer
2853@cindex Switching to a buffer
2854
2855The @code{other-buffer} function actually provides a buffer when it is
2856used as an argument to a function that requires one. We can see this
2857by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2858different buffer.
2859
2860But first, a brief introduction to the @code{switch-to-buffer}
2861function. When you switched back and forth from Info to the
2862@file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2863likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2864rather, to save typing, you probably typed just part of the name, such
2865as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2866expand to the full name; and then typed your @kbd{RET} key.} when
2867prompted in the minibuffer for the name of the buffer to which you
2868wanted to switch. The keystrokes, @kbd{C-x b}, cause the Lisp
2869interpreter to evaluate the interactive function
2870@code{switch-to-buffer}. As we said before, this is how Emacs works:
2871different keystrokes call or run different functions. For example,
2872@kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2873@code{forward-sentence}, and so on.
2874
2875By writing @code{switch-to-buffer} in an expression, and giving it a
2876buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2877does.
2878
2879@need 1000
2880Here is the Lisp expression:
2881
2882@smallexample
2883(switch-to-buffer (other-buffer))
2884@end smallexample
2885
2886@noindent
2887The symbol @code{switch-to-buffer} is the first element of the list,
2888so the Lisp interpreter will treat it as a function and carry out the
2889instructions that are attached to it. But before doing that, the
2890interpreter will note that @code{other-buffer} is inside parentheses
2891and work on that symbol first. @code{other-buffer} is the first (and
2892in this case, the only) element of this list, so the Lisp interpreter
2893calls or runs the function. It returns another buffer. Next, the
2894interpreter runs @code{switch-to-buffer}, passing to it, as an
2895argument, the other buffer, which is what Emacs will switch to. If
2896you are reading this in Info, try this now. Evaluate the expression.
2897(To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2898expression will move you to your most recent other buffer that you
2899cannot see. If you really want to go to your most recently selected
2900buffer, even if you can still see it, you need to evaluate the
2901following more complex expression:
2902
2903@smallexample
2904(switch-to-buffer (other-buffer (current-buffer) t))
2905@end smallexample
2906
2907@noindent
2908In this case, the first argument to @code{other-buffer} tells it which
2909buffer to skip---the current one---and the second argument tells
2910@code{other-buffer} it is OK to switch to a visible buffer.
2911In regular use, @code{switch-to-buffer} takes you to an invisible
2912window since you would most likely use @kbd{C-x o} (@code{other-window})
2913to go to another visible buffer.}
2914
2915In the programming examples in later sections of this document, you will
2916see the function @code{set-buffer} more often than
2917@code{switch-to-buffer}. This is because of a difference between
2918computer programs and humans: humans have eyes and expect to see the
2919buffer on which they are working on their computer terminals. This is
2920so obvious, it almost goes without saying. However, programs do not
2921have eyes. When a computer program works on a buffer, that buffer does
2922not need to be visible on the screen.
2923
2924@code{switch-to-buffer} is designed for humans and does two different
2925things: it switches the buffer to which Emacs' attention is directed; and
2926it switches the buffer displayed in the window to the new buffer.
2927@code{set-buffer}, on the other hand, does only one thing: it switches
2928the attention of the computer program to a different buffer. The buffer
2929on the screen remains unchanged (of course, normally nothing happens
2930there until the command finishes running).
2931
2932@cindex @samp{call} defined
2933Also, we have just introduced another jargon term, the word @dfn{call}.
2934When you evaluate a list in which the first symbol is a function, you
2935are calling that function. The use of the term comes from the notion of
2936the function as an entity that can do something for you if you `call'
2937it---just as a plumber is an entity who can fix a leak if you call him
2938or her.
2939
2940@node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2941@comment node-name, next, previous, up
2942@section Buffer Size and the Location of Point
2943@cindex Size of buffer
2944@cindex Buffer size
2945@cindex Point location
2946@cindex Location of point
2947
2948Finally, let's look at several rather simple functions,
2949@code{buffer-size}, @code{point}, @code{point-min}, and
2950@code{point-max}. These give information about the size of a buffer and
2951the location of point within it.
2952
2953The function @code{buffer-size} tells you the size of the current
2954buffer; that is, the function returns a count of the number of
2955characters in the buffer.
2956
2957@smallexample
2958(buffer-size)
2959@end smallexample
2960
2961@noindent
2962You can evaluate this in the usual way, by positioning the
2963cursor after the expression and typing @kbd{C-x C-e}.
2964
2965@cindex @samp{point} defined
2966In Emacs, the current position of the cursor is called @dfn{point}.
2967The expression @code{(point)} returns a number that tells you where the
2968cursor is located as a count of the number of characters from the
2969beginning of the buffer up to point.
2970
2971@need 1250
2972You can see the character count for point in this buffer by evaluating
2973the following expression in the usual way:
2974
2975@smallexample
2976(point)
2977@end smallexample
2978
2979@noindent
2980As I write this, the value of @code{point} is 65724. The @code{point}
2981function is frequently used in some of the examples later in this
2982book.
2983
2984@need 1250
2985The value of point depends, of course, on its location within the
2986buffer. If you evaluate point in this spot, the number will be larger:
2987
2988@smallexample
2989(point)
2990@end smallexample
2991
2992@noindent
2993For me, the value of point in this location is 66043, which means that
2994there are 319 characters (including spaces) between the two expressions.
2995
2996@cindex @samp{narrowing} defined
2997The function @code{point-min} is somewhat similar to @code{point}, but
2998it returns the value of the minimum permissible value of point in the
2999current buffer. This is the number 1 unless @dfn{narrowing} is in
3000effect. (Narrowing is a mechanism whereby you can restrict yourself,
3001or a program, to operations on just a part of a buffer.
3002@xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
3003function @code{point-max} returns the value of the maximum permissible
3004value of point in the current buffer.
3005
3006@node Evaluation Exercise, , Buffer Size & Locations, Practicing Evaluation
3007@section Exercise
3008
3009Find a file with which you are working and move towards its middle.
3010Find its buffer name, file name, length, and your position in the file.
3011
3012@node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
3013@comment node-name, next, previous, up
3014@chapter How To Write Function Definitions
3015@cindex Definition writing
3016@cindex Function definition writing
3017@cindex Writing a function definition
3018
3019When the Lisp interpreter evaluates a list, it looks to see whether the
3020first symbol on the list has a function definition attached to it; or,
3021put another way, whether the symbol points to a function definition. If
3022it does, the computer carries out the instructions in the definition. A
3023symbol that has a function definition is called, simply, a function
3024(although, properly speaking, the definition is the function and the
3025symbol refers to it.)
3026
3027@menu
3028* Primitive Functions::
3029* defun:: The @code{defun} special form.
3030* Install:: Install a function definition.
3031* Interactive:: Making a function interactive.
3032* Interactive Options:: Different options for @code{interactive}.
3033* Permanent Installation:: Installing code permanently.
3034* let:: Creating and initializing local variables.
3035* if:: What if?
3036* else:: If--then--else expressions.
3037* Truth & Falsehood:: What Lisp considers false and true.
3038* save-excursion:: Keeping track of point, mark, and buffer.
3039* Review::
3040* defun Exercises::
3041@end menu
3042
3043@node Primitive Functions, defun, Writing Defuns, Writing Defuns
3044@ifnottex
3045@unnumberedsec An Aside about Primitive Functions
3046@end ifnottex
3047@cindex Primitive functions
3048@cindex Functions, primitive
3049
3050@cindex C language primitives
3051@cindex Primitives written in C
3052All functions are defined in terms of other functions, except for a few
3053@dfn{primitive} functions that are written in the C programming
3054language. When you write functions' definitions, you will write them in
3055Emacs Lisp and use other functions as your building blocks. Some of the
3056functions you will use will themselves be written in Emacs Lisp (perhaps
3057by you) and some will be primitives written in C. The primitive
3058functions are used exactly like those written in Emacs Lisp and behave
3059like them. They are written in C so we can easily run GNU Emacs on any
3060computer that has sufficient power and can run C.
3061
3062Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3063distinguish between the use of functions written in C and the use of
3064functions written in Emacs Lisp. The difference is irrelevant. I
3065mention the distinction only because it is interesting to know. Indeed,
3066unless you investigate, you won't know whether an already-written
3067function is written in Emacs Lisp or C.
3068
3069@node defun, Install, Primitive Functions, Writing Defuns
3070@comment node-name, next, previous, up
3071@section The @code{defun} Special Form
3072@findex defun
3073@cindex Special form of @code{defun}
3074
3075@cindex @samp{function definition} defined
3076In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3077it that tells the computer what to do when the function is called.
3078This code is called the @dfn{function definition} and is created by
3079evaluating a Lisp expression that starts with the symbol @code{defun}
3080(which is an abbreviation for @emph{define function}). Because
3081@code{defun} does not evaluate its arguments in the usual way, it is
3082called a @dfn{special form}.
3083
3084In subsequent sections, we will look at function definitions from the
3085Emacs source code, such as @code{mark-whole-buffer}. In this section,
3086we will describe a simple function definition so you can see how it
3087looks. This function definition uses arithmetic because it makes for a
3088simple example. Some people dislike examples using arithmetic; however,
3089if you are such a person, do not despair. Hardly any of the code we
3090will study in the remainder of this introduction involves arithmetic or
3091mathematics. The examples mostly involve text in one way or another.
3092
3093A function definition has up to five parts following the word
3094@code{defun}:
3095
3096@enumerate
3097@item
3098The name of the symbol to which the function definition should be
3099attached.
3100
3101@item
3102A list of the arguments that will be passed to the function. If no
3103arguments will be passed to the function, this is an empty list,
3104@code{()}.
3105
3106@item
3107Documentation describing the function. (Technically optional, but
3108strongly recommended.)
3109
3110@item
3111Optionally, an expression to make the function interactive so you can
3112use it by typing @kbd{M-x} and then the name of the function; or by
3113typing an appropriate key or keychord.
3114
3115@cindex @samp{body} defined
3116@item
3117The code that instructs the computer what to do: the @dfn{body} of the
3118function definition.
3119@end enumerate
3120
3121It is helpful to think of the five parts of a function definition as
3122being organized in a template, with slots for each part:
3123
3124@smallexample
3125@group
3126(defun @var{function-name} (@var{arguments}@dots{})
3127 "@var{optional-documentation}@dots{}"
3128 (interactive @var{argument-passing-info}) ; @r{optional}
3129 @var{body}@dots{})
3130@end group
3131@end smallexample
3132
3133As an example, here is the code for a function that multiplies its
3134argument by 7. (This example is not interactive. @xref{Interactive,
3135, Making a Function Interactive}, for that information.)
3136
3137@smallexample
3138@group
3139(defun multiply-by-seven (number)
3140 "Multiply NUMBER by seven."
3141 (* 7 number))
3142@end group
3143@end smallexample
3144
3145This definition begins with a parenthesis and the symbol @code{defun},
3146followed by the name of the function.
3147
3148@cindex @samp{argument list} defined
3149The name of the function is followed by a list that contains the
3150arguments that will be passed to the function. This list is called
3151the @dfn{argument list}. In this example, the list has only one
3152element, the symbol, @code{number}. When the function is used, the
3153symbol will be bound to the value that is used as the argument to the
3154function.
3155
3156Instead of choosing the word @code{number} for the name of the argument,
3157I could have picked any other name. For example, I could have chosen
3158the word @code{multiplicand}. I picked the word `number' because it
3159tells what kind of value is intended for this slot; but I could just as
3160well have chosen the word `multiplicand' to indicate the role that the
3161value placed in this slot will play in the workings of the function. I
3162could have called it @code{foogle}, but that would have been a bad
3163choice because it would not tell humans what it means. The choice of
3164name is up to the programmer and should be chosen to make the meaning of
3165the function clear.
3166
3167Indeed, you can choose any name you wish for a symbol in an argument
3168list, even the name of a symbol used in some other function: the name
3169you use in an argument list is private to that particular definition.
3170In that definition, the name refers to a different entity than any use
3171of the same name outside the function definition. Suppose you have a
3172nick-name `Shorty' in your family; when your family members refer to
3173`Shorty', they mean you. But outside your family, in a movie, for
3174example, the name `Shorty' refers to someone else. Because a name in an
3175argument list is private to the function definition, you can change the
3176value of such a symbol inside the body of a function without changing
3177its value outside the function. The effect is similar to that produced
3178by a @code{let} expression. (@xref{let, , @code{let}}.)
3179
3180@ignore
3181Note also that we discuss the word `number' in two different ways: as a
3182symbol that appears in the code, and as the name of something that will
3183be replaced by a something else during the evaluation of the function.
3184In the first case, @code{number} is a symbol, not a number; it happens
3185that within the function, it is a variable who value is the number in
3186question, but our primary interest in it is as a symbol. On the other
3187hand, when we are talking about the function, our interest is that we
3188will substitute a number for the word @var{number}. To keep this
3189distinction clear, we use different typography for the two
3190circumstances. When we talk about this function, or about how it works,
3191we refer to this number by writing @var{number}. In the function
3192itself, we refer to it by writing @code{number}.
3193@end ignore
3194
3195The argument list is followed by the documentation string that
3196describes the function. This is what you see when you type
3197@w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3198write a documentation string like this, you should make the first line
3199a complete sentence since some commands, such as @code{apropos}, print
3200only the first line of a multi-line documentation string. Also, you
3201should not indent the second line of a documentation string, if you
3202have one, because that looks odd when you use @kbd{C-h f}
3203(@code{describe-function}). The documentation string is optional, but
3204it is so useful, it should be included in almost every function you
3205write.
3206
3207@findex * @r{(multiplication)}
3208The third line of the example consists of the body of the function
3209definition. (Most functions' definitions, of course, are longer than
3210this.) In this function, the body is the list, @code{(* 7 number)}, which
3211says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3212@code{*} is the function for multiplication, just as @code{+} is the
3213function for addition.)
3214
3215When you use the @code{multiply-by-seven} function, the argument
3216@code{number} evaluates to the actual number you want used. Here is an
3217example that shows how @code{multiply-by-seven} is used; but don't try
3218to evaluate this yet!
3219
3220@smallexample
3221(multiply-by-seven 3)
3222@end smallexample
3223
3224@noindent
3225The symbol @code{number}, specified in the function definition in the
3226next section, is given or ``bound to'' the value 3 in the actual use of
3227the function. Note that although @code{number} was inside parentheses
3228in the function definition, the argument passed to the
3229@code{multiply-by-seven} function is not in parentheses. The
3230parentheses are written in the function definition so the computer can
3231figure out where the argument list ends and the rest of the function
3232definition begins.
3233
3234If you evaluate this example, you are likely to get an error message.
3235(Go ahead, try it!) This is because we have written the function
3236definition, but not yet told the computer about the definition---we have
3237not yet installed (or `loaded') the function definition in Emacs.
3238Installing a function is the process that tells the Lisp interpreter the
3239definition of the function. Installation is described in the next
3240section.
3241
3242@node Install, Interactive, defun, Writing Defuns
3243@comment node-name, next, previous, up
3244@section Install a Function Definition
3245@cindex Install a Function Definition
3246@cindex Definition installation
3247@cindex Function definition installation
3248
3249If you are reading this inside of Info in Emacs, you can try out the
3250@code{multiply-by-seven} function by first evaluating the function
3251definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3252the function definition follows. Place the cursor after the last
3253parenthesis of the function definition and type @kbd{C-x C-e}. When you
3254do this, @code{multiply-by-seven} will appear in the echo area. (What
3255this means is that when a function definition is evaluated, the value it
3256returns is the name of the defined function.) At the same time, this
3257action installs the function definition.
3258
3259@smallexample
3260@group
3261(defun multiply-by-seven (number)
3262 "Multiply NUMBER by seven."
3263 (* 7 number))
3264@end group
3265@end smallexample
3266
3267@noindent
3268By evaluating this @code{defun}, you have just installed
3269@code{multiply-by-seven} in Emacs. The function is now just as much a
3270part of Emacs as @code{forward-word} or any other editing function you
3271use. (@code{multiply-by-seven} will stay installed until you quit
3272Emacs. To reload code automatically whenever you start Emacs, see
3273@ref{Permanent Installation, , Installing Code Permanently}.)
3274
3275
3276@menu
3277* Effect of installation::
3278* Change a defun:: How to change a function definition.
3279@end menu
3280
3281@node Effect of installation, Change a defun, Install, Install
3282@ifnottex
3283@unnumberedsubsec The effect of installation
3284@end ifnottex
3285
3286
3287You can see the effect of installing @code{multiply-by-seven} by
3288evaluating the following sample. Place the cursor after the following
3289expression and type @kbd{C-x C-e}. The number 21 will appear in the
3290echo area.
3291
3292@smallexample
3293(multiply-by-seven 3)
3294@end smallexample
3295
3296If you wish, you can read the documentation for the function by typing
3297@kbd{C-h f} (@code{describe-function}) and then the name of the
3298function, @code{multiply-by-seven}. When you do this, a
3299@file{*Help*} window will appear on your screen that says:
3300
3301@smallexample
3302@group
3303multiply-by-seven:
3304Multiply NUMBER by seven.
3305@end group
3306@end smallexample
3307
3308@noindent
3309(To return to a single window on your screen, type @kbd{C-x 1}.)
3310
3311@node Change a defun, , Effect of installation, Install
3312@comment node-name, next, previous, up
3313@subsection Change a Function Definition
3314@cindex Changing a function definition
3315@cindex Function definition, how to change
3316@cindex Definition, how to change
3317
3318If you want to change the code in @code{multiply-by-seven}, just rewrite
3319it. To install the new version in place of the old one, evaluate the
3320function definition again. This is how you modify code in Emacs. It is
3321very simple.
3322
3323As an example, you can change the @code{multiply-by-seven} function to
3324add the number to itself seven times instead of multiplying the number
3325by seven. It produces the same answer, but by a different path. At
3326the same time, we will add a comment to the code; a comment is text
3327that the Lisp interpreter ignores, but that a human reader may find
3328useful or enlightening. The comment is that this is the ``second
3329version''.
3330
3331@smallexample
3332@group
3333(defun multiply-by-seven (number) ; @r{Second version.}
3334 "Multiply NUMBER by seven."
3335 (+ number number number number number number number))
3336@end group
3337@end smallexample
3338
3339@cindex Comments in Lisp code
3340The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3341line that follows a semicolon is a comment. The end of the line is the
3342end of the comment. To stretch a comment over two or more lines, begin
3343each line with a semicolon.
3344
3345@xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3346File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3347Reference Manual}, for more about comments.
3348
3349You can install this version of the @code{multiply-by-seven} function by
3350evaluating it in the same way you evaluated the first function: place
3351the cursor after the last parenthesis and type @kbd{C-x C-e}.
3352
3353In summary, this is how you write code in Emacs Lisp: you write a
3354function; install it; test it; and then make fixes or enhancements and
3355install it again.
3356
3357@node Interactive, Interactive Options, Install, Writing Defuns
3358@comment node-name, next, previous, up
3359@section Make a Function Interactive
3360@cindex Interactive functions
3361@findex interactive
3362
3363You make a function interactive by placing a list that begins with
3364the special form @code{interactive} immediately after the
3365documentation. A user can invoke an interactive function by typing
3366@kbd{M-x} and then the name of the function; or by typing the keys to
3367which it is bound, for example, by typing @kbd{C-n} for
3368@code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3369
3370Interestingly, when you call an interactive function interactively,
3371the value returned is not automatically displayed in the echo area.
3372This is because you often call an interactive function for its side
3373effects, such as moving forward by a word or line, and not for the
3374value returned. If the returned value were displayed in the echo area
3375each time you typed a key, it would be very distracting.
3376
3377@menu
3378* Interactive multiply-by-seven:: An overview.
3379* multiply-by-seven in detail:: The interactive version.
3380@end menu
3381
3382@node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3383@ifnottex
3384@unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3385@end ifnottex
3386
3387Both the use of the special form @code{interactive} and one way to
3388display a value in the echo area can be illustrated by creating an
3389interactive version of @code{multiply-by-seven}.
3390
3391@need 1250
3392Here is the code:
3393
3394@smallexample
3395@group
3396(defun multiply-by-seven (number) ; @r{Interactive version.}
3397 "Multiply NUMBER by seven."
3398 (interactive "p")
3399 (message "The result is %d" (* 7 number)))
3400@end group
3401@end smallexample
3402
3403@noindent
3404You can install this code by placing your cursor after it and typing
3405@kbd{C-x C-e}. The name of the function will appear in your echo area.
3406Then, you can use this code by typing @kbd{C-u} and a number and then
3407typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3408@samp{The result is @dots{}} followed by the product will appear in the
3409echo area.
3410
3411Speaking more generally, you invoke a function like this in either of two
3412ways:
3413
3414@enumerate
3415@item
3416By typing a prefix argument that contains the number to be passed, and
3417then typing @kbd{M-x} and the name of the function, as with
3418@kbd{C-u 3 M-x forward-sentence}; or,
3419
3420@item
3421By typing whatever key or keychord the function is bound to, as with
3422@kbd{C-u 3 M-e}.
3423@end enumerate
3424
3425@noindent
3426Both the examples just mentioned work identically to move point forward
3427three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3428it could not be used as an example of key binding.)
3429
3430(@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3431to a key.)
3432
3433A prefix argument is passed to an interactive function by typing the
3434@key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3435typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3436type @kbd{C-u} without a number, it defaults to 4).
3437
3438@node multiply-by-seven in detail, , Interactive multiply-by-seven, Interactive
3439@comment node-name, next, previous, up
3440@subsection An Interactive @code{multiply-by-seven}
3441
3442Let's look at the use of the special form @code{interactive} and then at
3443the function @code{message} in the interactive version of
3444@code{multiply-by-seven}. You will recall that the function definition
3445looks like this:
3446
3447@smallexample
3448@group
3449(defun multiply-by-seven (number) ; @r{Interactive version.}
3450 "Multiply NUMBER by seven."
3451 (interactive "p")
3452 (message "The result is %d" (* 7 number)))
3453@end group
3454@end smallexample
3455
3456In this function, the expression, @code{(interactive "p")}, is a list of
3457two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3458the function and use its value for the argument of the function.
3459
3460@need 1000
3461The argument will be a number. This means that the symbol
3462@code{number} will be bound to a number in the line:
3463
3464@smallexample
3465(message "The result is %d" (* 7 number))
3466@end smallexample
3467
3468@need 1250
3469@noindent
3470For example, if your prefix argument is 5, the Lisp interpreter will
3471evaluate the line as if it were:
3472
3473@smallexample
3474(message "The result is %d" (* 7 5))
3475@end smallexample
3476
3477@noindent
3478(If you are reading this in GNU Emacs, you can evaluate this expression
3479yourself.) First, the interpreter will evaluate the inner list, which
3480is @code{(* 7 5)}. This returns a value of 35. Next, it
3481will evaluate the outer list, passing the values of the second and
3482subsequent elements of the list to the function @code{message}.
3483
3484As we have seen, @code{message} is an Emacs Lisp function especially
3485designed for sending a one line message to a user. (@xref{message, , The
3486@code{message} function}.)
3487In summary, the @code{message} function prints its first argument in the
3488echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3489@samp{%c}. When it sees one of these control sequences, the function
3490looks to the second and subsequent arguments and prints the value of the
3491argument in the location in the string where the control sequence is
3492located.
3493
3494In the interactive @code{multiply-by-seven} function, the control string
3495is @samp{%d}, which requires a number, and the value returned by
3496evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3497is printed in place of the @samp{%d} and the message is @samp{The result
3498is 35}.
3499
3500(Note that when you call the function @code{multiply-by-seven}, the
3501message is printed without quotes, but when you call @code{message}, the
3502text is printed in double quotes. This is because the value returned by
3503@code{message} is what appears in the echo area when you evaluate an
3504expression whose first element is @code{message}; but when embedded in a
3505function, @code{message} prints the text as a side effect without
3506quotes.)
3507
3508@node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3509@comment node-name, next, previous, up
3510@section Different Options for @code{interactive}
3511@cindex Options for @code{interactive}
3512@cindex Interactive options
3513
3514In the example, @code{multiply-by-seven} used @code{"p"} as the
3515argument to @code{interactive}. This argument told Emacs to interpret
3516your typing either @kbd{C-u} followed by a number or @key{META}
3517followed by a number as a command to pass that number to the function
3518as its argument. Emacs has more than twenty characters predefined for
3519use with @code{interactive}. In almost every case, one of these
3520options will enable you to pass the right information interactively to
3521a function. (@xref{Interactive Codes, , Code Characters for
3522@code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3523
3524@need 1250
3525For example, the character @samp{r} causes Emacs to pass the beginning
3526and end of the region (the current values of point and mark) to the
3527function as two separate arguments. It is used as follows:
3528
3529@smallexample
3530(interactive "r")
3531@end smallexample
3532
3533On the other hand, a @samp{B} tells Emacs to ask for the name of a
3534buffer that will be passed to the function. When it sees a @samp{B},
3535Emacs will ask for the name by prompting the user in the minibuffer,
3536using a string that follows the @samp{B}, as in @code{"BAppend to
3537buffer:@: "}. Not only will Emacs prompt for the name, but Emacs will
3538complete the name if you type enough of it and press @key{TAB}.
3539
3540A function with two or more arguments can have information passed to
3541each argument by adding parts to the string that follows
3542@code{interactive}. When you do this, the information is passed to
3543each argument in the same order it is specified in the
3544@code{interactive} list. In the string, each part is separated from
3545the next part by a @samp{\n}, which is a newline. For example, you
3546could follow @code{"BAppend to buffer:@: "} with a @samp{\n}) and an
3547@samp{r}. This would cause Emacs to pass the values of point and mark
3548to the function as well as prompt you for the buffer---three arguments
3549in all.
3550
3551In this case, the function definition would look like the following,
3552where @code{buffer}, @code{start}, and @code{end} are the symbols to
3553which @code{interactive} binds the buffer and the current values of the
3554beginning and ending of the region:
3555
3556@smallexample
3557@group
3558(defun @var{name-of-function} (buffer start end)
3559 "@var{documentation}@dots{}"
3560 (interactive "BAppend to buffer:@: \nr")
3561 @var{body-of-function}@dots{})
3562@end group
3563@end smallexample
3564
3565@noindent
3566(The space after the colon in the prompt makes it look better when you
3567are prompted. The @code{append-to-buffer} function looks exactly like
3568this. @xref{append-to-buffer, , The Definition of
3569@code{append-to-buffer}}.)
3570
3571If a function does not have arguments, then @code{interactive} does not
3572require any. Such a function contains the simple expression
3573@code{(interactive)}. The @code{mark-whole-buffer} function is like
3574this.
3575
3576Alternatively, if the special letter-codes are not right for your
3577application, you can pass your own arguments to @code{interactive} as
3578a list. @xref{interactive, , Using @code{Interactive}, elisp, The
3579GNU Emacs Lisp Reference Manual}, for more information about this advanced
3580technique.
3581
3582@node Permanent Installation, let, Interactive Options, Writing Defuns
3583@comment node-name, next, previous, up
3584@section Install Code Permanently
3585@cindex Install code permanently
3586@cindex Permanent code installation
3587@cindex Code installation
3588
3589When you install a function definition by evaluating it, it will stay
3590installed until you quit Emacs. The next time you start a new session
3591of Emacs, the function will not be installed unless you evaluate the
3592function definition again.
3593
3594At some point, you may want to have code installed automatically
3595whenever you start a new session of Emacs. There are several ways of
3596doing this:
3597
3598@itemize @bullet
3599@item
3600If you have code that is just for yourself, you can put the code for the
3601function definition in your @file{.emacs} initialization file. When you
3602start Emacs, your @file{.emacs} file is automatically evaluated and all
3603the function definitions within it are installed.
3604@xref{Emacs Initialization, , Your @file{.emacs} File}.
3605
3606@item
3607Alternatively, you can put the function definitions that you want
3608installed in one or more files of their own and use the @code{load}
3609function to cause Emacs to evaluate and thereby install each of the
3610functions in the files.
3611@xref{Loading Files, , Loading Files}.
3612
3613@item
3614On the other hand, if you have code that your whole site will use, it
3615is usual to put it in a file called @file{site-init.el} that is loaded
3616when Emacs is built. This makes the code available to everyone who
3617uses your machine. (See the @file{INSTALL} file that is part of the
3618Emacs distribution.)
3619@end itemize
3620
3621Finally, if you have code that everyone who uses Emacs may want, you
3622can post it on a computer network or send a copy to the Free Software
3623Foundation. (When you do this, please license the code and its
3624documentation under a license that permits other people to run, copy,
3625study, modify, and redistribute the code and which protects you from
3626having your work taken from you.) If you send a copy of your code to
3627the Free Software Foundation, and properly protect yourself and
3628others, it may be included in the next release of Emacs. In large
3629part, this is how Emacs has grown over the past years, by donations.
3630
3631@node let, if, Permanent Installation, Writing Defuns
3632@comment node-name, next, previous, up
3633@section @code{let}
3634@findex let
3635
3636The @code{let} expression is a special form in Lisp that you will need
3637to use in most function definitions.
3638
3639@code{let} is used to attach or bind a symbol to a value in such a way
3640that the Lisp interpreter will not confuse the variable with a
3641variable of the same name that is not part of the function.
3642
3643To understand why the @code{let} special form is necessary, consider
3644the situation in which you own a home that you generally refer to as
3645`the house', as in the sentence, ``The house needs painting.'' If you
3646are visiting a friend and your host refers to `the house', he is
3647likely to be referring to @emph{his} house, not yours, that is, to a
3648different house.
3649
3650If your friend is referring to his house and you think he is referring
3651to your house, you may be in for some confusion. The same thing could
3652happen in Lisp if a variable that is used inside of one function has
3653the same name as a variable that is used inside of another function,
3654and the two are not intended to refer to the same value. The
3655@code{let} special form prevents this kind of confusion.
3656
3657@menu
3658* Prevent confusion::
3659* Parts of let Expression::
3660* Sample let Expression::
3661* Uninitialized let Variables::
3662@end menu
3663
3664@node Prevent confusion, Parts of let Expression, let, let
3665@ifnottex
3666@unnumberedsubsec @code{let} Prevents Confusion
3667@end ifnottex
3668
3669@cindex @samp{local variable} defined
3670The @code{let} special form prevents confusion. @code{let} creates a
3671name for a @dfn{local variable} that overshadows any use of the same
3672name outside the @code{let} expression. This is like understanding
3673that whenever your host refers to `the house', he means his house, not
3674yours. (Symbols used in argument lists work the same way.
3675@xref{defun, , The @code{defun} Special Form}.)
3676
3677Local variables created by a @code{let} expression retain their value
3678@emph{only} within the @code{let} expression itself (and within
3679expressions called within the @code{let} expression); the local
3680variables have no effect outside the @code{let} expression.
3681
3682Another way to think about @code{let} is that it is like a @code{setq}
3683that is temporary and local. The values set by @code{let} are
3684automatically undone when the @code{let} is finished. The setting
3685only effects expressions that are inside the bounds of the @code{let}
3686expression. In computer science jargon, we would say ``the binding of
3687a symbol is visible only in functions called in the @code{let} form;
3688in Emacs Lisp, scoping is dynamic, not lexical.''
3689
3690@code{let} can create more than one variable at once. Also,
3691@code{let} gives each variable it creates an initial value, either a
3692value specified by you, or @code{nil}. (In the jargon, this is called
3693`binding the variable to the value'.) After @code{let} has created
3694and bound the variables, it executes the code in the body of the
3695@code{let}, and returns the value of the last expression in the body,
3696as the value of the whole @code{let} expression. (`Execute' is a jargon
3697term that means to evaluate a list; it comes from the use of the word
3698meaning `to give practical effect to' (@cite{Oxford English
3699Dictionary}). Since you evaluate an expression to perform an action,
3700`execute' has evolved as a synonym to `evaluate'.)
3701
3702@node Parts of let Expression, Sample let Expression, Prevent confusion, let
3703@comment node-name, next, previous, up
3704@subsection The Parts of a @code{let} Expression
3705@cindex @code{let} expression, parts of
3706@cindex Parts of @code{let} expression
3707
3708@cindex @samp{varlist} defined
3709A @code{let} expression is a list of three parts. The first part is
3710the symbol @code{let}. The second part is a list, called a
3711@dfn{varlist}, each element of which is either a symbol by itself or a
3712two-element list, the first element of which is a symbol. The third
3713part of the @code{let} expression is the body of the @code{let}. The
3714body usually consists of one or more lists.
3715
3716@need 800
3717A template for a @code{let} expression looks like this:
3718
3719@smallexample
3720(let @var{varlist} @var{body}@dots{})
3721@end smallexample
3722
3723@noindent
3724The symbols in the varlist are the variables that are given initial
3725values by the @code{let} special form. Symbols by themselves are given
3726the initial value of @code{nil}; and each symbol that is the first
3727element of a two-element list is bound to the value that is returned
3728when the Lisp interpreter evaluates the second element.
3729
3730Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3731this case, in a @code{let} expression, Emacs binds the symbol
3732@code{thread} to an initial value of @code{nil}, and binds the symbol
3733@code{needles} to an initial value of 3.
3734
3735When you write a @code{let} expression, what you do is put the
3736appropriate expressions in the slots of the @code{let} expression
3737template.
3738
3739If the varlist is composed of two-element lists, as is often the case,
3740the template for the @code{let} expression looks like this:
3741
3742@smallexample
3743@group
3744(let ((@var{variable} @var{value})
3745 (@var{variable} @var{value})
3746 @dots{})
3747 @var{body}@dots{})
3748@end group
3749@end smallexample
3750
3751@node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3752@comment node-name, next, previous, up
3753@subsection Sample @code{let} Expression
3754@cindex Sample @code{let} expression
3755@cindex @code{let} expression sample
3756
3757The following expression creates and gives initial values
3758to the two variables @code{zebra} and @code{tiger}. The body of the
3759@code{let} expression is a list which calls the @code{message} function.
3760
3761@smallexample
3762@group
3763(let ((zebra 'stripes)
3764 (tiger 'fierce))
3765 (message "One kind of animal has %s and another is %s."
3766 zebra tiger))
3767@end group
3768@end smallexample
3769
3770Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3771
3772The two variables are @code{zebra} and @code{tiger}. Each variable is
3773the first element of a two-element list and each value is the second
3774element of its two-element list. In the varlist, Emacs binds the
3775variable @code{zebra} to the value @code{stripes}, and binds the
3776variable @code{tiger} to the value @code{fierce}. In this example,
3777both values are symbols preceded by a quote. The values could just as
3778well have been another list or a string. The body of the @code{let}
3779follows after the list holding the variables. In this example, the body
3780is a list that uses the @code{message} function to print a string in
3781the echo area.
3782
3783@need 1500
3784You may evaluate the example in the usual fashion, by placing the
3785cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3786this, the following will appear in the echo area:
3787
3788@smallexample
3789"One kind of animal has stripes and another is fierce."
3790@end smallexample
3791
3792As we have seen before, the @code{message} function prints its first
3793argument, except for @samp{%s}. In this example, the value of the variable
3794@code{zebra} is printed at the location of the first @samp{%s} and the
3795value of the variable @code{tiger} is printed at the location of the
3796second @samp{%s}.
3797
3798@node Uninitialized let Variables, , Sample let Expression, let
3799@comment node-name, next, previous, up
3800@subsection Uninitialized Variables in a @code{let} Statement
3801@cindex Uninitialized @code{let} variables
3802@cindex @code{let} variables uninitialized
3803
3804If you do not bind the variables in a @code{let} statement to specific
3805initial values, they will automatically be bound to an initial value of
3806@code{nil}, as in the following expression:
3807
3808@smallexample
3809@group
3810(let ((birch 3)
3811 pine
3812 fir
3813 (oak 'some))
3814 (message
3815 "Here are %d variables with %s, %s, and %s value."
3816 birch pine fir oak))
3817@end group
3818@end smallexample
3819
3820@noindent
3821Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3822
3823@need 1250
3824If you evaluate this expression in the usual way, the following will
3825appear in your echo area:
3826
3827@smallexample
3828"Here are 3 variables with nil, nil, and some value."
3829@end smallexample
3830
3831@noindent
3832In this example, Emacs binds the symbol @code{birch} to the number 3,
3833binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3834the symbol @code{oak} to the value @code{some}.
3835
3836Note that in the first part of the @code{let}, the variables @code{pine}
3837and @code{fir} stand alone as atoms that are not surrounded by
3838parentheses; this is because they are being bound to @code{nil}, the
3839empty list. But @code{oak} is bound to @code{some} and so is a part of
3840the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3841number 3 and so is in a list with that number. (Since a number
3842evaluates to itself, the number does not need to be quoted. Also, the
3843number is printed in the message using a @samp{%d} rather than a
3844@samp{%s}.) The four variables as a group are put into a list to
3845delimit them from the body of the @code{let}.
3846
3847@node if, else, let, Writing Defuns
3848@comment node-name, next, previous, up
3849@section The @code{if} Special Form
3850@findex if
3851@cindex Conditional with @code{if}
3852
3853A third special form, in addition to @code{defun} and @code{let}, is the
3854conditional @code{if}. This form is used to instruct the computer to
3855make decisions. You can write function definitions without using
3856@code{if}, but it is used often enough, and is important enough, to be
3857included here. It is used, for example, in the code for the
3858function @code{beginning-of-buffer}.
3859
3860The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3861@emph{then} an expression is evaluated.'' If the test is not true, the
3862expression is not evaluated. For example, you might make a decision
3863such as, ``if it is warm and sunny, then go to the beach!''
3864
3865@menu
3866* if in more detail::
3867* type-of-animal in detail:: An example of an @code{if} expression.
3868@end menu
3869
3870@node if in more detail, type-of-animal in detail, if, if
3871@ifnottex
3872@unnumberedsubsec @code{if} in more detail
3873@end ifnottex
3874
3875@cindex @samp{if-part} defined
3876@cindex @samp{then-part} defined
3877An @code{if} expression written in Lisp does not use the word `then';
3878the test and the action are the second and third elements of the list
3879whose first element is @code{if}. Nonetheless, the test part of an
3880@code{if} expression is often called the @dfn{if-part} and the second
3881argument is often called the @dfn{then-part}.
3882
3883Also, when an @code{if} expression is written, the true-or-false-test
3884is usually written on the same line as the symbol @code{if}, but the
3885action to carry out if the test is true, the ``then-part'', is written
3886on the second and subsequent lines. This makes the @code{if}
3887expression easier to read.
3888
3889@smallexample
3890@group
3891(if @var{true-or-false-test}
3892 @var{action-to-carry-out-if-test-is-true})
3893@end group
3894@end smallexample
3895
3896@noindent
3897The true-or-false-test will be an expression that
3898is evaluated by the Lisp interpreter.
3899
3900Here is an example that you can evaluate in the usual manner. The test
3901is whether the number 5 is greater than the number 4. Since it is, the
3902message @samp{5 is greater than 4!} will be printed.
3903
3904@smallexample
3905@group
3906(if (> 5 4) ; @r{if-part}
3907 (message "5 is greater than 4!")) ; @r{then-part}
3908@end group
3909@end smallexample
3910
3911@noindent
3912(The function @code{>} tests whether its first argument is greater than
3913its second argument and returns true if it is.)
3914@findex > (greater than)
3915
3916Of course, in actual use, the test in an @code{if} expression will not
3917be fixed for all time as it is by the expression @code{(> 5 4)}.
3918Instead, at least one of the variables used in the test will be bound to
3919a value that is not known ahead of time. (If the value were known ahead
3920of time, we would not need to run the test!)
3921
3922For example, the value may be bound to an argument of a function
3923definition. In the following function definition, the character of the
3924animal is a value that is passed to the function. If the value bound to
3925@code{characteristic} is @code{fierce}, then the message, @samp{It's a
3926tiger!} will be printed; otherwise, @code{nil} will be returned.
3927
3928@smallexample
3929@group
3930(defun type-of-animal (characteristic)
3931 "Print message in echo area depending on CHARACTERISTIC.
3932If the CHARACTERISTIC is the symbol `fierce',
3933then warn of a tiger."
3934 (if (equal characteristic 'fierce)
3935 (message "It's a tiger!")))
3936@end group
3937@end smallexample
3938
3939@need 1500
3940@noindent
3941If you are reading this inside of GNU Emacs, you can evaluate the
3942function definition in the usual way to install it in Emacs, and then you
3943can evaluate the following two expressions to see the results:
3944
3945@smallexample
3946@group
3947(type-of-animal 'fierce)
3948
3949(type-of-animal 'zebra)
3950
3951@end group
3952@end smallexample
3953
3954@c Following sentences rewritten to prevent overfull hbox.
3955@noindent
3956When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3957following message printed in the echo area: @code{"It's a tiger!"}; and
3958when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3959printed in the echo area.
3960
3961@node type-of-animal in detail, , if in more detail, if
3962@comment node-name, next, previous, up
3963@subsection The @code{type-of-animal} Function in Detail
3964
3965Let's look at the @code{type-of-animal} function in detail.
3966
3967The function definition for @code{type-of-animal} was written by filling
3968the slots of two templates, one for a function definition as a whole, and
3969a second for an @code{if} expression.
3970
3971@need 1250
3972The template for every function that is not interactive is:
3973
3974@smallexample
3975@group
3976(defun @var{name-of-function} (@var{argument-list})
3977 "@var{documentation}@dots{}"
3978 @var{body}@dots{})
3979@end group
3980@end smallexample
3981
3982@need 800
3983The parts of the function that match this template look like this:
3984
3985@smallexample
3986@group
3987(defun type-of-animal (characteristic)
3988 "Print message in echo area depending on CHARACTERISTIC.
3989If the CHARACTERISTIC is the symbol `fierce',
3990then warn of a tiger."
3991 @var{body: the} @code{if} @var{expression})
3992@end group
3993@end smallexample
3994
3995The name of function is @code{type-of-animal}; it is passed the value
3996of one argument. The argument list is followed by a multi-line
3997documentation string. The documentation string is included in the
3998example because it is a good habit to write documentation string for
3999every function definition. The body of the function definition
4000consists of the @code{if} expression.
4001
4002@need 800
4003The template for an @code{if} expression looks like this:
4004
4005@smallexample
4006@group
4007(if @var{true-or-false-test}
4008 @var{action-to-carry-out-if-the-test-returns-true})
4009@end group
4010@end smallexample
4011
4012@need 1250
4013In the @code{type-of-animal} function, the code for the @code{if}
4014looks like this:
4015
4016@smallexample
4017@group
4018(if (equal characteristic 'fierce)
4019 (message "It's a tiger!")))
4020@end group
4021@end smallexample
4022
4023@need 800
4024Here, the true-or-false-test is the expression:
4025
4026@smallexample
4027(equal characteristic 'fierce)
4028@end smallexample
4029
4030@noindent
4031In Lisp, @code{equal} is a function that determines whether its first
4032argument is equal to its second argument. The second argument is the
4033quoted symbol @code{'fierce} and the first argument is the value of the
4034symbol @code{characteristic}---in other words, the argument passed to
4035this function.
4036
4037In the first exercise of @code{type-of-animal}, the argument
4038@code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4039is equal to @code{fierce}, the expression, @code{(equal characteristic
4040'fierce)}, returns a value of true. When this happens, the @code{if}
4041evaluates the second argument or then-part of the @code{if}:
4042@code{(message "It's tiger!")}.
4043
4044On the other hand, in the second exercise of @code{type-of-animal}, the
4045argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4046is not equal to @code{fierce}, so the then-part is not evaluated and
4047@code{nil} is returned by the @code{if} expression.
4048
4049@node else, Truth & Falsehood, if, Writing Defuns
4050@comment node-name, next, previous, up
4051@section If--then--else Expressions
4052@cindex Else
4053
4054An @code{if} expression may have an optional third argument, called
4055the @dfn{else-part}, for the case when the true-or-false-test returns
4056false. When this happens, the second argument or then-part of the
4057overall @code{if} expression is @emph{not} evaluated, but the third or
4058else-part @emph{is} evaluated. You might think of this as the cloudy
4059day alternative for the decision `if it is warm and sunny, then go to
4060the beach, else read a book!''.
4061
4062The word ``else'' is not written in the Lisp code; the else-part of an
4063@code{if} expression comes after the then-part. In the written Lisp, the
4064else-part is usually written to start on a line of its own and is
4065indented less than the then-part:
4066
4067@smallexample
4068@group
4069(if @var{true-or-false-test}
4070 @var{action-to-carry-out-if-the-test-returns-true}
4071 @var{action-to-carry-out-if-the-test-returns-false})
4072@end group
4073@end smallexample
4074
4075For example, the following @code{if} expression prints the message @samp{4
4076is not greater than 5!} when you evaluate it in the usual way:
4077
4078@smallexample
4079@group
4080(if (> 4 5) ; @r{if-part}
4081 (message "5 is greater than 4!") ; @r{then-part}
4082 (message "4 is not greater than 5!")) ; @r{else-part}
4083@end group
4084@end smallexample
4085
4086@noindent
4087Note that the different levels of indentation make it easy to
4088distinguish the then-part from the else-part. (GNU Emacs has several
4089commands that automatically indent @code{if} expressions correctly.
4090@xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4091
4092We can extend the @code{type-of-animal} function to include an
4093else-part by simply incorporating an additional part to the @code{if}
4094expression.
4095
4096@need 1500
4097You can see the consequences of doing this if you evaluate the following
4098version of the @code{type-of-animal} function definition to install it
4099and then evaluate the two subsequent expressions to pass different
4100arguments to the function.
4101
4102@smallexample
4103@group
4104(defun type-of-animal (characteristic) ; @r{Second version.}
4105 "Print message in echo area depending on CHARACTERISTIC.
4106If the CHARACTERISTIC is the symbol `fierce',
4107then warn of a tiger;
4108else say it's not fierce."
4109 (if (equal characteristic 'fierce)
4110 (message "It's a tiger!")
4111 (message "It's not fierce!")))
4112@end group
4113@end smallexample
4114@sp 1
4115
4116@smallexample
4117@group
4118(type-of-animal 'fierce)
4119
4120(type-of-animal 'zebra)
4121
4122@end group
4123@end smallexample
4124
4125@c Following sentence rewritten to prevent overfull hbox.
4126@noindent
4127When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4128following message printed in the echo area: @code{"It's a tiger!"}; but
4129when you evaluate @code{(type-of-animal 'zebra)}, you will see
4130@code{"It's not fierce!"}.
4131
4132(Of course, if the @var{characteristic} were @code{ferocious}, the
4133message @code{"It's not fierce!"} would be printed; and it would be
4134misleading! When you write code, you need to take into account the
4135possibility that some such argument will be tested by the @code{if} and
4136write your program accordingly.)
4137
4138@node Truth & Falsehood, save-excursion, else, Writing Defuns
4139@comment node-name, next, previous, up
4140@section Truth and Falsehood in Emacs Lisp
4141@cindex Truth and falsehood in Emacs Lisp
4142@cindex Falsehood and truth in Emacs Lisp
4143@findex nil
4144
4145There is an important aspect to the truth test in an @code{if}
4146expression. So far, we have spoken of `true' and `false' as values of
4147predicates as if they were new kinds of Emacs Lisp objects. In fact,
4148`false' is just our old friend @code{nil}. Anything else---anything
4149at all---is `true'.
4150
4151The expression that tests for truth is interpreted as @dfn{true}
4152if the result of evaluating it is a value that is not @code{nil}. In
4153other words, the result of the test is considered true if the value
4154returned is a number such as 47, a string such as @code{"hello"}, or a
4155symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4156even a buffer!
4157
4158@menu
4159* nil explained:: @code{nil} has two meanings.
4160@end menu
4161
4162@node nil explained, , Truth & Falsehood, Truth & Falsehood
4163@ifnottex
4164@unnumberedsubsec An explanation of @code{nil}
4165@end ifnottex
4166
4167Before illustrating a test for truth, we need an explanation of @code{nil}.
4168
4169In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4170empty list. Second, it means false and is the value returned when a
4171true-or-false-test tests false. @code{nil} can be written as an empty
4172list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4173concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4174to use @code{nil} for false and @code{()} for the empty list.
4175
4176In Emacs Lisp, any value that is not @code{nil}---is not the empty
4177list---is considered true. This means that if an evaluation returns
4178something that is not an empty list, an @code{if} expression will test
4179true. For example, if a number is put in the slot for the test, it
4180will be evaluated and will return itself, since that is what numbers
4181do when evaluated. In this conditional, the @code{if} expression will
4182test true. The expression tests false only when @code{nil}, an empty
4183list, is returned by evaluating the expression.
4184
4185You can see this by evaluating the two expressions in the following examples.
4186
4187In the first example, the number 4 is evaluated as the test in the
4188@code{if} expression and returns itself; consequently, the then-part
4189of the expression is evaluated and returned: @samp{true} appears in
4190the echo area. In the second example, the @code{nil} indicates false;
4191consequently, the else-part of the expression is evaluated and
4192returned: @samp{false} appears in the echo area.
4193
4194@smallexample
4195@group
4196(if 4
4197 'true
4198 'false)
4199@end group
4200
4201@group
4202(if nil
4203 'true
4204 'false)
4205@end group
4206@end smallexample
4207
4208@need 1250
4209Incidentally, if some other useful value is not available for a test that
4210returns true, then the Lisp interpreter will return the symbol @code{t}
4211for true. For example, the expression @code{(> 5 4)} returns @code{t}
4212when evaluated, as you can see by evaluating it in the usual way:
4213
4214@smallexample
4215(> 5 4)
4216@end smallexample
4217
4218@need 1250
4219@noindent
4220On the other hand, this function returns @code{nil} if the test is false.
4221
4222@smallexample
4223(> 4 5)
4224@end smallexample
4225
4226@node save-excursion, Review, Truth & Falsehood, Writing Defuns
4227@comment node-name, next, previous, up
4228@section @code{save-excursion}
4229@findex save-excursion
4230@cindex Region, what it is
4231@cindex Preserving point, mark, and buffer
4232@cindex Point, mark, buffer preservation
4233@findex point
4234@findex mark
4235
4236The @code{save-excursion} function is the fourth and final special form
4237that we will discuss in this chapter.
4238
4239In Emacs Lisp programs used for editing, the @code{save-excursion}
4240function is very common. It saves the location of point and mark,
4241executes the body of the function, and then restores point and mark to
4242their previous positions if their locations were changed. Its primary
4243purpose is to keep the user from being surprised and disturbed by
4244unexpected movement of point or mark.
4245
4246@menu
4247* Point and mark:: A review of various locations.
4248* Template for save-excursion::
4249@end menu
4250
4251@node Point and mark, Template for save-excursion, save-excursion, save-excursion
4252@ifnottex
4253@unnumberedsubsec Point and Mark
4254@end ifnottex
4255
4256Before discussing @code{save-excursion}, however, it may be useful
4257first to review what point and mark are in GNU Emacs. @dfn{Point} is
4258the current location of the cursor. Wherever the cursor
4259is, that is point. More precisely, on terminals where the cursor
4260appears to be on top of a character, point is immediately before the
4261character. In Emacs Lisp, point is an integer. The first character in
4262a buffer is number one, the second is number two, and so on. The
4263function @code{point} returns the current position of the cursor as a
4264number. Each buffer has its own value for point.
4265
4266The @dfn{mark} is another position in the buffer; its value can be set
4267with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4268a mark has been set, you can use the command @kbd{C-x C-x}
4269(@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4270and set the mark to be the previous position of point. In addition, if
4271you set another mark, the position of the previous mark is saved in the
4272mark ring. Many mark positions can be saved this way. You can jump the
4273cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4274times.
4275
4276The part of the buffer between point and mark is called @dfn{the
4277region}. Numerous commands work on the region, including
4278@code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4279@code{print-region}.
4280
4281The @code{save-excursion} special form saves the locations of point and
4282mark and restores those positions after the code within the body of the
4283special form is evaluated by the Lisp interpreter. Thus, if point were
4284in the beginning of a piece of text and some code moved point to the end
4285of the buffer, the @code{save-excursion} would put point back to where
4286it was before, after the expressions in the body of the function were
4287evaluated.
4288
4289In Emacs, a function frequently moves point as part of its internal
4290workings even though a user would not expect this. For example,
4291@code{count-lines-region} moves point. To prevent the user from being
4292bothered by jumps that are both unexpected and (from the user's point of
4293view) unnecessary, @code{save-excursion} is often used to keep point and
4294mark in the location expected by the user. The use of
4295@code{save-excursion} is good housekeeping.
4296
4297To make sure the house stays clean, @code{save-excursion} restores the
4298values of point and mark even if something goes wrong in the code inside
4299of it (or, to be more precise and to use the proper jargon, ``in case of
4300abnormal exit''). This feature is very helpful.
4301
4302In addition to recording the values of point and mark,
4303@code{save-excursion} keeps track of the current buffer, and restores
4304it, too. This means you can write code that will change the buffer and
4305have @code{save-excursion} switch you back to the original buffer. This
4306is how @code{save-excursion} is used in @code{append-to-buffer}.
4307(@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4308
4309@node Template for save-excursion, , Point and mark, save-excursion
4310@comment node-name, next, previous, up
4311@subsection Template for a @code{save-excursion} Expression
4312
4313@need 800
4314The template for code using @code{save-excursion} is simple:
4315
4316@smallexample
4317@group
4318(save-excursion
4319 @var{body}@dots{})
4320@end group
4321@end smallexample
4322
4323@noindent
4324The body of the function is one or more expressions that will be
4325evaluated in sequence by the Lisp interpreter. If there is more than
4326one expression in the body, the value of the last one will be returned
4327as the value of the @code{save-excursion} function. The other
4328expressions in the body are evaluated only for their side effects; and
4329@code{save-excursion} itself is used only for its side effect (which
4330is restoring the positions of point and mark).
4331
4332@need 1250
4333In more detail, the template for a @code{save-excursion} expression
4334looks like this:
4335
4336@smallexample
4337@group
4338(save-excursion
4339 @var{first-expression-in-body}
4340 @var{second-expression-in-body}
4341 @var{third-expression-in-body}
4342 @dots{}
4343 @var{last-expression-in-body})
4344@end group
4345@end smallexample
4346
4347@noindent
4348An expression, of course, may be a symbol on its own or a list.
4349
4350In Emacs Lisp code, a @code{save-excursion} expression often occurs
4351within the body of a @code{let} expression. It looks like this:
4352
4353@smallexample
4354@group
4355(let @var{varlist}
4356 (save-excursion
4357 @var{body}@dots{}))
4358@end group
4359@end smallexample
4360
4361@node Review, defun Exercises, save-excursion, Writing Defuns
4362@comment node-name, next, previous, up
4363@section Review
4364
4365In the last few chapters we have introduced a fair number of functions
4366and special forms. Here they are described in brief, along with a few
4367similar functions that have not been mentioned yet.
4368
4369@table @code
4370@item eval-last-sexp
4371Evaluate the last symbolic expression before the current location of
4372point. The value is printed in the echo area unless the function is
4373invoked with an argument; in that case, the output is printed in the
4374current buffer. This command is normally bound to @kbd{C-x C-e}.
4375
4376@item defun
4377Define function. This special form has up to five parts: the name,
4378a template for the arguments that will be passed to the function,
4379documentation, an optional interactive declaration, and the body of the
4380definition.
4381
4382@need 1250
4383For example:
4384
4385@smallexample
4386@group
4387(defun back-to-indentation ()
4388 "Move point to first visible character on line."
4389 (interactive)
4390 (beginning-of-line 1)
4391 (skip-chars-forward " \t"))
4392@end group
4393@end smallexample
4394
4395@item interactive
4396Declare to the interpreter that the function can be used
4397interactively. This special form may be followed by a string with one
4398or more parts that pass the information to the arguments of the
4399function, in sequence. These parts may also tell the interpreter to
4400prompt for information. Parts of the string are separated by
4401newlines, @samp{\n}.
4402
4403Common code characters are:
4404
4405@table @code
4406@item b
4407The name of an existing buffer.
4408
4409@item f
4410The name of an existing file.
4411
4412@item p
4413The numeric prefix argument. (Note that this `p' is lower case.)
4414
4415@item r
4416Point and the mark, as two numeric arguments, smallest first. This
4417is the only code letter that specifies two successive arguments
4418rather than one.
4419@end table
4420
4421@xref{Interactive Codes, , Code Characters for @samp{interactive},
4422elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4423code characters.
4424
4425@item let
4426Declare that a list of variables is for use within the body of the
4427@code{let} and give them an initial value, either @code{nil} or a
4428specified value; then evaluate the rest of the expressions in the body
4429of the @code{let} and return the value of the last one. Inside the
4430body of the @code{let}, the Lisp interpreter does not see the values of
4431the variables of the same names that are bound outside of the
4432@code{let}.
4433
4434@need 1250
4435For example,
4436
4437@smallexample
4438@group
4439(let ((foo (buffer-name))
4440 (bar (buffer-size)))
4441 (message
4442 "This buffer is %s and has %d characters."
4443 foo bar))
4444@end group
4445@end smallexample
4446
4447@item save-excursion
4448Record the values of point and mark and the current buffer before
4449evaluating the body of this special form. Restore the values of point
4450and mark and buffer afterward.
4451
4452@need 1250
4453For example,
4454
4455@smallexample
4456@group
4457(message "We are %d characters into this buffer."
4458 (- (point)
4459 (save-excursion
4460 (goto-char (point-min)) (point))))
4461@end group
4462@end smallexample
4463
4464@item if
4465Evaluate the first argument to the function; if it is true, evaluate
4466the second argument; else evaluate the third argument, if there is one.
4467
4468The @code{if} special form is called a @dfn{conditional}. There are
4469other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4470commonly used.
4471
4472@need 1250
4473For example,
4474
4475@smallexample
4476@group
4477(if (string-equal
4478 (number-to-string 21)
4479 (substring (emacs-version) 10 12))
4480 (message "This is version 21 Emacs")
4481 (message "This is not version 21 Emacs"))
4482@end group
4483@end smallexample
4484
4485@item equal
4486@itemx eq
4487Test whether two objects are the same. @code{equal} uses one meaning
4488of the word `same' and @code{eq} uses another: @code{equal} returns
4489true if the two objects have a similar structure and contents, such as
4490two copies of the same book. On the other hand, @code{eq}, returns
4491true if both arguments are actually the same object.
4492@findex equal
4493@findex eq
4494
4495@need 1250
4496@item <
4497@itemx >
4498@itemx <=
4499@itemx >=
4500The @code{<} function tests whether its first argument is smaller than
4501its second argument. A corresponding function, @code{>}, tests whether
4502the first argument is greater than the second. Likewise, @code{<=}
4503tests whether the first argument is less than or equal to the second and
4504@code{>=} tests whether the first argument is greater than or equal to
4505the second. In all cases, both arguments must be numbers or markers
4506(markers indicate positions in buffers).
4507
4508@item string<
4509@itemx string-lessp
4510@itemx string=
4511@itemx string-equal
4512The @code{string-lessp} function tests whether its first argument is
4513smaller than the second argument. A shorter, alternative name for the
4514same function (a @code{defalias}) is @code{string<}.
4515
4516The arguments to @code{string-lessp} must be strings or symbols; the
4517ordering is lexicographic, so case is significant. The print names of
4518symbols are used instead of the symbols themselves.
4519
4520@code{string-equal} provides the corresponding test for equality. Its
4521shorter, alternative name is @code{string=}. There are no string test
4522functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4523
4524@item message
4525Print a message in the echo area. The first argument is a string that
4526can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4527arguments that follow the string. The argument used by @samp{%s} must
4528be a string or a symbol; the argument used by @samp{%d} must be a
4529number. The argument used by @samp{%c} must be an ascii code number;
4530it will be printed as the character with that @sc{ascii} code.
4531
4532@item setq
4533@itemx set
4534The @code{setq} function sets the value of its first argument to the
4535value of the second argument. The first argument is automatically
4536quoted by @code{setq}. It does the same for succeeding pairs of
4537arguments. Another function, @code{set}, takes only two arguments and
4538evaluates both of them before setting the value returned by its first
4539argument to the value returned by its second argument.
4540
4541@item buffer-name
4542Without an argument, return the name of the buffer, as a string.
4543
4544@itemx buffer-file-name
4545Without an argument, return the name of the file the buffer is
4546visiting.
4547
4548@item current-buffer
4549Return the buffer in which Emacs is active; it may not be
4550the buffer that is visible on the screen.
4551
4552@item other-buffer
4553Return the most recently selected buffer (other than the buffer passed
4554to @code{other-buffer} as an argument and other than the current
4555buffer).
4556
4557@item switch-to-buffer
4558Select a buffer for Emacs to be active in and display it in the current
4559window so users can look at it. Usually bound to @kbd{C-x b}.
4560
4561@item set-buffer
4562Switch Emacs' attention to a buffer on which programs will run. Don't
4563alter what the window is showing.
4564
4565@item buffer-size
4566Return the number of characters in the current buffer.
4567
4568@item point
4569Return the value of the current position of the cursor, as an
4570integer counting the number of characters from the beginning of the
4571buffer.
4572
4573@item point-min
4574Return the minimum permissible value of point in
4575the current buffer. This is 1, unless narrowing is in effect.
4576
4577@item point-max
4578Return the value of the maximum permissible value of point in the
4579current buffer. This is the end of the buffer, unless narrowing is in
4580effect.
4581@end table
4582
4583@need 1500
4584@node defun Exercises, , Review, Writing Defuns
4585@section Exercises
4586
4587@itemize @bullet
4588@item
4589Write a non-interactive function that doubles the value of its
4590argument, a number. Make that function interactive.
4591
4592@item
4593Write a function that tests whether the current value of
4594@code{fill-column} is greater than the argument passed to the function,
4595and if so, prints an appropriate message.
4596@end itemize
4597
4598@node Buffer Walk Through, More Complex, Writing Defuns, Top
4599@comment node-name, next, previous, up
4600@chapter A Few Buffer--Related Functions
4601
4602In this chapter we study in detail several of the functions used in GNU
4603Emacs. This is called a ``walk-through''. These functions are used as
4604examples of Lisp code, but are not imaginary examples; with the
4605exception of the first, simplified function definition, these functions
4606show the actual code used in GNU Emacs. You can learn a great deal from
4607these definitions. The functions described here are all related to
4608buffers. Later, we will study other functions.
4609
4610@menu
4611* Finding More:: How to find more information.
4612* simplified-beginning-of-buffer:: Shows @code{goto-char},
4613 @code{point-min}, and @code{push-mark}.
4614* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4615* append-to-buffer:: Uses @code{save-excursion} and
4616 @code{insert-buffer-substring}.
4617* Buffer Related Review:: Review.
4618* Buffer Exercises::
4619@end menu
4620
4621@node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4622@section Finding More Information
4623
4624@findex describe-function, @r{introduced}
4625@cindex Find function documentation
4626In this walk-through, I will describe each new function as we come to
4627it, sometimes in detail and sometimes briefly. If you are interested,
4628you can get the full documentation of any Emacs Lisp function at any
4629time by typing @kbd{C-h f} and then the name of the function (and then
4630@key{RET}). Similarly, you can get the full documentation for a
4631variable by typing @kbd{C-h v} and then the name of the variable (and
4632then @key{RET}).
4633
4634@cindex Find source of function
4635In versions 20 and higher, when a function is written in Emacs Lisp,
4636@code{describe-function} will also tell you the location of the
4637function definition. If you move point over the file name and press
4638the @key{RET} key, which is this case means @code{help-follow} rather
4639than `return' or `enter', Emacs will take you directly to the function
4640definition.
4641
4642More generally, if you want to see a function in its original source
4643file, you can use the @code{find-tags} function to jump to it.
4644@code{find-tags} works with a wide variety of languages, not just
4645Lisp, and C, and it works with non-programming text as well. For
4646example, @code{find-tags} will jump to the various nodes in the
4647Texinfo source file of this document.
4648
4649The @code{find-tags} function depends on `tags tables' that record
4650the locations of the functions, variables, and other items to which
4651@code{find-tags} jumps.
4652
4653To use the @code{find-tags} command, type @kbd{M-.} (i.e., type the
4654@key{META} key and the period key at the same time, or else type the
4655@key{ESC} key and then type the period key), and then, at the prompt,
4656type in the name of the function whose source code you want to see,
4657such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4658switch buffers and display the source code for the function on your
4659screen. To switch back to your current buffer, type @kbd{C-x b
4660@key{RET}}. (On some keyboards, the @key{META} key is labelled
4661@key{ALT}.)
4662
4663@c !!! 21.0.100 tags table location in this paragraph
4664@cindex TAGS table, specifying
4665@findex find-tags
4666Depending on how the initial default values of your copy of Emacs are
4667set, you may also need to specify the location of your `tags table',
4668which is a file called @file{TAGS}. For example, if you are
4669interested in Emacs sources, the tags table you will most likely want,
4670if it has already been created for you, will be in a subdirectory of
4671the @file{/usr/local/share/emacs/} directory; thus you would use the
4672@code{M-x visit-tags-table} command and specify a pathname such as
4673@file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
4674@file{/usr/local/src/emacs/lisp/TAGS}. If the tags table has
4675not already been created, you will have to create it yourself.
4676
4677@need 1250
4678To create a @file{TAGS} file in a specific directory, switch to that
4679directory in Emacs using @kbd{M-x cd} command, or list the directory
4680with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4681@w{@code{etags *.el}} as the command to execute
4682
4683@smallexample
4684M-x compile RET etags *.el RET
4685@end smallexample
4686
4687For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4688
4689After you become more familiar with Emacs Lisp, you will find that you will
4690frequently use @code{find-tags} to navigate your way around source code;
4691and you will create your own @file{TAGS} tables.
4692
4693@cindex Library, as term for `file'
4694Incidentally, the files that contain Lisp code are conventionally
4695called @dfn{libraries}. The metaphor is derived from that of a
4696specialized library, such as a law library or an engineering library,
4697rather than a general library. Each library, or file, contains
4698functions that relate to a particular topic or activity, such as
4699@file{abbrev.el} for handling abbreviations and other typing
4700shortcuts, and @file{help.el} for on-line help. (Sometimes several
4701libraries provide code for a single activity, as the various
4702@file{rmail@dots{}} files provide code for reading electronic mail.)
4703In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4704@kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4705by topic keywords.''
4706
4707@node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4708@comment node-name, next, previous, up
4709@section A Simplified @code{beginning-of-buffer} Definition
4710@findex simplified-beginning-of-buffer
4711
4712The @code{beginning-of-buffer} command is a good function to start with
4713since you are likely to be familiar with it and it is easy to
4714understand. Used as an interactive command, @code{beginning-of-buffer}
4715moves the cursor to the beginning of the buffer, leaving the mark at the
4716previous position. It is generally bound to @kbd{M-<}.
4717
4718In this section, we will discuss a shortened version of the function
4719that shows how it is most frequently used. This shortened function
4720works as written, but it does not contain the code for a complex option.
4721In another section, we will describe the entire function.
4722(@xref{beginning-of-buffer, , Complete Definition of
4723@code{beginning-of-buffer}}.)
4724
4725Before looking at the code, let's consider what the function
4726definition has to contain: it must include an expression that makes
4727the function interactive so it can be called by typing @kbd{M-x
4728beginning-of-buffer} or by typing a keychord such as @kbd{C-<}; it
4729must include code to leave a mark at the original position in the
4730buffer; and it must include code to move the cursor to the beginning
4731of the buffer.
4732
4733@need 1250
4734Here is the complete text of the shortened version of the function:
4735
4736@smallexample
4737@group
4738(defun simplified-beginning-of-buffer ()
4739 "Move point to the beginning of the buffer;
4740leave mark at previous position."
4741 (interactive)
4742 (push-mark)
4743 (goto-char (point-min)))
4744@end group
4745@end smallexample
4746
4747Like all function definitions, this definition has five parts following
4748the special form @code{defun}:
4749
4750@enumerate
4751@item
4752The name: in this example, @code{simplified-beginning-of-buffer}.
4753
4754@item
4755A list of the arguments: in this example, an empty list, @code{()},
4756
4757@item
4758The documentation string.
4759
4760@item
4761The interactive expression.
4762
4763@item
4764The body.
4765@end enumerate
4766
4767@noindent
4768In this function definition, the argument list is empty; this means that
4769this function does not require any arguments. (When we look at the
4770definition for the complete function, we will see that it may be passed
4771an optional argument.)
4772
4773The interactive expression tells Emacs that the function is intended to
4774be used interactively. In this example, @code{interactive} does not have
4775an argument because @code{simplified-beginning-of-buffer} does not
4776require one.
4777
4778@need 800
4779The body of the function consists of the two lines:
4780
4781@smallexample
4782@group
4783(push-mark)
4784(goto-char (point-min))
4785@end group
4786@end smallexample
4787
4788The first of these lines is the expression, @code{(push-mark)}. When
4789this expression is evaluated by the Lisp interpreter, it sets a mark at
4790the current position of the cursor, wherever that may be. The position
4791of this mark is saved in the mark ring.
4792
4793The next line is @code{(goto-char (point-min))}. This expression
4794jumps the cursor to the minimum point in the buffer, that is, to the
4795beginning of the buffer (or to the beginning of the accessible portion
4796of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4797Narrowing and Widening}.)
4798
4799The @code{push-mark} command sets a mark at the place where the cursor
4800was located before it was moved to the beginning of the buffer by the
4801@code{(goto-char (point-min))} expression. Consequently, you can, if
4802you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4803
4804That is all there is to the function definition!
4805
4806@findex describe-function
4807When you are reading code such as this and come upon an unfamiliar
4808function, such as @code{goto-char}, you can find out what it does by
4809using the @code{describe-function} command. To use this command, type
4810@kbd{C-h f} and then type in the name of the function and press
4811@key{RET}. The @code{describe-function} command will print the
4812function's documentation string in a @file{*Help*} window. For
4813example, the documentation for @code{goto-char} is:
4814
4815@smallexample
4816@group
4817One arg, a number. Set point to that number.
4818Beginning of buffer is position (point-min),
4819end is (point-max).
4820@end group
4821@end smallexample
4822
4823@noindent
4824(The prompt for @code{describe-function} will offer you the symbol
4825under or preceding the cursor, so you can save typing by positioning
4826the cursor right over or after the function and then typing @kbd{C-h f
4827@key{RET}}.)
4828
4829The @code{end-of-buffer} function definition is written in the same way as
4830the @code{beginning-of-buffer} definition except that the body of the
4831function contains the expression @code{(goto-char (point-max))} in place
4832of @code{(goto-char (point-min))}.
4833
4834@node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4835@comment node-name, next, previous, up
4836@section The Definition of @code{mark-whole-buffer}
4837@findex mark-whole-buffer
4838
4839The @code{mark-whole-buffer} function is no harder to understand than the
4840@code{simplified-beginning-of-buffer} function. In this case, however,
4841we will look at the complete function, not a shortened version.
4842
4843The @code{mark-whole-buffer} function is not as commonly used as the
4844@code{beginning-of-buffer} function, but is useful nonetheless: it
4845marks a whole buffer as a region by putting point at the beginning and
4846a mark at the end of the buffer. It is generally bound to @kbd{C-x
4847h}.
4848
4849
4850@menu
4851* mark-whole-buffer overview::
4852* Body of mark-whole-buffer:: Only three lines of code.
4853@end menu
4854
4855
4856@node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4857@ifnottex
4858@unnumberedsubsec An overview of @code{mark-whole-buffer}
4859@end ifnottex
4860
4861@need 1250
4862In GNU Emacs 20, the code for the complete function looks like this:
4863
4864@smallexample
4865@group
4866(defun mark-whole-buffer ()
4867 "Put point at beginning and mark at end of buffer."
4868 (interactive)
4869 (push-mark (point))
4870 (push-mark (point-max))
4871 (goto-char (point-min)))
4872@end group
4873@end smallexample
4874
4875@need 1250
4876Like all other functions, the @code{mark-whole-buffer} function fits
4877into the template for a function definition. The template looks like
4878this:
4879
4880@smallexample
4881@group
4882(defun @var{name-of-function} (@var{argument-list})
4883 "@var{documentation}@dots{}"
4884 (@var{interactive-expression}@dots{})
4885 @var{body}@dots{})
4886@end group
4887@end smallexample
4888
4889Here is how the function works: the name of the function is
4890@code{mark-whole-buffer}; it is followed by an empty argument list,
4891@samp{()}, which means that the function does not require arguments.
4892The documentation comes next.
4893
4894The next line is an @code{(interactive)} expression that tells Emacs
4895that the function will be used interactively. These details are similar
4896to the @code{simplified-beginning-of-buffer} function described in the
4897previous section.
4898
4899@node Body of mark-whole-buffer, , mark-whole-buffer overview, mark-whole-buffer
4900@comment node-name, next, previous, up
4901@subsection Body of @code{mark-whole-buffer}
4902
4903The body of the @code{mark-whole-buffer} function consists of three
4904lines of code:
4905
4906@smallexample
4907@group
4908(push-mark (point))
4909(push-mark (point-max))
4910(goto-char (point-min))
4911@end group
4912@end smallexample
4913
4914The first of these lines is the expression, @code{(push-mark (point))}.
4915
4916This line does exactly the same job as the first line of the body of
4917the @code{simplified-beginning-of-buffer} function, which is written
4918@code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4919at the current position of the cursor.
4920
4921I don't know why the expression in @code{mark-whole-buffer} is written
4922@code{(push-mark (point))} and the expression in
4923@code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4924whoever wrote the code did not know that the arguments for
4925@code{push-mark} are optional and that if @code{push-mark} is not
4926passed an argument, the function automatically sets mark at the
4927location of point by default. Or perhaps the expression was written
4928so as to parallel the structure of the next line. In any case, the
4929line causes Emacs to determine the position of point and set a mark
4930there.
4931
4932The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4933This expression sets a mark at the point in the buffer
4934that has the highest number. This will be the end of the buffer (or,
4935if the buffer is narrowed, the end of the accessible portion of the
4936buffer. @xref{Narrowing & Widening, , Narrowing and Widening}, for
4937more about narrowing.) After this mark has been set, the previous
4938mark, the one set at point, is no longer set, but Emacs remembers its
4939position, just as all other recent marks are always remembered. This
4940means that you can, if you wish, go back to that position by typing
4941@kbd{C-u C-@key{SPC}} twice.
4942
4943(In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4944complicated than shown here. The line reads
4945
4946@smallexample
4947(push-mark (point-max) nil t)
4948@end smallexample
4949
4950@noindent
4951(The expression works nearly the same as before. It sets a mark at
4952the highest numbered place in the buffer that it can. However, in
4953this version, @code{push-mark} has two additional arguments The second
4954argument to @code{push-mark} is @code{nil}. This tells the function
4955it should @emph{not} display a message that says `Mark set' when it
4956pushes the mark. The third argument is @code{t}. This tells
4957@code{push-mark} to activate the mark when Transient Mark mode is
4958turned on. Transient Mark mode highlights the currently active
4959region. It is usually turned off.)
4960
4961Finally, the last line of the function is @code{(goto-char
4962(point-min)))}. This is written exactly the same way as it is written
4963in @code{beginning-of-buffer}. The expression moves the cursor to
4964the minimum point in the buffer, that is, to the beginning of the buffer
4965(or to the beginning of the accessible portion of the buffer). As a
4966result of this, point is placed at the beginning of the buffer and mark
4967is set at the end of the buffer. The whole buffer is, therefore, the
4968region.
4969
4970@node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4971@comment node-name, next, previous, up
4972@section The Definition of @code{append-to-buffer}
4973@findex append-to-buffer
4974
4975The @code{append-to-buffer} command is very nearly as simple as the
4976@code{mark-whole-buffer} command. What it does is copy the region (that
4977is, the part of the buffer between point and mark) from the current
4978buffer to a specified buffer.
4979
4980@menu
4981* append-to-buffer overview::
4982* append interactive:: A two part interactive expression.
4983* append-to-buffer body:: Incorporates a @code{let} expression.
4984* append save-excursion:: How the @code{save-excursion} works.
4985@end menu
4986
4987@node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4988@ifnottex
4989@unnumberedsubsec An Overview of @code{append-to-buffer}
4990@end ifnottex
4991
4992@findex insert-buffer-substring
4993The @code{append-to-buffer} command uses the
4994@code{insert-buffer-substring} function to copy the region.
4995@code{insert-buffer-substring} is described by its name: it takes a
4996string of characters from part of a buffer, a ``substring'', and
4997inserts them into another buffer. Most of @code{append-to-buffer} is
4998concerned with setting up the conditions for
4999@code{insert-buffer-substring} to work: the code must specify both the
5000buffer to which the text will go and the region that will be copied.
5001Here is the complete text of the function:
5002
5003@smallexample
5004@group
5005(defun append-to-buffer (buffer start end)
5006 "Append to specified buffer the text of the region.
5007It is inserted into that buffer before its point.
5008@end group
5009
5010@group
5011When calling from a program, give three arguments:
5012a buffer or the name of one, and two character numbers
5013specifying the portion of the current buffer to be copied."
5014 (interactive "BAppend to buffer:@: \nr")
5015 (let ((oldbuf (current-buffer)))
5016 (save-excursion
5017 (set-buffer (get-buffer-create buffer))
5018 (insert-buffer-substring oldbuf start end))))
5019@end group
5020@end smallexample
5021
5022The function can be understood by looking at it as a series of
5023filled-in templates.
5024
5025The outermost template is for the function definition. In this
5026function, it looks like this (with several slots filled in):
5027
5028@smallexample
5029@group
5030(defun append-to-buffer (buffer start end)
5031 "@var{documentation}@dots{}"
5032 (interactive "BAppend to buffer:@: \nr")
5033 @var{body}@dots{})
5034@end group
5035@end smallexample
5036
5037The first line of the function includes its name and three arguments.
5038The arguments are the @code{buffer} to which the text will be copied, and
5039the @code{start} and @code{end} of the region in the current buffer that
5040will be copied.
5041
5042The next part of the function is the documentation, which is clear and
5043complete.
5044
5045@node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
5046@comment node-name, next, previous, up
5047@subsection The @code{append-to-buffer} Interactive Expression
5048
5049Since the @code{append-to-buffer} function will be used interactively,
5050the function must have an @code{interactive} expression. (For a
5051review of @code{interactive}, see @ref{Interactive, , Making a
5052Function Interactive}.) The expression reads as follows:
5053
5054@smallexample
5055(interactive "BAppend to buffer:@: \nr")
5056@end smallexample
5057
5058@noindent
5059This expression has an argument inside of quotation marks and that
5060argument has two parts, separated by @samp{\n}.
5061
5062The first part is @samp{BAppend to buffer:@: }. Here, the @samp{B}
5063tells Emacs to ask for the name of the buffer that will be passed to the
5064function. Emacs will ask for the name by prompting the user in the
5065minibuffer, using the string following the @samp{B}, which is the string
5066@samp{Append to buffer:@: }. Emacs then binds the variable @code{buffer}
5067in the function's argument list to the specified buffer.
5068
5069The newline, @samp{\n}, separates the first part of the argument from
5070the second part. It is followed by an @samp{r} that tells Emacs to bind
5071the two arguments that follow the symbol @code{buffer} in the function's
5072argument list (that is, @code{start} and @code{end}) to the values of
5073point and mark.
5074
5075@node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5076@comment node-name, next, previous, up
5077@subsection The Body of @code{append-to-buffer}
5078
5079The body of the @code{append-to-buffer} function begins with @code{let}.
5080
5081As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5082@code{let} expression is to create and give initial values to one or
5083more variables that will only be used within the body of the
5084@code{let}. This means that such a variable will not be confused with
5085any variable of the same name outside the @code{let} expression.
5086
5087We can see how the @code{let} expression fits into the function as a
5088whole by showing a template for @code{append-to-buffer} with the
5089@code{let} expression in outline:
5090
5091@smallexample
5092@group
5093(defun append-to-buffer (buffer start end)
5094 "@var{documentation}@dots{}"
5095 (interactive "BAppend to buffer:@: \nr")
5096 (let ((@var{variable} @var{value}))
5097 @var{body}@dots{})
5098@end group
5099@end smallexample
5100
5101The @code{let} expression has three elements:
5102
5103@enumerate
5104@item
5105The symbol @code{let};
5106
5107@item
5108A varlist containing, in this case, a single two-element list,
5109@code{(@var{variable} @var{value})};
5110
5111@item
5112The body of the @code{let} expression.
5113@end enumerate
5114
5115@need 800
5116In the @code{append-to-buffer} function, the varlist looks like this:
5117
5118@smallexample
5119(oldbuf (current-buffer))
5120@end smallexample
5121
5122@noindent
5123In this part of the @code{let} expression, the one variable,
5124@code{oldbuf}, is bound to the value returned by the
5125@code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5126used to keep track of the buffer in which you are working and from
5127which you will copy.
5128
5129The element or elements of a varlist are surrounded by a set of
5130parentheses so the Lisp interpreter can distinguish the varlist from
5131the body of the @code{let}. As a consequence, the two-element list
5132within the varlist is surrounded by a circumscribing set of parentheses.
5133The line looks like this:
5134
5135@smallexample
5136@group
5137(let ((oldbuf (current-buffer)))
5138 @dots{} )
5139@end group
5140@end smallexample
5141
5142@noindent
5143The two parentheses before @code{oldbuf} might surprise you if you did
5144not realize that the first parenthesis before @code{oldbuf} marks the
5145boundary of the varlist and the second parenthesis marks the beginning
5146of the two-element list, @code{(oldbuf (current-buffer))}.
5147
5148@node append save-excursion, , append-to-buffer body, append-to-buffer
5149@comment node-name, next, previous, up
5150@subsection @code{save-excursion} in @code{append-to-buffer}
5151
5152The body of the @code{let} expression in @code{append-to-buffer}
5153consists of a @code{save-excursion} expression.
5154
5155The @code{save-excursion} function saves the locations of point and
5156mark, and restores them to those positions after the expressions in the
5157body of the @code{save-excursion} complete execution. In addition,
5158@code{save-excursion} keeps track of the original buffer, and
5159restores it. This is how @code{save-excursion} is used in
5160@code{append-to-buffer}.
5161
5162@need 1500
5163@cindex Indentation for formatting
5164@cindex Formatting convention
5165Incidentally, it is worth noting here that a Lisp function is normally
5166formatted so that everything that is enclosed in a multi-line spread is
5167indented more to the right than the first symbol. In this function
5168definition, the @code{let} is indented more than the @code{defun}, and
5169the @code{save-excursion} is indented more than the @code{let}, like
5170this:
5171
5172@smallexample
5173@group
5174(defun @dots{}
5175 @dots{}
5176 @dots{}
5177 (let@dots{}
5178 (save-excursion
5179 @dots{}
5180@end group
5181@end smallexample
5182
5183@need 1500
5184@noindent
5185This formatting convention makes it easy to see that the two lines in
5186the body of the @code{save-excursion} are enclosed by the parentheses
5187associated with @code{save-excursion}, just as the
5188@code{save-excursion} itself is enclosed by the parentheses associated
5189with the @code{let}:
5190
5191@smallexample
5192@group
5193(let ((oldbuf (current-buffer)))
5194 (save-excursion
5195 (set-buffer (get-buffer-create buffer))
5196 (insert-buffer-substring oldbuf start end))))
5197@end group
5198@end smallexample
5199
5200@need 1200
5201The use of the @code{save-excursion} function can be viewed as a process
5202of filling in the slots of a template:
5203
5204@smallexample
5205@group
5206(save-excursion
5207 @var{first-expression-in-body}
5208 @var{second-expression-in-body}
5209 @dots{}
5210 @var{last-expression-in-body})
5211@end group
5212@end smallexample
5213
5214@need 1200
5215@noindent
5216In this function, the body of the @code{save-excursion} contains only
5217two expressions. The body looks like this:
5218
5219@smallexample
5220@group
5221(set-buffer (get-buffer-create buffer))
5222(insert-buffer-substring oldbuf start end)
5223@end group
5224@end smallexample
5225
5226When the @code{append-to-buffer} function is evaluated, the two
5227expressions in the body of the @code{save-excursion} are evaluated in
5228sequence. The value of the last expression is returned as the value of
5229the @code{save-excursion} function; the other expression is evaluated
5230only for its side effects.
5231
5232The first line in the body of the @code{save-excursion} uses the
5233@code{set-buffer} function to change the current buffer to the one
5234specified in the first argument to @code{append-to-buffer}. (Changing
5235the buffer is the side effect; as we have said before, in Lisp, a side
5236effect is often the primary thing we want.) The second line does the
5237primary work of the function.
5238
5239The @code{set-buffer} function changes Emacs' attention to the buffer to
5240which the text will be copied and from which @code{save-excursion} will
5241return.
5242
5243@need 800
5244The line looks like this:
5245
5246@smallexample
5247(set-buffer (get-buffer-create buffer))
5248@end smallexample
5249
5250The innermost expression of this list is @code{(get-buffer-create
5251buffer)}. This expression uses the @code{get-buffer-create} function,
5252which either gets the named buffer, or if it does not exist, creates one
5253with the given name. This means you can use @code{append-to-buffer} to
5254put text into a buffer that did not previously exist.
5255
5256@code{get-buffer-create} also keeps @code{set-buffer} from getting an
5257unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5258were to specify a buffer that does not exist, Emacs would baulk.
5259Since @code{get-buffer-create} will create a buffer if none exists,
5260@code{set-buffer} is always provided with a buffer.
5261
5262@need 1250
5263The last line of @code{append-to-buffer} does the work of appending
5264the text:
5265
5266@smallexample
5267(insert-buffer-substring oldbuf start end)
5268@end smallexample
5269
5270@noindent
5271The @code{insert-buffer-substring} function copies a string @emph{from}
5272the buffer specified as its first argument and inserts the string into
5273the present buffer. In this case, the argument to
5274@code{insert-buffer-substring} is the value of the variable created and
5275bound by the @code{let}, namely the value of @code{oldbuf}, which was
5276the current buffer when you gave the @code{append-to-buffer} command.
5277
5278After @code{insert-buffer-substring} has done its work,
5279@code{save-excursion} will restore the action to the original buffer and
5280@code{append-to-buffer} will have done its job.
5281
5282@need 800
5283Written in skeletal form, the workings of the body look like this:
5284
5285@smallexample
5286@group
5287(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5288 (save-excursion ; @r{Keep track of buffer.}
5289 @var{change-buffer}
5290 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5291
5292 @var{change-back-to-original-buffer-when-finished}
5293@var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5294
5295@end group
5296@end smallexample
5297
5298In summary, @code{append-to-buffer} works as follows: it saves the value
5299of the current buffer in the variable called @code{oldbuf}. It gets the
5300new buffer, creating one if need be, and switches Emacs to it. Using
5301the value of @code{oldbuf}, it inserts the region of text from the old
5302buffer into the new buffer; and then using @code{save-excursion}, it
5303brings you back to your original buffer.
5304
5305In looking at @code{append-to-buffer}, you have explored a fairly
5306complex function. It shows how to use @code{let} and
5307@code{save-excursion}, and how to change to and come back from another
5308buffer. Many function definitions use @code{let},
5309@code{save-excursion}, and @code{set-buffer} this way.
5310
5311@node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5312@comment node-name, next, previous, up
5313@section Review
5314
5315Here is a brief summary of the various functions discussed in this chapter.
5316
5317@table @code
5318@item describe-function
5319@itemx describe-variable
5320Print the documentation for a function or variable.
5321Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5322
5323@item find-tag
5324Find the file containing the source for a function or variable and
5325switch buffers to it, positioning point at the beginning of the item.
5326Conventionally bound to @kbd{M-.} (that's a period following the
5327@key{META} key).
5328
5329@item save-excursion
5330Save the location of point and mark and restore their values after the
5331arguments to @code{save-excursion} have been evaluated. Also, remember
5332the current buffer and return to it.
5333
5334@item push-mark
5335Set mark at a location and record the value of the previous mark on the
5336mark ring. The mark is a location in the buffer that will keep its
5337relative position even if text is added to or removed from the buffer.
5338
5339@item goto-char
5340Set point to the location specified by the value of the argument, which
5341can be a number, a marker, or an expression that returns the number of
5342a position, such as @code{(point-min)}.
5343
5344@item insert-buffer-substring
5345Copy a region of text from a buffer that is passed to the function as
5346an argument and insert the region into the current buffer.
5347
5348@item mark-whole-buffer
5349Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5350
5351@item set-buffer
5352Switch the attention of Emacs to another buffer, but do not change the
5353window being displayed. Used when the program rather than a human is
5354to work on a different buffer.
5355
5356@item get-buffer-create
5357@itemx get-buffer
5358Find a named buffer or create one if a buffer of that name does not
5359exist. The @code{get-buffer} function returns @code{nil} if the named
5360buffer does not exist.
5361@end table
5362
5363@need 1500
5364@node Buffer Exercises, , Buffer Related Review, Buffer Walk Through
5365@section Exercises
5366
5367@itemize @bullet
5368@item
5369Write your own @code{simplified-end-of-buffer} function definition;
5370then test it to see whether it works.
5371
5372@item
5373Use @code{if} and @code{get-buffer} to write a function that prints a
5374message telling you whether a buffer exists.
5375
5376@item
5377Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5378function.
5379@end itemize
5380
5381@node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5382@comment node-name, next, previous, up
5383@chapter A Few More Complex Functions
5384
5385In this chapter, we build on what we have learned in previous chapters
5386by looking at more complex functions. The @code{copy-to-buffer}
5387function illustrates use of two @code{save-excursion} expressions in
5388one definition, while the @code{insert-buffer} function illustrates
5389use of an asterisk in an @code{interactive} expression, use of
5390@code{or}, and the important distinction between a name and the object
5391to which the name refers.
5392
5393@menu
5394* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5395* insert-buffer:: Read-only, and with @code{or}.
5396* beginning-of-buffer:: Shows @code{goto-char},
5397 @code{point-min}, and @code{push-mark}.
5398* Second Buffer Related Review::
5399* optional Exercise::
5400@end menu
5401
5402@node copy-to-buffer, insert-buffer, More Complex, More Complex
5403@comment node-name, next, previous, up
5404@section The Definition of @code{copy-to-buffer}
5405@findex copy-to-buffer
5406
5407After understanding how @code{append-to-buffer} works, it is easy to
5408understand @code{copy-to-buffer}. This function copies text into a
5409buffer, but instead of adding to the second buffer, it replaces the
5410previous text in the second buffer. The code for the
5411@code{copy-to-buffer} function is almost the same as the code for
5412@code{append-to-buffer}, except that @code{erase-buffer} and a second
5413@code{save-excursion} are used. (@xref{append-to-buffer, , The
5414Definition of @code{append-to-buffer}}, for the description of
5415@code{append-to-buffer}.)
5416
5417@need 800
5418The body of @code{copy-to-buffer} looks like this
5419
5420@smallexample
5421@group
5422@dots{}
5423(interactive "BCopy to buffer:@: \nr")
5424 (let ((oldbuf (current-buffer)))
5425 (save-excursion
5426 (set-buffer (get-buffer-create buffer))
5427 (erase-buffer)
5428 (save-excursion
5429 (insert-buffer-substring oldbuf start end)))))
5430@end group
5431@end smallexample
5432
5433This code is similar to the code in @code{append-to-buffer}: it is
5434only after changing to the buffer to which the text will be copied
5435that the definition for this function diverges from the definition for
5436@code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5437buffer's former contents. (This is what is meant by `replacement'; to
5438replace text, Emacs erases the previous text and then inserts new
5439text.) After erasing the previous contents of the buffer,
5440@code{save-excursion} is used for a second time and the new text is
5441inserted.
5442
5443Why is @code{save-excursion} used twice? Consider again what the
5444function does.
5445
5446@need 1250
5447In outline, the body of @code{copy-to-buffer} looks like this:
5448
5449@smallexample
5450@group
5451(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5452 (save-excursion ; @r{First use of @code{save-excursion}.}
5453 @var{change-buffer}
5454 (erase-buffer)
5455 (save-excursion ; @r{Second use of @code{save-excursion}.}
5456 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5457@end group
5458@end smallexample
5459
5460The first use of @code{save-excursion} returns Emacs to the buffer from
5461which the text is being copied. That is clear, and is just like its use
5462in @code{append-to-buffer}. Why the second use? The reason is that
5463@code{insert-buffer-substring} always leaves point at the @emph{end} of
5464the region being inserted. The second @code{save-excursion} causes
5465Emacs to leave point at the beginning of the text being inserted. In
5466most circumstances, users prefer to find point at the beginning of
5467inserted text. (Of course, the @code{copy-to-buffer} function returns
5468the user to the original buffer when done---but if the user @emph{then}
5469switches to the copied-to buffer, point will go to the beginning of the
5470text. Thus, this use of a second @code{save-excursion} is a little
5471nicety.)
5472
5473@node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5474@comment node-name, next, previous, up
5475@section The Definition of @code{insert-buffer}
5476@findex insert-buffer
5477
5478@code{insert-buffer} is yet another buffer-related function. This
5479command copies another buffer @emph{into} the current buffer. It is the
5480reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5481copy a region of text @emph{from} the current buffer to another buffer.
5482
5483In addition, this code illustrates the use of @code{interactive} with a
5484buffer that might be @dfn{read-only} and the important distinction
5485between the name of an object and the object actually referred to.
5486
5487@menu
5488* insert-buffer code::
5489* insert-buffer interactive:: When you can read, but not write.
5490* insert-buffer body:: The body has an @code{or} and a @code{let}.
5491* if & or:: Using an @code{if} instead of an @code{or}.
5492* Insert or:: How the @code{or} expression works.
5493* Insert let:: Two @code{save-excursion} expressions.
5494@end menu
5495
5496@node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5497@ifnottex
5498@unnumberedsubsec The Code for @code{insert-buffer}
5499@end ifnottex
5500
5501@need 800
5502Here is the code:
5503
5504@smallexample
5505@group
5506(defun insert-buffer (buffer)
5507 "Insert after point the contents of BUFFER.
5508Puts mark after the inserted text.
5509BUFFER may be a buffer or a buffer name."
5510 (interactive "*bInsert buffer:@: ")
5511@end group
5512@group
5513 (or (bufferp buffer)
5514 (setq buffer (get-buffer buffer)))
5515 (let (start end newmark)
5516 (save-excursion
5517 (save-excursion
5518 (set-buffer buffer)
5519 (setq start (point-min) end (point-max)))
5520@end group
5521@group
5522 (insert-buffer-substring buffer start end)
5523 (setq newmark (point)))
5524 (push-mark newmark)))
5525@end group
5526@end smallexample
5527
5528@need 1200
5529As with other function definitions, you can use a template to see an
5530outline of the function:
5531
5532@smallexample
5533@group
5534(defun insert-buffer (buffer)
5535 "@var{documentation}@dots{}"
5536 (interactive "*bInsert buffer:@: ")
5537 @var{body}@dots{})
5538@end group
5539@end smallexample
5540
5541@node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5542@comment node-name, next, previous, up
5543@subsection The Interactive Expression in @code{insert-buffer}
5544@findex interactive, @r{example use of}
5545
5546In @code{insert-buffer}, the argument to the @code{interactive}
5547declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5548buffer:@: }.
5549
5550@menu
5551* Read-only buffer:: When a buffer cannot be modified.
5552* b for interactive:: An existing buffer or else its name.
5553@end menu
5554
5555@node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5556@comment node-name, next, previous, up
5557@unnumberedsubsubsec A Read-only Buffer
5558@cindex Read-only buffer
5559@cindex Asterisk for read-only buffer
5560@findex * @r{for read-only buffer}
5561
5562The asterisk is for the situation when the buffer is a read-only
5563buffer---a buffer that cannot be modified. If @code{insert-buffer} is
5564called on a buffer that is read-only, a message to this effect is
5565printed in the echo area and the terminal may beep or blink at you;
5566you will not be permitted to insert anything into current buffer. The
5567asterisk does not need to be followed by a newline to separate it from
5568the next argument.
5569
5570@node b for interactive, , Read-only buffer, insert-buffer interactive
5571@comment node-name, next, previous, up
5572@unnumberedsubsubsec @samp{b} in an Interactive Expression
5573
5574The next argument in the interactive expression starts with a lower
5575case @samp{b}. (This is different from the code for
5576@code{append-to-buffer}, which uses an upper-case @samp{B}.
5577@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5578The lower-case @samp{b} tells the Lisp interpreter that the argument
5579for @code{insert-buffer} should be an existing buffer or else its
5580name. (The upper-case @samp{B} option provides for the possibility
5581that the buffer does not exist.) Emacs will prompt you for the name
5582of the buffer, offering you a default buffer, with name completion
5583enabled. If the buffer does not exist, you receive a message that
5584says ``No match''; your terminal may beep at you as well.
5585
5586@node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5587@comment node-name, next, previous, up
5588@subsection The Body of the @code{insert-buffer} Function
5589
5590The body of the @code{insert-buffer} function has two major parts: an
5591@code{or} expression and a @code{let} expression. The purpose of the
5592@code{or} expression is to ensure that the argument @code{buffer} is
5593bound to a buffer and not just the name of a buffer. The body of the
5594@code{let} expression contains the code which copies the other buffer
5595into the current buffer.
5596
5597@need 1250
5598In outline, the two expressions fit into the @code{insert-buffer}
5599function like this:
5600
5601@smallexample
5602@group
5603(defun insert-buffer (buffer)
5604 "@var{documentation}@dots{}"
5605 (interactive "*bInsert buffer:@: ")
5606 (or @dots{}
5607 @dots{}
5608@end group
5609@group
5610 (let (@var{varlist})
5611 @var{body-of-}@code{let}@dots{} )
5612@end group
5613@end smallexample
5614
5615To understand how the @code{or} expression ensures that the argument
5616@code{buffer} is bound to a buffer and not to the name of a buffer, it
5617is first necessary to understand the @code{or} function.
5618
5619Before doing this, let me rewrite this part of the function using
5620@code{if} so that you can see what is done in a manner that will be familiar.
5621
5622@node if & or, Insert or, insert-buffer body, insert-buffer
5623@comment node-name, next, previous, up
5624@subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5625
5626The job to be done is to make sure the value of @code{buffer} is a
5627buffer itself and not the name of a buffer. If the value is the name,
5628then the buffer itself must be got.
5629
5630You can imagine yourself at a conference where an usher is wandering
5631around holding a list with your name on it and looking for you: the
5632usher is ``bound'' to your name, not to you; but when the usher finds
5633you and takes your arm, the usher becomes ``bound'' to you.
5634
5635@need 800
5636In Lisp, you might describe this situation like this:
5637
5638@smallexample
5639@group
5640(if (not (holding-on-to-guest))
5641 (find-and-take-arm-of-guest))
5642@end group
5643@end smallexample
5644
5645We want to do the same thing with a buffer---if we do not have the
5646buffer itself, we want to get it.
5647
5648@need 1200
5649Using a predicate called @code{bufferp} that tells us whether we have a
5650buffer (rather than its name), we can write the code like this:
5651
5652@smallexample
5653@group
5654(if (not (bufferp buffer)) ; @r{if-part}
5655 (setq buffer (get-buffer buffer))) ; @r{then-part}
5656@end group
5657@end smallexample
5658
5659@noindent
5660Here, the true-or-false-test of the @code{if} expression is
5661@w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5662@w{@code{(setq buffer (get-buffer buffer))}}.
5663
5664In the test, the function @code{bufferp} returns true if its argument is
5665a buffer---but false if its argument is the name of the buffer. (The
5666last character of the function name @code{bufferp} is the character
5667@samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5668indicates that the function is a predicate, which is a term that means
5669that the function will determine whether some property is true or false.
5670@xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5671Argument}.)
5672
5673@need 1200
5674The function @code{not} precedes the expression @code{(bufferp buffer)},
5675so the true-or-false-test looks like this:
5676
5677@smallexample
5678(not (bufferp buffer))
5679@end smallexample
5680
5681@noindent
5682@code{not} is a function that returns true if its argument is false
5683and false if its argument is true. So if @code{(bufferp buffer)}
5684returns true, the @code{not} expression returns false and vice-versa:
5685what is ``not true'' is false and what is ``not false'' is true.
5686
5687Using this test, the @code{if} expression works as follows: when the
5688value of the variable @code{buffer} is actually a buffer rather then
5689its name, the true-or-false-test returns false and the @code{if}
5690expression does not evaluate the then-part. This is fine, since we do
5691not need to do anything to the variable @code{buffer} if it really is
5692a buffer.
5693
5694On the other hand, when the value of @code{buffer} is not a buffer
5695itself, but the name of a buffer, the true-or-false-test returns true
5696and the then-part of the expression is evaluated. In this case, the
5697then-part is @code{(setq buffer (get-buffer buffer))}. This
5698expression uses the @code{get-buffer} function to return an actual
5699buffer itself, given its name. The @code{setq} then sets the variable
5700@code{buffer} to the value of the buffer itself, replacing its previous
5701value (which was the name of the buffer).
5702
5703@node Insert or, Insert let, if & or, insert-buffer
5704@comment node-name, next, previous, up
5705@subsection The @code{or} in the Body
5706
5707The purpose of the @code{or} expression in the @code{insert-buffer}
5708function is to ensure that the argument @code{buffer} is bound to a
5709buffer and not just to the name of a buffer. The previous section shows
5710how the job could have been done using an @code{if} expression.
5711However, the @code{insert-buffer} function actually uses @code{or}.
5712To understand this, it is necessary to understand how @code{or} works.
5713
5714@findex or
5715An @code{or} function can have any number of arguments. It evaluates
5716each argument in turn and returns the value of the first of its
5717arguments that is not @code{nil}. Also, and this is a crucial feature
5718of @code{or}, it does not evaluate any subsequent arguments after
5719returning the first non-@code{nil} value.
5720
5721@need 800
5722The @code{or} expression looks like this:
5723
5724@smallexample
5725@group
5726(or (bufferp buffer)
5727 (setq buffer (get-buffer buffer)))
5728@end group
5729@end smallexample
5730
5731@noindent
5732The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5733This expression returns true (a non-@code{nil} value) if the buffer is
5734actually a buffer, and not just the name of a buffer. In the @code{or}
5735expression, if this is the case, the @code{or} expression returns this
5736true value and does not evaluate the next expression---and this is fine
5737with us, since we do not want to do anything to the value of
5738@code{buffer} if it really is a buffer.
5739
5740On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5741which it will be if the value of @code{buffer} is the name of a buffer,
5742the Lisp interpreter evaluates the next element of the @code{or}
5743expression. This is the expression @code{(setq buffer (get-buffer
5744buffer))}. This expression returns a non-@code{nil} value, which
5745is the value to which it sets the variable @code{buffer}---and this
5746value is a buffer itself, not the name of a buffer.
5747
5748The result of all this is that the symbol @code{buffer} is always
5749bound to a buffer itself rather than to the name of a buffer. All
5750this is necessary because the @code{set-buffer} function in a
5751following line only works with a buffer itself, not with the name to a
5752buffer.
5753
5754@need 1250
5755Incidentally, using @code{or}, the situation with the usher would be
5756written like this:
5757
5758@smallexample
5759(or (holding-on-to-guest) (find-and-take-arm-of-guest))
5760@end smallexample
5761
5762@node Insert let, , Insert or, insert-buffer
5763@comment node-name, next, previous, up
5764@subsection The @code{let} Expression in @code{insert-buffer}
5765
5766After ensuring that the variable @code{buffer} refers to a buffer itself
5767and not just to the name of a buffer, the @code{insert-buffer function}
5768continues with a @code{let} expression. This specifies three local
5769variables, @code{start}, @code{end}, and @code{newmark} and binds them
5770to the initial value @code{nil}. These variables are used inside the
5771remainder of the @code{let} and temporarily hide any other occurrence of
5772variables of the same name in Emacs until the end of the @code{let}.
5773
5774@need 1200
5775The body of the @code{let} contains two @code{save-excursion}
5776expressions. First, we will look at the inner @code{save-excursion}
5777expression in detail. The expression looks like this:
5778
5779@smallexample
5780@group
5781(save-excursion
5782 (set-buffer buffer)
5783 (setq start (point-min) end (point-max)))
5784@end group
5785@end smallexample
5786
5787@noindent
5788The expression @code{(set-buffer buffer)} changes Emacs' attention
5789from the current buffer to the one from which the text will copied.
5790In that buffer, the variables @code{start} and @code{end} are set to
5791the beginning and end of the buffer, using the commands
5792@code{point-min} and @code{point-max}. Note that we have here an
5793illustration of how @code{setq} is able to set two variables in the
5794same expression. The first argument of @code{setq} is set to the
5795value of its second, and its third argument is set to the value of its
5796fourth.
5797
5798After the body of the inner @code{save-excursion} is evaluated, the
5799@code{save-excursion} restores the original buffer, but @code{start} and
5800@code{end} remain set to the values of the beginning and end of the
5801buffer from which the text will be copied.
5802
5803@need 1250
5804The outer @code{save-excursion} expression looks like this:
5805
5806@smallexample
5807@group
5808(save-excursion
5809 (@var{inner-}@code{save-excursion}@var{-expression}
5810 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5811 (insert-buffer-substring buffer start end)
5812 (setq newmark (point)))
5813@end group
5814@end smallexample
5815
5816@noindent
5817The @code{insert-buffer-substring} function copies the text
5818@emph{into} the current buffer @emph{from} the region indicated by
5819@code{start} and @code{end} in @code{buffer}. Since the whole of the
5820second buffer lies between @code{start} and @code{end}, the whole of
5821the second buffer is copied into the buffer you are editing. Next,
5822the value of point, which will be at the end of the inserted text, is
5823recorded in the variable @code{newmark}.
5824
5825After the body of the outer @code{save-excursion} is evaluated, point
5826and mark are relocated to their original places.
5827
5828However, it is convenient to locate a mark at the end of the newly
5829inserted text and locate point at its beginning. The @code{newmark}
5830variable records the end of the inserted text. In the last line of
5831the @code{let} expression, the @code{(push-mark newmark)} expression
5832function sets a mark to this location. (The previous location of the
5833mark is still accessible; it is recorded on the mark ring and you can
5834go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5835located at the beginning of the inserted text, which is where it was
5836before you called the insert function.
5837
5838@need 1250
5839The whole @code{let} expression looks like this:
5840
5841@smallexample
5842@group
5843(let (start end newmark)
5844 (save-excursion
5845 (save-excursion
5846 (set-buffer buffer)
5847 (setq start (point-min) end (point-max)))
5848 (insert-buffer-substring buffer start end)
5849 (setq newmark (point)))
5850 (push-mark newmark))
5851@end group
5852@end smallexample
5853
5854Like the @code{append-to-buffer} function, the @code{insert-buffer}
5855function uses @code{let}, @code{save-excursion}, and
5856@code{set-buffer}. In addition, the function illustrates one way to
5857use @code{or}. All these functions are building blocks that we will
5858find and use again and again.
5859
5860@node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5861@comment node-name, next, previous, up
5862@section Complete Definition of @code{beginning-of-buffer}
5863@findex beginning-of-buffer
5864
5865The basic structure of the @code{beginning-of-buffer} function has
5866already been discussed. (@xref{simplified-beginning-of-buffer, , A
5867Simplified @code{beginning-of-buffer} Definition}.)
5868This section describes the complex part of the definition.
5869
5870As previously described, when invoked without an argument,
5871@code{beginning-of-buffer} moves the cursor to the beginning of the
5872buffer, leaving the mark at the previous position. However, when the
5873command is invoked with a number between one and ten, the function
5874considers that number to be a fraction of the length of the buffer,
5875measured in tenths, and Emacs moves the cursor that fraction of the way
5876from the beginning of the buffer. Thus, you can either call this
5877function with the key command @kbd{M-<}, which will move the cursor to
5878the beginning of the buffer, or with a key command such as @kbd{C-u 7
5879M-<} which will move the cursor to a point 70% of the way through the
5880buffer. If a number bigger than ten is used for the argument, it moves
5881to the end of the buffer.
5882
5883The @code{beginning-of-buffer} function can be called with or without an
5884argument. The use of the argument is optional.
5885
5886@menu
5887* Optional Arguments::
5888* beginning-of-buffer opt arg:: Example with optional argument.
5889* beginning-of-buffer complete::
5890@end menu
5891
5892@node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5893@subsection Optional Arguments
5894
5895Unless told otherwise, Lisp expects that a function with an argument in
5896its function definition will be called with a value for that argument.
5897If that does not happen, you get an error and a message that says
5898@samp{Wrong number of arguments}.
5899
5900@cindex Optional arguments
5901@cindex Keyword
5902@findex optional
5903However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5904be used to tell the Lisp interpreter that an argument is optional.
5905The keyword is @code{&optional}. (The @samp{&} in front of
5906@samp{optional} is part of the keyword.) In a function definition, if
5907an argument follows the keyword @code{&optional}, a value does not
5908need to be passed to that argument when the function is called.
5909
5910@need 1200
5911The first line of the function definition of @code{beginning-of-buffer}
5912therefore looks like this:
5913
5914@smallexample
5915(defun beginning-of-buffer (&optional arg)
5916@end smallexample
5917
5918@need 1250
5919In outline, the whole function looks like this:
5920
5921@smallexample
5922@group
5923(defun beginning-of-buffer (&optional arg)
5924 "@var{documentation}@dots{}"
5925 (interactive "P")
5926 (push-mark)
5927 (goto-char
5928 (@var{if-there-is-an-argument}
5929 @var{figure-out-where-to-go}
5930 @var{else-go-to}
5931 (point-min))))
5932@end group
5933@end smallexample
5934
5935The function is similar to the @code{simplified-beginning-of-buffer}
5936function except that the @code{interactive} expression has @code{"P"}
5937as an argument and the @code{goto-char} function is followed by an
5938if-then-else expression that figures out where to put the cursor if
5939there is an argument.
5940
5941The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5942a prefix argument, if there is one, to the function. A prefix argument
5943is made by typing the @key{META} key followed by a number, or by typing
5944@kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5945defaults to 4).
5946
5947The true-or-false-test of the @code{if} expression is simple: it is
5948simply the argument @code{arg}. If @code{arg} has a value that is not
5949@code{nil}, which will be the case if @code{beginning-of-buffer} is
5950called with an argument, then this true-or-false-test will return true
5951and the then-part of the @code{if} expression will be evaluated. On the
5952other hand, if @code{beginning-of-buffer} is not called with an
5953argument, the value of @code{arg} will be @code{nil} and the else-part
5954of the @code{if} expression will be evaluated. The else-part is simply
5955@code{point-min}, and when this is the outcome, the whole
5956@code{goto-char} expression is @code{(goto-char (point-min))}, which is
5957how we saw the @code{beginning-of-buffer} function in its simplified
5958form.
5959
5960@node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5961@subsection @code{beginning-of-buffer} with an Argument
5962
5963When @code{beginning-of-buffer} is called with an argument, an
5964expression is evaluated which calculates what value to pass to
5965@code{goto-char}. This expression is rather complicated at first sight.
5966It includes an inner @code{if} expression and much arithmetic. It looks
5967like this:
5968
5969@smallexample
5970@group
5971(if (> (buffer-size) 10000)
5972 ;; @r{Avoid overflow for large buffer sizes!}
5973 (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5974 (/
5975 (+ 10
5976 (*
5977 (buffer-size) (prefix-numeric-value arg))) 10))
5978@end group
5979@end smallexample
5980
5981@menu
5982* Disentangle beginning-of-buffer::
5983* Large buffer case::
5984* Small buffer case::
5985@end menu
5986
5987@node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5988@ifnottex
5989@unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5990@end ifnottex
5991
5992Like other complex-looking expressions, the conditional expression
5993within @code{beginning-of-buffer} can be disentangled by looking at it
5994as parts of a template, in this case, the template for an if-then-else
5995expression. In skeletal form, the expression looks like this:
5996
5997@smallexample
5998@group
5999(if (@var{buffer-is-large}
6000 @var{divide-buffer-size-by-10-and-multiply-by-arg}
6001 @var{else-use-alternate-calculation}
6002@end group
6003@end smallexample
6004
6005The true-or-false-test of this inner @code{if} expression checks the
6006size of the buffer. The reason for this is that the old Version 18
6007Emacs used numbers that are no bigger than eight million or so
6008and in the computation that followed, the programmer feared that Emacs
6009might try to use over-large numbers if the buffer were large. The
6010term `overflow', mentioned in the comment, means numbers that are over
6011large. Version 21 Emacs uses larger numbers, but this code has not
6012been touched, if only because people now look at buffers that are far,
6013far larger than ever before.
6014
6015There are two cases: if the buffer is large and if it is not.
6016
6017@node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
6018@comment node-name, next, previous, up
6019@unnumberedsubsubsec What happens in a large buffer
6020
6021In @code{beginning-of-buffer}, the inner @code{if} expression tests
6022whether the size of the buffer is greater than 10,000 characters. To do
6023this, it uses the @code{>} function and the @code{buffer-size} function.
6024
6025@need 800
6026The line looks like this:
6027
6028@smallexample
6029(if (> (buffer-size) 10000)
6030@end smallexample
6031
6032@need 1200
6033@noindent
6034When the buffer is large, the then-part of the @code{if} expression is
6035evaluated. It reads like this (after formatting for easy reading):
6036
6037@smallexample
6038@group
6039(*
6040 (prefix-numeric-value arg)
6041 (/ (buffer-size) 10))
6042@end group
6043@end smallexample
6044
6045@noindent
6046This expression is a multiplication, with two arguments to the function
6047@code{*}.
6048
6049The first argument is @code{(prefix-numeric-value arg)}. When
6050@code{"P"} is used as the argument for @code{interactive}, the value
6051passed to the function as its argument is passed a ``raw prefix
6052argument'', and not a number. (It is a number in a list.) To perform
6053the arithmetic, a conversion is necessary, and
6054@code{prefix-numeric-value} does the job.
6055
6056@findex / @r{(division)}
6057@cindex Division
6058The second argument is @code{(/ (buffer-size) 10)}. This expression
6059divides the numeric value of the buffer by ten. This produces a number
6060that tells how many characters make up one tenth of the buffer size.
6061(In Lisp, @code{/} is used for division, just as @code{*} is
6062used for multiplication.)
6063
6064@need 1200
6065In the multiplication expression as a whole, this amount is multiplied
6066by the value of the prefix argument---the multiplication looks like this:
6067
6068@smallexample
6069@group
6070(* @var{numeric-value-of-prefix-arg}
6071 @var{number-of-characters-in-one-tenth-of-the-buffer})
6072@end group
6073@end smallexample
6074
6075@noindent
6076If, for example, the prefix argument is @samp{7}, the one-tenth value
6077will be multiplied by 7 to give a position 70% of the way through the
6078buffer.
6079
6080@need 1200
6081The result of all this is that if the buffer is large, the
6082@code{goto-char} expression reads like this:
6083
6084@smallexample
6085@group
6086(goto-char (* (prefix-numeric-value arg)
6087 (/ (buffer-size) 10)))
6088@end group
6089@end smallexample
6090
6091This puts the cursor where we want it.
6092
6093@node Small buffer case, , Large buffer case, beginning-of-buffer opt arg
6094@comment node-name, next, previous, up
6095@unnumberedsubsubsec What happens in a small buffer
6096
6097If the buffer contains fewer than 10,000 characters, a slightly
6098different computation is performed. You might think this is not
6099necessary, since the first computation could do the job. However, in
6100a small buffer, the first method may not put the cursor on exactly the
6101desired line; the second method does a better job.
6102
6103@need 800
6104The code looks like this:
6105
6106@c Keep this on one line.
6107@smallexample
6108(/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6109@end smallexample
6110
6111@need 1200
6112@noindent
6113This is code in which you figure out what happens by discovering how the
6114functions are embedded in parentheses. It is easier to read if you
6115reformat it with each expression indented more deeply than its
6116enclosing expression:
6117
6118@smallexample
6119@group
6120 (/
6121 (+ 10
6122 (*
6123 (buffer-size)
6124 (prefix-numeric-value arg)))
6125 10))
6126@end group
6127@end smallexample
6128
6129@need 1200
6130@noindent
6131Looking at parentheses, we see that the innermost operation is
6132@code{(prefix-numeric-value arg)}, which converts the raw argument to a
6133number. This number is multiplied by the buffer size in the following
6134expression:
6135
6136@smallexample
6137(* (buffer-size) (prefix-numeric-value arg)
6138@end smallexample
6139
6140@noindent
6141This multiplication creates a number that may be larger than the size of
6142the buffer---seven times larger if the argument is 7, for example. Ten
6143is then added to this number and finally the large number is divided by
6144ten to provide a value that is one character larger than the percentage
6145position in the buffer.
6146
6147The number that results from all this is passed to @code{goto-char} and
6148the cursor is moved to that point.
6149
6150@node beginning-of-buffer complete, , beginning-of-buffer opt arg, beginning-of-buffer
6151@comment node-name, next, previous, up
6152@subsection The Complete @code{beginning-of-buffer}
6153
6154@need 800
6155Here is the complete text of the @code{beginning-of-buffer} function:
6156
6157@smallexample
6158@group
6159(defun beginning-of-buffer (&optional arg)
6160 "Move point to the beginning of the buffer;
6161leave mark at previous position.
6162With arg N, put point N/10 of the way
6163from the true beginning.
6164Don't use this in Lisp programs!
6165\(goto-char (point-min)) is faster
6166and does not set the mark."
6167 (interactive "P")
6168 (push-mark)
6169@end group
6170@group
6171 (goto-char
6172 (if arg
6173 (if (> (buffer-size) 10000)
6174 ;; @r{Avoid overflow for large buffer sizes!}
6175 (* (prefix-numeric-value arg)
6176 (/ (buffer-size) 10))
6177@end group
6178@group
6179 (/ (+ 10 (* (buffer-size)
6180 (prefix-numeric-value arg)))
6181 10))
6182 (point-min)))
6183 (if arg (forward-line 1)))
6184@end group
6185@end smallexample
6186
6187@noindent
6188Except for two small points, the previous discussion shows how this
6189function works. The first point deals with a detail in the
6190documentation string, and the second point concerns the last line of
6191the function.
6192
6193@need 800
6194In the documentation string, there is reference to an expression:
6195
6196@smallexample
6197\(goto-char (point-min))
6198@end smallexample
6199
6200@noindent
6201A @samp{\} is used before the first parenthesis of this expression.
6202This @samp{\} tells the Lisp interpreter that the expression should be
6203printed as shown in the documentation rather than evaluated as a
6204symbolic expression, which is what it looks like.
6205
6206@need 1200
6207Finally, the last line of the @code{beginning-of-buffer} command says to
6208move point to the beginning of the next line if the command is
6209invoked with an argument:
6210
6211@smallexample
6212(if arg (forward-line 1)))
6213@end smallexample
6214
6215@noindent
6216This puts the cursor at the beginning of the first line after the
6217appropriate tenths position in the buffer. This is a flourish that
6218means that the cursor is always located @emph{at least} the requested
6219tenths of the way through the buffer, which is a nicety that is,
6220perhaps, not necessary, but which, if it did not occur, would be sure to
6221draw complaints.
6222
6223@node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6224@comment node-name, next, previous, up
6225@section Review
6226
6227Here is a brief summary of some of the topics covered in this chapter.
6228
6229@table @code
6230@item or
6231Evaluate each argument in sequence, and return the value of the first
6232argument that is not @code{nil}; if none return a value that is not
6233@code{nil}, return @code{nil}. In brief, return the first true value
6234of the arguments; return a true value if one @emph{or} any of the
6235other are true.
6236
6237@item and
6238Evaluate each argument in sequence, and if any are @code{nil}, return
6239@code{nil}; if none are @code{nil}, return the value of the last
6240argument. In brief, return a true value only if all the arguments are
6241true; return a true value if one @emph{and} each of the others is
6242true.
6243
6244@item &optional
6245A keyword used to indicate that an argument to a function definition
6246is optional; this means that the function can be evaluated without the
6247argument, if desired.
6248
6249@item prefix-numeric-value
6250Convert the `raw prefix argument' produced by @code{(interactive
6251"P")} to a numeric value.
6252
6253@item forward-line
6254Move point forward to the beginning of the next line, or if the argument
6255is greater than one, forward that many lines. If it can't move as far
6256forward as it is supposed to, @code{forward-line} goes forward as far as
6257it can and then returns a count of the number of additional lines it was
6258supposed to move but couldn't.
6259
6260@item erase-buffer
6261Delete the entire contents of the current buffer.
6262
6263@item bufferp
6264Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6265@end table
6266
6267@node optional Exercise, , Second Buffer Related Review, More Complex
6268@section @code{optional} Argument Exercise
6269
6270Write an interactive function with an optional argument that tests
6271whether its argument, a number, is greater or less than the value of
6272@code{fill-column}, and tells you which, in a message. However, if you
6273do not pass an argument to the function, use 56 as a default value.
6274
6275@node Narrowing & Widening, car cdr & cons, More Complex, Top
6276@comment node-name, next, previous, up
6277@chapter Narrowing and Widening
6278@cindex Focusing attention (narrowing)
6279@cindex Narrowing
6280@cindex Widening
6281
6282Narrowing is a feature of Emacs that makes it possible for you to focus
6283on a specific part of a buffer, and work without accidentally changing
6284other parts. Narrowing is normally disabled since it can confuse
6285novices.
6286
6287@menu
6288* Narrowing advantages:: The advantages of narrowing
6289* save-restriction:: The @code{save-restriction} special form.
6290* what-line:: The number of the line that point is on.
6291* narrow Exercise::
6292@end menu
6293
6294@node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6295@ifnottex
6296@unnumberedsec The Advantages of Narrowing
6297@end ifnottex
6298
6299With narrowing, the rest of a buffer is made invisible, as if it weren't
6300there. This is an advantage if, for example, you want to replace a word
6301in one part of a buffer but not in another: you narrow to the part you want
6302and the replacement is carried out only in that section, not in the rest
6303of the buffer. Searches will only work within a narrowed region, not
6304outside of one, so if you are fixing a part of a document, you can keep
6305yourself from accidentally finding parts you do not need to fix by
6306narrowing just to the region you want.
6307(The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6308
6309However, narrowing does make the rest of the buffer invisible, which
6310can scare people who inadvertently invoke narrowing and think they
6311have deleted a part of their file. Moreover, the @code{undo} command
6312(which is usually bound to @kbd{C-x u}) does not turn off narrowing
6313(nor should it), so people can become quite desperate if they do not
6314know that they can return the rest of a buffer to visibility with the
6315@code{widen} command.
6316(The key binding for @code{widen} is @kbd{C-x n w}.)
6317
6318Narrowing is just as useful to the Lisp interpreter as to a human.
6319Often, an Emacs Lisp function is designed to work on just part of a
6320buffer; or conversely, an Emacs Lisp function needs to work on all of a
6321buffer that has been narrowed. The @code{what-line} function, for
6322example, removes the narrowing from a buffer, if it has any narrowing
6323and when it has finished its job, restores the narrowing to what it was.
6324On the other hand, the @code{count-lines} function, which is called by
6325@code{what-line}, uses narrowing to restrict itself to just that portion
6326of the buffer in which it is interested and then restores the previous
6327situation.
6328
6329@node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6330@comment node-name, next, previous, up
6331@section The @code{save-restriction} Special Form
6332@findex save-restriction
6333
6334In Emacs Lisp, you can use the @code{save-restriction} special form to
6335keep track of whatever narrowing is in effect, if any. When the Lisp
6336interpreter meets with @code{save-restriction}, it executes the code
6337in the body of the @code{save-restriction} expression, and then undoes
6338any changes to narrowing that the code caused. If, for example, the
6339buffer is narrowed and the code that follows @code{save-restriction}
6340gets rid of the narrowing, @code{save-restriction} returns the buffer
6341to its narrowed region afterwards. In the @code{what-line} command,
6342any narrowing the buffer may have is undone by the @code{widen}
6343command that immediately follows the @code{save-restriction} command.
6344Any original narrowing is restored just before the completion of the
6345function.
6346
6347@need 1250
6348The template for a @code{save-restriction} expression is simple:
6349
6350@smallexample
6351@group
6352(save-restriction
6353 @var{body}@dots{} )
6354@end group
6355@end smallexample
6356
6357@noindent
6358The body of the @code{save-restriction} is one or more expressions that
6359will be evaluated in sequence by the Lisp interpreter.
6360
6361Finally, a point to note: when you use both @code{save-excursion} and
6362@code{save-restriction}, one right after the other, you should use
6363@code{save-excursion} outermost. If you write them in reverse order,
6364you may fail to record narrowing in the buffer to which Emacs switches
6365after calling @code{save-excursion}. Thus, when written together,
6366@code{save-excursion} and @code{save-restriction} should be written
6367like this:
6368
6369@smallexample
6370@group
6371(save-excursion
6372 (save-restriction
6373 @var{body}@dots{}))
6374@end group
6375@end smallexample
6376
6377In other circumstances, when not written together, the
6378@code{save-excursion} and @code{save-restriction} special forms must
6379be written in the order appropriate to the function.
6380
6381@need 1250
6382For example,
6383
6384@smallexample
6385@group
6386 (save-restriction
6387 (widen)
6388 (save-excursion
6389 @var{body}@dots{}))
6390@end group
6391@end smallexample
6392
6393@node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6394@comment node-name, next, previous, up
6395@section @code{what-line}
6396@findex what-line
6397@cindex Widening, example of
6398
6399The @code{what-line} command tells you the number of the line in which
6400the cursor is located. The function illustrates the use of the
6401@code{save-restriction} and @code{save-excursion} commands. Here is the
6402text of the function in full:
6403
6404@smallexample
6405@group
6406(defun what-line ()
6407 "Print the current line number (in the buffer) of point."
6408 (interactive)
6409 (save-restriction
6410 (widen)
6411 (save-excursion
6412 (beginning-of-line)
6413 (message "Line %d"
6414 (1+ (count-lines 1 (point)))))))
6415@end group
6416@end smallexample
6417
6418The function has a documentation line and is interactive, as you would
6419expect. The next two lines use the functions @code{save-restriction} and
6420@code{widen}.
6421
6422The @code{save-restriction} special form notes whatever narrowing is in
6423effect, if any, in the current buffer and restores that narrowing after
6424the code in the body of the @code{save-restriction} has been evaluated.
6425
6426The @code{save-restriction} special form is followed by @code{widen}.
6427This function undoes any narrowing the current buffer may have had
6428when @code{what-line} was called. (The narrowing that was there is
6429the narrowing that @code{save-restriction} remembers.) This widening
6430makes it possible for the line counting commands to count from the
6431beginning of the buffer. Otherwise, they would have been limited to
6432counting within the accessible region. Any original narrowing is
6433restored just before the completion of the function by the
6434@code{save-restriction} special form.
6435
6436The call to @code{widen} is followed by @code{save-excursion}, which
6437saves the location of the cursor (i.e., of point) and of the mark, and
6438restores them after the code in the body of the @code{save-excursion}
6439uses the @code{beginning-of-line} function to move point.
6440
6441(Note that the @code{(widen)} expression comes between the
6442@code{save-restriction} and @code{save-excursion} special forms. When
6443you write the two @code{save- @dots{}} expressions in sequence, write
6444@code{save-excursion} outermost.)
6445
6446@need 1200
6447The last two lines of the @code{what-line} function are functions to
6448count the number of lines in the buffer and then print the number in the
6449echo area.
6450
6451@smallexample
6452@group
6453(message "Line %d"
6454 (1+ (count-lines 1 (point)))))))
6455@end group
6456@end smallexample
6457
6458The @code{message} function prints a one-line message at the bottom of the
6459Emacs screen. The first argument is inside of quotation marks and is
6460printed as a string of characters. However, it may contain @samp{%d},
6461@samp{%s}, or @samp{%c} to print arguments that follow the string.
6462@samp{%d} prints the argument as a decimal, so the message will say
6463something such as @samp{Line 243}.
6464
6465@need 1200
6466The number that is printed in place of the @samp{%d} is computed by the
6467last line of the function:
6468
6469@smallexample
6470(1+ (count-lines 1 (point)))
6471@end smallexample
6472
6473@noindent
6474What this does is count the lines from the first position of the
6475buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6476one to that number. (The @code{1+} function adds one to its
6477argument.) We add one to it because line 2 has only one line before
6478it, and @code{count-lines} counts only the lines @emph{before} the
6479current line.
6480
6481After @code{count-lines} has done its job, and the message has been
6482printed in the echo area, the @code{save-excursion} restores point and
6483mark to their original positions; and @code{save-restriction} restores
6484the original narrowing, if any.
6485
6486@node narrow Exercise, , what-line, Narrowing & Widening
6487@section Exercise with Narrowing
6488
6489Write a function that will display the first 60 characters of the
6490current buffer, even if you have narrowed the buffer to its latter
6491half so that the first line is inaccessible. Restore point, mark,
6492and narrowing. For this exercise, you need to use
6493@code{save-restriction}, @code{widen}, @code{goto-char},
6494@code{point-min}, @code{buffer-substring}, @code{message}, and other
6495functions, a whole potpourri.
6496
6497@node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6498@comment node-name, next, previous, up
6499@chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6500@findex car, @r{introduced}
6501@findex cdr, @r{introduced}
6502
6503In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6504functions. The @code{cons} function is used to construct lists, and
6505the @code{car} and @code{cdr} functions are used to take them apart.
6506
6507In the walk through of the @code{copy-region-as-kill} function, we
6508will see @code{cons} as well as two variants on @code{cdr},
6509namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6510
6511@menu
6512* Strange Names:: An historical aside: why the strange names?
6513* car & cdr:: Functions for extracting part of a list.
6514* cons:: Constructing a list.
6515* nthcdr:: Calling @code{cdr} repeatedly.
6516* nth::
6517* setcar:: Changing the first element of a list.
6518* setcdr:: Changing the rest of a list.
6519* cons Exercise::
6520@end menu
6521
6522@node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6523@ifnottex
6524@unnumberedsec Strange Names
6525@end ifnottex
6526
6527The name of the @code{cons} function is not unreasonable: it is an
6528abbreviation of the word `construct'. The origins of the names for
6529@code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6530is an acronym from the phrase `Contents of the Address part of the
6531Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6532the phrase `Contents of the Decrement part of the Register'. These
6533phrases refer to specific pieces of hardware on the very early
6534computer on which the original Lisp was developed. Besides being
6535obsolete, the phrases have been completely irrelevant for more than 25
6536years to anyone thinking about Lisp. Nonetheless, although a few
6537brave scholars have begun to use more reasonable names for these
6538functions, the old terms are still in use. In particular, since the
6539terms are used in the Emacs Lisp source code, we will use them in this
6540introduction.
6541
6542@node car & cdr, cons, Strange Names, car cdr & cons
6543@comment node-name, next, previous, up
6544@section @code{car} and @code{cdr}
6545
6546The @sc{car} of a list is, quite simply, the first item in the list.
6547Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6548@code{rose}.
6549
6550@need 1200
6551If you are reading this in Info in GNU Emacs, you can see this by
6552evaluating the following:
6553
6554@smallexample
6555(car '(rose violet daisy buttercup))
6556@end smallexample
6557
6558@noindent
6559After evaluating the expression, @code{rose} will appear in the echo
6560area.
6561
6562Clearly, a more reasonable name for the @code{car} function would be
6563@code{first} and this is often suggested.
6564
6565@code{car} does not remove the first item from the list; it only reports
6566what it is. After @code{car} has been applied to a list, the list is
6567still the same as it was. In the jargon, @code{car} is
6568`non-destructive'. This feature turns out to be important.
6569
6570The @sc{cdr} of a list is the rest of the list, that is, the
6571@code{cdr} function returns the part of the list that follows the
6572first item. Thus, while the @sc{car} of the list @code{'(rose violet
6573daisy buttercup)} is @code{rose}, the rest of the list, the value
6574returned by the @code{cdr} function, is @code{(violet daisy
6575buttercup)}.
6576
6577@need 1250
6578You can see this by evaluating the following in the usual way:
6579
6580@smallexample
6581(cdr '(rose violet daisy buttercup))
6582@end smallexample
6583
6584@noindent
6585When you evaluate this, @code{(violet daisy buttercup)} will appear in
6586the echo area.
6587
6588Like @code{car}, @code{cdr} does not remove any elements from the
6589list---it just returns a report of what the second and subsequent
6590elements are.
6591
6592Incidentally, in the example, the list of flowers is quoted. If it were
6593not, the Lisp interpreter would try to evaluate the list by calling
6594@code{rose} as a function. In this example, we do not want to do that.
6595
6596Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6597
6598(There is a lesson here: when you name new functions, consider very
6599carefully what you are doing, since you may be stuck with the names
6600for far longer than you expect. The reason this document perpetuates
6601these names is that the Emacs Lisp source code uses them, and if I did
6602not use them, you would have a hard time reading the code; but do,
6603please, try to avoid using these terms yourself. The people who come
6604after you will be grateful to you.)
6605
6606When @code{car} and @code{cdr} are applied to a list made up of symbols,
6607such as the list @code{(pine fir oak maple)}, the element of the list
6608returned by the function @code{car} is the symbol @code{pine} without
6609any parentheses around it. @code{pine} is the first element in the
6610list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6611oak maple)}, as you can see by evaluating the following expressions in
6612the usual way:
6613
6614@smallexample
6615@group
6616(car '(pine fir oak maple))
6617
6618(cdr '(pine fir oak maple))
6619@end group
6620@end smallexample
6621
6622On the other hand, in a list of lists, the first element is itself a
6623list. @code{car} returns this first element as a list. For example,
6624the following list contains three sub-lists, a list of carnivores, a
6625list of herbivores and a list of sea mammals:
6626
6627@smallexample
6628@group
6629(car '((lion tiger cheetah)
6630 (gazelle antelope zebra)
6631 (whale dolphin seal)))
6632@end group
6633@end smallexample
6634
6635@noindent
6636In this example, the first element or @sc{car} of the list is the list of
6637carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6638@code{((gazelle antelope zebra) (whale dolphin seal))}.
6639
6640@smallexample
6641@group
6642(cdr '((lion tiger cheetah)
6643 (gazelle antelope zebra)
6644 (whale dolphin seal)))
6645@end group
6646@end smallexample
6647
6648It is worth saying again that @code{car} and @code{cdr} are
6649non-destructive---that is, they do not modify or change lists to which
6650they are applied. This is very important for how they are used.
6651
6652Also, in the first chapter, in the discussion about atoms, I said that
6653in Lisp, ``certain kinds of atom, such as an array, can be separated
6654into parts; but the mechanism for doing this is different from the
6655mechanism for splitting a list. As far as Lisp is concerned, the
6656atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
6657@code{car} and @code{cdr} functions are used for splitting lists and
6658are considered fundamental to Lisp. Since they cannot split or gain
6659access to the parts of an array, an array is considered an atom.
6660Conversely, the other fundamental function, @code{cons}, can put
6661together or construct a list, but not an array. (Arrays are handled
6662by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
6663Emacs Lisp Reference Manual}.)
6664
6665@node cons, nthcdr, car & cdr, car cdr & cons
6666@comment node-name, next, previous, up
6667@section @code{cons}
6668@findex cons, @r{introduced}
6669
6670The @code{cons} function constructs lists; it is the inverse of
6671@code{car} and @code{cdr}. For example, @code{cons} can be used to make
6672a four element list from the three element list, @code{(fir oak maple)}:
6673
6674@smallexample
6675(cons 'pine '(fir oak maple))
6676@end smallexample
6677
6678@need 800
6679@noindent
6680After evaluating this list, you will see
6681
6682@smallexample
6683(pine fir oak maple)
6684@end smallexample
6685
6686@noindent
6687appear in the echo area. @code{cons} puts a new element at the
6688beginning of a list; it attaches or pushes elements onto the list.
6689
6690@menu
6691* Build a list::
6692* length:: How to find the length of a list.
6693@end menu
6694
6695@node Build a list, length, cons, cons
6696@ifnottex
6697@unnumberedsubsec Build a list
6698@end ifnottex
6699
6700@code{cons} must have a list to attach to.@footnote{Actually, you can
6701@code{cons} an element to an atom to produce a dotted pair. Dotted
6702pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6703Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
6704cannot start from absolutely nothing. If you are building a list, you
6705need to provide at least an empty list at the beginning. Here is a
6706series of @code{cons} expressions that build up a list of flowers. If
6707you are reading this in Info in GNU Emacs, you can evaluate each of
6708the expressions in the usual way; the value is printed in this text
6709after @samp{@result{}}, which you may read as `evaluates to'.
6710
6711@smallexample
6712@group
6713(cons 'buttercup ())
6714 @result{} (buttercup)
6715@end group
6716
6717@group
6718(cons 'daisy '(buttercup))
6719 @result{} (daisy buttercup)
6720@end group
6721
6722@group
6723(cons 'violet '(daisy buttercup))
6724 @result{} (violet daisy buttercup)
6725@end group
6726
6727@group
6728(cons 'rose '(violet daisy buttercup))
6729 @result{} (rose violet daisy buttercup)
6730@end group
6731@end smallexample
6732
6733@noindent
6734In the first example, the empty list is shown as @code{()} and a list
6735made up of @code{buttercup} followed by the empty list is constructed.
6736As you can see, the empty list is not shown in the list that was
6737constructed. All that you see is @code{(buttercup)}. The empty list is
6738not counted as an element of a list because there is nothing in an empty
6739list. Generally speaking, an empty list is invisible.
6740
6741The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6742two element list by putting @code{daisy} in front of @code{buttercup};
6743and the third example constructs a three element list by putting
6744@code{violet} in front of @code{daisy} and @code{buttercup}.
6745
6746@node length, , Build a list, cons
6747@comment node-name, next, previous, up
6748@subsection Find the Length of a List: @code{length}
6749@findex length
6750
6751You can find out how many elements there are in a list by using the Lisp
6752function @code{length}, as in the following examples:
6753
6754@smallexample
6755@group
6756(length '(buttercup))
6757 @result{} 1
6758@end group
6759
6760@group
6761(length '(daisy buttercup))
6762 @result{} 2
6763@end group
6764
6765@group
6766(length (cons 'violet '(daisy buttercup)))
6767 @result{} 3
6768@end group
6769@end smallexample
6770
6771@noindent
6772In the third example, the @code{cons} function is used to construct a
6773three element list which is then passed to the @code{length} function as
6774its argument.
6775
6776@need 1200
6777We can also use @code{length} to count the number of elements in an
6778empty list:
6779
6780@smallexample
6781@group
6782(length ())
6783 @result{} 0
6784@end group
6785@end smallexample
6786
6787@noindent
6788As you would expect, the number of elements in an empty list is zero.
6789
6790An interesting experiment is to find out what happens if you try to find
6791the length of no list at all; that is, if you try to call @code{length}
6792without giving it an argument, not even an empty list:
6793
6794@smallexample
6795(length )
6796@end smallexample
6797
6798@need 800
6799@noindent
6800What you see, if you evaluate this, is the error message
6801
6802@smallexample
6803Wrong number of arguments: #<subr length>, 0
6804@end smallexample
6805
6806@noindent
6807This means that the function receives the wrong number of
6808arguments, zero, when it expects some other number of arguments. In
6809this case, one argument is expected, the argument being a list whose
6810length the function is measuring. (Note that @emph{one} list is
6811@emph{one} argument, even if the list has many elements inside it.)
6812
6813The part of the error message that says @samp{#<subr length>} is the
6814name of the function. This is written with a special notation,
6815@samp{#<subr}, that indicates that the function @code{length} is one
6816of the primitive functions written in C rather than in Emacs Lisp.
6817(@samp{subr} is an abbreviation for `subroutine'.) @xref{What Is a
6818Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6819Manual}, for more about subroutines.
6820
6821@node nthcdr, nth, cons, car cdr & cons
6822@comment node-name, next, previous, up
6823@section @code{nthcdr}
6824@findex nthcdr
6825
6826The @code{nthcdr} function is associated with the @code{cdr} function.
6827What it does is take the @sc{cdr} of a list repeatedly.
6828
6829If you take the @sc{cdr} of the list @code{(pine fir
6830oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
6831repeat this on what was returned, you will be returned the list
6832@code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
6833list will just give you the original @sc{cdr} since the function does
6834not change the list. You need to evaluate the @sc{cdr} of the
6835@sc{cdr} and so on.) If you continue this, eventually you will be
6836returned an empty list, which in this case, instead of being shown as
6837@code{()} is shown as @code{nil}.
6838
6839@need 1200
6840For review, here is a series of repeated @sc{cdr}s, the text following
6841the @samp{@result{}} shows what is returned.
6842
6843@smallexample
6844@group
6845(cdr '(pine fir oak maple))
6846 @result{}(fir oak maple)
6847@end group
6848
6849@group
6850(cdr '(fir oak maple))
6851 @result{} (oak maple)
6852@end group
6853
6854@group
6855(cdr '(oak maple))
6856 @result{}(maple)
6857@end group
6858
6859@group
6860(cdr '(maple))
6861 @result{} nil
6862@end group
6863
6864@group
6865(cdr 'nil)
6866 @result{} nil
6867@end group
6868
6869@group
6870(cdr ())
6871 @result{} nil
6872@end group
6873@end smallexample
6874
6875@need 1200
6876You can also do several @sc{cdr}s without printing the values in
6877between, like this:
6878
6879@smallexample
6880@group
6881(cdr (cdr '(pine fir oak maple)))
6882 @result{} (oak maple)
6883@end group
6884@end smallexample
6885
6886@noindent
6887In this example, the Lisp interpreter evaluates the innermost list first.
6888The innermost list is quoted, so it just passes the list as it is to the
6889innermost @code{cdr}. This @code{cdr} passes a list made up of the
6890second and subsequent elements of the list to the outermost @code{cdr},
6891which produces a list composed of the third and subsequent elements of
6892the original list. In this example, the @code{cdr} function is repeated
6893and returns a list that consists of the original list without its
6894first two elements.
6895
6896The @code{nthcdr} function does the same as repeating the call to
6897@code{cdr}. In the following example, the argument 2 is passed to the
6898function @code{nthcdr}, along with the list, and the value returned is
6899the list without its first two items, which is exactly the same
6900as repeating @code{cdr} twice on the list:
6901
6902@smallexample
6903@group
6904(nthcdr 2 '(pine fir oak maple))
6905 @result{} (oak maple)
6906@end group
6907@end smallexample
6908
6909@need 1200
6910Using the original four element list, we can see what happens when
6911various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6912and 5:
6913
6914@smallexample
6915@group
6916;; @r{Leave the list as it was.}
6917(nthcdr 0 '(pine fir oak maple))
6918 @result{} (pine fir oak maple)
6919@end group
6920
6921@group
6922;; @r{Return a copy without the first element.}
6923(nthcdr 1 '(pine fir oak maple))
6924 @result{} (fir oak maple)
6925@end group
6926
6927@group
6928;; @r{Return a copy of the list without three elements.}
6929(nthcdr 3 '(pine fir oak maple))
6930 @result{} (maple)
6931@end group
6932
6933@group
6934;; @r{Return a copy lacking all four elements.}
6935(nthcdr 4 '(pine fir oak maple))
6936 @result{} nil
6937@end group
6938
6939@group
6940;; @r{Return a copy lacking all elements.}
6941(nthcdr 5 '(pine fir oak maple))
6942 @result{} nil
6943@end group
6944@end smallexample
6945
6946@node nth, setcar, nthcdr, car cdr & cons
6947@comment node-name, next, previous, up
6948@section @code{nth}
6949@findex nth
6950
6951The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6952The @code{nth} function takes the @sc{car} of the result returned by
6953@code{nthcdr}. It returns the Nth element of the list.
6954
6955@need 1500
6956Thus, if it were not defined in C for speed, the definition of
6957@code{nth} would be:
6958
6959@smallexample
6960@group
6961(defun nth (n list)
6962 "Returns the Nth element of LIST.
6963N counts from zero. If LIST is not that long, nil is returned."
6964 (car (nthcdr n list)))
6965@end group
6966@end smallexample
6967
6968@noindent
6969(Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6970but its definition was redone in C in the 1980s.)
6971
6972The @code{nth} function returns a single element of a list.
6973This can be very convenient.
6974
6975Note that the elements are numbered from zero, not one. That is to
6976say, the first element of a list, its @sc{car} is the zeroth element.
6977This is called `zero-based' counting and often bothers people who
6978are accustomed to the first element in a list being number one, which
6979is `one-based'.
6980
6981@need 1250
6982For example:
6983
6984@smallexample
6985@group
6986(nth 0 '("one" "two" "three"))
6987 @result{} "one"
6988
6989(nth 1 '("one" "two" "three"))
6990 @result{} "two"
6991@end group
6992@end smallexample
6993
6994It is worth mentioning that @code{nth}, like @code{nthcdr} and
6995@code{cdr}, does not change the original list---the function is
6996non-destructive. This is in sharp contrast to the @code{setcar} and
6997@code{setcdr} functions.
6998
6999@node setcar, setcdr, nth, car cdr & cons
7000@comment node-name, next, previous, up
7001@section @code{setcar}
7002@findex setcar
7003
7004As you might guess from their names, the @code{setcar} and @code{setcdr}
7005functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7006They actually change the original list, unlike @code{car} and @code{cdr}
7007which leave the original list as it was. One way to find out how this
7008works is to experiment. We will start with the @code{setcar} function.
7009
7010@need 1200
7011First, we can make a list and then set the value of a variable to the
7012list, using the @code{setq} function. Here is a list of animals:
7013
7014@smallexample
7015(setq animals '(antelope giraffe lion tiger))
7016@end smallexample
7017
7018@noindent
7019If you are reading this in Info inside of GNU Emacs, you can evaluate
7020this expression in the usual fashion, by positioning the cursor after
7021the expression and typing @kbd{C-x C-e}. (I'm doing this right here as
7022I write this. This is one of the advantages of having the interpreter
7023built into the computing environment.)
7024
7025@need 1200
7026When we evaluate the variable @code{animals}, we see that it is bound to
7027the list @code{(antelope giraffe lion tiger)}:
7028
7029@smallexample
7030@group
7031animals
7032 @result{} (antelope giraffe lion tiger)
7033@end group
7034@end smallexample
7035
7036@noindent
7037Put another way, the variable @code{animals} points to the list
7038@code{(antelope giraffe lion tiger)}.
7039
7040Next, evaluate the function @code{setcar} while passing it two
7041arguments, the variable @code{animals} and the quoted symbol
7042@code{hippopotamus}; this is done by writing the three element list
7043@code{(setcar animals 'hippopotamus)} and then evaluating it in the
7044usual fashion:
7045
7046@smallexample
7047(setcar animals 'hippopotamus)
7048@end smallexample
7049
7050@need 1200
7051@noindent
7052After evaluating this expression, evaluate the variable @code{animals}
7053again. You will see that the list of animals has changed:
7054
7055@smallexample
7056@group
7057animals
7058 @result{} (hippopotamus giraffe lion tiger)
7059@end group
7060@end smallexample
7061
7062@noindent
7063The first element on the list, @code{antelope} is replaced by
7064@code{hippopotamus}.
7065
7066So we can see that @code{setcar} did not add a new element to the list
7067as @code{cons} would have; it replaced @code{giraffe} with
7068@code{hippopotamus}; it @emph{changed} the list.
7069
7070@node setcdr, cons Exercise, setcar, car cdr & cons
7071@comment node-name, next, previous, up
7072@section @code{setcdr}
7073@findex setcdr
7074
7075The @code{setcdr} function is similar to the @code{setcar} function,
7076except that the function replaces the second and subsequent elements of
7077a list rather than the first element.
7078
7079@need 1200
7080To see how this works, set the value of the variable to a list of
7081domesticated animals by evaluating the following expression:
7082
7083@smallexample
7084(setq domesticated-animals '(horse cow sheep goat))
7085@end smallexample
7086
7087@need 1200
7088@noindent
7089If you now evaluate the list, you will be returned the list
7090@code{(horse cow sheep goat)}:
7091
7092@smallexample
7093@group
7094domesticated-animals
7095 @result{} (horse cow sheep goat)
7096@end group
7097@end smallexample
7098
7099@need 1200
7100Next, evaluate @code{setcdr} with two arguments, the name of the
7101variable which has a list as its value, and the list to which the
7102@sc{cdr} of the first list will be set;
7103
7104@smallexample
7105(setcdr domesticated-animals '(cat dog))
7106@end smallexample
7107
7108@noindent
7109If you evaluate this expression, the list @code{(cat dog)} will appear
7110in the echo area. This is the value returned by the function. The
7111result we are interested in is the ``side effect'', which we can see by
7112evaluating the variable @code{domesticated-animals}:
7113
7114@smallexample
7115@group
7116domesticated-animals
7117 @result{} (horse cat dog)
7118@end group
7119@end smallexample
7120
7121@noindent
7122Indeed, the list is changed from @code{(horse cow sheep goat)} to
7123@code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7124@code{(cow sheep goat)} to @code{(cat dog)}.
7125
7126@node cons Exercise, , setcdr, car cdr & cons
7127@section Exercise
7128
7129Construct a list of four birds by evaluating several expressions with
7130@code{cons}. Find out what happens when you @code{cons} a list onto
7131itself. Replace the first element of the list of four birds with a
7132fish. Replace the rest of that list with a list of other fish.
7133@node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7134@comment node-name, next, previous, up
7135@chapter Cutting and Storing Text
7136@cindex Cutting and storing text
7137@cindex Storing and cutting text
7138@cindex Killing text
7139@cindex Clipping text
7140@cindex Erasing text
7141@cindex Deleting text
7142
7143Whenever you cut or clip text out of a buffer with a `kill' command in
7144GNU Emacs, it is stored in a list and you can bring it back with a
7145`yank' command.
7146
7147(The use of the word `kill' in Emacs for processes which specifically
7148@emph{do not} destroy the values of the entities is an unfortunate
7149historical accident. A much more appropriate word would be `clip' since
7150that is what the kill commands do; they clip text out of a buffer and
7151put it into storage from which it can be brought back. I have often
7152been tempted to replace globally all occurrences of `kill' in the Emacs
7153sources with `clip' and all occurrences of `killed' with `clipped'.)
7154
7155@menu
7156* Storing Text:: Text is stored in a list.
7157* zap-to-char:: Cutting out text up to a character.
7158* kill-region:: Cutting text out of a region.
7159* Digression into C:: Minor note on C programming language macros.
7160* defvar:: How to give a variable an initial value.
7161* copy-region-as-kill:: A definition for copying text.
7162* cons & search-fwd Review::
7163* search Exercises::
7164@end menu
7165
7166@node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7167@ifnottex
7168@unnumberedsec Storing Text in a List
7169@end ifnottex
7170
7171When text is cut out of a buffer, it is stored on a list. Successive
7172pieces of text are stored on the list successively, so the list might
7173look like this:
7174
7175@smallexample
7176("a piece of text" "previous piece")
7177@end smallexample
7178
7179@need 1200
7180@noindent
7181The function @code{cons} can be used to add a piece of text to the list,
7182like this:
7183
7184@smallexample
7185@group
7186(cons "another piece"
7187 '("a piece of text" "previous piece"))
7188@end group
7189@end smallexample
7190
7191@need 1200
7192@noindent
7193If you evaluate this expression, a list of three elements will appear in
7194the echo area:
7195
7196@smallexample
7197("another piece" "a piece of text" "previous piece")
7198@end smallexample
7199
7200With the @code{car} and @code{nthcdr} functions, you can retrieve
7201whichever piece of text you want. For example, in the following code,
7202@code{nthcdr 1 @dots{}} returns the list with the first item removed;
7203and the @code{car} returns the first element of that remainder---the
7204second element of the original list:
7205
7206@smallexample
7207@group
7208(car (nthcdr 1 '("another piece"
7209 "a piece of text"
7210 "previous piece")))
7211 @result{} "a piece of text"
7212@end group
7213@end smallexample
7214
7215The actual functions in Emacs are more complex than this, of course.
7216The code for cutting and retrieving text has to be written so that
7217Emacs can figure out which element in the list you want---the first,
7218second, third, or whatever. In addition, when you get to the end of
7219the list, Emacs should give you the first element of the list, rather
7220than nothing at all.
7221
7222The list that holds the pieces of text is called the @dfn{kill ring}.
7223This chapter leads up to a description of the kill ring and how it is
7224used by first tracing how the @code{zap-to-char} function works. This
7225function uses (or `calls') a function that invokes a function that
7226manipulates the kill ring. Thus, before reaching the mountains, we
7227climb the foothills.
7228
7229A subsequent chapter describes how text that is cut from the buffer is
7230retrieved. @xref{Yanking, , Yanking Text Back}.
7231
7232@node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7233@comment node-name, next, previous, up
7234@section @code{zap-to-char}
7235@findex zap-to-char
7236
7237The @code{zap-to-char} function barely changed between GNU Emacs
7238version 19 and GNU Emacs version 21. However, @code{zap-to-char}
7239calls another function, @code{kill-region}, which enjoyed a major rewrite
7240on the way to version 21.
7241
7242The @code{kill-region} function in Emacs 19 is complex, but does not
7243use code that is important at this time. We will skip it.
7244
7245The @code{kill-region} function in Emacs 21 is easier to read than the
7246same function in Emacs 19 and introduces a very important concept,
7247that of error handling. We will walk through the function.
7248
7249But first, let us look at the interactive @code{zap-to-char} function.
7250
7251@menu
7252* Complete zap-to-char:: The complete implementation.
7253* zap-to-char interactive:: A three part interactive expression.
7254* zap-to-char body:: A short overview.
7255* search-forward:: How to search for a string.
7256* progn:: The @code{progn} special form.
7257* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7258@end menu
7259
7260@node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7261@ifnottex
7262@unnumberedsubsec The Complete @code{zap-to-char} Implementation
7263@end ifnottex
7264
7265The GNU Emacs version 19 and version 21 implementations of the
7266@code{zap-to-char} function are nearly identical in form, and they
7267work alike. The function removes the text in the region between the
7268location of the cursor (i.e., of point) up to and including the next
7269occurrence of a specified character. The text that @code{zap-to-char}
7270removes is put in the kill ring; and it can be retrieved from the kill
7271ring by typing @kbd{C-y} (@code{yank}). If the command is given an
7272argument, it removes text through that number of occurrences. Thus,
7273if the cursor were at the beginning of this sentence and the character
7274were @samp{s}, @samp{Thus} would be removed. If the argument were
7275two, @samp{Thus, if the curs} would be removed, up to and including
7276the @samp{s} in @samp{cursor}.
7277
7278If the specified character is not found, @code{zap-to-char} will say
7279``Search failed'', tell you the character you typed, and not remove
7280any text.
7281
7282In order to determine how much text to remove, @code{zap-to-char} uses
7283a search function. Searches are used extensively in code that
7284manipulates text, and we will focus attention on them as well as on the
7285deletion command.
7286
7287@need 800
7288Here is the complete text of the version 19 implementation of the function:
7289
7290@c v 19
7291@smallexample
7292@group
7293(defun zap-to-char (arg char) ; version 19 implementation
7294 "Kill up to and including ARG'th occurrence of CHAR.
7295Goes backward if ARG is negative; error if CHAR not found."
7296 (interactive "*p\ncZap to char: ")
7297 (kill-region (point)
7298 (progn
7299 (search-forward
7300 (char-to-string char) nil nil arg)
7301 (point))))
7302@end group
7303@end smallexample
7304
7305@node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7306@comment node-name, next, previous, up
7307@subsection The @code{interactive} Expression
7308
7309@need 800
7310The interactive expression in the @code{zap-to-char} command looks like
7311this:
7312
7313@smallexample
7314(interactive "*p\ncZap to char: ")
7315@end smallexample
7316
7317The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7318three different things. First, and most simply, the asterisk, @samp{*},
7319causes an error to be signalled if the buffer is read-only. This means that
7320if you try @code{zap-to-char} in a read-only buffer you will not be able to
7321remove text, and you will receive a message that says ``Buffer is
7322read-only''; your terminal may beep at you as well.
7323
7324The version 21 implementation does not have the asterisk, @samp{*}. The
7325function works the same as in version 19: in both cases, it cannot
7326remove text from a read-only buffer but the function does copy the
7327text that would have been removed to the kill ring. Also, in both
7328cases, you see an error message.
7329
7330However, the version 19 implementation copies text from a read-only
7331buffer only because of a mistake in the implementation of
7332@code{interactive}. According to the documentation for
7333@code{interactive}, the asterisk, @samp{*}, should prevent the
7334@code{zap-to-char} function from doing anything at all when the buffer
7335is read only. The function should not copy the text to the kill ring.
7336It is a bug that it does.
7337
7338In version 21, @code{interactive} is implemented correctly. So the
7339asterisk, @samp{*}, had to be removed from the interactive
7340specification. If you insert an @samp{*} and evaluate the function
7341definition, then the next time you run the @code{zap-to-char} function
7342on a read-only buffer, you will not copy any text.
7343
7344That change aside, and a change to the documentation, the two versions
7345of the @code{zap-to-char} function are identical.
7346
7347Let us continue with the interactive specification.
7348
7349The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7350This part is separated from the next part by a newline, @samp{\n}.
7351The @samp{p} means that the first argument to the function will be
7352passed the value of a `processed prefix'. The prefix argument is
7353passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7354the function is called interactively without a prefix, 1 is passed to
7355this argument.
7356
7357The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7358}. In this part, the lower case @samp{c} indicates that
7359@code{interactive} expects a prompt and that the argument will be a
7360character. The prompt follows the @samp{c} and is the string @samp{Zap
7361to char:@: } (with a space after the colon to make it look good).
7362
7363What all this does is prepare the arguments to @code{zap-to-char} so they
7364are of the right type, and give the user a prompt.
7365
7366@node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7367@comment node-name, next, previous, up
7368@subsection The Body of @code{zap-to-char}
7369
7370The body of the @code{zap-to-char} function contains the code that
7371kills (that is, removes) the text in the region from the current
7372position of the cursor up to and including the specified character.
7373The first part of the code looks like this:
7374
7375@smallexample
7376(kill-region (point) @dots{}
7377@end smallexample
7378
7379@noindent
7380@code{(point)} is the current position of the cursor.
7381
7382The next part of the code is an expression using @code{progn}. The body
7383of the @code{progn} consists of calls to @code{search-forward} and
7384@code{point}.
7385
7386It is easier to understand how @code{progn} works after learning about
7387@code{search-forward}, so we will look at @code{search-forward} and
7388then at @code{progn}.
7389
7390@node search-forward, progn, zap-to-char body, zap-to-char
7391@comment node-name, next, previous, up
7392@subsection The @code{search-forward} Function
7393@findex search-forward
7394
7395The @code{search-forward} function is used to locate the
7396zapped-for-character in @code{zap-to-char}. If the search is
7397successful, @code{search-forward} leaves point immediately after the
7398last character in the target string. (In @code{zap-to-char}, the
7399target string is just one character long.) If the search is
7400backwards, @code{search-forward} leaves point just before the first
7401character in the target. Also, @code{search-forward} returns @code{t}
7402for true. (Moving point is therefore a `side effect'.)
7403
7404@need 1250
7405In @code{zap-to-char}, the @code{search-forward} function looks like this:
7406
7407@smallexample
7408(search-forward (char-to-string char) nil nil arg)
7409@end smallexample
7410
7411The @code{search-forward} function takes four arguments:
7412
7413@enumerate
7414@item
7415The first argument is the target, what is searched for. This must be a
7416string, such as @samp{"z"}.
7417
7418As it happens, the argument passed to @code{zap-to-char} is a single
7419character. Because of the way computers are built, the Lisp
7420interpreter may treat a single character as being different from a
7421string of characters. Inside the computer, a single character has a
7422different electronic format than a string of one character. (A single
7423character can often be recorded in the computer using exactly one
7424byte; but a string may be longer, and the computer needs to be ready
7425for this.) Since the @code{search-forward} function searches for a
7426string, the character that the @code{zap-to-char} function receives as
7427its argument must be converted inside the computer from one format to
7428the other; otherwise the @code{search-forward} function will fail.
7429The @code{char-to-string} function is used to make this conversion.
7430
7431@item
7432The second argument bounds the search; it is specified as a position in
7433the buffer. In this case, the search can go to the end of the buffer,
7434so no bound is set and the second argument is @code{nil}.
7435
7436@item
7437The third argument tells the function what it should do if the search
7438fails---it can signal an error (and print a message) or it can return
7439@code{nil}. A @code{nil} as the third argument causes the function to
7440signal an error when the search fails.
7441
7442@item
7443The fourth argument to @code{search-forward} is the repeat count---how
7444many occurrences of the string to look for. This argument is optional
7445and if the function is called without a repeat count, this argument is
7446passed the value 1. If this argument is negative, the search goes
7447backwards.
7448@end enumerate
7449
7450@need 800
7451In template form, a @code{search-forward} expression looks like this:
7452
7453@smallexample
7454@group
7455(search-forward "@var{target-string}"
7456 @var{limit-of-search}
7457 @var{what-to-do-if-search-fails}
7458 @var{repeat-count})
7459@end group
7460@end smallexample
7461
7462We will look at @code{progn} next.
7463
7464@node progn, Summing up zap-to-char, search-forward, zap-to-char
7465@comment node-name, next, previous, up
7466@subsection The @code{progn} Special Form
7467@findex progn
7468
7469@code{progn} is a special form that causes each of its arguments to be
7470evaluated in sequence and then returns the value of the last one. The
7471preceding expressions are evaluated only for the side effects they
7472perform. The values produced by them are discarded.
7473
7474@need 800
7475The template for a @code{progn} expression is very simple:
7476
7477@smallexample
7478@group
7479(progn
7480 @var{body}@dots{})
7481@end group
7482@end smallexample
7483
7484In @code{zap-to-char}, the @code{progn} expression has to do two things:
7485put point in exactly the right position; and return the location of
7486point so that @code{kill-region} will know how far to kill to.
7487
7488The first argument to the @code{progn} is @code{search-forward}. When
7489@code{search-forward} finds the string, the function leaves point
7490immediately after the last character in the target string. (In this
7491case the target string is just one character long.) If the search is
7492backwards, @code{search-forward} leaves point just before the first
7493character in the target. The movement of point is a side effect.
7494
7495The second and last argument to @code{progn} is the expression
7496@code{(point)}. This expression returns the value of point, which in
7497this case will be the location to which it has been moved by
7498@code{search-forward}. This value is returned by the @code{progn}
7499expression and is passed to @code{kill-region} as @code{kill-region}'s
7500second argument.
7501
7502@node Summing up zap-to-char, , progn, zap-to-char
7503@comment node-name, next, previous, up
7504@subsection Summing up @code{zap-to-char}
7505
7506Now that we have seen how @code{search-forward} and @code{progn} work,
7507we can see how the @code{zap-to-char} function works as a whole.
7508
7509The first argument to @code{kill-region} is the position of the cursor
7510when the @code{zap-to-char} command is given---the value of point at
7511that time. Within the @code{progn}, the search function then moves
7512point to just after the zapped-to-character and @code{point} returns the
7513value of this location. The @code{kill-region} function puts together
7514these two values of point, the first one as the beginning of the region
7515and the second one as the end of the region, and removes the region.
7516
7517The @code{progn} special form is necessary because the @code{kill-region}
7518command takes two arguments; and it would fail if @code{search-forward}
7519and @code{point} expressions were written in sequence as two
7520additional arguments. The @code{progn} expression is a single argument
7521to @code{kill-region} and returns the one value that @code{kill-region}
7522needs for its second argument.
7523
7524@node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7525@comment node-name, next, previous, up
7526@section @code{kill-region}
7527@findex kill-region
7528
7529The @code{zap-to-char} function uses the @code{kill-region} function.
7530This function clips text from a region and copies that text to
7531the kill ring, from which it may be retrieved.
7532
7533The Emacs 21 version of that function uses @code{condition-case} and
7534@code{copy-region-as-kill}, both of which we will explain.
7535@code{condition-case} is an important special form.
7536
7537In essence, the @code{kill-region} function calls
7538@code{condition-case}, which takes three arguments. In this function,
7539the first argument does nothing. The second argument contains the
7540code that does the work when all goes well. The third argument
7541contains the code that is called in the event of an error.
7542
7543@menu
7544* Complete kill-region:: The function definition.
7545* condition-case:: Dealing with a problem.
7546* delete-and-extract-region:: Doing the work.
7547@end menu
7548
7549@node Complete kill-region, condition-case, kill-region, kill-region
7550@ifnottex
7551@unnumberedsubsec The Complete @code{kill-region} Definition
7552@end ifnottex
7553
7554@need 1200
7555We will go through the @code{condition-case} code in a moment. First,
7556let us look at the complete definition of @code{kill-region}, with
7557comments added:
7558
7559@c v 21
7560@smallexample
7561@group
7562(defun kill-region (beg end)
7563 "Kill between point and mark.
7564The text is deleted but saved in the kill ring."
7565 (interactive "r")
7566@end group
7567
7568@group
7569 ;; 1. `condition-case' takes three arguments.
7570 ;; If the first argument is nil, as it is here,
7571 ;; information about the error signal is not
7572 ;; stored for use by another function.
7573 (condition-case nil
7574@end group
7575
7576@group
7577 ;; 2. The second argument to `condition-case'
7578 ;; tells the Lisp interpreter what to do when all goes well.
7579@end group
7580
7581@group
7582 ;; The `delete-and-extract-region' function usually does the
7583 ;; work. If the beginning and ending of the region are both
7584 ;; the same, then the variable `string' will be empty, or nil
7585 (let ((string (delete-and-extract-region beg end)))
7586@end group
7587
7588@group
7589 ;; `when' is an `if' clause that cannot take an `else-part'.
7590 ;; Emacs normally sets the value of `last-command' to the
7591 ;; previous command.
7592@end group
7593@group
7594 ;; `kill-append' concatenates the new string and the old.
7595 ;; `kill-new' inserts text into a new item in the kill ring.
7596 (when string
7597 (if (eq last-command 'kill-region)
7598 ;; if true, prepend string
7599 (kill-append string (< end beg))
7600 (kill-new string)))
7601 (setq this-command 'kill-region))
7602@end group
7603
7604@group
7605 ;; 3. The third argument to `condition-case' tells the interpreter
7606 ;; what to do with an error.
7607@end group
7608@group
7609 ;; The third argument has a conditions part and a body part.
7610 ;; If the conditions are met (in this case,
7611 ;; if text or buffer is read-only)
7612 ;; then the body is executed.
7613@end group
7614@group
7615 ((buffer-read-only text-read-only) ;; this is the if-part
7616 ;; then...
7617 (copy-region-as-kill beg end)
7618@end group
7619@group
7620 (if kill-read-only-ok ;; usually this variable is nil
7621 (message "Read only text copied to kill ring")
7622 ;; or else, signal an error if the buffer is read-only;
7623 (barf-if-buffer-read-only)
7624 ;; and, in any case, signal that the text is read-only.
7625 (signal 'text-read-only (list (current-buffer)))))))
7626@end group
7627@end smallexample
7628
7629@node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7630@comment node-name, next, previous, up
7631@subsection @code{condition-case}
7632@findex condition-case
7633
7634As we have seen earlier (@pxref{Making Errors, , Generate an Error
7635Message}), when the Emacs Lisp interpreter has trouble evaluating an
7636expression, it provides you with help; in the jargon, this is called
7637``signaling an error''. Usually, the computer stops the program and
7638shows you a message.
7639
7640However, some programs undertake complicated actions. They should not
7641simply stop on an error. In the @code{kill-region} function, the most
7642likely error is that you will try to kill text that is read-only and
7643cannot be removed. So the @code{kill-region} function contains code
7644to handle this circumstance. This code, which makes up the body of
7645the @code{kill-region} function, is inside of a @code{condition-case}
7646special form.
7647
7648@need 800
7649The template for @code{condition-case} looks like this:
7650
7651@smallexample
7652@group
7653(condition-case
7654 @var{var}
7655 @var{bodyform}
7656 @var{error-handler}@dots{})
7657@end group
7658@end smallexample
7659
7660The second argument, @var{bodyform}, is straightforward. The
7661@code{condition-case} special form causes the Lisp interpreter to
7662evaluate the code in @var{bodyform}. If no error occurs, the special
7663form returns the code's value and produces the side-effects, if any.
7664
7665In short, the @var{bodyform} part of a @code{condition-case}
7666expression determines what should happen when everything works
7667correctly.
7668
7669However, if an error occurs, among its other actions, the function
7670generating the error signal will define one or more error condition
7671names.
7672
7673An error handler is the third argument to @code{condition case}.
7674An error handler has two parts, a @var{condition-name} and a
7675@var{body}. If the @var{condition-name} part of an error handler
7676matches a condition name generated by an error, then the @var{body}
7677part of the error handler is run.
7678
7679As you will expect, the @var{condition-name} part of an error handler
7680may be either a single condition name or a list of condition names.
7681
7682Also, a complete @code{condition-case} expression may contain more
7683than one error handler. When an error occurs, the first applicable
7684handler is run.
7685
7686Lastly, the first argument to the @code{condition-case} expression,
7687the @var{var} argument, is sometimes bound to a variable that
7688contains information about the error. However, if that argument is
7689nil, as is the case in @code{kill-region}, that information is
7690discarded.
7691
7692@need 1200
7693In brief, in the @code{kill-region} function, the code
7694@code{condition-case} works like this:
7695
7696@smallexample
7697@group
7698@var{If no errors}, @var{run only this code}
7699 @var{but}, @var{if errors}, @var{run this other code}.
7700@end group
7701@end smallexample
7702
7703@node delete-and-extract-region, , condition-case, kill-region
7704@comment node-name, next, previous, up
7705@subsection @code{delete-and-extract-region}
7706@findex delete-and-extract-region
7707
7708A @code{condition-case} expression has two parts, a part that is
7709evaluated in the expectation that all will go well, but which may
7710generate an error; and a part that is evaluated when there is an
7711error.
7712
7713First, let us look at the code in @code{kill-region} that is run in
7714the expectation that all goes well. This is the core of the function.
7715The code looks like this:
7716
7717@smallexample
7718@group
7719(let ((string (delete-and-extract-region beg end)))
7720 (when string
7721 (if (eq last-command 'kill-region)
7722 (kill-append string (< end beg))
7723 (kill-new string)))
7724 (setq this-command 'kill-region))
7725@end group
7726@end smallexample
7727
7728It looks complicated because we have the new functions
7729@code{delete-and-extract-region}, @code{kill-append}, and
7730@code{kill-new} as well as the new variables,
7731@code{last-command} and @code{this-command}.
7732
7733The @code{delete-and-extract-region} function is straightforward. It
7734is a built-in function that deletes the text in a region (a side
7735effect) and also returns that text. This is the function that
7736actually removes the text. (And if it cannot do that, it signals the
7737error.)
7738
7739In this @code{let} expression, the text that
7740@code{delete-and-extract-region} returns is placed in the local
7741variable called @samp{string}. This is the text that is removed from
7742the buffer. (To be more precise, the variable is set to point to the
7743address of the extracted text; to say it is `placed in' the variable
7744is simply a shorthand.)
7745
7746If the variable @samp{string} does point to text, that text is added
7747to the kill ring. The variable will have a @code{nil} value if no
7748text was removed.
7749
7750The code uses @code{when} to determine whether the variable
7751@samp{string} points to text. A @code{when} statement is simply a
7752programmers' convenience. A @code{when} statement is an @code{if}
7753statement without the possibility of an else clause. In your mind, you
7754can replace @code{when} with @code{if} and understand what goes on.
7755That is what the Lisp interpreter does.
7756
7757@cindex Macro, lisp
7758@cindex Lisp macro
7759Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
7760enables you to define new control constructs and other language
7761features. It tells the interpreter how to compute another Lisp
7762expression which will in turn compute the value. In this case, the
7763`other expression' is an @code{if} expression. For more about Lisp
7764macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7765Manual}. The C programming language also provides macros. These are
7766different, but also useful. We will briefly look at C macros in
7767@ref{Digression into C, , @code{delete-and-extract-region}:
7768Digressing into C}.
7769
7770@need 1200
7771If the string has content, then another conditional expression is
7772executed. This is an @code{if} with both a then-part and an else-part.
7773
7774@smallexample
7775@group
7776(if (eq last-command 'kill-region)
7777 (kill-append string (< end beg))
7778 (kill-new string)))
7779@end group
7780@end smallexample
7781
7782The then-part is evaluated if the previous command was another call to
7783@code{kill-region}; if not, the else-part is evaluated.
7784
7785@code{last-command} is a variable that comes with Emacs that we have
7786not seen before. Normally, whenever a function is executed, Emacs
7787sets the value of @code{last-command} to the previous command.
7788
7789@need 1200
7790In this segment of the definition, the @code{if} expression checks
7791whether the previous command was @code{kill-region}. If it was,
7792
7793@smallexample
7794(kill-append string (< end beg))
7795@end smallexample
7796
7797@noindent
7798concatenates a copy of the newly clipped text to the just previously
7799clipped text in the kill ring. (If the @w{@code{(< end beg))}}
7800expression is true, @code{kill-append} prepends the string to the just
7801previously clipped text. For a detailed discussion, see
7802@ref{kill-append function, , The @code{kill-append} function}.)
7803
7804If you then yank back the text, i.e., `paste' it, you get both
7805pieces of text at once. That way, if you delete two words in a row,
7806and then yank them back, you get both words, in their proper order,
7807with one yank. (The @w{@code{(< end beg))}} expression makes sure the
7808order is correct.)
7809
7810On the other hand, if the previous command is not @code{kill-region},
7811then the @code{kill-new} function is called, which adds the text to
7812the kill ring as the latest item, and sets the
7813@code{kill-ring-yank-pointer} variable to point to it.
7814
7815@node Digression into C, defvar, kill-region, Cutting & Storing Text
7816@comment node-name, next, previous, up
7817@section @code{delete-and-extract-region}: Digressing into C
7818@findex delete-and-extract-region
7819@cindex C, a digression into
7820@cindex Digression into C
7821
7822The @code{zap-to-char} command uses the
7823@code{delete-and-extract-region} function, which in turn uses two
7824other functions, @code{copy-region-as-kill} and
7825@code{del_range_1}. The @code{copy-region-as-kill} function will be
7826described in a following section; it puts a copy of the region in the
7827kill ring so it can be yanked back. (@xref{copy-region-as-kill, ,
7828@code{copy-region-as-kill}}.)
7829
7830The @code{delete-and-extract-region} function removes the contents of
7831a region and you cannot get them back.
7832
7833Unlike the other code discussed here, @code{delete-and-extract-region}
7834is not written in Emacs Lisp; it is written in C and is one of the
7835primitives of the GNU Emacs system. Since it is very simple, I will
7836digress briefly from Lisp and describe it here.
7837
7838@need 1500
7839Like many of the other Emacs primitives,
7840@code{delete-and-extract-region} is written as an instance of a C
7841macro, a macro being a template for code. The complete macro looks
7842like this:
7843
7844@c /usr/local/src/emacs/src/editfns.c
7845@smallexample
7846@group
7847DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7848 Sdelete_and_extract_region, 2, 2, 0,
7849 "Delete the text between START and END and return it.")
7850 (start, end)
7851 Lisp_Object start, end;
7852@{
7853 validate_region (&start, &end);
7854 return del_range_1 (XINT (start), XINT (end), 1, 1);
7855@}
7856@end group
7857@end smallexample
7858
7859Without going into the details of the macro writing process, let me
7860point out that this macro starts with the word @code{DEFUN}. The word
7861@code{DEFUN} was chosen since the code serves the same purpose as
7862@code{defun} does in Lisp. The word @code{DEFUN} is followed by seven
7863parts inside of parentheses:
7864
7865@itemize @bullet
7866@item
7867The first part is the name given to the function in Lisp,
7868@code{delete-and-extract-region}.
7869
7870@item
7871The second part is the name of the function in C,
7872@code{Fdelete_and_extract_region}. By convention, it starts with
7873@samp{F}. Since C does not use hyphens in names, underscores are used
7874instead.
7875
7876@item
7877The third part is the name for the C constant structure that records
7878information on this function for internal use. It is the name of the
7879function in C but begins with an @samp{S} instead of an @samp{F}.
7880
7881@item
7882The fourth and fifth parts specify the minimum and maximum number of
7883arguments the function can have. This function demands exactly 2
7884arguments.
7885
7886@item
7887The sixth part is nearly like the argument that follows the
7888@code{interactive} declaration in a function written in Lisp: a letter
7889followed, perhaps, by a prompt. The only difference from the Lisp is
7890when the macro is called with no arguments. Then you write a @code{0}
7891(which is a `null string'), as in this macro.
7892
7893If you were to specify arguments, you would place them between
7894quotation marks. The C macro for @code{goto-char} includes
7895@code{"NGoto char: "} in this position to indicate that the function
7896expects a raw prefix, in this case, a numerical location in a buffer,
7897and provides a prompt.
7898
7899@item
7900The seventh part is a documentation string, just like the one for a
7901function written in Emacs Lisp, except that every newline must be
7902written explicitly as @samp{\n} followed by a backslash and carriage
7903return.
7904
7905@need 1000
7906Thus, the first two lines of documentation for @code{goto-char} are
7907written like this:
7908
7909@smallexample
7910@group
7911 "Set point to POSITION, a number or marker.\n\
7912Beginning of buffer is position (point-min), end is (point-max).
7913@end group
7914@end smallexample
7915@end itemize
7916
7917@need 1200
7918In a C macro, the formal parameters come next, with a statement of
7919what kind of object they are, followed by what might be called the `body'
7920of the macro. For @code{delete-and-extract-region} the `body'
7921consists of the following two lines:
7922
7923@smallexample
7924@group
7925validate_region (&start, &end);
7926return del_range_1 (XINT (start), XINT (end), 1, 1);
7927@end group
7928@end smallexample
7929
7930The first function, @code{validate_region} checks whether the values
7931passed as the beginning and end of the region are the proper type and
7932are within range. The second function, @code{del_range_1}, actually
7933deletes the text.
7934
7935@code{del_range_1} is a complex function we will not look into. It
7936updates the buffer and does other things.
7937
7938However, it is worth looking at the two arguments passed to
7939@code{del_range}. These are @w{@code{XINT (start)}} and @w{@code{XINT
7940(end)}}.
7941
7942As far as the C language is concerned, @code{start} and @code{end} are
7943two integers that mark the beginning and end of the region to be
7944deleted@footnote{More precisely, and requiring more expert knowledge
7945to understand, the two integers are of type `Lisp_Object', which can
7946also be a C union instead of an integer type.}.
7947
7948In early versions of Emacs, these two numbers were thirty-two bits
7949long, but the code is slowly being generalized to handle other
7950lengths. Three of the available bits are used to specify the type of
7951information and a fourth bit is used for handling the computer's
7952memory; the remaining bits are used as `content'.
7953
7954@samp{XINT} is a C macro that extracts the relevant number from the
7955longer collection of bits; the four other bits are discarded.
7956
7957@need 800
7958The command in @code{delete-and-extract-region} looks like this:
7959
7960@smallexample
7961del_range_1 (XINT (start), XINT (end), 1, 1);
7962@end smallexample
7963
7964@noindent
7965It deletes the region between the beginning position, @code{start},
7966and the ending position, @code{end}.
7967
7968From the point of view of the person writing Lisp, Emacs is all very
7969simple; but hidden underneath is a great deal of complexity to make it
7970all work.
7971
7972@node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7973@comment node-name, next, previous, up
7974@section Initializing a Variable with @code{defvar}
7975@findex defvar
7976@cindex Initializing a variable
7977@cindex Variable initialization
7978
7979Unlike the @code{delete-and-extract-region} function, the
7980@code{copy-region-as-kill} function is written in Emacs Lisp. Two
7981functions within it, @code{kill-append} and @code{kill-new}, copy a
7982region in a buffer and save it in a variable called the
7983@code{kill-ring}. This section describes how the @code{kill-ring}
7984variable is created and initialized using the @code{defvar} special
7985form.
7986
7987(Again we note that the term @code{kill-ring} is a misnomer. The text
7988that is clipped out of the buffer can be brought back; it is not a ring
7989of corpses, but a ring of resurrectable text.)
7990
7991In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7992given an initial value by using the @code{defvar} special form. The
7993name comes from ``define variable''.
7994
7995The @code{defvar} special form is similar to @code{setq} in that it sets
7996the value of a variable. It is unlike @code{setq} in two ways: first,
7997it only sets the value of the variable if the variable does not already
7998have a value. If the variable already has a value, @code{defvar} does
7999not override the existing value. Second, @code{defvar} has a
8000documentation string.
8001
8002(Another special form, @code{defcustom}, is designed for variables
8003that people customize. It has more features than @code{defvar}.
8004(@xref{defcustom, , Setting Variables with @code{defcustom}}.)
8005
8006@menu
8007* See variable current value::
8008* defvar and asterisk:: An old-time convention.
8009@end menu
8010
8011@node See variable current value, defvar and asterisk, defvar, defvar
8012@ifnottex
8013@unnumberedsubsec Seeing the Current Value of a Variable
8014@end ifnottex
8015
8016You can see the current value of a variable, any variable, by using
8017the @code{describe-variable} function, which is usually invoked by
8018typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
8019(followed by @key{RET}) when prompted, you will see what is in your
8020current kill ring---this may be quite a lot! Conversely, if you have
8021been doing nothing this Emacs session except read this document, you
8022may have nothing in it. Also, you will see the documentation for
8023@code{kill-ring}:
8024
8025@smallexample
8026@group
8027Documentation:
8028List of killed text sequences.
8029Since the kill ring is supposed to interact nicely with cut-and-paste
8030facilities offered by window systems, use of this variable should
8031@end group
8032@group
8033interact nicely with `interprogram-cut-function' and
8034`interprogram-paste-function'. The functions `kill-new',
8035`kill-append', and `current-kill' are supposed to implement this
8036interaction; you may want to use them instead of manipulating the kill
8037ring directly.
8038@end group
8039@end smallexample
8040
8041@need 800
8042The kill ring is defined by a @code{defvar} in the following way:
8043
8044@smallexample
8045@group
8046(defvar kill-ring nil
8047 "List of killed text sequences.
8048@dots{}")
8049@end group
8050@end smallexample
8051
8052@noindent
8053In this variable definition, the variable is given an initial value of
8054@code{nil}, which makes sense, since if you have saved nothing, you want
8055nothing back if you give a @code{yank} command. The documentation
8056string is written just like the documentation string of a @code{defun}.
8057As with the documentation string of the @code{defun}, the first line of
8058the documentation should be a complete sentence, since some commands,
8059like @code{apropos}, print only the first line of documentation.
8060Succeeding lines should not be indented; otherwise they look odd when
8061you use @kbd{C-h v} (@code{describe-variable}).
8062
8063@node defvar and asterisk, , See variable current value, defvar
8064@subsection @code{defvar} and an asterisk
8065@findex defvar @r{for a user customizable variable}
8066@findex defvar @r{with an asterisk}
8067
8068In the past, Emacs used the @code{defvar} special form both for
8069internal variables that you would not expect a user to change and for
8070variables that you do expect a user to change. Although you can still
8071use @code{defvar} for user customizable variables, please use
8072@code{defcustom} instead, since that special form provides a path into
8073the Customization commands. (@xref{defcustom, , Setting Variables
8074with @code{defcustom}}.)
8075
8076When you specified a variable using the @code{defvar} special form,
8077you could distinguish a readily settable variable from others by
8078typing an asterisk, @samp{*}, in the first column of its documentation
8079string. For example:
8080
8081@smallexample
8082@group
8083(defvar shell-command-default-error-buffer nil
8084 "*Buffer name for `shell-command' @dots{} error output.
8085@dots{} ")
8086@end group
8087@end smallexample
8088
8089@noindent
8090This means that you could (and still can) use the @code{edit-options}
8091command to change the value of
8092@code{shell-command-default-error-buffer} temporarily.
8093
8094@findex edit-options
8095However, options set using @code{edit-options} are set only for the
8096duration of your editing session. The new values are not saved
8097between sessions. Each time Emacs starts, it reads the original
8098value, unless you change the value within your @file{.emacs} file,
8099either by setting it manually or by using @code{customize}.
8100@xref{Emacs Initialization, , Your @file{.emacs} File}.
8101
8102For me, the major use of the @code{edit-options} command is to suggest
8103variables that I might want to set in my @file{.emacs} file. I urge
8104you to look through the list. (@xref{Edit Options, , Editing Variable
8105Values, emacs, The GNU Emacs Manual}.)
8106
8107@node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8108@comment node-name, next, previous, up
8109@section @code{copy-region-as-kill}
8110@findex copy-region-as-kill
8111@findex nthcdr
8112
8113The @code{copy-region-as-kill} function copies a region of text from a
8114buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8115in the @code{kill-ring}.
8116
8117If you call @code{copy-region-as-kill} immediately after a
8118@code{kill-region} command, Emacs appends the newly copied text to the
8119previously copied text. This means that if you yank back the text, you
8120get it all, from both this and the previous operation. On the other
8121hand, if some other command precedes the @code{copy-region-as-kill},
8122the function copies the text into a separate entry in the kill ring.
8123
8124@menu
8125* Complete copy-region-as-kill:: The complete function definition.
8126* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8127@end menu
8128
8129@node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8130@ifnottex
8131@unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8132@end ifnottex
8133
8134@need 1200
8135Here is the complete text of the version 21 @code{copy-region-as-kill}
8136function:
8137
8138@smallexample
8139@group
8140(defun copy-region-as-kill (beg end)
8141 "Save the region as if killed, but don't kill it.
8142In Transient Mark mode, deactivate the mark.
8143If `interprogram-cut-function' is non-nil, also save
8144the text for a window system cut and paste."
8145 (interactive "r")
8146@end group
8147@group
8148 (if (eq last-command 'kill-region)
8149 (kill-append (buffer-substring beg end) (< end beg))
8150 (kill-new (buffer-substring beg end)))
8151@end group
8152@group
8153 (if transient-mark-mode
8154 (setq deactivate-mark t))
8155 nil)
8156@end group
8157@end smallexample
8158
8159@need 800
8160As usual, this function can be divided into its component parts:
8161
8162@smallexample
8163@group
8164(defun copy-region-as-kill (@var{argument-list})
8165 "@var{documentation}@dots{}"
8166 (interactive "r")
8167 @var{body}@dots{})
8168@end group
8169@end smallexample
8170
8171The arguments are @code{beg} and @code{end} and the function is
8172interactive with @code{"r"}, so the two arguments must refer to the
8173beginning and end of the region. If you have been reading though this
8174document from the beginning, understanding these parts of a function is
8175almost becoming routine.
8176
8177The documentation is somewhat confusing unless you remember that the
8178word `kill' has a meaning different from its usual meaning. The
8179`Transient Mark' and @code{interprogram-cut-function} comments explain
8180certain side-effects.
8181
8182After you once set a mark, a buffer always contains a region. If you
8183wish, you can use Transient Mark mode to highlight the region
8184temporarily. (No one wants to highlight the region all the time, so
8185Transient Mark mode highlights it only at appropriate times. Many
8186people turn off Transient Mark mode, so the region is never
8187highlighted.)
8188
8189Also, a windowing system allows you to copy, cut, and paste among
8190different programs. In the X windowing system, for example, the
8191@code{interprogram-cut-function} function is @code{x-select-text},
8192which works with the windowing system's equivalent of the Emacs kill
8193ring.
8194
8195The body of the @code{copy-region-as-kill} function starts with an
8196@code{if} clause. What this clause does is distinguish between two
8197different situations: whether or not this command is executed
8198immediately after a previous @code{kill-region} command. In the first
8199case, the new region is appended to the previously copied text.
8200Otherwise, it is inserted into the beginning of the kill ring as a
8201separate piece of text from the previous piece.
8202
8203The last two lines of the function prevent the region from lighting up
8204if Transient Mark mode is turned on.
8205
8206The body of @code{copy-region-as-kill} merits discussion in detail.
8207
8208@node copy-region-as-kill body, , Complete copy-region-as-kill, copy-region-as-kill
8209@comment node-name, next, previous, up
8210@subsection The Body of @code{copy-region-as-kill}
8211
8212The @code{copy-region-as-kill} function works in much the same way as
8213the @code{kill-region} function (@pxref{kill-region,
8214,@code{kill-region}}). Both are written so that two or more kills in
8215a row combine their text into a single entry. If you yank back the
8216text from the kill ring, you get it all in one piece. Moreover, kills
8217that kill forward from the current position of the cursor are added to
8218the end of the previously copied text and commands that copy text
8219backwards add it to the beginning of the previously copied text. This
8220way, the words in the text stay in the proper order.
8221
8222Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8223use of the @code{last-command} variable that keeps track of the
8224previous Emacs command.
8225
8226@menu
8227* last-command & this-command::
8228* kill-append function::
8229* kill-new function::
8230@end menu
8231
8232@node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8233@ifnottex
8234@unnumberedsubsubsec @code{last-command} and @code{this-command}
8235@end ifnottex
8236
8237Normally, whenever a function is executed, Emacs sets the value of
8238@code{this-command} to the function being executed (which in this case
8239would be @code{copy-region-as-kill}). At the same time, Emacs sets
8240the value of @code{last-command} to the previous value of
8241@code{this-command}.
8242
8243In the first part of the body of the @code{copy-region-as-kill}
8244function, an @code{if} expression determines whether the value of
8245@code{last-command} is @code{kill-region}. If so, the then-part of
8246the @code{if} expression is evaluated; it uses the @code{kill-append}
8247function to concatenate the text copied at this call to the function
8248with the text already in the first element (the @sc{car}) of the kill
8249ring. On the other hand, if the value of @code{last-command} is not
8250@code{kill-region}, then the @code{copy-region-as-kill} function
8251attaches a new element to the kill ring using the @code{kill-new}
8252function.
8253
8254@need 1250
8255The @code{if} expression reads as follows; it uses @code{eq}, which is
8256a function we have not yet seen:
8257
8258@smallexample
8259@group
8260 (if (eq last-command 'kill-region)
8261 ;; @r{then-part}
8262 (kill-append (buffer-substring beg end) (< end beg))
8263 ;; @r{else-part}
8264 (kill-new (buffer-substring beg end)))
8265@end group
8266@end smallexample
8267
8268@findex eq @r{(example of use)}
8269@noindent
8270The @code{eq} function tests whether its first argument is the same Lisp
8271object as its second argument. The @code{eq} function is similar to the
8272@code{equal} function in that it is used to test for equality, but
8273differs in that it determines whether two representations are actually
8274the same object inside the computer, but with different names.
8275@code{equal} determines whether the structure and contents of two
8276expressions are the same.
8277
8278If the previous command was @code{kill-region}, then the Emacs Lisp
8279interpreter calls the @code{kill-append} function
8280
8281@node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8282@unnumberedsubsubsec The @code{kill-append} function
8283@findex kill-append
8284
8285@need 800
8286The @code{kill-append} function looks like this:
8287
8288@smallexample
8289@group
8290(defun kill-append (string before-p)
8291 "Append STRING to the end of the latest kill in the kill ring.
8292If BEFORE-P is non-nil, prepend STRING to the kill.
8293If `interprogram-cut-function' is set, pass the resulting kill to
8294it."
8295 (kill-new (if before-p
8296 (concat string (car kill-ring))
8297 (concat (car kill-ring) string))
8298 t))
8299@end group
8300@end smallexample
8301
8302@noindent
8303The @code{kill-append} function is fairly straightforward. It uses
8304the @code{kill-new} function, which we will discuss in more detail in
8305a moment.
8306
8307First, let us look at the conditional that is one of the two arguments
8308to @code{kill-new}. It uses @code{concat} to concatenate the new text
8309to the @sc{car} of the kill ring. Whether it prepends or appends the
8310text depends on the results of an @code{if} expression:
8311
8312@smallexample
8313@group
8314(if before-p ; @r{if-part}
8315 (concat string (car kill-ring)) ; @r{then-part}
8316 (concat (car kill-ring) string)) ; @r{else-part}
8317@end group
8318@end smallexample
8319
8320@noindent
8321If the region being killed is before the region that was killed in the
8322last command, then it should be prepended before the material that was
8323saved in the previous kill; and conversely, if the killed text follows
8324what was just killed, it should be appended after the previous text.
8325The @code{if} expression depends on the predicate @code{before-p} to
8326decide whether the newly saved text should be put before or after the
8327previously saved text.
8328
8329The symbol @code{before-p} is the name of one of the arguments to
8330@code{kill-append}. When the @code{kill-append} function is
8331evaluated, it is bound to the value returned by evaluating the actual
8332argument. In this case, this is the expression @code{(< end beg)}.
8333This expression does not directly determine whether the killed text in
8334this command is located before or after the kill text of the last
8335command; what is does is determine whether the value of the variable
8336@code{end} is less than the value of the variable @code{beg}. If it
8337is, it means that the user is most likely heading towards the
8338beginning of the buffer. Also, the result of evaluating the predicate
8339expression, @code{(< end beg)}, will be true and the text will be
8340prepended before the previous text. On the other hand, if the value of
8341the variable @code{end} is greater than the value of the variable
8342@code{beg}, the text will be appended after the previous text.
8343
8344@need 800
8345When the newly saved text will be prepended, then the string with the new
8346text will be concatenated before the old text:
8347
8348@smallexample
8349(concat string (car kill-ring))
8350@end smallexample
8351
8352@need 1200
8353@noindent
8354But if the text will be appended, it will be concatenated
8355after the old text:
8356
8357@smallexample
8358(concat (car kill-ring) string))
8359@end smallexample
8360
8361To understand how this works, we first need to review the
8362@code{concat} function. The @code{concat} function links together or
8363unites two strings of text. The result is a string. For example:
8364
8365@smallexample
8366@group
8367(concat "abc" "def")
8368 @result{} "abcdef"
8369@end group
8370
8371@group
8372(concat "new "
8373 (car '("first element" "second element")))
8374 @result{} "new first element"
8375
8376(concat (car
8377 '("first element" "second element")) " modified")
8378 @result{} "first element modified"
8379@end group
8380@end smallexample
8381
8382We can now make sense of @code{kill-append}: it modifies the contents
8383of the kill ring. The kill ring is a list, each element of which is
8384saved text. The @code{kill-append} function uses the @code{kill-new}
8385function which in turn uses the @code{setcar} function.
8386
8387@node kill-new function, , kill-append function, copy-region-as-kill body
8388@unnumberedsubsubsec The @code{kill-new} function
8389@findex kill-new
8390
8391@need 1200
8392The @code{kill-new} function looks like this:
8393
8394@smallexample
8395@group
8396(defun kill-new (string &optional replace)
8397 "Make STRING the latest kill in the kill ring.
8398Set the kill-ring-yank pointer to point to it.
8399If `interprogram-cut-function' is non-nil, apply it to STRING.
8400Optional second argument REPLACE non-nil means that STRING will replace
8401the front of the kill ring, rather than being added to the list."
8402@end group
8403@group
8404 (and (fboundp 'menu-bar-update-yank-menu)
8405 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8406@end group
8407@group
8408 (if (and replace kill-ring)
8409 (setcar kill-ring string)
8410 (setq kill-ring (cons string kill-ring))
8411 (if (> (length kill-ring) kill-ring-max)
8412 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8413@end group
8414@group
8415 (setq kill-ring-yank-pointer kill-ring)
8416 (if interprogram-cut-function
8417 (funcall interprogram-cut-function string (not replace))))
8418@end group
8419@end smallexample
8420
8421As usual, we can look at this function in parts.
8422
8423@need 1200
8424The first line of the documentation makes sense:
8425
8426@smallexample
8427Make STRING the latest kill in the kill ring.
8428@end smallexample
8429
8430@noindent
8431Let's skip over the rest of the documentation for the moment.
8432
8433Also, let's skip over the first two lines of code, those involving
8434@code{menu-bar-update-yank-menu}. We will explain them below.
8435
8436@need 1200
8437The critical lines are these:
8438
8439@smallexample
8440@group
8441 (if (and replace kill-ring)
8442 ;; @r{then}
8443 (setcar kill-ring string)
8444@end group
8445@group
8446 ;; @r{else}
8447 (setq kill-ring (cons string kill-ring))
8448 (if (> (length kill-ring) kill-ring-max)
8449 ;; @r{avoid overly long kill ring}
8450 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8451@end group
8452@group
8453 (setq kill-ring-yank-pointer kill-ring)
8454 (if interprogram-cut-function
8455 (funcall interprogram-cut-function string (not replace))))
8456@end group
8457@end smallexample
8458
8459The conditional test is @w{@code{(and replace kill-ring)}}.
8460This will be true when two conditions are met: the kill ring has
8461something in it, and the @code{replace} variable is true.
8462
8463@need 1250
8464The @code{kill-append} function sets @code{replace} to be true; then,
8465when the kill ring has at least one item in it, the @code{setcar}
8466expression is executed:
8467
8468@smallexample
8469(setcar kill-ring string)
8470@end smallexample
8471
8472The @code{setcar} function actually changes the first element of the
8473@code{kill-ring} list to the value of @code{string}. It replaces the
8474first element.
8475
8476On the other hand, if the kill ring is empty, or replace is false, the
8477else-part of the condition is executed:
8478
8479@smallexample
8480@group
8481(setq kill-ring (cons string kill-ring))
8482(if (> (length kill-ring) kill-ring-max)
8483 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8484@end group
8485@end smallexample
8486
8487@noindent
8488This expression first constructs a new version of the kill ring by
8489prepending @code{string} to the existing kill ring as a new element.
8490Then it executes a second @code{if} clause. This second @code{if}
8491clause keeps the kill ring from growing too long.
8492
8493Let's look at these two expressions in order.
8494
8495The @code{setq} line of the else-part sets the new value of the kill
8496ring to what results from adding the string being killed to the old kill
8497ring.
8498
8499@need 800
8500We can see how this works with an example:
8501
8502@smallexample
8503(setq example-list '("here is a clause" "another clause"))
8504@end smallexample
8505
8506@need 1200
8507@noindent
8508After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8509@code{example-list} and see what it returns:
8510
8511@smallexample
8512@group
8513example-list
8514 @result{} ("here is a clause" "another clause")
8515@end group
8516@end smallexample
8517
8518@need 1200
8519@noindent
8520Now, we can add a new element on to this list by evaluating the
8521following expression:
8522@findex cons, @r{example}
8523
8524@smallexample
8525(setq example-list (cons "a third clause" example-list))
8526@end smallexample
8527
8528@need 800
8529@noindent
8530When we evaluate @code{example-list}, we find its value is:
8531
8532@smallexample
8533@group
8534example-list
8535 @result{} ("a third clause" "here is a clause" "another clause")
8536@end group
8537@end smallexample
8538
8539@noindent
8540Thus, the third clause was added to the list by @code{cons}.
8541
8542@need 1200
8543This is exactly similar to what the @code{setq} and @code{cons} do in
8544the function. Here is the line again:
8545
8546@smallexample
8547(setq kill-ring (cons string kill-ring))
8548@end smallexample
8549
8550@need 1200
8551Now for the second part of the @code{if} clause. This expression
8552keeps the kill ring from growing too long. It looks like this:
8553
8554@smallexample
8555@group
8556(if (> (length kill-ring) kill-ring-max)
8557 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8558@end group
8559@end smallexample
8560
8561The code checks whether the length of the kill ring is greater than
8562the maximum permitted length. This is the value of
8563@code{kill-ring-max} (which is 60, by default). If the length of the
8564kill ring is too long, then this code sets the last element of the
8565kill ring to @code{nil}. It does this by using two functions,
8566@code{nthcdr} and @code{setcdr}.
8567
8568We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8569It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8570@sc{car} of a list. In this case, however, @code{setcdr} will not be
8571setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8572function is used to cause it to set the @sc{cdr} of the next to last
8573element of the kill ring---this means that since the @sc{cdr} of the
8574next to last element is the last element of the kill ring, it will set
8575the last element of the kill ring.
8576
8577@findex nthcdr, @r{example}
8578The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8579list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8580@dots{} It does this @var{N} times and returns the results.
8581
8582@findex setcdr, @r{example}
8583Thus, if we had a four element list that was supposed to be three
8584elements long, we could set the @sc{cdr} of the next to last element
8585to @code{nil}, and thereby shorten the list.
8586
8587You can see this by evaluating the following three expressions in turn.
8588First set the value of @code{trees} to @code{(maple oak pine birch)},
8589then set the @sc{cdr} of its second @sc{cdr} to @code{nil} and then
8590find the value of @code{trees}:
8591
8592@smallexample
8593@group
8594(setq trees '(maple oak pine birch))
8595 @result{} (maple oak pine birch)
8596@end group
8597
8598@group
8599(setcdr (nthcdr 2 trees) nil)
8600 @result{} nil
8601
8602trees
8603 @result{} (maple oak pine)
8604@end group
8605@end smallexample
8606
8607@noindent
8608(The value returned by the @code{setcdr} expression is @code{nil} since
8609that is what the @sc{cdr} is set to.)
8610
8611To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8612@sc{cdr} a number of times that is one less than the maximum permitted
8613size of the kill ring and sets the @sc{cdr} of that element (which
8614will be the rest of the elements in the kill ring) to @code{nil}.
8615This prevents the kill ring from growing too long.
8616
8617@need 800
8618The next to last expression in the @code{kill-new} function is
8619
8620@smallexample
8621(setq kill-ring-yank-pointer kill-ring)
8622@end smallexample
8623
8624The @code{kill-ring-yank-pointer} is a global variable that is set to be
8625the @code{kill-ring}.
8626
8627Even though the @code{kill-ring-yank-pointer} is called a
8628@samp{pointer}, it is a variable just like the kill ring. However, the
8629name has been chosen to help humans understand how the variable is used.
8630The variable is used in functions such as @code{yank} and
8631@code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8632
8633@need 1200
8634Now, to return to the first two lines in the body of the function:
8635
8636@smallexample
8637@group
8638 (and (fboundp 'menu-bar-update-yank-menu)
8639 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8640@end group
8641@end smallexample
8642
8643@noindent
8644This is an expression whose first element is the function @code{and}.
8645
8646@findex and, @r{introduced}
8647The @code{and} special form evaluates each of its arguments until one of
8648the arguments returns a value of @code{nil}, in which case the
8649@code{and} expression returns @code{nil}; however, if none of the
8650arguments returns a value of @code{nil}, the value resulting from
8651evaluating the last argument is returned. (Since such a value is not
8652@code{nil}, it is considered true in Emacs Lisp.) In other words, an
8653@code{and} expression returns a true value only if all its arguments
8654are true.
8655@findex and
8656
8657In this case, the expression tests first to see whether
8658@code{menu-bar-update-yank-menu} exists as a function, and if so,
8659calls it. The @code{fboundp} function returns true if the symbol it
8660is testing has a function definition that `is not void'. If the
8661symbol's function definition were void, we would receive an error
8662message, as we did when we created errors intentionally (@pxref{Making
8663Errors, , Generate an Error Message}).
8664
8665@need 1200
8666Essentially, the @code{and} is an @code{if} expression that reads like
8667this:
8668
8669@smallexample
8670@group
8671if @var{the-menu-bar-function-exists}
8672 then @var{execute-it}
8673@end group
8674@end smallexample
8675
8676@code{menu-bar-update-yank-menu} is one of the functions that make it
8677possible to use the `Select and Paste' menu in the Edit item of a menu
8678bar; using a mouse, you can look at the various pieces of text you
8679have saved and select one piece to paste.
8680
8681Finally, the last expression in the @code{kill-new} function adds the
8682newly copied string to whatever facility exists for copying and
8683pasting among different programs running in a windowing system. In
8684the X Windowing system, for example, the @code{x-select-text} function
8685takes the string and stores it in memory operated by X. You can paste
8686the string in another program, such as an Xterm.
8687
8688@need 1200
8689The expression looks like this:
8690
8691@smallexample
8692@group
8693 (if interprogram-cut-function
8694 (funcall interprogram-cut-function string (not replace))))
8695@end group
8696@end smallexample
8697
8698If an @code{interprogram-cut-function} exists, then Emacs executes
8699@code{funcall}, which in turn calls its first argument as a function
8700and passes the remaining arguments to it. (Incidentally, as far as I
8701can see, this @code{if} expression could be replaced by an @code{and}
8702expression similar to the one in the first part of the function.)
8703
8704We are not going to discuss windowing systems and other programs
8705further, but merely note that this is a mechanism that enables GNU
8706Emacs to work easily and well with other programs.
8707
8708This code for placing text in the kill ring, either concatenated with
8709an existing element or as a new element, leads us to the code for
8710bringing back text that has been cut out of the buffer---the yank
8711commands. However, before discussing the yank commands, it is better
8712to learn how lists are implemented in a computer. This will make
8713clear such mysteries as the use of the term `pointer'.
8714
8715@node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8716@comment node-name, next, previous, up
8717@section Review
8718
8719Here is a brief summary of some recently introduced functions.
8720
8721@table @code
8722@item car
8723@itemx cdr
8724@code{car} returns the first element of a list; @code{cdr} returns the
8725second and subsequent elements of a list.
8726
8727@need 1250
8728For example:
8729
8730@smallexample
8731@group
8732(car '(1 2 3 4 5 6 7))
8733 @result{} 1
8734(cdr '(1 2 3 4 5 6 7))
8735 @result{} (2 3 4 5 6 7)
8736@end group
8737@end smallexample
8738
8739@item cons
8740@code{cons} constructs a list by prepending its first argument to its
8741second argument.
8742
8743@need 1250
8744For example:
8745
8746@smallexample
8747@group
8748(cons 1 '(2 3 4))
8749 @result{} (1 2 3 4)
8750@end group
8751@end smallexample
8752
8753@item nthcdr
8754Return the result of taking @sc{cdr} `n' times on a list.
8755@iftex
8756The
8757@tex
8758$n^{th}$
8759@end tex
8760@code{cdr}.
8761@end iftex
8762The `rest of the rest', as it were.
8763
8764@need 1250
8765For example:
8766
8767@smallexample
8768@group
8769(nthcdr 3 '(1 2 3 4 5 6 7))
8770 @result{} (4 5 6 7)
8771@end group
8772@end smallexample
8773
8774@item setcar
8775@itemx setcdr
8776@code{setcar} changes the first element of a list; @code{setcdr}
8777changes the second and subsequent elements of a list.
8778
8779@need 1250
8780For example:
8781
8782@smallexample
8783@group
8784(setq triple '(1 2 3))
8785
8786(setcar triple '37)
8787
8788triple
8789 @result{} (37 2 3)
8790
8791(setcdr triple '("foo" "bar"))
8792
8793triple
8794 @result{} (37 "foo" "bar")
8795@end group
8796@end smallexample
8797
8798@item progn
8799Evaluate each argument in sequence and then return the value of the
8800last.
8801
8802@need 1250
8803For example:
8804
8805@smallexample
8806@group
8807(progn 1 2 3 4)
8808 @result{} 4
8809@end group
8810@end smallexample
8811
8812@item save-restriction
8813Record whatever narrowing is in effect in the current buffer, if any,
8814and restore that narrowing after evaluating the arguments.
8815
8816@item search-forward
8817Search for a string, and if the string is found, move point.
8818
8819@need 1250
8820@noindent
8821Takes four arguments:
8822
8823@enumerate
8824@item
8825The string to search for.
8826
8827@item
8828Optionally, the limit of the search.
8829
8830@item
8831Optionally, what to do if the search fails, return @code{nil} or an
8832error message.
8833
8834@item
8835Optionally, how many times to repeat the search; if negative, the
8836search goes backwards.
8837@end enumerate
8838
8839@item kill-region
8840@itemx delete-region
8841@itemx copy-region-as-kill
8842
8843@code{kill-region} cuts the text between point and mark from the
8844buffer and stores that text in the kill ring, so you can get it back
8845by yanking.
8846
8847@code{delete-and-extract-region} removes the text between point and
8848mark from the buffer and throws it away. You cannot get it back.
8849
8850@code{copy-region-as-kill} copies the text between point and mark into
8851the kill ring, from which you can get it by yanking. The function
8852does not cut or remove the text from the buffer.
8853@end table
8854
8855@need 1500
8856@node search Exercises, , cons & search-fwd Review, Cutting & Storing Text
8857@section Searching Exercises
8858
8859@itemize @bullet
8860@item
8861Write an interactive function that searches for a string. If the
8862search finds the string, leave point after it and display a message
8863that says ``Found!''. (Do not use @code{search-forward} for the name
8864of this function; if you do, you will overwrite the existing version of
8865@code{search-forward} that comes with Emacs. Use a name such as
8866@code{test-search} instead.)
8867
8868@item
8869Write a function that prints the third element of the kill ring in the
8870echo area, if any; if the kill ring does not contain a third element,
8871print an appropriate message.
8872@end itemize
8873
8874@node List Implementation, Yanking, Cutting & Storing Text, Top
8875@comment node-name, next, previous, up
8876@chapter How Lists are Implemented
8877@cindex Lists in a computer
8878
8879In Lisp, atoms are recorded in a straightforward fashion; if the
8880implementation is not straightforward in practice, it is, nonetheless,
8881straightforward in theory. The atom @samp{rose}, for example, is
8882recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8883@samp{e}. A list, on the other hand, is kept differently. The mechanism
8884is equally simple, but it takes a moment to get used to the idea. A
8885list is kept using a series of pairs of pointers. In the series, the
8886first pointer in each pair points to an atom or to another list, and the
8887second pointer in each pair points to the next pair, or to the symbol
8888@code{nil}, which marks the end of the list.
8889
8890A pointer itself is quite simply the electronic address of what is
8891pointed to. Hence, a list is kept as a series of electronic addresses.
8892
8893@menu
8894* Lists diagrammed::
8895* Symbols as Chest:: Exploring a powerful metaphor.
8896* List Exercise::
8897@end menu
8898
8899@node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8900@ifnottex
8901@unnumberedsec Lists diagrammed
8902@end ifnottex
8903
8904For example, the list @code{(rose violet buttercup)} has three elements,
8905@samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
8906electronic address of @samp{rose} is recorded in a segment of computer
8907memory along with the address that gives the electronic address of where
8908the atom @samp{violet} is located; and that address (the one that tells
8909where @samp{violet} is located) is kept along with an address that tells
8910where the address for the atom @samp{buttercup} is located.
8911
8912@need 1200
8913This sounds more complicated than it is and is easier seen in a diagram:
8914
8915@c clear print-postscript-figures
8916@c !!! cons-cell-diagram #1
8917@ifnottex
8918@smallexample
8919@group
8920 ___ ___ ___ ___ ___ ___
8921 |___|___|--> |___|___|--> |___|___|--> nil
8922 | | |
8923 | | |
8924 --> rose --> violet --> buttercup
8925@end group
8926@end smallexample
8927@end ifnottex
8928@ifset print-postscript-figures
8929@sp 1
8930@tex
8931@image{cons-1}
8932%%%% old method of including an image
8933% \input /usr/local/lib/tex/inputs/psfig.tex
8934% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8935% \catcode`\@=0 %
8936@end tex
8937@sp 1
8938@end ifset
8939@ifclear print-postscript-figures
8940@iftex
8941@smallexample
8942@group
8943 ___ ___ ___ ___ ___ ___
8944 |___|___|--> |___|___|--> |___|___|--> nil
8945 | | |
8946 | | |
8947 --> rose --> violet --> buttercup
8948@end group
8949@end smallexample
8950@end iftex
8951@end ifclear
8952
8953@noindent
8954In the diagram, each box represents a word of computer memory that
8955holds a Lisp object, usually in the form of a memory address. The boxes,
8956i.e.@: the addresses, are in pairs. Each arrow points to what the address
8957is the address of, either an atom or another pair of addresses. The
8958first box is the electronic address of @samp{rose} and the arrow points
8959to @samp{rose}; the second box is the address of the next pair of boxes,
8960the first part of which is the address of @samp{violet} and the second
8961part of which is the address of the next pair. The very last box
8962points to the symbol @code{nil}, which marks the end of the list.
8963
8964@need 1200
8965When a variable is set to a list with a function such as @code{setq},
8966it stores the address of the first box in the variable. Thus,
8967evaluation of the expression
8968
8969@smallexample
8970(setq bouquet '(rose violet buttercup))
8971@end smallexample
8972
8973@need 1250
8974@noindent
8975creates a situation like this:
8976
8977@c cons-cell-diagram #2
8978@ifnottex
8979@smallexample
8980@group
8981bouquet
8982 |
8983 | ___ ___ ___ ___ ___ ___
8984 --> |___|___|--> |___|___|--> |___|___|--> nil
8985 | | |
8986 | | |
8987 --> rose --> violet --> buttercup
8988@end group
8989@end smallexample
8990@end ifnottex
8991@ifset print-postscript-figures
8992@sp 1
8993@tex
8994@image{cons-2}
8995%%%% old method of including an image
8996% \input /usr/local/lib/tex/inputs/psfig.tex
8997% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
8998% \catcode`\@=0 %
8999@end tex
9000@sp 1
9001@end ifset
9002@ifclear print-postscript-figures
9003@iftex
9004@smallexample
9005@group
9006bouquet
9007 |
9008 | ___ ___ ___ ___ ___ ___
9009 --> |___|___|--> |___|___|--> |___|___|--> nil
9010 | | |
9011 | | |
9012 --> rose --> violet --> buttercup
9013@end group
9014@end smallexample
9015@end iftex
9016@end ifclear
9017
9018@noindent
9019In this example, the symbol @code{bouquet} holds the address of the first
9020pair of boxes.
9021
9022@need 1200
9023This same list can be illustrated in a different sort of box notation
9024like this:
9025
9026@c cons-cell-diagram #2a
9027@ifnottex
9028@smallexample
9029@group
9030bouquet
9031 |
9032 | -------------- --------------- ----------------
9033 | | car | cdr | | car | cdr | | car | cdr |
9034 -->| rose | o------->| violet | o------->| butter- | nil |
9035 | | | | | | | cup | |
9036 -------------- --------------- ----------------
9037@end group
9038@end smallexample
9039@end ifnottex
9040@ifset print-postscript-figures
9041@sp 1
9042@tex
9043@image{cons-2a}
9044%%%% old method of including an image
9045% \input /usr/local/lib/tex/inputs/psfig.tex
9046% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9047% \catcode`\@=0 %
9048@end tex
9049@sp 1
9050@end ifset
9051@ifclear print-postscript-figures
9052@iftex
9053@smallexample
9054@group
9055bouquet
9056 |
9057 | -------------- --------------- ----------------
9058 | | car | cdr | | car | cdr | | car | cdr |
9059 -->| rose | o------->| violet | o------->| butter- | nil |
9060 | | | | | | | cup | |
9061 -------------- --------------- ----------------
9062@end group
9063@end smallexample
9064@end iftex
9065@end ifclear
9066
9067(Symbols consist of more than pairs of addresses, but the structure of
9068a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9069consists of a group of address-boxes, one of which is the address of
9070the printed word @samp{bouquet}, a second of which is the address of a
9071function definition attached to the symbol, if any, a third of which
9072is the address of the first pair of address-boxes for the list
9073@code{(rose violet buttercup)}, and so on. Here we are showing that
9074the symbol's third address-box points to the first pair of
9075address-boxes for the list.)
9076
9077If a symbol is set to the @sc{cdr} of a list, the list itself is not
9078changed; the symbol simply has an address further down the list. (In
9079the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9080evaluation of the following expression
9081
9082@smallexample
9083(setq flowers (cdr bouquet))
9084@end smallexample
9085
9086@need 800
9087@noindent
9088produces this:
9089
9090@c cons-cell-diagram #3
9091@ifnottex
9092@sp 1
9093@smallexample
9094@group
9095bouquet flowers
9096 | |
9097 | ___ ___ | ___ ___ ___ ___
9098 --> | | | --> | | | | | |
9099 |___|___|----> |___|___|--> |___|___|--> nil
9100 | | |
9101 | | |
9102 --> rose --> violet --> buttercup
9103@end group
9104@end smallexample
9105@sp 1
9106@end ifnottex
9107@ifset print-postscript-figures
9108@sp 1
9109@tex
9110@image{cons-3}
9111%%%% old method of including an image
9112% \input /usr/local/lib/tex/inputs/psfig.tex
9113% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9114% \catcode`\@=0 %
9115@end tex
9116@sp 1
9117@end ifset
9118@ifclear print-postscript-figures
9119@iftex
9120@sp 1
9121@smallexample
9122@group
9123bouquet flowers
9124 | |
9125 | ___ ___ | ___ ___ ___ ___
9126 --> | | | --> | | | | | |
9127 |___|___|----> |___|___|--> |___|___|--> nil
9128 | | |
9129 | | |
9130 --> rose --> violet --> buttercup
9131@end group
9132@end smallexample
9133@sp 1
9134@end iftex
9135@end ifclear
9136
9137@noindent
9138The value of @code{flowers} is @code{(violet buttercup)}, which is
9139to say, the symbol @code{flowers} holds the address of the pair of
9140address-boxes, the first of which holds the address of @code{violet},
9141and the second of which holds the address of @code{buttercup}.
9142
9143A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9144pair}. @xref{List Type, , List Type , elisp, The GNU Emacs Lisp
9145Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9146Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9147information about cons cells and dotted pairs.
9148
9149@need 1200
9150The function @code{cons} adds a new pair of addresses to the front of
9151a series of addresses like that shown above. For example, evaluating
9152the expression
9153
9154@smallexample
9155(setq bouquet (cons 'lily bouquet))
9156@end smallexample
9157
9158@need 1500
9159@noindent
9160produces:
9161
9162@c cons-cell-diagram #4
9163@ifnottex
9164@sp 1
9165@smallexample
9166@group
9167bouquet flowers
9168 | |
9169 | ___ ___ ___ ___ | ___ ___ ___ ___
9170 --> | | | | | | --> | | | | | |
9171 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9172 | | | |
9173 | | | |
9174 --> lily --> rose --> violet --> buttercup
9175@end group
9176@end smallexample
9177@sp 1
9178@end ifnottex
9179@ifset print-postscript-figures
9180@sp 1
9181@tex
9182@image{cons-4}
9183%%%% old method of including an image
9184% \input /usr/local/lib/tex/inputs/psfig.tex
9185% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9186% \catcode`\@=0 %
9187@end tex
9188@sp 1
9189@end ifset
9190@ifclear print-postscript-figures
9191@iftex
9192@sp 1
9193@smallexample
9194@group
9195bouquet flowers
9196 | |
9197 | ___ ___ ___ ___ | ___ ___ ___ ___
9198 --> | | | | | | --> | | | | | |
9199 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9200 | | | |
9201 | | | |
9202 --> lily --> rose --> violet --> buttercup
9203@end group
9204@end smallexample
9205@sp 1
9206@end iftex
9207@end ifclear
9208
9209@need 1200
9210@noindent
9211However, this does not change the value of the symbol
9212@code{flowers}, as you can see by evaluating the following,
9213
9214@smallexample
9215(eq (cdr (cdr bouquet)) flowers)
9216@end smallexample
9217
9218@noindent
9219which returns @code{t} for true.
9220
9221Until it is reset, @code{flowers} still has the value
9222@code{(violet buttercup)}; that is, it has the address of the cons
9223cell whose first address is of @code{violet}. Also, this does not
9224alter any of the pre-existing cons cells; they are all still there.
9225
9226Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9227of the next cons cell in the series; to get the @sc{car} of a list,
9228you get the address of the first element of the list; to @code{cons} a
9229new element on a list, you add a new cons cell to the front of the list.
9230That is all there is to it! The underlying structure of Lisp is
9231brilliantly simple!
9232
9233And what does the last address in a series of cons cells refer to? It
9234is the address of the empty list, of @code{nil}.
9235
9236In summary, when a Lisp variable is set to a value, it is provided with
9237the address of the list to which the variable refers.
9238
9239@node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9240@section Symbols as a Chest of Drawers
9241@cindex Symbols as a Chest of Drawers
9242@cindex Chest of Drawers, metaphor for a symbol
9243@cindex Drawers, Chest of, metaphor for a symbol
9244
9245In an earlier section, I suggested that you might imagine a symbol as
9246being a chest of drawers. The function definition is put in one
9247drawer, the value in another, and so on. What is put in the drawer
9248holding the value can be changed without affecting the contents of the
9249drawer holding the function definition, and vice-versa.
9250
9251Actually, what is put in each drawer is the address of the value or
9252function definition. It is as if you found an old chest in the attic,
9253and in one of its drawers you found a map giving you directions to
9254where the buried treasure lies.
9255
9256(In addition to its name, symbol definition, and variable value, a
9257symbol has a `drawer' for a @dfn{property list} which can be used to
9258record other information. Property lists are not discussed here; see
9259@ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9260Reference Manual}.)
9261
9262@need 1500
9263Here is a fanciful representation:
9264
9265@c chest-of-drawers diagram
9266@ifnottex
9267@sp 1
9268@smallexample
9269@group
9270 Chest of Drawers Contents of Drawers
9271
9272 __ o0O0o __
9273 / \
9274 ---------------------
9275 | directions to | [map to]
9276 | symbol name | bouquet
9277 | |
9278 +---------------------+
9279 | directions to |
9280 | symbol definition | [none]
9281 | |
9282 +---------------------+
9283 | directions to | [map to]
9284 | variable value | (rose violet buttercup)
9285 | |
9286 +---------------------+
9287 | directions to |
9288 | property list | [not described here]
9289 | |
9290 +---------------------+
9291 |/ \|
9292@end group
9293@end smallexample
9294@sp 1
9295@end ifnottex
9296@ifset print-postscript-figures
9297@sp 1
9298@tex
9299@image{drawers}
9300%%%% old method of including an image
9301% \input /usr/local/lib/tex/inputs/psfig.tex
9302% \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9303% \catcode`\@=0 %
9304@end tex
9305@sp 1
9306@end ifset
9307@ifclear print-postscript-figures
9308@iftex
9309@sp 1
9310@smallexample
9311@group
9312 Chest of Drawers Contents of Drawers
9313
9314 __ o0O0o __
9315 / \
9316 ---------------------
9317 | directions to | [map to]
9318 | symbol name | bouquet
9319 | |
9320 +---------------------+
9321 | directions to |
9322 | symbol definition | [none]
9323 | |
9324 +---------------------+
9325 | directions to | [map to]
9326 | variable value | (rose violet buttercup)
9327 | |
9328 +---------------------+
9329 | directions to |
9330 | property list | [not described here]
9331 | |
9332 +---------------------+
9333 |/ \|
9334@end group
9335@end smallexample
9336@sp 1
9337@end iftex
9338@end ifclear
9339
9340@node List Exercise, , Symbols as Chest, List Implementation
9341@section Exercise
9342
9343Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
9344more flowers on to this list and set this new list to
9345@code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
9346What does the @code{more-flowers} list now contain?
9347
9348@node Yanking, Loops & Recursion, List Implementation, Top
9349@comment node-name, next, previous, up
9350@chapter Yanking Text Back
9351@findex yank
9352@findex rotate-yank-pointer
9353@cindex Text retrieval
9354@cindex Retrieving text
9355@cindex Pasting text
9356
9357Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9358you can bring it back with a `yank' command. The text that is cut out of
9359the buffer is put in the kill ring and the yank commands insert the
9360appropriate contents of the kill ring back into a buffer (not necessarily
9361the original buffer).
9362
9363A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9364the kill ring into the current buffer. If the @kbd{C-y} command is
9365followed immediately by @kbd{M-y}, the first element is replaced by
9366the second element. Successive @kbd{M-y} commands replace the second
9367element with the third, fourth, or fifth element, and so on. When the
9368last element in the kill ring is reached, it is replaced by the first
9369element and the cycle is repeated. (Thus the kill ring is called a
9370`ring' rather than just a `list'. However, the actual data structure
9371that holds the text is a list.
9372@xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9373list is handled as a ring.)
9374
9375@menu
9376* Kill Ring Overview:: The kill ring is a list.
9377* kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
9378* yank nthcdr Exercises::
9379@end menu
9380
9381@node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9382@comment node-name, next, previous, up
9383@section Kill Ring Overview
9384@cindex Kill ring overview
9385
9386The kill ring is a list of textual strings. This is what it looks like:
9387
9388@smallexample
9389("some text" "a different piece of text" "yet more text")
9390@end smallexample
9391
9392If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9393string of characters saying @samp{some text} would be inserted in this
9394buffer where my cursor is located.
9395
9396The @code{yank} command is also used for duplicating text by copying it.
9397The copied text is not cut from the buffer, but a copy of it is put on the
9398kill ring and is inserted by yanking it back.
9399
9400Three functions are used for bringing text back from the kill ring:
9401@code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9402which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9403which is used by the two other functions.
9404
9405These functions refer to the kill ring through a variable called the
9406@code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
9407@code{yank} and @code{yank-pop} functions is:
9408
9409@smallexample
9410(insert (car kill-ring-yank-pointer))
9411@end smallexample
9412
9413To begin to understand how @code{yank} and @code{yank-pop} work, it is
9414first necessary to look at the @code{kill-ring-yank-pointer} variable
9415and the @code{rotate-yank-pointer} function.
9416
9417@node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9418@comment node-name, next, previous, up
9419@section The @code{kill-ring-yank-pointer} Variable
9420
9421@code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9422a variable. It points to something by being bound to the value of what
9423it points to, like any other Lisp variable.
9424
9425@need 1000
9426Thus, if the value of the kill ring is:
9427
9428@smallexample
9429("some text" "a different piece of text" "yet more text")
9430@end smallexample
9431
9432@need 1250
9433@noindent
9434and the @code{kill-ring-yank-pointer} points to the second clause, the
9435value of @code{kill-ring-yank-pointer} is:
9436
9437@smallexample
9438("a different piece of text" "yet more text")
9439@end smallexample
9440
9441As explained in the previous chapter (@pxref{List Implementation}), the
9442computer does not keep two different copies of the text being pointed to
9443by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
9444words ``a different piece of text'' and ``yet more text'' are not
9445duplicated. Instead, the two Lisp variables point to the same pieces of
9446text. Here is a diagram:
9447
9448@c cons-cell-diagram #5
9449@ifnottex
9450@smallexample
9451@group
9452kill-ring kill-ring-yank-pointer
9453 | |
9454 | ___ ___ | ___ ___ ___ ___
9455 ---> | | | --> | | | | | |
9456 |___|___|----> |___|___|--> |___|___|--> nil
9457 | | |
9458 | | |
9459 | | --> "yet more text"
9460 | |
9461 | --> "a different piece of text
9462 |
9463 --> "some text"
9464@end group
9465@end smallexample
9466@sp 1
9467@end ifnottex
9468@ifset print-postscript-figures
9469@sp 1
9470@tex
9471@image{cons-5}
9472%%%% old method of including an image
9473% \input /usr/local/lib/tex/inputs/psfig.tex
9474% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9475% \catcode`\@=0 %
9476@end tex
9477@sp 1
9478@end ifset
9479@ifclear print-postscript-figures
9480@iftex
9481@smallexample
9482@group
9483kill-ring kill-ring-yank-pointer
9484 | |
9485 | ___ ___ | ___ ___ ___ ___
9486 ---> | | | --> | | | | | |
9487 |___|___|----> |___|___|--> |___|___|--> nil
9488 | | |
9489 | | |
9490 | | --> "yet more text"
9491 | |
9492 | --> "a different piece of text
9493 |
9494 --> "some text"
9495@end group
9496@end smallexample
9497@sp 1
9498@end iftex
9499@end ifclear
9500
9501Both the variable @code{kill-ring} and the variable
9502@code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
9503usually described as if it were actually what it is composed of. The
9504@code{kill-ring} is spoken of as if it were the list rather than that it
9505points to the list. Conversely, the @code{kill-ring-yank-pointer} is
9506spoken of as pointing to a list.
9507
9508These two ways of talking about the same thing sound confusing at first but
9509make sense on reflection. The kill ring is generally thought of as the
9510complete structure of data that holds the information of what has recently
9511been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
9512on the other hand, serves to indicate---that is, to `point to'---that part
9513of the kill ring of which the first element (the @sc{car}) will be
9514inserted.
9515
9516The @code{rotate-yank-pointer} function changes the element in the
9517kill ring to which the @code{kill-ring-yank-pointer} points; when the
9518pointer is set to point to the next element beyond the end of the kill
9519ring, it automatically sets it to point to the first element of the
9520kill ring. This is how the list is transformed into a ring. The
9521@code{rotate-yank-pointer} function itself is not difficult, but
9522contains many details. It and the much simpler @code{yank} and
9523@code{yank-pop} functions are described in an appendix.
9524@xref{Kill Ring, , Handling the Kill Ring}.
9525
9526@need 1500
9527@node yank nthcdr Exercises, , kill-ring-yank-pointer, Yanking
9528@section Exercises with @code{yank} and @code{nthcdr}
9529
9530@itemize @bullet
9531@item
9532Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9533your kill ring. Add several items to your kill ring; look at its
9534value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
9535around the kill ring. How many items were in your kill ring? Find
9536the value of @code{kill-ring-max}. Was your kill ring full, or could
9537you have kept more blocks of text within it?
9538
9539@item
9540Using @code{nthcdr} and @code{car}, construct a series of expressions
9541to return the first, second, third, and fourth elements of a list.
9542@end itemize
9543
9544@node Loops & Recursion, Regexp Search, Yanking, Top
9545@comment node-name, next, previous, up
9546@chapter Loops and Recursion
9547@cindex Loops and recursion
9548@cindex Recursion and loops
9549@cindex Repetition (loops)
9550
9551Emacs Lisp has two primary ways to cause an expression, or a series of
9552expressions, to be evaluated repeatedly: one uses a @code{while}
9553loop, and the other uses @dfn{recursion}.
9554
9555Repetition can be very valuable. For example, to move forward four
9556sentences, you need only write a program that will move forward one
9557sentence and then repeat the process four times. Since a computer does
9558not get bored or tired, such repetitive action does not have the
9559deleterious effects that excessive or the wrong kinds of repetition can
9560have on humans.
9561
9562People mostly write Emacs Lisp functions using @code{while} loops and
9563their kin; but you can use recursion, which provides a very powerful
9564way to think about and then to solve problems@footnote{You can write
9565recursive functions to be frugal or wasteful of mental or computer
9566resources; as it happens, methods that people find easy---that are
9567frugal of `mental resources'---sometimes use considerable computer
9568resources. Emacs was designed to run on machines that we now consider
9569limited and its default settings are conservative. You may want to
9570increase the values of @code{max-specpdl-size} and
9571@code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
957215 and 30 times their default value.}.
9573
9574@menu
9575* while:: Causing a stretch of code to repeat.
9576* dolist dotimes::
9577* Recursion:: Causing a function to call itself.
9578* Looping exercise::
9579@end menu
9580
9581@node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9582@comment node-name, next, previous, up
9583@section @code{while}
9584@cindex Loops
9585@findex while
9586
9587The @code{while} special form tests whether the value returned by
9588evaluating its first argument is true or false. This is similar to what
9589the Lisp interpreter does with an @code{if}; what the interpreter does
9590next, however, is different.
9591
9592In a @code{while} expression, if the value returned by evaluating the
9593first argument is false, the Lisp interpreter skips the rest of the
9594expression (the @dfn{body} of the expression) and does not evaluate it.
9595However, if the value is true, the Lisp interpreter evaluates the body
9596of the expression and then again tests whether the first argument to
9597@code{while} is true or false. If the value returned by evaluating the
9598first argument is again true, the Lisp interpreter again evaluates the
9599body of the expression.
9600
9601@need 1200
9602The template for a @code{while} expression looks like this:
9603
9604@smallexample
9605@group
9606(while @var{true-or-false-test}
9607 @var{body}@dots{})
9608@end group
9609@end smallexample
9610
9611@menu
9612* Looping with while:: Repeat so long as test returns true.
9613* Loop Example:: A @code{while} loop that uses a list.
9614* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
9615* Incrementing Loop:: A loop with an incrementing counter.
9616* Decrementing Loop:: A loop with a decrementing counter.
9617@end menu
9618
9619@node Looping with while, Loop Example, while, while
9620@ifnottex
9621@unnumberedsubsec Looping with @code{while}
9622@end ifnottex
9623
9624So long as the true-or-false-test of the @code{while} expression
9625returns a true value when it is evaluated, the body is repeatedly
9626evaluated. This process is called a loop since the Lisp interpreter
9627repeats the same thing again and again, like an airplane doing a loop.
9628When the result of evaluating the true-or-false-test is false, the
9629Lisp interpreter does not evaluate the rest of the @code{while}
9630expression and `exits the loop'.
9631
9632Clearly, if the value returned by evaluating the first argument to
9633@code{while} is always true, the body following will be evaluated
9634again and again @dots{} and again @dots{} forever. Conversely, if the
9635value returned is never true, the expressions in the body will never
9636be evaluated. The craft of writing a @code{while} loop consists of
9637choosing a mechanism such that the true-or-false-test returns true
9638just the number of times that you want the subsequent expressions to
9639be evaluated, and then have the test return false.
9640
9641The value returned by evaluating a @code{while} is the value of the
9642true-or-false-test. An interesting consequence of this is that a
9643@code{while} loop that evaluates without error will return @code{nil}
9644or false regardless of whether it has looped 1 or 100 times or none at
9645all. A @code{while} expression that evaluates successfully never
9646returns a true value! What this means is that @code{while} is always
9647evaluated for its side effects, which is to say, the consequences of
9648evaluating the expressions within the body of the @code{while} loop.
9649This makes sense. It is not the mere act of looping that is desired,
9650but the consequences of what happens when the expressions in the loop
9651are repeatedly evaluated.
9652
9653@node Loop Example, print-elements-of-list, Looping with while, while
9654@comment node-name, next, previous, up
9655@subsection A @code{while} Loop and a List
9656
9657A common way to control a @code{while} loop is to test whether a list
9658has any elements. If it does, the loop is repeated; but if it does not,
9659the repetition is ended. Since this is an important technique, we will
9660create a short example to illustrate it.
9661
9662A simple way to test whether a list has elements is to evaluate the
9663list: if it has no elements, it is an empty list and will return the
9664empty list, @code{()}, which is a synonym for @code{nil} or false. On
9665the other hand, a list with elements will return those elements when it
9666is evaluated. Since Emacs Lisp considers as true any value that is not
9667@code{nil}, a list that returns elements will test true in a
9668@code{while} loop.
9669
9670@need 1200
9671For example, you can set the variable @code{empty-list} to @code{nil} by
9672evaluating the following @code{setq} expression:
9673
9674@smallexample
9675(setq empty-list ())
9676@end smallexample
9677
9678@noindent
9679After evaluating the @code{setq} expression, you can evaluate the
9680variable @code{empty-list} in the usual way, by placing the cursor after
9681the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9682echo area:
9683
9684@smallexample
9685empty-list
9686@end smallexample
9687
9688On the other hand, if you set a variable to be a list with elements, the
9689list will appear when you evaluate the variable, as you can see by
9690evaluating the following two expressions:
9691
9692@smallexample
9693@group
9694(setq animals '(gazelle giraffe lion tiger))
9695
9696animals
9697@end group
9698@end smallexample
9699
9700Thus, to create a @code{while} loop that tests whether there are any
9701items in the list @code{animals}, the first part of the loop will be
9702written like this:
9703
9704@smallexample
9705@group
9706(while animals
9707 @dots{}
9708@end group
9709@end smallexample
9710
9711@noindent
9712When the @code{while} tests its first argument, the variable
9713@code{animals} is evaluated. It returns a list. So long as the list
9714has elements, the @code{while} considers the results of the test to be
9715true; but when the list is empty, it considers the results of the test
9716to be false.
9717
9718To prevent the @code{while} loop from running forever, some mechanism
9719needs to be provided to empty the list eventually. An oft-used
9720technique is to have one of the subsequent forms in the @code{while}
9721expression set the value of the list to be the @sc{cdr} of the list.
9722Each time the @code{cdr} function is evaluated, the list will be made
9723shorter, until eventually only the empty list will be left. At this
9724point, the test of the @code{while} loop will return false, and the
9725arguments to the @code{while} will no longer be evaluated.
9726
9727For example, the list of animals bound to the variable @code{animals}
9728can be set to be the @sc{cdr} of the original list with the
9729following expression:
9730
9731@smallexample
9732(setq animals (cdr animals))
9733@end smallexample
9734
9735@noindent
9736If you have evaluated the previous expressions and then evaluate this
9737expression, you will see @code{(giraffe lion tiger)} appear in the echo
9738area. If you evaluate the expression again, @code{(lion tiger)} will
9739appear in the echo area. If you evaluate it again and yet again,
9740@code{(tiger)} appears and then the empty list, shown by @code{nil}.
9741
9742A template for a @code{while} loop that uses the @code{cdr} function
9743repeatedly to cause the true-or-false-test eventually to test false
9744looks like this:
9745
9746@smallexample
9747@group
9748(while @var{test-whether-list-is-empty}
9749 @var{body}@dots{}
9750 @var{set-list-to-cdr-of-list})
9751@end group
9752@end smallexample
9753
9754This test and use of @code{cdr} can be put together in a function that
9755goes through a list and prints each element of the list on a line of its
9756own.
9757
9758@node print-elements-of-list, Incrementing Loop, Loop Example, while
9759@subsection An Example: @code{print-elements-of-list}
9760@findex print-elements-of-list
9761
9762The @code{print-elements-of-list} function illustrates a @code{while}
9763loop with a list.
9764
9765@cindex @file{*scratch*} buffer
9766The function requires several lines for its output. If you are
9767reading this in Emacs 21 or a later version, you can evaluate the
9768following expression inside of Info, as usual.
9769
9770If you are using an earlier version of Emacs, you need to copy the
9771necessary expressions to your @file{*scratch*} buffer and evaluate
9772them there. This is because the echo area had only one line in the
9773earlier versions.
9774
9775You can copy the expressions by marking the beginning of the region
9776with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9777the end of the region and then copying the region using @kbd{M-w}
9778(@code{copy-region-as-kill}). In the @file{*scratch*} buffer, you can
9779yank the expressions back by typing @kbd{C-y} (@code{yank}).
9780
9781After you have copied the expressions to the @file{*scratch*} buffer,
9782evaluate each expression in turn. Be sure to evaluate the last
9783expression, @code{(print-elements-of-list animals)}, by typing
9784@kbd{C-u C-x C-e}, that is, by giving an argument to
9785@code{eval-last-sexp}. This will cause the result of the evaluation
9786to be printed in the @file{*scratch*} buffer instead of being printed
9787in the echo area. (Otherwise you will see something like this in your
9788echo area: @code{^Jgiraffe^J^Jgazelle^J^Jlion^J^Jtiger^Jnil}, in which
9789each @samp{^J} stands for a `newline'.)
9790
9791@need 1500
9792If you are using Emacs 21 or later, you can evaluate these expressions
9793directly in the Info buffer, and the echo area will grow to show the
9794results.
9795
9796@smallexample
9797@group
9798(setq animals '(gazelle giraffe lion tiger))
9799
9800(defun print-elements-of-list (list)
9801 "Print each element of LIST on a line of its own."
9802 (while list
9803 (print (car list))
9804 (setq list (cdr list))))
9805
9806(print-elements-of-list animals)
9807@end group
9808@end smallexample
9809
9810@need 1200
9811@noindent
9812When you evaluate the three expressions in sequence, you will see
9813this:
9814
9815@smallexample
9816@group
9817giraffe
9818
9819gazelle
9820
9821lion
9822
9823tiger
9824nil
9825@end group
9826@end smallexample
9827
9828Each element of the list is printed on a line of its own (that is what
9829the function @code{print} does) and then the value returned by the
9830function is printed. Since the last expression in the function is the
9831@code{while} loop, and since @code{while} loops always return
9832@code{nil}, a @code{nil} is printed after the last element of the list.
9833
9834@node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9835@comment node-name, next, previous, up
9836@subsection A Loop with an Incrementing Counter
9837
9838A loop is not useful unless it stops when it ought. Besides
9839controlling a loop with a list, a common way of stopping a loop is to
9840write the first argument as a test that returns false when the correct
9841number of repetitions are complete. This means that the loop must
9842have a counter---an expression that counts how many times the loop
9843repeats itself.
9844
9845The test can be an expression such as @code{(< count desired-number)}
9846which returns @code{t} for true if the value of @code{count} is less
9847than the @code{desired-number} of repetitions and @code{nil} for false if
9848the value of @code{count} is equal to or is greater than the
9849@code{desired-number}. The expression that increments the count can be
9850a simple @code{setq} such as @code{(setq count (1+ count))}, where
9851@code{1+} is a built-in function in Emacs Lisp that adds 1 to its
9852argument. (The expression @code{(1+ count)} has the same result as
9853@code{(+ count 1)}, but is easier for a human to read.)
9854
9855@need 1250
9856The template for a @code{while} loop controlled by an incrementing
9857counter looks like this:
9858
9859@smallexample
9860@group
9861@var{set-count-to-initial-value}
9862(while (< count desired-number) ; @r{true-or-false-test}
9863 @var{body}@dots{}
9864 (setq count (1+ count))) ; @r{incrementer}
9865@end group
9866@end smallexample
9867
9868@noindent
9869Note that you need to set the initial value of @code{count}; usually it
9870is set to 1.
9871
9872@menu
9873* Incrementing Example:: Counting pebbles in a triangle.
9874* Inc Example parts:: The parts of the function definition.
9875* Inc Example altogether:: Putting the function definition together.
9876@end menu
9877
9878@node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9879@unnumberedsubsubsec Example with incrementing counter
9880
9881Suppose you are playing on the beach and decide to make a triangle of
9882pebbles, putting one pebble in the first row, two in the second row,
9883three in the third row and so on, like this:
9884
9885@sp 1
9886@c pebble diagram
9887@ifnottex
9888@smallexample
9889@group
9890 *
9891 * *
9892 * * *
9893 * * * *
9894@end group
9895@end smallexample
9896@end ifnottex
9897@iftex
9898@smallexample
9899@group
9900 @bullet{}
9901 @bullet{} @bullet{}
9902 @bullet{} @bullet{} @bullet{}
9903 @bullet{} @bullet{} @bullet{} @bullet{}
9904@end group
9905@end smallexample
9906@end iftex
9907@sp 1
9908
9909@noindent
9910(About 2500 years ago, Pythagoras and others developed the beginnings of
9911number theory by considering questions such as this.)
9912
9913Suppose you want to know how many pebbles you will need to make a
9914triangle with 7 rows?
9915
9916Clearly, what you need to do is add up the numbers from 1 to 7. There
9917are two ways to do this; start with the smallest number, one, and add up
9918the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9919number and add the list going down: 7, 6, 5, 4 and so on. Because both
9920mechanisms illustrate common ways of writing @code{while} loops, we will
9921create two examples, one counting up and the other counting down. In
9922this first example, we will start with 1 and add 2, 3, 4 and so on.
9923
9924If you are just adding up a short list of numbers, the easiest way to do
9925it is to add up all the numbers at once. However, if you do not know
9926ahead of time how many numbers your list will have, or if you want to be
9927prepared for a very long list, then you need to design your addition so
9928that what you do is repeat a simple process many times instead of doing
9929a more complex process once.
9930
9931For example, instead of adding up all the pebbles all at once, what you
9932can do is add the number of pebbles in the first row, 1, to the number
9933in the second row, 2, and then add the total of those two rows to the
9934third row, 3. Then you can add the number in the fourth row, 4, to the
9935total of the first three rows; and so on.
9936
9937The critical characteristic of the process is that each repetitive
9938action is simple. In this case, at each step we add only two numbers,
9939the number of pebbles in the row and the total already found. This
9940process of adding two numbers is repeated again and again until the last
9941row has been added to the total of all the preceding rows. In a more
9942complex loop the repetitive action might not be so simple, but it will
9943be simpler than doing everything all at once.
9944
9945@node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9946@unnumberedsubsubsec The parts of the function definition
9947
9948The preceding analysis gives us the bones of our function definition:
9949first, we will need a variable that we can call @code{total} that will
9950be the total number of pebbles. This will be the value returned by
9951the function.
9952
9953Second, we know that the function will require an argument: this
9954argument will be the total number of rows in the triangle. It can be
9955called @code{number-of-rows}.
9956
9957Finally, we need a variable to use as a counter. We could call this
9958variable @code{counter}, but a better name is @code{row-number}.
9959That is because what the counter does is count rows, and a program
9960should be written to be as understandable as possible.
9961
9962When the Lisp interpreter first starts evaluating the expressions in the
9963function, the value of @code{total} should be set to zero, since we have
9964not added anything to it. Then the function should add the number of
9965pebbles in the first row to the total, and then add the number of
9966pebbles in the second to the total, and then add the number of
9967pebbles in the third row to the total, and so on, until there are no
9968more rows left to add.
9969
9970Both @code{total} and @code{row-number} are used only inside the
9971function, so they can be declared as local variables with @code{let}
9972and given initial values. Clearly, the initial value for @code{total}
9973should be 0. The initial value of @code{row-number} should be 1,
9974since we start with the first row. This means that the @code{let}
9975statement will look like this:
9976
9977@smallexample
9978@group
9979 (let ((total 0)
9980 (row-number 1))
9981 @var{body}@dots{})
9982@end group
9983@end smallexample
9984
9985After the internal variables are declared and bound to their initial
9986values, we can begin the @code{while} loop. The expression that serves
9987as the test should return a value of @code{t} for true so long as the
9988@code{row-number} is less than or equal to the @code{number-of-rows}.
9989(If the expression tests true only so long as the row number is less
9990than the number of rows in the triangle, the last row will never be
9991added to the total; hence the row number has to be either less than or
9992equal to the number of rows.)
9993
9994@need 1500
9995@findex <= @r{(less than or equal)}
9996Lisp provides the @code{<=} function that returns true if the value of
9997its first argument is less than or equal to the value of its second
9998argument and false otherwise. So the expression that the @code{while}
9999will evaluate as its test should look like this:
10000
10001@smallexample
10002(<= row-number number-of-rows)
10003@end smallexample
10004
10005The total number of pebbles can be found by repeatedly adding the number
10006of pebbles in a row to the total already found. Since the number of
10007pebbles in the row is equal to the row number, the total can be found by
10008adding the row number to the total. (Clearly, in a more complex
10009situation, the number of pebbles in the row might be related to the row
10010number in a more complicated way; if this were the case, the row number
10011would be replaced by the appropriate expression.)
10012
10013@smallexample
10014(setq total (+ total row-number))
10015@end smallexample
10016
10017@noindent
10018What this does is set the new value of @code{total} to be equal to the
10019sum of adding the number of pebbles in the row to the previous total.
10020
10021After setting the value of @code{total}, the conditions need to be
10022established for the next repetition of the loop, if there is one. This
10023is done by incrementing the value of the @code{row-number} variable,
10024which serves as a counter. After the @code{row-number} variable has
10025been incremented, the true-or-false-test at the beginning of the
10026@code{while} loop tests whether its value is still less than or equal to
10027the value of the @code{number-of-rows} and if it is, adds the new value
10028of the @code{row-number} variable to the @code{total} of the previous
10029repetition of the loop.
10030
10031@need 1200
10032The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10033@code{row-number} variable can be incremented with this expression:
10034
10035@smallexample
10036(setq row-number (1+ row-number))
10037@end smallexample
10038
10039@node Inc Example altogether, , Inc Example parts, Incrementing Loop
10040@unnumberedsubsubsec Putting the function definition together
10041
10042We have created the parts for the function definition; now we need to
10043put them together.
10044
10045@need 800
10046First, the contents of the @code{while} expression:
10047
10048@smallexample
10049@group
10050(while (<= row-number number-of-rows) ; @r{true-or-false-test}
10051 (setq total (+ total row-number))
10052 (setq row-number (1+ row-number))) ; @r{incrementer}
10053@end group
10054@end smallexample
10055
10056Along with the @code{let} expression varlist, this very nearly
10057completes the body of the function definition. However, it requires
10058one final element, the need for which is somewhat subtle.
10059
10060The final touch is to place the variable @code{total} on a line by
10061itself after the @code{while} expression. Otherwise, the value returned
10062by the whole function is the value of the last expression that is
10063evaluated in the body of the @code{let}, and this is the value
10064returned by the @code{while}, which is always @code{nil}.
10065
10066This may not be evident at first sight. It almost looks as if the
10067incrementing expression is the last expression of the whole function.
10068But that expression is part of the body of the @code{while}; it is the
10069last element of the list that starts with the symbol @code{while}.
10070Moreover, the whole of the @code{while} loop is a list within the body
10071of the @code{let}.
10072
10073@need 1250
10074In outline, the function will look like this:
10075
10076@smallexample
10077@group
10078(defun @var{name-of-function} (@var{argument-list})
10079 "@var{documentation}@dots{}"
10080 (let (@var{varlist})
10081 (while (@var{true-or-false-test})
10082 @var{body-of-while}@dots{} )
10083 @dots{} ) ; @r{Need final expression here.}
10084@end group
10085@end smallexample
10086
10087The result of evaluating the @code{let} is what is going to be returned
10088by the @code{defun} since the @code{let} is not embedded within any
10089containing list, except for the @code{defun} as a whole. However, if
10090the @code{while} is the last element of the @code{let} expression, the
10091function will always return @code{nil}. This is not what we want!
10092Instead, what we want is the value of the variable @code{total}. This
10093is returned by simply placing the symbol as the last element of the list
10094starting with @code{let}. It gets evaluated after the preceding
10095elements of the list are evaluated, which means it gets evaluated after
10096it has been assigned the correct value for the total.
10097
10098It may be easier to see this by printing the list starting with
10099@code{let} all on one line. This format makes it evident that the
10100@var{varlist} and @code{while} expressions are the second and third
10101elements of the list starting with @code{let}, and the @code{total} is
10102the last element:
10103
10104@smallexample
10105@group
10106(let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10107@end group
10108@end smallexample
10109
10110@need 1200
10111Putting everything together, the @code{triangle} function definition
10112looks like this:
10113
10114@smallexample
10115@group
10116(defun triangle (number-of-rows) ; @r{Version with}
10117 ; @r{ incrementing counter.}
10118 "Add up the number of pebbles in a triangle.
10119The first row has one pebble, the second row two pebbles,
10120the third row three pebbles, and so on.
10121The argument is NUMBER-OF-ROWS."
10122@end group
10123@group
10124 (let ((total 0)
10125 (row-number 1))
10126 (while (<= row-number number-of-rows)
10127 (setq total (+ total row-number))
10128 (setq row-number (1+ row-number)))
10129 total))
10130@end group
10131@end smallexample
10132
10133@need 1200
10134After you have installed @code{triangle} by evaluating the function, you
10135can try it out. Here are two examples:
10136
10137@smallexample
10138@group
10139(triangle 4)
10140
10141(triangle 7)
10142@end group
10143@end smallexample
10144
10145@noindent
10146The sum of the first four numbers is 10 and the sum of the first seven
10147numbers is 28.
10148
10149@node Decrementing Loop, , Incrementing Loop, while
10150@comment node-name, next, previous, up
10151@subsection Loop with a Decrementing Counter
10152
10153Another common way to write a @code{while} loop is to write the test
10154so that it determines whether a counter is greater than zero. So long
10155as the counter is greater than zero, the loop is repeated. But when
10156the counter is equal to or less than zero, the loop is stopped. For
10157this to work, the counter has to start out greater than zero and then
10158be made smaller and smaller by a form that is evaluated
10159repeatedly.
10160
10161The test will be an expression such as @code{(> counter 0)} which
10162returns @code{t} for true if the value of @code{counter} is greater
10163than zero, and @code{nil} for false if the value of @code{counter} is
10164equal to or less than zero. The expression that makes the number
10165smaller and smaller can be a simple @code{setq} such as @code{(setq
10166counter (1- counter))}, where @code{1-} is a built-in function in
10167Emacs Lisp that subtracts 1 from its argument.
10168
10169@need 1250
10170The template for a decrementing @code{while} loop looks like this:
10171
10172@smallexample
10173@group
10174(while (> counter 0) ; @r{true-or-false-test}
10175 @var{body}@dots{}
10176 (setq counter (1- counter))) ; @r{decrementer}
10177@end group
10178@end smallexample
10179
10180@menu
10181* Decrementing Example:: More pebbles on the beach.
10182* Dec Example parts:: The parts of the function definition.
10183* Dec Example altogether:: Putting the function definition together.
10184@end menu
10185
10186@node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10187@unnumberedsubsubsec Example with decrementing counter
10188
10189To illustrate a loop with a decrementing counter, we will rewrite the
10190@code{triangle} function so the counter decreases to zero.
10191
10192This is the reverse of the earlier version of the function. In this
10193case, to find out how many pebbles are needed to make a triangle with
101943 rows, add the number of pebbles in the third row, 3, to the number
10195in the preceding row, 2, and then add the total of those two rows to
10196the row that precedes them, which is 1.
10197
10198Likewise, to find the number of pebbles in a triangle with 7 rows, add
10199the number of pebbles in the seventh row, 7, to the number in the
10200preceding row, which is 6, and then add the total of those two rows to
10201the row that precedes them, which is 5, and so on. As in the previous
10202example, each addition only involves adding two numbers, the total of
10203the rows already added up and the number of pebbles in the row that is
10204being added to the total. This process of adding two numbers is
10205repeated again and again until there are no more pebbles to add.
10206
10207We know how many pebbles to start with: the number of pebbles in the
10208last row is equal to the number of rows. If the triangle has seven
10209rows, the number of pebbles in the last row is 7. Likewise, we know how
10210many pebbles are in the preceding row: it is one less than the number in
10211the row.
10212
10213@node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10214@unnumberedsubsubsec The parts of the function definition
10215
10216We start with three variables: the total number of rows in the
10217triangle; the number of pebbles in a row; and the total number of
10218pebbles, which is what we want to calculate. These variables can be
10219named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10220@code{total}, respectively.
10221
10222Both @code{total} and @code{number-of-pebbles-in-row} are used only
10223inside the function and are declared with @code{let}. The initial
10224value of @code{total} should, of course, be zero. However, the
10225initial value of @code{number-of-pebbles-in-row} should be equal to
10226the number of rows in the triangle, since the addition will start with
10227the longest row.
10228
10229@need 1250
10230This means that the beginning of the @code{let} expression will look
10231like this:
10232
10233@smallexample
10234@group
10235(let ((total 0)
10236 (number-of-pebbles-in-row number-of-rows))
10237 @var{body}@dots{})
10238@end group
10239@end smallexample
10240
10241The total number of pebbles can be found by repeatedly adding the number
10242of pebbles in a row to the total already found, that is, by repeatedly
10243evaluating the following expression:
10244
10245@smallexample
10246(setq total (+ total number-of-pebbles-in-row))
10247@end smallexample
10248
10249@noindent
10250After the @code{number-of-pebbles-in-row} is added to the @code{total},
10251the @code{number-of-pebbles-in-row} should be decremented by one, since
10252the next time the loop repeats, the preceding row will be
10253added to the total.
10254
10255The number of pebbles in a preceding row is one less than the number of
10256pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10257used to compute the number of pebbles in the preceding row. This can be
10258done with the following expression:
10259
10260@smallexample
10261@group
10262(setq number-of-pebbles-in-row
10263 (1- number-of-pebbles-in-row))
10264@end group
10265@end smallexample
10266
10267Finally, we know that the @code{while} loop should stop making repeated
10268additions when there are no pebbles in a row. So the test for
10269the @code{while} loop is simply:
10270
10271@smallexample
10272(while (> number-of-pebbles-in-row 0)
10273@end smallexample
10274
10275@node Dec Example altogether, , Dec Example parts, Decrementing Loop
10276@unnumberedsubsubsec Putting the function definition together
10277
10278We can put these expressions together to create a function definition
10279that works. However, on examination, we find that one of the local
10280variables is unneeded!
10281
10282@need 1250
10283The function definition looks like this:
10284
10285@smallexample
10286@group
10287;;; @r{First subtractive version.}
10288(defun triangle (number-of-rows)
10289 "Add up the number of pebbles in a triangle."
10290 (let ((total 0)
10291 (number-of-pebbles-in-row number-of-rows))
10292 (while (> number-of-pebbles-in-row 0)
10293 (setq total (+ total number-of-pebbles-in-row))
10294 (setq number-of-pebbles-in-row
10295 (1- number-of-pebbles-in-row)))
10296 total))
10297@end group
10298@end smallexample
10299
10300As written, this function works.
10301
10302However, we do not need @code{number-of-pebbles-in-row}.
10303
10304@cindex Argument as local variable
10305When the @code{triangle} function is evaluated, the symbol
10306@code{number-of-rows} will be bound to a number, giving it an initial
10307value. That number can be changed in the body of the function as if
10308it were a local variable, without any fear that such a change will
10309effect the value of the variable outside of the function. This is a
10310very useful characteristic of Lisp; it means that the variable
10311@code{number-of-rows} can be used anywhere in the function where
10312@code{number-of-pebbles-in-row} is used.
10313
10314@need 800
10315Here is a second version of the function written a bit more cleanly:
10316
10317@smallexample
10318@group
10319(defun triangle (number) ; @r{Second version.}
10320 "Return sum of numbers 1 through NUMBER inclusive."
10321 (let ((total 0))
10322 (while (> number 0)
10323 (setq total (+ total number))
10324 (setq number (1- number)))
10325 total))
10326@end group
10327@end smallexample
10328
10329In brief, a properly written @code{while} loop will consist of three parts:
10330
10331@enumerate
10332@item
10333A test that will return false after the loop has repeated itself the
10334correct number of times.
10335
10336@item
10337An expression the evaluation of which will return the value desired
10338after being repeatedly evaluated.
10339
10340@item
10341An expression to change the value passed to the true-or-false-test so
10342that the test returns false after the loop has repeated itself the right
10343number of times.
10344@end enumerate
10345
10346@node dolist dotimes, Recursion, while, Loops & Recursion
10347@comment node-name, next, previous, up
10348@section Save your time: @code{dolist} and @code{dotimes}
10349
10350In addition to @code{while}, both @code{dolist} and @code{dotimes}
10351provide for looping. Sometimes these are quicker to write than the
10352equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
10353Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10354
10355@code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10356list': @code{dolist} automatically shortens the list each time it
10357loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10358each shorter version of the list to the first of its arguments.
10359
10360@code{dotimes} loops a specific number of time: you specify the number.
10361
10362@menu
10363* dolist::
10364* dotimes::
10365@end menu
10366
10367@node dolist, dotimes, dolist dotimes, dolist dotimes
10368@unnumberedsubsubsec The @code{dolist} Macro
10369@findex dolist
10370
10371Suppose, for example, you want to reverse a list, so that
10372``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10373
10374@need 1250
10375In practice, you would use the @code{reverse} function, like this:
10376
10377@smallexample
10378@group
10379(setq animals '(gazelle giraffe lion tiger))
10380
10381(reverse animals)
10382@end group
10383@end smallexample
10384
10385@need 800
10386@noindent
10387Here is how you could reverse the list using a @code{while} loop:
10388
10389@smallexample
10390@group
10391(setq animals '(gazelle giraffe lion tiger))
10392
10393(defun reverse-list-with-while (list)
10394 "Using while, reverse the order of LIST."
10395 (let (value) ; make sure list starts empty
10396 (while list
10397 (setq value (cons (car list) value))
10398 (setq list (cdr list)))
10399 value))
10400
10401(reverse-list-with-while animals)
10402@end group
10403@end smallexample
10404
10405@need 800
10406@noindent
10407And here is how you could use the @code{dolist} macro:
10408
10409@smallexample
10410@group
10411(setq animals '(gazelle giraffe lion tiger))
10412
10413(defun reverse-list-with-dolist (list)
10414 "Using dolist, reverse the order of LIST."
10415 (let (value) ; make sure list starts empty
10416 (dolist (element list value)
10417 (setq value (cons element value)))))
10418
10419(reverse-list-with-dolist animals)
10420@end group
10421@end smallexample
10422
10423@need 1250
10424@noindent
10425In Info, you can place your cursor after the closing parenthesis of
10426each expression and type @kbd{C-x C-e}; in each case, you should see
10427
10428@smallexample
10429(tiger lion giraffe gazelle)
10430@end smallexample
10431
10432@noindent
10433in the echo area.
10434
10435For this example, the existing @code{reverse} function is obviously best.
10436The @code{while} loop is just like our first example (@pxref{Loop
10437Example, , A @code{while} Loop and a List}). The @code{while} first
10438checks whether the list has elements; if so, it constructs a new list
10439by adding the first element of the list to the existing list (which in
10440the first iteration of the loop is @code{nil}). Since the second
10441element is prepended in front of the first element, and the third
10442element is prepended in front of the second element, the list is reversed.
10443
10444In the expression using a @code{while} loop,
10445the @w{@code{(setq list (cdr list))}}
10446expression shortens the list, so the @code{while} loop eventually
10447stops. In addition, it provides the @code{cons} expression with a new
10448first element by creating a new and shorter list at each repetition of
10449the loop.
10450
10451The @code{dolist} expression does very much the same as the
10452@code{while} expression, except that the @code{dolist} macro does some
10453of the work you have to do when writing a @code{while} expression.
10454
10455Like a @code{while} loop, a @code{dolist} loops. What is different is
10456that it automatically shortens the list each time it loops --- it
10457`@sc{cdr}s down the list' on its own --- and it automatically binds
10458the @sc{car} of each shorter version of the list to the first of its
10459arguments.
10460
10461In the example, the @sc{car} of each shorter version of the list is
10462referred to using the symbol @samp{element}, the list itself is called
10463@samp{list}, and the value returned is called @samp{value}. The
10464remainder of the @code{dolist} expression is the body.
10465
10466The @code{dolist} expression binds the @sc{car} of each shorter
10467version of the list to @code{element} and then evaluates the body of
10468the expression; and repeats the loop. The result is returned in
10469@code{value}.
10470
10471@node dotimes, , dolist, dolist dotimes
10472@unnumberedsubsubsec The @code{dotimes} Macro
10473@findex dotimes
10474
10475The @code{dotimes} macro is similar to @code{dolist}, except that it
10476loops a specific number of times.
10477
10478The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10479and so forth each time around the loop, and the value of the third
10480argument is returned. You need to provide the value of the second
10481argument, which is how many times the macro loops.
10482
10483@need 1250
10484For example, the following binds the numbers from 0 up to, but not
10485including, the number 3 to the first argument, @var{number}, and then
10486constructs a list of the three numbers. (The first number is 0, the
10487second number is 1, and the third number is 2; this makes a total of
10488three numbers in all, starting with zero as the first number.)
10489
10490@smallexample
10491@group
10492(let (value) ; otherwise a value is a void variable
10493 (dotimes (number 3 value)
10494 (setq value (cons number value))))
10495
10496@result{} (2 1 0)
10497@end group
10498@end smallexample
10499
10500@noindent
10501@code{dotimes} returns @code{value}, so the way to use
10502@code{dotimes} is to operate on some expression @var{number} number of
10503times and then return the result, either as a list or an atom.
10504
10505@need 1250
10506Here is an example of a @code{defun} that uses @code{dotimes} to add
10507up the number of pebbles in a triangle.
10508
10509@smallexample
10510@group
10511(defun triangle-using-dotimes (number-of-rows)
10512 "Using dotimes, add up the number of pebbles in a triangle."
10513(let ((total 0)) ; otherwise a total is a void variable
10514 (dotimes (number number-of-rows total)
10515 (setq total (+ total (1+ number))))))
10516
10517(triangle-using-dotimes 4)
10518@end group
10519@end smallexample
10520
10521@node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10522@comment node-name, next, previous, up
10523@section Recursion
10524@cindex Recursion
10525
10526A recursive function contains code that tells the Lisp interpreter to
10527call a program that runs exactly like itself, but with slightly
10528different arguments. The code runs exactly the same because it has
10529the same name. However, even though it has the same name, it is not
10530the same thread of execution. It is different. In the jargon, it is
10531a different `instance'.
10532
10533Eventually, if the program is written correctly, the `slightly
10534different arguments' will become sufficiently different from the first
10535arguments that the final instance will stop.
10536
10537@menu
10538* Building Robots:: Same model, different serial number ...
10539* Recursive Definition Parts:: Walk until you stop ...
10540* Recursion with list:: Using a list as the test whether to recurse.
10541* Recursive triangle function::
10542* Recursion with cond::
10543* Recursive Patterns:: Often used templates.
10544* No Deferment:: Don't store up work ...
10545* No deferment solution::
10546@end menu
10547
10548@node Building Robots, Recursive Definition Parts, Recursion, Recursion
10549@comment node-name, next, previous, up
10550@subsection Building Robots: Extending the Metaphor
10551@cindex Building robots
10552@cindex Robots, building
10553
10554It is sometimes helpful to think of a running program as a robot that
10555does a job. In doing its job, a recursive function calls on a second
10556robot to help it. The second robot is identical to the first in every
10557way, except that the second robot helps the first and has been
10558passed different arguments than the first.
10559
10560In a recursive function, the second robot may call a third; and the
10561third may call a fourth, and so on. Each of these is a different
10562entity; but all are clones.
10563
10564Since each robot has slightly different instructions---the arguments
10565will differ from one robot to the next---the last robot should know
10566when to stop.
10567
10568Let's expand on the metaphor in which a computer program is a robot.
10569
10570A function definition provides the blueprints for a robot. When you
10571install a function definition, that is, when you evaluate a
10572@code{defun} special form, you install the necessary equipment to
10573build robots. It is as if you were in a factory, setting up an
10574assembly line. Robots with the same name are built according to the
10575same blueprints. So they have, as it were, the same `model number',
10576but a different `serial number'.
10577
10578We often say that a recursive function `calls itself'. What we mean
10579is that the instructions in a recursive function cause the Lisp
10580interpreter to run a different function that has the same name and
10581does the same job as the first, but with different arguments.
10582
10583It is important that the arguments differ from one instance to the
10584next; otherwise, the process will never stop.
10585
10586@node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10587@comment node-name, next, previous, up
10588@subsection The Parts of a Recursive Definition
10589@cindex Parts of a Recursive Definition
10590@cindex Recursive Definition Parts
10591
10592A recursive function typically contains a conditional expression which
10593has three parts:
10594
10595@enumerate
10596@item
10597A true-or-false-test that determines whether the function is called
10598again, here called the @dfn{do-again-test}.
10599
10600@item
10601The name of the function. When this name is called, a new instance of
10602the function---a new robot, as it were---is created and told what to do.
10603
10604@item
10605An expression that returns a different value each time the function is
10606called, here called the @dfn{next-step-expression}. Consequently, the
10607argument (or arguments) passed to the new instance of the function
10608will be different from that passed to the previous instance. This
10609causes the conditional expression, the @dfn{do-again-test}, to test
10610false after the correct number of repetitions.
10611@end enumerate
10612
10613Recursive functions can be much simpler than any other kind of
10614function. Indeed, when people first start to use them, they often look
10615so mysteriously simple as to be incomprehensible. Like riding a
10616bicycle, reading a recursive function definition takes a certain knack
10617which is hard at first but then seems simple.
10618
10619@need 1200
10620There are several different common recursive patterns. A very simple
10621pattern looks like this:
10622
10623@smallexample
10624@group
10625(defun @var{name-of-recursive-function} (@var{argument-list})
10626 "@var{documentation}@dots{}"
10627 (if @var{do-again-test}
10628 @var{body}@dots{}
10629 (@var{name-of-recursive-function}
10630 @var{next-step-expression})))
10631@end group
10632@end smallexample
10633
10634Each time a recursive function is evaluated, a new instance of it is
10635created and told what to do. The arguments tell the instance what to do.
10636
10637An argument is bound to the value of the next-step-expression. Each
10638instance runs with a different value of the next-step-expression.
10639
10640The value in the next-step-expression is used in the do-again-test.
10641
10642The value returned by the next-step-expression is passed to the new
10643instance of the function, which evaluates it (or some
10644transmogrification of it) to determine whether to continue or stop.
10645The next-step-expression is designed so that the do-again-test returns
10646false when the function should no longer be repeated.
10647
10648The do-again-test is sometimes called the @dfn{stop condition},
10649since it stops the repetitions when it tests false.
10650
10651@node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10652@comment node-name, next, previous, up
10653@subsection Recursion with a List
10654
10655The example of a @code{while} loop that printed the elements of a list
10656of numbers can be written recursively. Here is the code, including
10657an expression to set the value of the variable @code{animals} to a list.
10658
10659If you are using Emacs 20 or before, this example must be copied to
10660the @file{*scratch*} buffer and each expression must be evaluated
10661there. Use @kbd{C-u C-x C-e} to evaluate the
10662@code{(print-elements-recursively animals)} expression so that the
10663results are printed in the buffer; otherwise the Lisp interpreter will
10664try to squeeze the results into the one line of the echo area.
10665
10666Also, place your cursor immediately after the last closing parenthesis
10667of the @code{print-elements-recursively} function, before the comment.
10668Otherwise, the Lisp interpreter will try to evaluate the comment.
10669
10670If you are using Emacs 21 or later, you can evaluate this expression
10671directly in Info.
10672
10673@findex print-elements-recursively
10674@smallexample
10675@group
10676(setq animals '(gazelle giraffe lion tiger))
10677
10678(defun print-elements-recursively (list)
10679 "Print each element of LIST on a line of its own.
10680Uses recursion."
10681 (if list ; @r{do-again-test}
10682 (progn
10683 (print (car list)) ; @r{body}
10684 (print-elements-recursively ; @r{recursive call}
10685 (cdr list))))) ; @r{next-step-expression}
10686
10687(print-elements-recursively animals)
10688@end group
10689@end smallexample
10690
10691The @code{print-elements-recursively} function first tests whether
10692there is any content in the list; if there is, the function prints the
10693first element of the list, the @sc{car} of the list. Then the
10694function `invokes itself', but gives itself as its argument, not the
10695whole list, but the second and subsequent elements of the list, the
10696@sc{cdr} of the list.
10697
10698Put another way, if the list is not empty, the function invokes
10699another instance of code that is similar to the initial code, but is a
10700different thread of execution, with different arguments than the first
10701instance.
10702
10703Put in yet another way, if the list is not empty, the first robot
10704assemblies a second robot and tells it what to do; the second robot is
10705a different individual from the first, but is the same model.
10706
10707When the second evaluation occurs, the @code{if} expression is
10708evaluated and if true, prints the first element of the list it
10709receives as its argument (which is the second element of the original
10710list). Then the function `calls itself' with the @sc{cdr} of the list
10711it is invoked with, which (the second time around) is the @sc{cdr} of
10712the @sc{cdr} of the original list.
10713
10714Note that although we say that the function `calls itself', what we
10715mean is that the Lisp interpreter assembles and instructs a new
10716instance of the program. The new instance is a clone of the first,
10717but is a separate individual.
10718
10719Each time the function `invokes itself', it invokes itself on a
10720shorter version of the original list. It creates a new instance that
10721works on a shorter list.
10722
10723Eventually, the function invokes itself on an empty list. It creates
10724a new instance whose argument is @code{nil}. The conditional expression
10725tests the value of @code{list}. Since the value of @code{list} is
10726@code{nil}, the @code{if} expression tests false so the then-part is
10727not evaluated. The function as a whole then returns @code{nil}.
10728
10729@need 1200
10730When you evaluate @code{(print-elements-recursively animals)} in the
10731@file{*scratch*} buffer, you see this result:
10732
10733@smallexample
10734@group
10735giraffe
10736
10737gazelle
10738
10739lion
10740
10741tiger
10742nil
10743@end group
10744@end smallexample
10745
10746@node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10747@comment node-name, next, previous, up
10748@subsection Recursion in Place of a Counter
10749@findex triangle-recursively
10750
10751@need 1200
10752The @code{triangle} function described in a previous section can also
10753be written recursively. It looks like this:
10754
10755@smallexample
10756@group
10757(defun triangle-recursively (number)
10758 "Return the sum of the numbers 1 through NUMBER inclusive.
10759Uses recursion."
10760 (if (= number 1) ; @r{do-again-test}
10761 1 ; @r{then-part}
10762 (+ number ; @r{else-part}
10763 (triangle-recursively ; @r{recursive call}
10764 (1- number))))) ; @r{next-step-expression}
10765
10766(triangle-recursively 7)
10767@end group
10768@end smallexample
10769
10770@noindent
10771You can install this function by evaluating it and then try it by
10772evaluating @code{(triangle-recursively 7)}. (Remember to put your
10773cursor immediately after the last parenthesis of the function
10774definition, before the comment.) The function evaluates to 28.
10775
10776To understand how this function works, let's consider what happens in the
10777various cases when the function is passed 1, 2, 3, or 4 as the value of
10778its argument.
10779
10780@menu
10781* Recursive Example arg of 1 or 2::
10782* Recursive Example arg of 3 or 4::
10783@end menu
10784
10785@node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10786@ifnottex
10787@unnumberedsubsubsec An argument of 1 or 2
10788@end ifnottex
10789
10790First, what happens if the value of the argument is 1?
10791
10792The function has an @code{if} expression after the documentation
10793string. It tests whether the value of @code{number} is equal to 1; if
10794so, Emacs evaluates the then-part of the @code{if} expression, which
10795returns the number 1 as the value of the function. (A triangle with
10796one row has one pebble in it.)
10797
10798Suppose, however, that the value of the argument is 2. In this case,
10799Emacs evaluates the else-part of the @code{if} expression.
10800
10801@need 1200
10802The else-part consists of an addition, the recursive call to
10803@code{triangle-recursively} and a decrementing action; and it looks like
10804this:
10805
10806@smallexample
10807(+ number (triangle-recursively (1- number)))
10808@end smallexample
10809
10810When Emacs evaluates this expression, the innermost expression is
10811evaluated first; then the other parts in sequence. Here are the steps
10812in detail:
10813
10814@table @i
10815@item Step 1 @w{ } Evaluate the innermost expression.
10816
10817The innermost expression is @code{(1- number)} so Emacs decrements the
10818value of @code{number} from 2 to 1.
10819
10820@item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
10821
10822The Lisp interpreter creates an individual instance of
10823@code{triangle-recursively}. It does not matter that this function is
10824contained within itself. Emacs passes the result Step 1 as the
10825argument used by this instance of the @code{triangle-recursively}
10826function
10827
10828In this case, Emacs evaluates @code{triangle-recursively} with an
10829argument of 1. This means that this evaluation of
10830@code{triangle-recursively} returns 1.
10831
10832@item Step 3 @w{ } Evaluate the value of @code{number}.
10833
10834The variable @code{number} is the second element of the list that
10835starts with @code{+}; its value is 2.
10836
10837@item Step 4 @w{ } Evaluate the @code{+} expression.
10838
10839The @code{+} expression receives two arguments, the first
10840from the evaluation of @code{number} (Step 3) and the second from the
10841evaluation of @code{triangle-recursively} (Step 2).
10842
10843The result of the addition is the sum of 2 plus 1, and the number 3 is
10844returned, which is correct. A triangle with two rows has three
10845pebbles in it.
10846@end table
10847
10848@node Recursive Example arg of 3 or 4, , Recursive Example arg of 1 or 2, Recursive triangle function
10849@unnumberedsubsubsec An argument of 3 or 4
10850
10851Suppose that @code{triangle-recursively} is called with an argument of
108523.
10853
10854@table @i
10855@item Step 1 @w{ } Evaluate the do-again-test.
10856
10857The @code{if} expression is evaluated first. This is the do-again
10858test and returns false, so the else-part of the @code{if} expression
10859is evaluated. (Note that in this example, the do-again-test causes
10860the function to call itself when it tests false, not when it tests
10861true.)
10862
10863@item Step 2 @w{ } Evaluate the innermost expression of the else-part.
10864
10865The innermost expression of the else-part is evaluated, which decrements
108663 to 2. This is the next-step-expression.
10867
10868@item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
10869
10870The number 2 is passed to the @code{triangle-recursively} function.
10871
10872We know what happens when Emacs evaluates @code{triangle-recursively} with
10873an argument of 2. After going through the sequence of actions described
10874earlier, it returns a value of 3. So that is what will happen here.
10875
10876@item Step 4 @w{ } Evaluate the addition.
10877
108783 will be passed as an argument to the addition and will be added to the
10879number with which the function was called, which is 3.
10880@end table
10881
10882@noindent
10883The value returned by the function as a whole will be 6.
10884
10885Now that we know what will happen when @code{triangle-recursively} is
10886called with an argument of 3, it is evident what will happen if it is
10887called with an argument of 4:
10888
10889@quotation
10890@need 800
10891In the recursive call, the evaluation of
10892
10893@smallexample
10894(triangle-recursively (1- 4))
10895@end smallexample
10896
10897@need 800
10898@noindent
10899will return the value of evaluating
10900
10901@smallexample
10902(triangle-recursively 3)
10903@end smallexample
10904
10905@noindent
10906which is 6 and this value will be added to 4 by the addition in the
10907third line.
10908@end quotation
10909
10910@noindent
10911The value returned by the function as a whole will be 10.
10912
10913Each time @code{triangle-recursively} is evaluated, it evaluates a
10914version of itself---a different instance of itself---with a smaller
10915argument, until the argument is small enough so that it does not
10916evaluate itself.
10917
10918Note that this particular design for a recursive function
10919requires that operations be deferred.
10920
10921Before @code{(triangle-recursively 7)} can calculate its answer, it
10922must call @code{(triangle-recursively 6)}; and before
10923@code{(triangle-recursively 6)} can calculate its answer, it must call
10924@code{(triangle-recursively 5)}; and so on. That is to say, the
10925calculation that @code{(triangle-recursively 7)} makes must be
10926deferred until @code{(triangle-recursively 6)} makes its calculation;
10927and @code{(triangle-recursively 6)} must defer until
10928@code{(triangle-recursively 5)} completes; and so on.
10929
10930If each of these instances of @code{triangle-recursively} are thought
10931of as different robots, the first robot must wait for the second to
10932complete its job, which must wait until the third completes, and so
10933on.
10934
10935There is a way around this kind of waiting, which we will discuss in
10936@ref{No Deferment, , Recursion without Deferments}.
10937
10938@node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10939@comment node-name, next, previous, up
10940@subsection Recursion Example Using @code{cond}
10941@findex cond
10942
10943The version of @code{triangle-recursively} described earlier is written
10944with the @code{if} special form. It can also be written using another
10945special form called @code{cond}. The name of the special form
10946@code{cond} is an abbreviation of the word @samp{conditional}.
10947
10948Although the @code{cond} special form is not used as often in the
10949Emacs Lisp sources as @code{if}, it is used often enough to justify
10950explaining it.
10951
10952@need 800
10953The template for a @code{cond} expression looks like this:
10954
10955@smallexample
10956@group
10957(cond
10958 @var{body}@dots{})
10959@end group
10960@end smallexample
10961
10962@noindent
10963where the @var{body} is a series of lists.
10964
10965@need 800
10966Written out more fully, the template looks like this:
10967
10968@smallexample
10969@group
10970(cond
10971 (@var{first-true-or-false-test} @var{first-consequent})
10972 (@var{second-true-or-false-test} @var{second-consequent})
10973 (@var{third-true-or-false-test} @var{third-consequent})
10974 @dots{})
10975@end group
10976@end smallexample
10977
10978When the Lisp interpreter evaluates the @code{cond} expression, it
10979evaluates the first element (the @sc{car} or true-or-false-test) of
10980the first expression in a series of expressions within the body of the
10981@code{cond}.
10982
10983If the true-or-false-test returns @code{nil} the rest of that
10984expression, the consequent, is skipped and the true-or-false-test of the
10985next expression is evaluated. When an expression is found whose
10986true-or-false-test returns a value that is not @code{nil}, the
10987consequent of that expression is evaluated. The consequent can be one
10988or more expressions. If the consequent consists of more than one
10989expression, the expressions are evaluated in sequence and the value of
10990the last one is returned. If the expression does not have a consequent,
10991the value of the true-or-false-test is returned.
10992
10993If none of the true-or-false-tests test true, the @code{cond} expression
10994returns @code{nil}.
10995
10996@need 1250
10997Written using @code{cond}, the @code{triangle} function looks like this:
10998
10999@smallexample
11000@group
11001(defun triangle-using-cond (number)
11002 (cond ((<= number 0) 0)
11003 ((= number 1) 1)
11004 ((> number 1)
11005 (+ number (triangle-using-cond (1- number))))))
11006@end group
11007@end smallexample
11008
11009@noindent
11010In this example, the @code{cond} returns 0 if the number is less than or
11011equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11012number (triangle-using-cond (1- number)))} if the number is greater than
110131.
11014
11015@node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11016@comment node-name, next, previous, up
11017@subsection Recursive Patterns
11018@cindex Recursive Patterns
11019
11020Here are three common recursive patterns. Each involves a list.
11021Recursion does not need to involve lists, but Lisp is designed for lists
11022and this provides a sense of its primal capabilities.
11023
11024@menu
11025* Every::
11026* Accumulate::
11027* Keep::
11028@end menu
11029
11030@node Every, Accumulate, Recursive Patterns, Recursive Patterns
11031@comment node-name, next, previous, up
11032@unnumberedsubsubsec Recursive Pattern: @emph{every}
11033@cindex Every, type of recursive pattern
11034@cindex Recursive pattern: every
11035
11036In the @code{every} recursive pattern, an action is performed on every
11037element of a list.
11038
11039@need 1500
11040The basic pattern is:
11041
11042@itemize @bullet
11043@item
11044If a list be empty, return @code{nil}.
11045@item
11046Else, act on the beginning of the list (the @sc{car} of the list)
11047 @itemize @minus
11048 @item
11049 through a recursive call by the function on the rest (the
11050 @sc{cdr}) of the list,
11051 @item
11052 and, optionally, combine the acted-on element, using @code{cons},
11053 with the results of acting on the rest.
11054 @end itemize
11055@end itemize
11056
11057@need 1500
11058Here is example:
11059
11060@smallexample
11061@group
11062(defun square-each (numbers-list)
11063 "Square each of a NUMBERS LIST, recursively."
11064 (if (not numbers-list) ; do-again-test
11065 nil
11066 (cons
11067 (* (car numbers-list) (car numbers-list))
11068 (square-each (cdr numbers-list))))) ; next-step-expression
11069@end group
11070
11071@group
11072(square-each '(1 2 3))
11073 @result{} (1 4 9)
11074@end group
11075@end smallexample
11076
11077@need 1200
11078@noindent
11079If @code{numbers-list} is empty, do nothing. But if it has content,
11080construct a list combining the square of the first number in the list
11081with the result of the recursive call.
11082
11083(The example follows the pattern exactly: @code{nil} is returned if
11084the numbers' list is empty. In practice, you would write the
11085conditional so it carries out the action when the numbers' list is not
11086empty.)
11087
11088The @code{print-elements-recursively} function (@pxref{Recursion with
11089list, , Recursion with a List}) is another example of an @code{every}
11090pattern, except in this case, rather than bring the results together
11091using @code{cons}, we print each element of output.
11092
11093@need 1250
11094The @code{print-elements-recursively} function looks like this:
11095
11096@smallexample
11097@group
11098(setq animals '(gazelle giraffe lion tiger))
11099@end group
11100
11101@group
11102(defun print-elements-recursively (list)
11103 "Print each element of LIST on a line of its own.
11104Uses recursion."
11105 (if list ; @r{do-again-test}
11106 (progn
11107 (print (car list)) ; @r{body}
11108 (print-elements-recursively ; @r{recursive call}
11109 (cdr list))))) ; @r{next-step-expression}
11110
11111(print-elements-recursively animals)
11112@end group
11113@end smallexample
11114
11115@need 1500
11116The pattern for @code{print-elements-recursively} is:
11117
11118@itemize @bullet
11119@item
11120If the list be empty, do nothing.
11121@item
11122But if the list has at least one element,
11123 @itemize @minus
11124 @item
11125 act on the beginning of the list (the @sc{car} of the list),
11126 @item
11127 and make a recursive call on the rest (the @sc{cdr}) of the list.
11128 @end itemize
11129@end itemize
11130
11131@node Accumulate, Keep, Every, Recursive Patterns
11132@comment node-name, next, previous, up
11133@unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11134@cindex Accumulate, type of recursive pattern
11135@cindex Recursive pattern: accumulate
11136
11137Another recursive pattern is called the @code{accumulate} pattern. In
11138the @code{accumulate} recursive pattern, an action is performed on
11139every element of a list and the result of that action is accumulated
11140with the results of performing the action on the other elements.
11141
11142This is very like the `every' pattern using @code{cons}, except that
11143@code{cons} is not used, but some other combiner.
11144
11145@need 1500
11146The pattern is:
11147
11148@itemize @bullet
11149@item
11150If a list be empty, return zero or some other constant.
11151@item
11152Else, act on the beginning of the list (the @sc{car} of the list),
11153 @itemize @minus
11154 @item
11155 and combine that acted-on element, using @code{+} or
11156 some other combining function, with
11157 @item
11158 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11159 @end itemize
11160@end itemize
11161
11162@need 1500
11163Here is an example:
11164
11165@smallexample
11166@group
11167(defun add-elements (numbers-list)
11168 "Add the elements of NUMBERS-LIST together."
11169 (if (not numbers-list)
11170 0
11171 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11172@end group
11173
11174@group
11175(add-elements '(1 2 3 4))
11176 @result{} 10
11177@end group
11178@end smallexample
11179
11180@xref{Files List, , Making a List of Files}, for an example of the
11181accumulate pattern.
11182
11183@node Keep, , Accumulate, Recursive Patterns
11184@comment node-name, next, previous, up
11185@unnumberedsubsubsec Recursive Pattern: @emph{keep}
11186@cindex Keep, type of recursive pattern
11187@cindex Recursive pattern: keep
11188
11189A third recursive pattern is called the @code{keep} pattern.
11190In the @code{keep} recursive pattern, each element of a list is tested;
11191the element is acted on and the results are kept only if the element
11192meets a criterion.
11193
11194Again, this is very like the `every' pattern, except the element is
11195skipped unless it meets a criterion.
11196
11197@need 1500
11198The pattern has three parts:
11199
11200@itemize @bullet
11201@item
11202If a list be empty, return @code{nil}.
11203@item
11204Else, if the beginning of the list (the @sc{car} of the list) passes
11205 a test
11206 @itemize @minus
11207 @item
11208 act on that element and combine it, using @code{cons} with
11209 @item
11210 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11211 @end itemize
11212@item
11213Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11214the test
11215 @itemize @minus
11216 @item
11217 skip on that element,
11218 @item
11219 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11220 @end itemize
11221@end itemize
11222
11223@need 1500
11224Here is an example that uses @code{cond}:
11225
11226@smallexample
11227@group
11228(defun keep-three-letter-words (word-list)
11229 "Keep three letter words in WORD-LIST."
11230 (cond
11231 ;; First do-again-test: stop-condition
11232 ((not word-list) nil)
11233
11234 ;; Second do-again-test: when to act
11235 ((eq 3 (length (symbol-name (car word-list))))
11236 ;; combine acted-on element with recursive call on shorter list
11237 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11238
11239 ;; Third do-again-test: when to skip element;
11240 ;; recursively call shorter list with next-step expression
11241 (t (keep-three-letter-words (cdr word-list)))))
11242@end group
11243
11244@group
11245(keep-three-letter-words '(one two three four five six))
11246 @result{} (one two six)
11247@end group
11248@end smallexample
11249
11250It goes without saying that you need not use @code{nil} as the test for
11251when to stop; and you can, of course, combine these patterns.
11252
11253@node No Deferment, No deferment solution, Recursive Patterns, Recursion
11254@subsection Recursion without Deferments
11255@cindex Deferment in recursion
11256@cindex Recursion without Deferments
11257
11258Let's consider again what happens with the @code{triangle-recursively}
11259function. We will find that the intermediate calculations are
11260deferred until all can be done.
11261
11262@need 800
11263Here is the function definition:
11264
11265@smallexample
11266@group
11267(defun triangle-recursively (number)
11268 "Return the sum of the numbers 1 through NUMBER inclusive.
11269Uses recursion."
11270 (if (= number 1) ; @r{do-again-test}
11271 1 ; @r{then-part}
11272 (+ number ; @r{else-part}
11273 (triangle-recursively ; @r{recursive call}
11274 (1- number))))) ; @r{next-step-expression}
11275@end group
11276@end smallexample
11277
11278What happens when we call this function with a argument of 7?
11279
11280The first instance of the @code{triangle-recursively} function adds
11281the number 7 to the value returned by a second instance of
11282@code{triangle-recursively}, an instance that has been passed an
11283argument of 6. That is to say, the first calculation is:
11284
11285@smallexample
11286(+ 7 (triangle-recursively 6)
11287@end smallexample
11288
11289@noindent
11290The first instance of @code{triangle-recursively}---you may want to
11291think of it as a little robot---cannot complete its job. It must hand
11292off the calculation for @code{(triangle-recursively 6)} to a second
11293instance of the program, to a second robot. This second individual is
11294completely different from the first one; it is, in the jargon, a
11295`different instantiation'. Or, put another way, it is a different
11296robot. It is the same model as the first; it calculates triangle
11297numbers recursively; but it has a different serial number.
11298
11299And what does @code{(triangle-recursively 6)} return? It returns the
11300number 6 added to the value returned by evaluating
11301@code{triangle-recursively} with an argument of 5. Using the robot
11302metaphor, it asks yet another robot to help it.
11303
11304@need 800
11305Now the total is:
11306
11307@smallexample
11308(+ 7 6 (triangle-recursively 5)
11309@end smallexample
11310
11311@need 800
11312And what happens next?
11313
11314@smallexample
11315(+ 7 6 5 (triangle-recursively 4)
11316@end smallexample
11317
11318Each time @code{triangle-recursively} is called, except for the last
11319time, it creates another instance of the program---another robot---and
11320asks it to make a calculation.
11321
11322@need 800
11323Eventually, the full addition is set up and performed:
11324
11325@smallexample
11326(+ 7 6 5 4 3 2 1)
11327@end smallexample
11328
11329This design for the function defers the calculation of the first step
11330until the second can be done, and defers that until the third can be
11331done, and so on. Each deferment means the computer must remember what
11332is being waited on. This is not a problem when there are only a few
11333steps, as in this example. But it can be a problem when there are
11334more steps.
11335
11336@node No deferment solution, , No Deferment, Recursion
11337@subsection No Deferment Solution
11338@cindex No deferment solution
11339@cindex Defermentless solution
11340@cindex Solution without deferment
11341
11342The solution to the problem of deferred operations is to write in a
11343manner that does not defer operations@footnote{The phrase @dfn{tail
11344recursive} is used to describe such a process, one that uses
11345`constant space'.}. This requires
11346writing to a different pattern, often one that involves writing two
11347function definitions, an `initialization' function and a `helper'
11348function.
11349
11350The `initialization' function sets up the job; the `helper' function
11351does the work.
11352
11353@need 1200
11354Here are the two function definitions for adding up numbers. They are
11355so simple, I find them hard to understand.
11356
11357@smallexample
11358@group
11359(defun triangle-initialization (number)
11360 "Return the sum of the numbers 1 through NUMBER inclusive.
11361This is the `initialization' component of a two function
11362duo that uses recursion."
11363 (triangle-recursive-helper 0 0 number))
11364@end group
11365@end smallexample
11366
11367@smallexample
11368@group
11369(defun triangle-recursive-helper (sum counter number)
11370 "Return SUM, using COUNTER, through NUMBER inclusive.
11371This is the `helper' component of a two function duo
11372that uses recursion."
11373 (if (> counter number)
11374 sum
11375 (triangle-recursive-helper (+ sum counter) ; @r{sum}
11376 (1+ counter) ; @r{counter}
11377 number))) ; @r{number}
11378@end group
11379@end smallexample
11380
11381@need 1250
11382Install both function definitions by evaluating them, then call
11383@code{triangle-initialization} with 2 rows:
11384
11385@smallexample
11386@group
11387(triangle-initialization 2)
11388 @result{} 3
11389@end group
11390@end smallexample
11391
11392The `initialization' function calls the first instance of the `helper'
11393function with three arguments: zero, zero, and a number which is the
11394number of rows in the triangle.
11395
11396The first two arguments passed to the `helper' function are
11397initialization values. These values are changed when
11398@code{triangle-recursive-helper} invokes new instances.@footnote{The
11399jargon is mildly confusing: @code{triangle-recursive-helper} uses a
11400process that is iterative in a procedure that is recursive. The
11401process is called iterative because the computer need only record the
11402three values, @code{sum}, @code{counter}, and @code{number}; the
11403procedure is recursive because the function `calls itself'. On the
11404other hand, both the process and the procedure used by
11405@code{triangle-recursively} are called recursive. The word
11406`recursive' has different meanings in the two contexts.}
11407
11408Let's see what happens when we have a triangle that has one row. (This
11409triangle will have one pebble in it!)
11410
11411@need 1200
11412@code{triangle-initialization} will call its helper with
11413the arguments @w{@code{0 0 1}}. That function will run the conditional
11414test whether @code{(> counter number)}:
11415
11416@smallexample
11417(> 0 1)
11418@end smallexample
11419
11420@need 1200
11421@noindent
11422and find that the result is false, so it will invoke
11423the then-part of the @code{if} clause:
11424
11425@smallexample
11426@group
11427 (triangle-recursive-helper
11428 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11429 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11430 number) ; @r{number stays the same}
11431@end group
11432@end smallexample
11433
11434@need 800
11435@noindent
11436which will first compute:
11437
11438@smallexample
11439@group
11440(triangle-recursive-helper (+ 0 0) ; @r{sum}
11441 (1+ 0) ; @r{counter}
11442 1) ; @r{number}
11443@exdent which is:
11444
11445(triangle-recursive-helper 0 1 1)
11446@end group
11447@end smallexample
11448
11449Again, @code{(> counter number)} will be false, so again, the Lisp
11450interpreter will evaluate @code{triangle-recursive-helper}, creating a
11451new instance with new arguments.
11452
11453@need 800
11454This new instance will be;
11455
11456@smallexample
11457@group
11458 (triangle-recursive-helper
11459 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11460 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11461 number) ; @r{number stays the same}
11462
11463@exdent which is:
11464
11465(triangle-recursive-helper 1 2 1)
11466@end group
11467@end smallexample
11468
11469In this case, the @code{(> counter number)} test will be true! So the
11470instance will return the value of the sum, which will be 1, as
11471expected.
11472
11473Now, let's pass @code{triangle-initialization} an argument
11474of 2, to find out how many pebbles there are in a triangle with two rows.
11475
11476That function calls @code{(triangle-recursive-helper 0 0 2)}.
11477
11478@need 800
11479In stages, the instances called will be:
11480
11481@smallexample
11482@group
11483 @r{sum counter number}
11484(triangle-recursive-helper 0 1 2)
11485
11486(triangle-recursive-helper 1 2 2)
11487
11488(triangle-recursive-helper 3 3 2)
11489@end group
11490@end smallexample
11491
11492When the last instance is called, the @code{(> counter number)} test
11493will be true, so the instance will return the value of @code{sum},
11494which will be 3.
11495
11496This kind of pattern helps when you are writing functions that can use
11497many resources in a computer.
11498
11499@need 1500
11500@node Looping exercise, , Recursion, Loops & Recursion
11501@section Looping Exercise
11502
11503@itemize @bullet
11504@item
11505Write a function similar to @code{triangle} in which each row has a
11506value which is the square of the row number. Use a @code{while} loop.
11507
11508@item
11509Write a function similar to @code{triangle} that multiplies instead of
11510adds the values.
11511
11512@item
11513Rewrite these two functions recursively. Rewrite these functions
11514using @code{cond}.
11515
11516@c comma in printed title causes problem in Info cross reference
11517@item
11518Write a function for Texinfo mode that creates an index entry at the
11519beginning of a paragraph for every @samp{@@dfn} within the paragraph.
11520(In a Texinfo file, @samp{@@dfn} marks a definition. For more
11521information, see
11522@ifinfo
11523@ref{Indicating, , Indicating Definitions, texinfo}.)
11524@end ifinfo
11525@ifhtml
11526@ref{Indicating, , Indicating, texinfo, Texinfo Manual}.)
11527@end ifhtml
11528@iftex
11529``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
11530Documentation Format}.)
11531@end iftex
11532@end itemize
11533
11534@node Regexp Search, Counting Words, Loops & Recursion, Top
11535@comment node-name, next, previous, up
11536@chapter Regular Expression Searches
11537@cindex Searches, illustrating
11538@cindex Regular expression searches
11539@cindex Patterns, searching for
11540@cindex Motion by sentence and paragraph
11541@cindex Sentences, movement by
11542@cindex Paragraphs, movement by
11543
11544Regular expression searches are used extensively in GNU Emacs. The
11545two functions, @code{forward-sentence} and @code{forward-paragraph},
11546illustrate these searches well. They use regular expressions to find
11547where to move point. The phrase `regular expression' is often written
11548as `regexp'.
11549
11550Regular expression searches are described in @ref{Regexp Search, ,
11551Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11552@ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11553Manual}. In writing this chapter, I am presuming that you have at
11554least a mild acquaintance with them. The major point to remember is
11555that regular expressions permit you to search for patterns as well as
11556for literal strings of characters. For example, the code in
11557@code{forward-sentence} searches for the pattern of possible
11558characters that could mark the end of a sentence, and moves point to
11559that spot.
11560
11561Before looking at the code for the @code{forward-sentence} function, it
11562is worth considering what the pattern that marks the end of a sentence
11563must be. The pattern is discussed in the next section; following that
11564is a description of the regular expression search function,
11565@code{re-search-forward}. The @code{forward-sentence} function
11566is described in the section following. Finally, the
11567@code{forward-paragraph} function is described in the last section of
11568this chapter. @code{forward-paragraph} is a complex function that
11569introduces several new features.
11570
11571@menu
11572* sentence-end:: The regular expression for @code{sentence-end}.
11573* re-search-forward:: Very similar to @code{search-forward}.
11574* forward-sentence:: A straightforward example of regexp search.
11575* forward-paragraph:: A somewhat complex example.
11576* etags:: How to create your own @file{TAGS} table.
11577* Regexp Review::
11578* re-search Exercises::
11579@end menu
11580
11581@node sentence-end, re-search-forward, Regexp Search, Regexp Search
11582@comment node-name, next, previous, up
11583@section The Regular Expression for @code{sentence-end}
11584@findex sentence-end
11585
11586The symbol @code{sentence-end} is bound to the pattern that marks the
11587end of a sentence. What should this regular expression be?
11588
11589Clearly, a sentence may be ended by a period, a question mark, or an
11590exclamation mark. Indeed, only clauses that end with one of those three
11591characters should be considered the end of a sentence. This means that
11592the pattern should include the character set:
11593
11594@smallexample
11595[.?!]
11596@end smallexample
11597
11598However, we do not want @code{forward-sentence} merely to jump to a
11599period, a question mark, or an exclamation mark, because such a character
11600might be used in the middle of a sentence. A period, for example, is
11601used after abbreviations. So other information is needed.
11602
11603According to convention, you type two spaces after every sentence, but
11604only one space after a period, a question mark, or an exclamation mark in
11605the body of a sentence. So a period, a question mark, or an exclamation
11606mark followed by two spaces is a good indicator of an end of sentence.
11607However, in a file, the two spaces may instead be a tab or the end of a
11608line. This means that the regular expression should include these three
11609items as alternatives.
11610
11611@need 800
11612This group of alternatives will look like this:
11613
11614@smallexample
11615@group
11616\\($\\| \\| \\)
11617 ^ ^^
11618 TAB SPC
11619@end group
11620@end smallexample
11621
11622@noindent
11623Here, @samp{$} indicates the end of the line, and I have pointed out
11624where the tab and two spaces are inserted in the expression. Both are
11625inserted by putting the actual characters into the expression.
11626
11627Two backslashes, @samp{\\}, are required before the parentheses and
11628vertical bars: the first backslash quotes the following backslash in
11629Emacs; and the second indicates that the following character, the
11630parenthesis or the vertical bar, is special.
11631
11632@need 1000
11633Also, a sentence may be followed by one or more carriage returns, like
11634this:
11635
11636@smallexample
11637@group
11638[
11639]*
11640@end group
11641@end smallexample
11642
11643@noindent
11644Like tabs and spaces, a carriage return is inserted into a regular
11645expression by inserting it literally. The asterisk indicates that the
11646@key{RET} is repeated zero or more times.
11647
11648But a sentence end does not consist only of a period, a question mark or
11649an exclamation mark followed by appropriate space: a closing quotation
11650mark or a closing brace of some kind may precede the space. Indeed more
11651than one such mark or brace may precede the space. These require a
11652expression that looks like this:
11653
11654@smallexample
11655[]\"')@}]*
11656@end smallexample
11657
11658In this expression, the first @samp{]} is the first character in the
11659expression; the second character is @samp{"}, which is preceded by a
11660@samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
11661three characters are @samp{'}, @samp{)}, and @samp{@}}.
11662
11663All this suggests what the regular expression pattern for matching the
11664end of a sentence should be; and, indeed, if we evaluate
11665@code{sentence-end} we find that it returns the following value:
11666
11667@smallexample
11668@group
11669sentence-end
11670 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
11671]*"
11672@end group
11673@end smallexample
11674
11675@ignore
11676
11677@noindent
11678(Note that here the @key{TAB}, two spaces, and @key{RET} are shown
11679literally in the pattern.)
11680
11681This regular expression can be decyphered as follows:
11682
11683@table @code
11684@item [.?!]
11685The first part of the pattern is the three characters, a period, a question
11686mark and an exclamation mark, within square brackets. The pattern must
11687begin with one or other of these characters.
11688
11689@item []\"')@}]*
11690The second part of the pattern is the group of closing braces and
11691quotation marks, which can appear zero or more times. These may follow
11692the period, question mark or exclamation mark. In a regular expression,
11693the backslash, @samp{\}, followed by the double quotation mark,
11694@samp{"}, indicates the class of string-quote characters. Usually, the
11695double quotation mark is the only character in this class. The
11696asterisk, @samp{*}, indicates that the items in the previous group (the
11697group surrounded by square brackets, @samp{[]}) may be repeated zero or
11698more times.
11699
11700@item \\($\\| \\| \\)
11701The third part of the pattern is one or other of: either the end of a
11702line, or two blank spaces, or a tab. The double back-slashes are used
11703to prevent Emacs from reading the parentheses and vertical bars as part
11704of the search pattern; the parentheses are used to mark the group and
11705the vertical bars are used to indicated that the patterns to either side
11706of them are alternatives. The dollar sign is used to indicate the end
11707of a line and both the two spaces and the tab are each inserted as is to
11708indicate what they are.
11709
11710@item [@key{RET}]*
11711Finally, the last part of the pattern indicates that the end of the line
11712or the whitespace following the period, question mark or exclamation
11713mark may, but need not, be followed by one or more carriage returns. In
11714the pattern, the carriage return is inserted as an actual carriage
11715return between square brackets but here it is shown as @key{RET}.
11716@end table
11717
11718@end ignore
11719
11720@node re-search-forward, forward-sentence, sentence-end, Regexp Search
11721@comment node-name, next, previous, up
11722@section The @code{re-search-forward} Function
11723@findex re-search-forward
11724
11725The @code{re-search-forward} function is very like the
11726@code{search-forward} function. (@xref{search-forward, , The
11727@code{search-forward} Function}.)
11728
11729@code{re-search-forward} searches for a regular expression. If the
11730search is successful, it leaves point immediately after the last
11731character in the target. If the search is backwards, it leaves point
11732just before the first character in the target. You may tell
11733@code{re-search-forward} to return @code{t} for true. (Moving point
11734is therefore a `side effect'.)
11735
11736Like @code{search-forward}, the @code{re-search-forward} function takes
11737four arguments:
11738
11739@enumerate
11740@item
11741The first argument is the regular expression that the function searches
11742for. The regular expression will be a string between quotations marks.
11743
11744@item
11745The optional second argument limits how far the function will search; it is a
11746bound, which is specified as a position in the buffer.
11747
11748@item
11749The optional third argument specifies how the function responds to
11750failure: @code{nil} as the third argument causes the function to
11751signal an error (and print a message) when the search fails; any other
11752value causes it to return @code{nil} if the search fails and @code{t}
11753if the search succeeds.
11754
11755@item
11756The optional fourth argument is the repeat count. A negative repeat
11757count causes @code{re-search-forward} to search backwards.
11758@end enumerate
11759
11760@need 800
11761The template for @code{re-search-forward} looks like this:
11762
11763@smallexample
11764@group
11765(re-search-forward "@var{regular-expression}"
11766 @var{limit-of-search}
11767 @var{what-to-do-if-search-fails}
11768 @var{repeat-count})
11769@end group
11770@end smallexample
11771
11772The second, third, and fourth arguments are optional. However, if you
11773want to pass a value to either or both of the last two arguments, you
11774must also pass a value to all the preceding arguments. Otherwise, the
11775Lisp interpreter will mistake which argument you are passing the value
11776to.
11777
11778@need 1200
11779In the @code{forward-sentence} function, the regular expression will be
11780the value of the variable @code{sentence-end}, namely:
11781
11782@smallexample
11783@group
11784"[.?!][]\"')@}]*\\($\\| \\| \\)[
11785]*"
11786@end group
11787@end smallexample
11788
11789@noindent
11790The limit of the search will be the end of the paragraph (since a
11791sentence cannot go beyond a paragraph). If the search fails, the
11792function will return @code{nil}; and the repeat count will be provided
11793by the argument to the @code{forward-sentence} function.
11794
11795@node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11796@comment node-name, next, previous, up
11797@section @code{forward-sentence}
11798@findex forward-sentence
11799
11800The command to move the cursor forward a sentence is a straightforward
11801illustration of how to use regular expression searches in Emacs Lisp.
11802Indeed, the function looks longer and more complicated than it is; this
11803is because the function is designed to go backwards as well as forwards;
11804and, optionally, over more than one sentence. The function is usually
11805bound to the key command @kbd{M-e}.
11806
11807@menu
11808* Complete forward-sentence::
11809* fwd-sentence while loops:: Two @code{while} loops.
11810* fwd-sentence re-search:: A regular expression search.
11811@end menu
11812
11813@node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11814@ifnottex
11815@unnumberedsubsec Complete @code{forward-sentence} function definition
11816@end ifnottex
11817
11818@need 1250
11819Here is the code for @code{forward-sentence}:
11820
11821@smallexample
11822@group
11823(defun forward-sentence (&optional arg)
11824 "Move forward to next sentence-end. With argument, repeat.
11825With negative argument, move backward repeatedly to sentence-beginning.
11826Sentence ends are identified by the value of sentence-end
11827treated as a regular expression. Also, every paragraph boundary
11828terminates sentences as well."
11829@end group
11830@group
11831 (interactive "p")
11832 (or arg (setq arg 1))
11833 (while (< arg 0)
11834 (let ((par-beg
11835 (save-excursion (start-of-paragraph-text) (point))))
11836 (if (re-search-backward
11837 (concat sentence-end "[^ \t\n]") par-beg t)
11838 (goto-char (1- (match-end 0)))
11839 (goto-char par-beg)))
11840 (setq arg (1+ arg)))
11841 (while (> arg 0)
11842 (let ((par-end
11843 (save-excursion (end-of-paragraph-text) (point))))
11844 (if (re-search-forward sentence-end par-end t)
11845 (skip-chars-backward " \t\n")
11846 (goto-char par-end)))
11847 (setq arg (1- arg))))
11848@end group
11849@end smallexample
11850
11851The function looks long at first sight and it is best to look at its
11852skeleton first, and then its muscle. The way to see the skeleton is to
11853look at the expressions that start in the left-most columns:
11854
11855@smallexample
11856@group
11857(defun forward-sentence (&optional arg)
11858 "@var{documentation}@dots{}"
11859 (interactive "p")
11860 (or arg (setq arg 1))
11861 (while (< arg 0)
11862 @var{body-of-while-loop}
11863 (while (> arg 0)
11864 @var{body-of-while-loop}
11865@end group
11866@end smallexample
11867
11868This looks much simpler! The function definition consists of
11869documentation, an @code{interactive} expression, an @code{or}
11870expression, and @code{while} loops.
11871
11872Let's look at each of these parts in turn.
11873
11874We note that the documentation is thorough and understandable.
11875
11876The function has an @code{interactive "p"} declaration. This means
11877that the processed prefix argument, if any, is passed to the
11878function as its argument. (This will be a number.) If the function
11879is not passed an argument (it is optional) then the argument
11880@code{arg} will be bound to 1. When @code{forward-sentence} is called
11881non-interactively without an argument, @code{arg} is bound to
11882@code{nil}.
11883
11884The @code{or} expression handles the prefix argument. What it does is
11885either leave the value of @code{arg} as it is, but only if @code{arg}
11886is bound to a value; or it sets the value of @code{arg} to 1, in the
11887case when @code{arg} is bound to @code{nil}.
11888
11889@node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11890@unnumberedsubsec The @code{while} loops
11891
11892Two @code{while} loops follow the @code{or} expression. The first
11893@code{while} has a true-or-false-test that tests true if the prefix
11894argument for @code{forward-sentence} is a negative number. This is for
11895going backwards. The body of this loop is similar to the body of the
11896second @code{while} clause, but it is not exactly the same. We will
11897skip this @code{while} loop and concentrate on the second @code{while}
11898loop.
11899
11900@need 1500
11901The second @code{while} loop is for moving point forward. Its skeleton
11902looks like this:
11903
11904@smallexample
11905@group
11906(while (> arg 0) ; @r{true-or-false-test}
11907 (let @var{varlist}
11908 (if (@var{true-or-false-test})
11909 @var{then-part}
11910 @var{else-part}
11911 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
11912@end group
11913@end smallexample
11914
11915The @code{while} loop is of the decrementing kind.
11916(@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
11917has a true-or-false-test that tests true so long as the counter (in
11918this case, the variable @code{arg}) is greater than zero; and it has a
11919decrementer that subtracts 1 from the value of the counter every time
11920the loop repeats.
11921
11922If no prefix argument is given to @code{forward-sentence}, which is
11923the most common way the command is used, this @code{while} loop will
11924run once, since the value of @code{arg} will be 1.
11925
11926The body of the @code{while} loop consists of a @code{let} expression,
11927which creates and binds a local variable, and has, as its body, an
11928@code{if} expression.
11929
11930@need 1250
11931The body of the @code{while} loop looks like this:
11932
11933@smallexample
11934@group
11935(let ((par-end
11936 (save-excursion (end-of-paragraph-text) (point))))
11937 (if (re-search-forward sentence-end par-end t)
11938 (skip-chars-backward " \t\n")
11939 (goto-char par-end)))
11940@end group
11941@end smallexample
11942
11943The @code{let} expression creates and binds the local variable
11944@code{par-end}. As we shall see, this local variable is designed to
11945provide a bound or limit to the regular expression search. If the
11946search fails to find a proper sentence ending in the paragraph, it will
11947stop on reaching the end of the paragraph.
11948
11949But first, let us examine how @code{par-end} is bound to the value of
11950the end of the paragraph. What happens is that the @code{let} sets the
11951value of @code{par-end} to the value returned when the Lisp interpreter
11952evaluates the expression
11953
11954@smallexample
11955@group
11956(save-excursion (end-of-paragraph-text) (point))
11957@end group
11958@end smallexample
11959
11960@noindent
11961In this expression, @code{(end-of-paragraph-text)} moves point to the
11962end of the paragraph, @code{(point)} returns the value of point, and then
11963@code{save-excursion} restores point to its original position. Thus,
11964the @code{let} binds @code{par-end} to the value returned by the
11965@code{save-excursion} expression, which is the position of the end of
11966the paragraph. (The @code{(end-of-paragraph-text)} function uses
11967@code{forward-paragraph}, which we will discuss shortly.)
11968
11969@need 1200
11970Emacs next evaluates the body of the @code{let}, which is an @code{if}
11971expression that looks like this:
11972
11973@smallexample
11974@group
11975(if (re-search-forward sentence-end par-end t) ; @r{if-part}
11976 (skip-chars-backward " \t\n") ; @r{then-part}
11977 (goto-char par-end))) ; @r{else-part}
11978@end group
11979@end smallexample
11980
11981The @code{if} tests whether its first argument is true and if so,
11982evaluates its then-part; otherwise, the Emacs Lisp interpreter
11983evaluates the else-part. The true-or-false-test of the @code{if}
11984expression is the regular expression search.
11985
11986It may seem odd to have what looks like the `real work' of
11987the @code{forward-sentence} function buried here, but this is a common
11988way this kind of operation is carried out in Lisp.
11989
11990@node fwd-sentence re-search, , fwd-sentence while loops, forward-sentence
11991@unnumberedsubsec The regular expression search
11992
11993The @code{re-search-forward} function searches for the end of the
11994sentence, that is, for the pattern defined by the @code{sentence-end}
11995regular expression. If the pattern is found---if the end of the sentence is
11996found---then the @code{re-search-forward} function does two things:
11997
11998@enumerate
11999@item
12000The @code{re-search-forward} function carries out a side effect, which
12001is to move point to the end of the occurrence found.
12002
12003@item
12004The @code{re-search-forward} function returns a value of true. This is
12005the value received by the @code{if}, and means that the search was
12006successful.
12007@end enumerate
12008
12009@noindent
12010The side effect, the movement of point, is completed before the
12011@code{if} function is handed the value returned by the successful
12012conclusion of the search.
12013
12014When the @code{if} function receives the value of true from a successful
12015call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12016which is the expression @code{(skip-chars-backward " \t\n")}. This
12017expression moves backwards over any blank spaces, tabs or carriage
12018returns until a printed character is found and then leaves point after
12019the character. Since point has already been moved to the end of the
12020pattern that marks the end of the sentence, this action leaves point
12021right after the closing printed character of the sentence, which is
12022usually a period.
12023
12024On the other hand, if the @code{re-search-forward} function fails to
12025find a pattern marking the end of the sentence, the function returns
12026false. The false then causes the @code{if} to evaluate its third
12027argument, which is @code{(goto-char par-end)}: it moves point to the
12028end of the paragraph.
12029
12030Regular expression searches are exceptionally useful and the pattern
12031illustrated by @code{re-search-forward}, in which the search is the
12032test of an @code{if} expression, is handy. You will see or write code
12033incorporating this pattern often.
12034
12035@node forward-paragraph, etags, forward-sentence, Regexp Search
12036@comment node-name, next, previous, up
12037@section @code{forward-paragraph}: a Goldmine of Functions
12038@findex forward-paragraph
12039
12040The @code{forward-paragraph} function moves point forward to the end
12041of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12042number of functions that are important in themselves, including
12043@code{let*}, @code{match-beginning}, and @code{looking-at}.
12044
12045The function definition for @code{forward-paragraph} is considerably
12046longer than the function definition for @code{forward-sentence}
12047because it works with a paragraph, each line of which may begin with a
12048fill prefix.
12049
12050A fill prefix consists of a string of characters that are repeated at
12051the beginning of each line. For example, in Lisp code, it is a
12052convention to start each line of a paragraph-long comment with
12053@samp{;;; }. In Text mode, four blank spaces make up another common
12054fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
12055emacs, The GNU Emacs Manual}, for more information about fill
12056prefixes.)
12057
12058The existence of a fill prefix means that in addition to being able to
12059find the end of a paragraph whose lines begin on the left-most
12060column, the @code{forward-paragraph} function must be able to find the
12061end of a paragraph when all or many of the lines in the buffer begin
12062with the fill prefix.
12063
12064Moreover, it is sometimes practical to ignore a fill prefix that
12065exists, especially when blank lines separate paragraphs.
12066This is an added complication.
12067
12068@menu
12069* forward-paragraph in brief:: Key parts of the function definition.
12070* fwd-para let:: The @code{let*} expression.
12071* fwd-para while:: The forward motion @code{while} loop.
12072* fwd-para between paragraphs:: Movement between paragraphs.
12073* fwd-para within paragraph:: Movement within paragraphs.
12074* fwd-para no fill prefix:: When there is no fill prefix.
12075* fwd-para with fill prefix:: When there is a fill prefix.
12076* fwd-para summary:: Summary of @code{forward-paragraph} code.
12077@end menu
12078
12079@node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12080@ifnottex
12081@unnumberedsubsec Shortened @code{forward-paragraph} function definition
12082@end ifnottex
12083
12084Rather than print all of the @code{forward-paragraph} function, we
12085will only print parts of it. Read without preparation, the function
12086can be daunting!
12087
12088@need 800
12089In outline, the function looks like this:
12090
12091@smallexample
12092@group
12093(defun forward-paragraph (&optional arg)
12094 "@var{documentation}@dots{}"
12095 (interactive "p")
12096 (or arg (setq arg 1))
12097 (let*
12098 @var{varlist}
12099 (while (< arg 0) ; @r{backward-moving-code}
12100 @dots{}
12101 (setq arg (1+ arg)))
12102 (while (> arg 0) ; @r{forward-moving-code}
12103 @dots{}
12104 (setq arg (1- arg)))))
12105@end group
12106@end smallexample
12107
12108The first parts of the function are routine: the function's argument
12109list consists of one optional argument. Documentation follows.
12110
12111The lower case @samp{p} in the @code{interactive} declaration means
12112that the processed prefix argument, if any, is passed to the function.
12113This will be a number, and is the repeat count of how many paragraphs
12114point will move. The @code{or} expression in the next line handles
12115the common case when no argument is passed to the function, which occurs
12116if the function is called from other code rather than interactively.
12117This case was described earlier. (@xref{forward-sentence, The
12118@code{forward-sentence} function}.) Now we reach the end of the
12119familiar part of this function.
12120
12121@node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12122@unnumberedsubsec The @code{let*} expression
12123
12124The next line of the @code{forward-paragraph} function begins a
12125@code{let*} expression. This is a different kind of expression than
12126we have seen so far. The symbol is @code{let*} not @code{let}.
12127
12128The @code{let*} special form is like @code{let} except that Emacs sets
12129each variable in sequence, one after another, and variables in the
12130latter part of the varlist can make use of the values to which Emacs
12131set variables in the earlier part of the varlist.
12132
12133In the @code{let*} expression in this function, Emacs binds two
12134variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12135The value to which @code{paragraph-separate} is bound depends on the
12136value of @code{fill-prefix-regexp}.
12137
12138@need 1200
12139Let's look at each in turn. The symbol @code{fill-prefix-regexp} is
12140set to the value returned by evaluating the following list:
12141
12142@smallexample
12143@group
12144(and fill-prefix
12145 (not (equal fill-prefix ""))
12146 (not paragraph-ignore-fill-prefix)
12147 (regexp-quote fill-prefix))
12148@end group
12149@end smallexample
12150
12151@noindent
12152This is an expression whose first element is the @code{and} special form.
12153
12154As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12155function}), the @code{and} special form evaluates each of its
12156arguments until one of the arguments returns a value of @code{nil}, in
12157which case the @code{and} expression returns @code{nil}; however, if
12158none of the arguments returns a value of @code{nil}, the value
12159resulting from evaluating the last argument is returned. (Since such
12160a value is not @code{nil}, it is considered true in Lisp.) In other
12161words, an @code{and} expression returns a true value only if all its
12162arguments are true.
12163@findex and
12164
12165In this case, the variable @code{fill-prefix-regexp} is bound to a
12166non-@code{nil} value only if the following four expressions produce a
12167true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12168@code{fill-prefix-regexp} is bound to @code{nil}.
12169
12170@table @code
12171@item fill-prefix
12172When this variable is evaluated, the value of the fill prefix, if any,
12173is returned. If there is no fill prefix, this variable returns
12174@code{nil}.
12175
12176@item (not (equal fill-prefix "")
12177This expression checks whether an existing fill prefix is an empty
12178string, that is, a string with no characters in it. An empty string is
12179not a useful fill prefix.
12180
12181@item (not paragraph-ignore-fill-prefix)
12182This expression returns @code{nil} if the variable
12183@code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12184true value such as @code{t}.
12185
12186@item (regexp-quote fill-prefix)
12187This is the last argument to the @code{and} special form. If all the
12188arguments to the @code{and} are true, the value resulting from
12189evaluating this expression will be returned by the @code{and} expression
12190and bound to the variable @code{fill-prefix-regexp},
12191@end table
12192
12193@findex regexp-quote
12194@noindent
12195The result of evaluating this @code{and} expression successfully is that
12196@code{fill-prefix-regexp} will be bound to the value of
12197@code{fill-prefix} as modified by the @code{regexp-quote} function.
12198What @code{regexp-quote} does is read a string and return a regular
12199expression that will exactly match the string and match nothing else.
12200This means that @code{fill-prefix-regexp} will be set to a value that
12201will exactly match the fill prefix if the fill prefix exists.
12202Otherwise, the variable will be set to @code{nil}.
12203
12204The second local variable in the @code{let*} expression is
12205@code{paragraph-separate}. It is bound to the value returned by
12206evaluating the expression:
12207
12208@smallexample
12209@group
12210(if fill-prefix-regexp
12211 (concat paragraph-separate
12212 "\\|^" fill-prefix-regexp "[ \t]*$")
12213 paragraph-separate)))
12214@end group
12215@end smallexample
12216
12217This expression shows why @code{let*} rather than @code{let} was used.
12218The true-or-false-test for the @code{if} depends on whether the variable
12219@code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12220
12221If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12222the else-part of the @code{if} expression and binds
12223@code{paragraph-separate} to its local value.
12224(@code{paragraph-separate} is a regular expression that matches what
12225separates paragraphs.)
12226
12227But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12228the then-part of the @code{if} expression and binds
12229@code{paragraph-separate} to a regular expression that includes the
12230@code{fill-prefix-regexp} as part of the pattern.
12231
12232Specifically, @code{paragraph-separate} is set to the original value
12233of the paragraph separate regular expression concatenated with an
12234alternative expression that consists of the @code{fill-prefix-regexp}
12235followed by a blank line. The @samp{^} indicates that the
12236@code{fill-prefix-regexp} must begin a line, and the optional
12237whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12238The @samp{\\|} defines this portion of the regexp as an alternative to
12239@code{paragraph-separate}.
12240
12241Now we get into the body of the @code{let*}. The first part of the body
12242of the @code{let*} deals with the case when the function is given a
12243negative argument and is therefore moving backwards. We will skip this
12244section.
12245
12246@node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12247@unnumberedsubsec The forward motion @code{while} loop
12248
12249The second part of the body of the @code{let*} deals with forward
12250motion. It is a @code{while} loop that repeats itself so long as the
12251value of @code{arg} is greater than zero. In the most common use of
12252the function, the value of the argument is 1, so the body of the
12253@code{while} loop is evaluated exactly once, and the cursor moves
12254forward one paragraph.
12255
12256This part handles three situations: when point is between paragraphs,
12257when point is within a paragraph and there is a fill prefix, and
12258when point is within a paragraph and there is no fill prefix.
12259
12260@need 800
12261The @code{while} loop looks like this:
12262
12263@smallexample
12264@group
12265(while (> arg 0)
12266 (beginning-of-line)
12267
12268 ;; @r{between paragraphs}
12269 (while (prog1 (and (not (eobp))
12270 (looking-at paragraph-separate))
12271 (forward-line 1)))
12272@end group
12273
12274@group
12275 ;; @r{within paragraphs, with a fill prefix}
12276 (if fill-prefix-regexp
12277 ;; @r{There is a fill prefix; it overrides paragraph-start.}
12278 (while (and (not (eobp))
12279 (not (looking-at paragraph-separate))
12280 (looking-at fill-prefix-regexp))
12281 (forward-line 1))
12282@end group
12283
12284@group
12285 ;; @r{within paragraphs, no fill prefix}
12286 (if (re-search-forward paragraph-start nil t)
12287 (goto-char (match-beginning 0))
12288 (goto-char (point-max))))
12289
12290 (setq arg (1- arg)))
12291@end group
12292@end smallexample
12293
12294We can see immediately that this is a decrementing counter @code{while}
12295loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12296
12297@need 800
12298The body of the loop consists of three expressions:
12299
12300@smallexample
12301@group
12302;; @r{between paragraphs}
12303(beginning-of-line)
12304(while
12305 @var{body-of-while})
12306@end group
12307
12308@group
12309;; @r{within paragraphs, with fill prefix}
12310(if @var{true-or-false-test}
12311 @var{then-part}
12312@end group
12313
12314@group
12315;; @r{within paragraphs, no fill prefix}
12316 @var{else-part}
12317@end group
12318@end smallexample
12319
12320@noindent
12321When the Emacs Lisp interpreter evaluates the body of the
12322@code{while} loop, the first thing it does is evaluate the
12323@code{(beginning-of-line)} expression and move point to the beginning
12324of the line. Then there is an inner @code{while} loop. This
12325@code{while} loop is designed to move the cursor out of the blank
12326space between paragraphs, if it should happen to be there. Finally,
12327there is an @code{if} expression that actually moves point to the end
12328of the paragraph.
12329
12330@node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12331@unnumberedsubsec Between paragraphs
12332
12333First, let us look at the inner @code{while} loop. This loop handles
12334the case when point is between paragraphs; it uses three functions
12335that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12336@findex prog1
12337@findex eobp
12338@findex looking-at
12339
12340@itemize @bullet
12341@item
12342@code{prog1} is similar to the @code{progn} special form,
12343except that @code{prog1} evaluates its arguments in sequence and then
12344returns the value of its first argument as the value of the whole
12345expression. (@code{progn} returns the value of its last argument as the
12346value of the expression.) The second and subsequent arguments to
12347@code{prog1} are evaluated only for their side effects.
12348
12349@item
12350@code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12351function that returns true if point is at the end of the buffer.
12352
12353@item
12354@code{looking-at} is a function that returns true if the text following
12355point matches the regular expression passed @code{looking-at} as its
12356argument.
12357@end itemize
12358
12359@need 800
12360The @code{while} loop we are studying looks like this:
12361
12362@smallexample
12363@group
12364(while (prog1 (and (not (eobp))
12365 (looking-at paragraph-separate))
12366 (forward-line 1)))
12367@end group
12368@end smallexample
12369
12370@need 1200
12371@noindent
12372This is a @code{while} loop with no body! The true-or-false-test of the
12373loop is the expression:
12374
12375@smallexample
12376@group
12377(prog1 (and (not (eobp))
12378 (looking-at paragraph-separate))
12379 (forward-line 1))
12380@end group
12381@end smallexample
12382
12383@noindent
12384The first argument to the @code{prog1} is the @code{and} expression. It
12385has within in it a test of whether point is at the end of the buffer and
12386also a test of whether the pattern following point matches the regular
12387expression for separating paragraphs.
12388
12389If the cursor is not at the end of the buffer and if the characters
12390following the cursor mark the separation between two paragraphs, then
12391the @code{and} expression is true. After evaluating the @code{and}
12392expression, the Lisp interpreter evaluates the second argument to
12393@code{prog1}, which is @code{forward-line}. This moves point forward
12394one line. The value returned by the @code{prog1} however, is the
12395value of its first argument, so the @code{while} loop continues so
12396long as point is not at the end of the buffer and is between
12397paragraphs. When, finally, point is moved to a paragraph, the
12398@code{and} expression tests false. Note however, that the
12399@code{forward-line} command is carried out anyhow. This means that
12400when point is moved from between paragraphs to a paragraph, it is left
12401at the beginning of the second line of the paragraph.
12402
12403@node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12404@unnumberedsubsec Within paragraphs
12405
12406The next expression in the outer @code{while} loop is an @code{if}
12407expression. The Lisp interpreter evaluates the then-part of the
12408@code{if} when the @code{fill-prefix-regexp} variable has a value other
12409than @code{nil}, and it evaluates the else-part when the value of
12410@code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12411fill prefix.
12412
12413@node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12414@unnumberedsubsec No fill prefix
12415
12416It is simplest to look at the code for the case when there is no fill
12417prefix first. This code consists of yet another inner @code{if}
12418expression, and reads as follows:
12419
12420@smallexample
12421@group
12422(if (re-search-forward paragraph-start nil t)
12423 (goto-char (match-beginning 0))
12424 (goto-char (point-max)))
12425@end group
12426@end smallexample
12427
12428@noindent
12429This expression actually does the work that most people think of as
12430the primary purpose of the @code{forward-paragraph} command: it causes
12431a regular expression search to occur that searches forward to the
12432start of the next paragraph and if it is found, moves point there; but
12433if the start of another paragraph if not found, it moves point to the
12434end of the accessible region of the buffer.
12435
12436The only unfamiliar part of this is the use of @code{match-beginning}.
12437This is another function that is new to us. The
12438@code{match-beginning} function returns a number specifying the
12439location of the start of the text that was matched by the last regular
12440expression search.
12441
12442The @code{match-beginning} function is used here because of a
12443characteristic of a forward search: a successful forward search,
12444regardless of whether it is a plain search or a regular expression
12445search, will move point to the end of the text that is found. In this
12446case, a successful search will move point to the end of the pattern for
12447@code{paragraph-start}, which will be the beginning of the next
12448paragraph rather than the end of the current one.
12449
12450However, we want to put point at the end of the current paragraph, not at
12451the beginning of the next one. The two positions may be different,
12452because there may be several blank lines between paragraphs.
12453
12454@findex match-beginning
12455When given an argument of 0, @code{match-beginning} returns the position
12456that is the start of the text that the most recent regular
12457expression search matched. In this case, the most recent regular
12458expression search is the one looking for @code{paragraph-start}, so
12459@code{match-beginning} returns the beginning position of the pattern,
12460rather than the end of the pattern. The beginning position is the end
12461of the paragraph.
12462
12463(Incidentally, when passed a positive number as an argument, the
12464@code{match-beginning} function will place point at that parenthesized
12465expression in the last regular expression. It is a useful function.)
12466
12467@node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12468@unnumberedsubsec With a fill prefix
12469
12470The inner @code{if} expression just discussed is the else-part of an enclosing
12471@code{if} expression which tests whether there is a fill prefix. If
12472there is a fill prefix, the then-part of this @code{if} is evaluated.
12473It looks like this:
12474
12475@smallexample
12476@group
12477(while (and (not (eobp))
12478 (not (looking-at paragraph-separate))
12479 (looking-at fill-prefix-regexp))
12480 (forward-line 1))
12481@end group
12482@end smallexample
12483
12484@noindent
12485What this expression does is move point forward line by line so long
12486as three conditions are true:
12487
12488@enumerate
12489@item
12490Point is not at the end of the buffer.
12491
12492@item
12493The text following point does not separate paragraphs.
12494
12495@item
12496The pattern following point is the fill prefix regular expression.
12497@end enumerate
12498
12499The last condition may be puzzling, until you remember that point was
12500moved to the beginning of the line early in the @code{forward-paragraph}
12501function. This means that if the text has a fill prefix, the
12502@code{looking-at} function will see it.
12503
12504@node fwd-para summary, , fwd-para with fill prefix, forward-paragraph
12505@unnumberedsubsec Summary
12506
12507In summary, when moving forward, the @code{forward-paragraph} function
12508does the following:
12509
12510@itemize @bullet
12511@item
12512Move point to the beginning of the line.
12513
12514@item
12515Skip over lines between paragraphs.
12516
12517@item
12518Check whether there is a fill prefix, and if there is:
12519
12520@itemize ---
12521
12522@item
12523Go forward line by line so long as the line is not a paragraph
12524separating line.
12525@end itemize
12526
12527@item
12528But if there is no fill prefix,
12529
12530@itemize ---
12531
12532@item
12533Search for the next paragraph start pattern.
12534
12535@item
12536Go to the beginning of the paragraph start pattern, which will be the
12537end of the previous paragraph.
12538
12539@item
12540Or else go to the end of the accessible portion of the buffer.
12541@end itemize
12542@end itemize
12543
12544@need 1200
12545For review, here is the code we have just been discussing, formatted
12546for clarity:
12547
12548@smallexample
12549@group
12550(interactive "p")
12551(or arg (setq arg 1))
12552(let* (
12553 (fill-prefix-regexp
12554 (and fill-prefix (not (equal fill-prefix ""))
12555 (not paragraph-ignore-fill-prefix)
12556 (regexp-quote fill-prefix)))
12557@end group
12558
12559@group
12560 (paragraph-separate
12561 (if fill-prefix-regexp
12562 (concat paragraph-separate
12563 "\\|^"
12564 fill-prefix-regexp
12565 "[ \t]*$")
12566 paragraph-separate)))
12567
12568 @var{omitted-backward-moving-code} @dots{}
12569@end group
12570
12571@group
12572 (while (> arg 0) ; @r{forward-moving-code}
12573 (beginning-of-line)
12574
12575 (while (prog1 (and (not (eobp))
12576 (looking-at paragraph-separate))
12577 (forward-line 1)))
12578@end group
12579
12580@group
12581 (if fill-prefix-regexp
12582 (while (and (not (eobp)) ; @r{then-part}
12583 (not (looking-at paragraph-separate))
12584 (looking-at fill-prefix-regexp))
12585 (forward-line 1))
12586@end group
12587@group
12588 ; @r{else-part: the inner-if}
12589 (if (re-search-forward paragraph-start nil t)
12590 (goto-char (match-beginning 0))
12591 (goto-char (point-max))))
12592
12593 (setq arg (1- arg))))) ; @r{decrementer}
12594@end group
12595@end smallexample
12596
12597The full definition for the @code{forward-paragraph} function not only
12598includes this code for going forwards, but also code for going backwards.
12599
12600If you are reading this inside of GNU Emacs and you want to see the
12601whole function, you can type @kbd{C-h f} (@code{describe-function})
12602and the name of the function. This gives you the function
12603documentation and the name of the library containing the function's
12604source. Place point over the name of the library and press the RET
12605key; you will be taken directly to the source. (Be sure to install
12606your sources! Without them, you are like a person who tries to drive
12607a car with his eyes shut!)
12608
12609@c !!! again, 21.0.100 tags table location in this paragraph
12610Or -- a good habit to get into -- you can type @kbd{M-.}
12611(@code{find-tag}) and the name of the function when prompted for it.
12612This will take you directly to the source. If the @code{find-tag}
12613function first asks you for the name of a @file{TAGS} table, give it
12614the name of the @file{TAGS} file such as
12615@file{/usr/local/share/emacs/21.0.100/lisp/TAGS}. (The exact path to your
12616@file{TAGS} file depends on how your copy of Emacs was installed.)
12617
12618You can also create your own @file{TAGS} file for directories that
12619lack one.
12620@ifnottex
12621@xref{etags, , Create Your Own @file{TAGS} File}.
12622@end ifnottex
12623
12624@node etags, Regexp Review, forward-paragraph, Regexp Search
12625@section Create Your Own @file{TAGS} File
12626@findex etags
12627@cindex @file{TAGS} file, create own
12628
12629The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12630source for a function, variable, node, or other source. The function
12631depends on tags tables to tell it where to go.
12632
12633You often need to build and install tags tables yourself. They are
12634not built automatically. A tags table is called a @file{TAGS} file;
12635the name is in upper case letters.
12636
12637You can create a @file{TAGS} file by calling the @code{etags} program
12638that comes as a part of the Emacs distribution. Usually, @code{etags}
12639is compiled and installed when Emacs is built. (@code{etags} is not
12640an Emacs Lisp function or a part of Emacs; it is a C program.)
12641
12642@need 1250
12643To create a @file{TAGS} file, first switch to the directory in which
12644you want to create the file. In Emacs you can do this with the
12645@kbd{M-x cd} command, or by visiting a file in the directory, or by
12646listing the directory with @kbd{C-x d} (@code{dired}). Then run the
12647compile command, with @w{@code{etags *.el}} as the command to execute
12648
12649@smallexample
12650M-x compile RET etags *.el RET
12651@end smallexample
12652
12653@noindent
12654to create a @file{TAGS} file.
12655
12656For example, if you have a large number of files in your
12657@file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12658of which I load 12---you can create a @file{TAGS} file for the Emacs
12659Lisp files in that directory.
12660
12661@need 1250
12662The @code{etags} program takes all the
12663usual shell `wildcards'. For example, if you have two directories for
12664which you want a single @file{TAGS file}, type
12665@w{@code{etags *.el ../elisp/*.el}},
12666where @file{../elisp/} is the second directory:
12667
12668@smallexample
12669M-x compile RET etags *.el ../elisp/*.el RET
12670@end smallexample
12671
12672@need 1250
12673Type
12674
12675@smallexample
12676M-x compile RET etags --help RET
12677@end smallexample
12678
12679@noindent
12680to see a list of the options accepted by @code{etags} as well as a
12681list of supported languages.
12682
12683The @code{etags} program handles more than 20 languages, including
12684Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12685Pascal, Perl, Python, Texinfo, makefiles, and most assemblers. The
12686program has no switches for specifying the language; it recognizes the
12687language in an input file according to its file name and contents.
12688
12689@file{etags} is very helpful when you are writing code yourself and
12690want to refer back to functions you have already written. Just run
12691@code{etags} again at intervals as you write new functions, so they
12692become part of the @file{TAGS} file.
12693
12694If you think an appropriate @file{TAGS} file already exists for what
12695you want, but do not know where it is, you can use the @code{locate}
12696program to attempt to find it.
12697
12698Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12699full path names of all your @file{TAGS} files. On my system, this
12700command lists 34 @file{TAGS} files. On the other hand, a `plain
12701vanilla' system I recently installed did not contain any @file{TAGS}
12702files.
12703
12704If the tags table you want has been created, you can use the @code{M-x
12705visit-tags-table} command to specify it. Otherwise, you will need to
12706create the tag table yourself and then use @code{M-x
12707visit-tags-table}.
12708
12709@subsubheading Building Tags in the Emacs sources
12710@cindex Building Tags in the Emacs sources
12711@cindex Tags in the Emacs sources
12712@findex make tags
12713
12714The GNU Emacs sources come with a @file{Makefile} that contains a
12715sophisticated @code{etags} command that creates, collects, and merges
12716tags tables from all over the Emacs sources and puts the information
12717into one @file{TAGS} file in the @file{src/} directory below the top
12718level of your Emacs source directory.
12719
12720@need 1250
12721To build this @file{TAGS} file, go to the top level of your Emacs
12722source directory and run the compile command @code{make tags}:
12723
12724@smallexample
12725M-x compile RET make tags RET
12726@end smallexample
12727
12728@noindent
12729(The @code{make tags} command works well with the GNU Emacs sources,
12730as well as with some other source packages.)
12731
12732For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12733Manual}.
12734
12735@node Regexp Review, re-search Exercises, etags, Regexp Search
12736@comment node-name, next, previous, up
12737@section Review
12738
12739Here is a brief summary of some recently introduced functions.
12740
12741@table @code
12742@item while
12743Repeatedly evaluate the body of the expression so long as the first
12744element of the body tests true. Then return @code{nil}. (The
12745expression is evaluated only for its side effects.)
12746
12747@need 1250
12748For example:
12749
12750@smallexample
12751@group
12752(let ((foo 2))
12753 (while (> foo 0)
12754 (insert (format "foo is %d.\n" foo))
12755 (setq foo (1- foo))))
12756
12757 @result{} foo is 2.
12758 foo is 1.
12759 nil
12760@end group
12761@end smallexample
12762@noindent
12763(The @code{insert} function inserts its arguments at point; the
12764@code{format} function returns a string formatted from its arguments
12765the way @code{message} formats its arguments; @code{\n} produces a new
12766line.)
12767
12768@item re-search-forward
12769Search for a pattern, and if the pattern is found, move point to rest
12770just after it.
12771
12772@noindent
12773Takes four arguments, like @code{search-forward}:
12774
12775@enumerate
12776@item
12777A regular expression that specifies the pattern to search for.
12778
12779@item
12780Optionally, the limit of the search.
12781
12782@item
12783Optionally, what to do if the search fails, return @code{nil} or an
12784error message.
12785
12786@item
12787Optionally, how many times to repeat the search; if negative, the
12788search goes backwards.
12789@end enumerate
12790
12791@item let*
12792Bind some variables locally to particular values,
12793and then evaluate the remaining arguments, returning the value of the
12794last one. While binding the local variables, use the local values of
12795variables bound earlier, if any.
12796
12797@need 1250
12798For example:
12799
12800@smallexample
12801@group
12802(let* ((foo 7)
12803 (bar (* 3 foo)))
12804 (message "`bar' is %d." bar))
12805 @result{} `bar' is 21.
12806@end group
12807@end smallexample
12808
12809@item match-beginning
12810Return the position of the start of the text found by the last regular
12811expression search.
12812
12813@item looking-at
12814Return @code{t} for true if the text after point matches the argument,
12815which should be a regular expression.
12816
12817@item eobp
12818Return @code{t} for true if point is at the end of the accessible part
12819of a buffer. The end of the accessible part is the end of the buffer
12820if the buffer is not narrowed; it is the end of the narrowed part if
12821the buffer is narrowed.
12822
12823@item prog1
12824Evaluate each argument in sequence and then return the value of the
12825@emph{first}.
12826
12827@need 1250
12828For example:
12829
12830@smallexample
12831@group
12832(prog1 1 2 3 4)
12833 @result{} 1
12834@end group
12835@end smallexample
12836@end table
12837
12838@need 1500
12839@node re-search Exercises, , Regexp Review, Regexp Search
12840@section Exercises with @code{re-search-forward}
12841
12842@itemize @bullet
12843@item
12844Write a function to search for a regular expression that matches two
12845or more blank lines in sequence.
12846
12847@item
12848Write a function to search for duplicated words, such as `the the'.
12849@xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12850Manual}, for information on how to write a regexp (a regular
12851expression) to match a string that is composed of two identical
12852halves. You can devise several regexps; some are better than others.
12853The function I use is described in an appendix, along with several
12854regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
12855@end itemize
12856
12857@node Counting Words, Words in a defun, Regexp Search, Top
12858@chapter Counting: Repetition and Regexps
12859@cindex Repetition for word counting
12860@cindex Regular expressions for word counting
12861
12862Repetition and regular expression searches are powerful tools that you
12863often use when you write code in Emacs Lisp. This chapter illustrates
12864the use of regular expression searches through the construction of
12865word count commands using @code{while} loops and recursion.
12866
12867@menu
12868* Why Count Words::
12869* count-words-region:: Use a regexp, but find a problem.
12870* recursive-count-words:: Start with case of no words in region.
12871* Counting Exercise::
12872@end menu
12873
12874@node Why Count Words, count-words-region, Counting Words, Counting Words
12875@ifnottex
12876@unnumberedsec Counting words
12877@end ifnottex
12878
12879The standard Emacs distribution contains a function for counting the
12880number of lines within a region. However, there is no corresponding
12881function for counting words.
12882
12883Certain types of writing ask you to count words. Thus, if you write
12884an essay, you may be limited to 800 words; if you write a novel, you
12885may discipline yourself to write 1000 words a day. It seems odd to me
12886that Emacs lacks a word count command. Perhaps people use Emacs
12887mostly for code or types of documentation that do not require word
12888counts; or perhaps they restrict themselves to the operating system
12889word count command, @code{wc}. Alternatively, people may follow
12890the publishers' convention and compute a word count by dividing the
12891number of characters in a document by five. In any event, here are
12892commands to count words.
12893
12894@node count-words-region, recursive-count-words, Why Count Words, Counting Words
12895@comment node-name, next, previous, up
12896@section The @code{count-words-region} Function
12897@findex count-words-region
12898
12899A word count command could count words in a line, paragraph, region,
12900or buffer. What should the command cover? You could design the
12901command to count the number of words in a complete buffer. However,
12902the Emacs tradition encourages flexibility---you may want to count
12903words in just a section, rather than all of a buffer. So it makes
12904more sense to design the command to count the number of words in a
12905region. Once you have a @code{count-words-region} command, you can,
12906if you wish, count words in a whole buffer by marking it with @kbd{C-x
12907h} (@code{mark-whole-buffer}).
12908
12909Clearly, counting words is a repetitive act: starting from the
12910beginning of the region, you count the first word, then the second
12911word, then the third word, and so on, until you reach the end of the
12912region. This means that word counting is ideally suited to recursion
12913or to a @code{while} loop.
12914
12915@menu
12916* Design count-words-region:: The definition using a @code{while} loop.
12917* Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
12918@end menu
12919
12920@node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12921@ifnottex
12922@unnumberedsubsec Designing @code{count-words-region}
12923@end ifnottex
12924
12925First, we will implement the word count command with a @code{while}
12926loop, then with recursion. The command will, of course, be
12927interactive.
12928
12929@need 800
12930The template for an interactive function definition is, as always:
12931
12932@smallexample
12933@group
12934(defun @var{name-of-function} (@var{argument-list})
12935 "@var{documentation}@dots{}"
12936 (@var{interactive-expression}@dots{})
12937 @var{body}@dots{})
12938@end group
12939@end smallexample
12940
12941What we need to do is fill in the slots.
12942
12943The name of the function should be self-explanatory and similar to the
12944existing @code{count-lines-region} name. This makes the name easier
12945to remember. @code{count-words-region} is a good choice.
12946
12947The function counts words within a region. This means that the
12948argument list must contain symbols that are bound to the two
12949positions, the beginning and end of the region. These two positions
12950can be called @samp{beginning} and @samp{end} respectively. The first
12951line of the documentation should be a single sentence, since that is
12952all that is printed as documentation by a command such as
12953@code{apropos}. The interactive expression will be of the form
12954@samp{(interactive "r")}, since that will cause Emacs to pass the
12955beginning and end of the region to the function's argument list. All
12956this is routine.
12957
12958The body of the function needs to be written to do three tasks:
12959first, to set up conditions under which the @code{while} loop can
12960count words, second, to run the @code{while} loop, and third, to send
12961a message to the user.
12962
12963When a user calls @code{count-words-region}, point may be at the
12964beginning or the end of the region. However, the counting process
12965must start at the beginning of the region. This means we will want
12966to put point there if it is not already there. Executing
12967@code{(goto-char beginning)} ensures this. Of course, we will want to
12968return point to its expected position when the function finishes its
12969work. For this reason, the body must be enclosed in a
12970@code{save-excursion} expression.
12971
12972The central part of the body of the function consists of a
12973@code{while} loop in which one expression jumps point forward word by
12974word, and another expression counts those jumps. The true-or-false-test
12975of the @code{while} loop should test true so long as point should jump
12976forward, and false when point is at the end of the region.
12977
12978We could use @code{(forward-word 1)} as the expression for moving point
12979forward word by word, but it is easier to see what Emacs identifies as a
12980`word' if we use a regular expression search.
12981
12982A regular expression search that finds the pattern for which it is
12983searching leaves point after the last character matched. This means
12984that a succession of successful word searches will move point forward
12985word by word.
12986
12987As a practical matter, we want the regular expression search to jump
12988over whitespace and punctuation between words as well as over the
12989words themselves. A regexp that refuses to jump over interword
12990whitespace would never jump more than one word! This means that
12991the regexp should include the whitespace and punctuation that follows
12992a word, if any, as well as the word itself. (A word may end a buffer
12993and not have any following whitespace or punctuation, so that part of
12994the regexp must be optional.)
12995
12996Thus, what we want for the regexp is a pattern defining one or more
12997word constituent characters followed, optionally, by one or more
12998characters that are not word constituents. The regular expression for
12999this is:
13000
13001@smallexample
13002\w+\W*
13003@end smallexample
13004
13005@noindent
13006The buffer's syntax table determines which characters are and are not
13007word constituents. (@xref{Syntax, , What Constitutes a Word or
13008Symbol?}, for more about syntax. Also, see @ref{Syntax, Syntax, The
13009Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
13010Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13011
13012@need 800
13013The search expression looks like this:
13014
13015@smallexample
13016(re-search-forward "\\w+\\W*")
13017@end smallexample
13018
13019@noindent
13020(Note that paired backslashes precede the @samp{w} and @samp{W}. A
13021single backslash has special meaning to the Emacs Lisp interpreter. It
13022indicates that the following character is interpreted differently than
13023usual. For example, the two characters, @samp{\n}, stand for
13024@samp{newline}, rather than for a backslash followed by @samp{n}. Two
13025backslashes in a row stand for an ordinary, `unspecial' backslash.)
13026
13027We need a counter to count how many words there are; this variable
13028must first be set to 0 and then incremented each time Emacs goes
13029around the @code{while} loop. The incrementing expression is simply:
13030
13031@smallexample
13032(setq count (1+ count))
13033@end smallexample
13034
13035Finally, we want to tell the user how many words there are in the
13036region. The @code{message} function is intended for presenting this
13037kind of information to the user. The message has to be phrased so
13038that it reads properly regardless of how many words there are in the
13039region: we don't want to say that ``there are 1 words in the region''.
13040The conflict between singular and plural is ungrammatical. We can
13041solve this problem by using a conditional expression that evaluates
13042different messages depending on the number of words in the region.
13043There are three possibilities: no words in the region, one word in the
13044region, and more than one word. This means that the @code{cond}
13045special form is appropriate.
13046
13047@need 1500
13048All this leads to the following function definition:
13049
13050@smallexample
13051@group
13052;;; @r{First version; has bugs!}
13053(defun count-words-region (beginning end)
13054 "Print number of words in the region.
13055Words are defined as at least one word-constituent
13056character followed by at least one character that
13057is not a word-constituent. The buffer's syntax
13058table determines which characters these are."
13059 (interactive "r")
13060 (message "Counting words in region ... ")
13061@end group
13062
13063@group
13064;;; @r{1. Set up appropriate conditions.}
13065 (save-excursion
13066 (goto-char beginning)
13067 (let ((count 0))
13068@end group
13069
13070@group
13071;;; @r{2. Run the} while @r{loop.}
13072 (while (< (point) end)
13073 (re-search-forward "\\w+\\W*")
13074 (setq count (1+ count)))
13075@end group
13076
13077@group
13078;;; @r{3. Send a message to the user.}
13079 (cond ((zerop count)
13080 (message
13081 "The region does NOT have any words."))
13082 ((= 1 count)
13083 (message
13084 "The region has 1 word."))
13085 (t
13086 (message
13087 "The region has %d words." count))))))
13088@end group
13089@end smallexample
13090
13091@noindent
13092As written, the function works, but not in all circumstances.
13093
13094@node Whitespace Bug, , Design count-words-region, count-words-region
13095@comment node-name, next, previous, up
13096@subsection The Whitespace Bug in @code{count-words-region}
13097
13098The @code{count-words-region} command described in the preceding
13099section has two bugs, or rather, one bug with two manifestations.
13100First, if you mark a region containing only whitespace in the middle
13101of some text, the @code{count-words-region} command tells you that the
13102region contains one word! Second, if you mark a region containing
13103only whitespace at the end of the buffer or the accessible portion of
13104a narrowed buffer, the command displays an error message that looks
13105like this:
13106
13107@smallexample
13108Search failed: "\\w+\\W*"
13109@end smallexample
13110
13111If you are reading this in Info in GNU Emacs, you can test for these
13112bugs yourself.
13113
13114First, evaluate the function in the usual manner to install it.
13115@ifinfo
13116Here is a copy of the definition. Place your cursor after the closing
13117parenthesis and type @kbd{C-x C-e} to install it.
13118
13119@smallexample
13120@group
13121;; @r{First version; has bugs!}
13122(defun count-words-region (beginning end)
13123 "Print number of words in the region.
13124Words are defined as at least one word-constituent character followed
13125by at least one character that is not a word-constituent. The buffer's
13126syntax table determines which characters these are."
13127@end group
13128@group
13129 (interactive "r")
13130 (message "Counting words in region ... ")
13131@end group
13132
13133@group
13134;;; @r{1. Set up appropriate conditions.}
13135 (save-excursion
13136 (goto-char beginning)
13137 (let ((count 0))
13138@end group
13139
13140@group
13141;;; @r{2. Run the} while @r{loop.}
13142 (while (< (point) end)
13143 (re-search-forward "\\w+\\W*")
13144 (setq count (1+ count)))
13145@end group
13146
13147@group
13148;;; @r{3. Send a message to the user.}
13149 (cond ((zerop count)
13150 (message "The region does NOT have any words."))
13151 ((= 1 count) (message "The region has 1 word."))
13152 (t (message "The region has %d words." count))))))
13153@end group
13154@end smallexample
13155@end ifinfo
13156
13157@need 1000
13158If you wish, you can also install this keybinding by evaluating it:
13159
13160@smallexample
13161(global-set-key "\C-c=" 'count-words-region)
13162@end smallexample
13163
13164To conduct the first test, set mark and point to the beginning and end
13165of the following line and then type @kbd{C-c =} (or @kbd{M-x
13166count-words-region} if you have not bound @kbd{C-c =}):
13167
13168@smallexample
13169 one two three
13170@end smallexample
13171
13172@noindent
13173Emacs will tell you, correctly, that the region has three words.
13174
13175Repeat the test, but place mark at the beginning of the line and place
13176point just @emph{before} the word @samp{one}. Again type the command
13177@kbd{C-c =} (or @kbd{M-x count-words-region}). Emacs should tell you
13178that the region has no words, since it is composed only of the
13179whitespace at the beginning of the line. But instead Emacs tells you
13180that the region has one word!
13181
13182For the third test, copy the sample line to the end of the
13183@file{*scratch*} buffer and then type several spaces at the end of the
13184line. Place mark right after the word @samp{three} and point at the
13185end of line. (The end of the line will be the end of the buffer.)
13186Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13187Again, Emacs should tell you that the region has no words, since it is
13188composed only of the whitespace at the end of the line. Instead,
13189Emacs displays an error message saying @samp{Search failed}.
13190
13191The two bugs stem from the same problem.
13192
13193Consider the first manifestation of the bug, in which the command
13194tells you that the whitespace at the beginning of the line contains
13195one word. What happens is this: The @code{M-x count-words-region}
13196command moves point to the beginning of the region. The @code{while}
13197tests whether the value of point is smaller than the value of
13198@code{end}, which it is. Consequently, the regular expression search
13199looks for and finds the first word. It leaves point after the word.
13200@code{count} is set to one. The @code{while} loop repeats; but this
13201time the value of point is larger than the value of @code{end}, the
13202loop is exited; and the function displays a message saying the number
13203of words in the region is one. In brief, the regular expression
13204search looks for and finds the word even though it is outside
13205the marked region.
13206
13207In the second manifestation of the bug, the region is whitespace at
13208the end of the buffer. Emacs says @samp{Search failed}. What happens
13209is that the true-or-false-test in the @code{while} loop tests true, so
13210the search expression is executed. But since there are no more words
13211in the buffer, the search fails.
13212
13213In both manifestations of the bug, the search extends or attempts to
13214extend outside of the region.
13215
13216The solution is to limit the search to the region---this is a fairly
13217simple action, but as you may have come to expect, it is not quite as
13218simple as you might think.
13219
13220As we have seen, the @code{re-search-forward} function takes a search
13221pattern as its first argument. But in addition to this first,
13222mandatory argument, it accepts three optional arguments. The optional
13223second argument bounds the search. The optional third argument, if
13224@code{t}, causes the function to return @code{nil} rather than signal
13225an error if the search fails. The optional fourth argument is a
13226repeat count. (In Emacs, you can see a function's documentation by
13227typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13228
13229In the @code{count-words-region} definition, the value of the end of
13230the region is held by the variable @code{end} which is passed as an
13231argument to the function. Thus, we can add @code{end} as an argument
13232to the regular expression search expression:
13233
13234@smallexample
13235(re-search-forward "\\w+\\W*" end)
13236@end smallexample
13237
13238However, if you make only this change to the @code{count-words-region}
13239definition and then test the new version of the definition on a
13240stretch of whitespace, you will receive an error message saying
13241@samp{Search failed}.
13242
13243What happens is this: the search is limited to the region, and fails
13244as you expect because there are no word-constituent characters in the
13245region. Since it fails, we receive an error message. But we do not
13246want to receive an error message in this case; we want to receive the
13247message that "The region does NOT have any words."
13248
13249The solution to this problem is to provide @code{re-search-forward}
13250with a third argument of @code{t}, which causes the function to return
13251@code{nil} rather than signal an error if the search fails.
13252
13253However, if you make this change and try it, you will see the message
13254``Counting words in region ... '' and @dots{} you will keep on seeing
13255that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13256
13257Here is what happens: the search is limited to the region, as before,
13258and it fails because there are no word-constituent characters in the
13259region, as expected. Consequently, the @code{re-search-forward}
13260expression returns @code{nil}. It does nothing else. In particular,
13261it does not move point, which it does as a side effect if it finds the
13262search target. After the @code{re-search-forward} expression returns
13263@code{nil}, the next expression in the @code{while} loop is evaluated.
13264This expression increments the count. Then the loop repeats. The
13265true-or-false-test tests true because the value of point is still less
13266than the value of end, since the @code{re-search-forward} expression
13267did not move point. @dots{} and the cycle repeats @dots{}
13268
13269The @code{count-words-region} definition requires yet another
13270modification, to cause the true-or-false-test of the @code{while} loop
13271to test false if the search fails. Put another way, there are two
13272conditions that must be satisfied in the true-or-false-test before the
13273word count variable is incremented: point must still be within the
13274region and the search expression must have found a word to count.
13275
13276Since both the first condition and the second condition must be true
13277together, the two expressions, the region test and the search
13278expression, can be joined with an @code{and} special form and embedded in
13279the @code{while} loop as the true-or-false-test, like this:
13280
13281@smallexample
13282(and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13283@end smallexample
13284
13285@c colon in printed section title causes problem in Info cross reference
13286@c also trouble with an overfull hbox
13287@iftex
13288@noindent
13289(For information about @code{and}, see
13290@ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13291Functions}.)
13292@end iftex
13293@ifinfo
13294@noindent
13295(@xref{forward-paragraph}, for information about @code{and}.)
13296@end ifinfo
13297
13298The @code{re-search-forward} expression returns @code{t} if the search
13299succeeds and as a side effect moves point. Consequently, as words are
13300found, point is moved through the region. When the search
13301expression fails to find another word, or when point reaches the end
13302of the region, the true-or-false-test tests false, the @code{while}
13303loop exists, and the @code{count-words-region} function displays one
13304or other of its messages.
13305
13306After incorporating these final changes, the @code{count-words-region}
13307works without bugs (or at least, without bugs that I have found!).
13308Here is what it looks like:
13309
13310@smallexample
13311@group
13312;;; @r{Final version:} @code{while}
13313(defun count-words-region (beginning end)
13314 "Print number of words in the region."
13315 (interactive "r")
13316 (message "Counting words in region ... ")
13317@end group
13318
13319@group
13320;;; @r{1. Set up appropriate conditions.}
13321 (save-excursion
13322 (let ((count 0))
13323 (goto-char beginning)
13324@end group
13325
13326@group
13327;;; @r{2. Run the} while @r{loop.}
13328 (while (and (< (point) end)
13329 (re-search-forward "\\w+\\W*" end t))
13330 (setq count (1+ count)))
13331@end group
13332
13333@group
13334;;; @r{3. Send a message to the user.}
13335 (cond ((zerop count)
13336 (message
13337 "The region does NOT have any words."))
13338 ((= 1 count)
13339 (message
13340 "The region has 1 word."))
13341 (t
13342 (message
13343 "The region has %d words." count))))))
13344@end group
13345@end smallexample
13346
13347@node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13348@comment node-name, next, previous, up
13349@section Count Words Recursively
13350@cindex Count words recursively
13351@cindex Recursively counting words
13352@cindex Words, counted recursively
13353
13354You can write the function for counting words recursively as well as
13355with a @code{while} loop. Let's see how this is done.
13356
13357First, we need to recognize that the @code{count-words-region}
13358function has three jobs: it sets up the appropriate conditions for
13359counting to occur; it counts the words in the region; and it sends a
13360message to the user telling how many words there are.
13361
13362If we write a single recursive function to do everything, we will
13363receive a message for every recursive call. If the region contains 13
13364words, we will receive thirteen messages, one right after the other.
13365We don't want this! Instead, we must write two functions to do the
13366job, one of which (the recursive function) will be used inside of the
13367other. One function will set up the conditions and display the
13368message; the other will return the word count.
13369
13370Let us start with the function that causes the message to be displayed.
13371We can continue to call this @code{count-words-region}.
13372
13373This is the function that the user will call. It will be interactive.
13374Indeed, it will be similar to our previous versions of this
13375function, except that it will call @code{recursive-count-words} to
13376determine how many words are in the region.
13377
13378@need 1250
13379We can readily construct a template for this function, based on our
13380previous versions:
13381
13382@smallexample
13383@group
13384;; @r{Recursive version; uses regular expression search}
13385(defun count-words-region (beginning end)
13386 "@var{documentation}@dots{}"
13387 (@var{interactive-expression}@dots{})
13388@end group
13389@group
13390
13391;;; @r{1. Set up appropriate conditions.}
13392 (@var{explanatory message})
13393 (@var{set-up functions}@dots{}
13394@end group
13395@group
13396
13397;;; @r{2. Count the words.}
13398 @var{recursive call}
13399@end group
13400@group
13401
13402;;; @r{3. Send a message to the user.}
13403 @var{message providing word count}))
13404@end group
13405@end smallexample
13406
13407The definition looks straightforward, except that somehow the count
13408returned by the recursive call must be passed to the message
13409displaying the word count. A little thought suggests that this can be
13410done by making use of a @code{let} expression: we can bind a variable
13411in the varlist of a @code{let} expression to the number of words in
13412the region, as returned by the recursive call; and then the
13413@code{cond} expression, using binding, can display the value to the
13414user.
13415
13416Often, one thinks of the binding within a @code{let} expression as
13417somehow secondary to the `primary' work of a function. But in this
13418case, what you might consider the `primary' job of the function,
13419counting words, is done within the @code{let} expression.
13420
13421@need 1250
13422Using @code{let}, the function definition looks like this:
13423
13424@smallexample
13425@group
13426(defun count-words-region (beginning end)
13427 "Print number of words in the region."
13428 (interactive "r")
13429@end group
13430
13431@group
13432;;; @r{1. Set up appropriate conditions.}
13433 (message "Counting words in region ... ")
13434 (save-excursion
13435 (goto-char beginning)
13436@end group
13437
13438@group
13439;;; @r{2. Count the words.}
13440 (let ((count (recursive-count-words end)))
13441@end group
13442
13443@group
13444;;; @r{3. Send a message to the user.}
13445 (cond ((zerop count)
13446 (message
13447 "The region does NOT have any words."))
13448 ((= 1 count)
13449 (message
13450 "The region has 1 word."))
13451 (t
13452 (message
13453 "The region has %d words." count))))))
13454@end group
13455@end smallexample
13456
13457Next, we need to write the recursive counting function.
13458
13459A recursive function has at least three parts: the `do-again-test', the
13460`next-step-expression', and the recursive call.
13461
13462The do-again-test determines whether the function will or will not be
13463called again. Since we are counting words in a region and can use a
13464function that moves point forward for every word, the do-again-test
13465can check whether point is still within the region. The do-again-test
13466should find the value of point and determine whether point is before,
13467at, or after the value of the end of the region. We can use the
13468@code{point} function to locate point. Clearly, we must pass the
13469value of the end of the region to the recursive counting function as an
13470argument.
13471
13472In addition, the do-again-test should also test whether the search finds a
13473word. If it does not, the function should not call itself again.
13474
13475The next-step-expression changes a value so that when the recursive
13476function is supposed to stop calling itself, it stops. More
13477precisely, the next-step-expression changes a value so that at the
13478right time, the do-again-test stops the recursive function from
13479calling itself again. In this case, the next-step-expression can be
13480the expression that moves point forward, word by word.
13481
13482The third part of a recursive function is the recursive call.
13483
13484Somewhere, also, we also need a part that does the `work' of the
13485function, a part that does the counting. A vital part!
13486
13487@need 1250
13488But already, we have an outline of the recursive counting function:
13489
13490@smallexample
13491@group
13492(defun recursive-count-words (region-end)
13493 "@var{documentation}@dots{}"
13494 @var{do-again-test}
13495 @var{next-step-expression}
13496 @var{recursive call})
13497@end group
13498@end smallexample
13499
13500Now we need to fill in the slots. Let's start with the simplest cases
13501first: if point is at or beyond the end of the region, there cannot
13502be any words in the region, so the function should return zero.
13503Likewise, if the search fails, there are no words to count, so the
13504function should return zero.
13505
13506On the other hand, if point is within the region and the search
13507succeeds, the function should call itself again.
13508
13509@need 800
13510Thus, the do-again-test should look like this:
13511
13512@smallexample
13513@group
13514(and (< (point) region-end)
13515 (re-search-forward "\\w+\\W*" region-end t))
13516@end group
13517@end smallexample
13518
13519Note that the search expression is part of the do-again-test---the
13520function returns @code{t} if its search succeeds and @code{nil} if it
13521fails. (@xref{Whitespace Bug, , The Whitespace Bug in
13522@code{count-words-region}}, for an explanation of how
13523@code{re-search-forward} works.)
13524
13525The do-again-test is the true-or-false test of an @code{if} clause.
13526Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13527clause should call the function again; but if it fails, the else-part
13528should return zero since either point is outside the region or the
13529search failed because there were no words to find.
13530
13531But before considering the recursive call, we need to consider the
13532next-step-expression. What is it? Interestingly, it is the search
13533part of the do-again-test.
13534
13535In addition to returning @code{t} or @code{nil} for the
13536do-again-test, @code{re-search-forward} moves point forward as a side
13537effect of a successful search. This is the action that changes the
13538value of point so that the recursive function stops calling itself
13539when point completes its movement through the region. Consequently,
13540the @code{re-search-forward} expression is the next-step-expression.
13541
13542@need 1200
13543In outline, then, the body of the @code{recursive-count-words}
13544function looks like this:
13545
13546@smallexample
13547@group
13548(if @var{do-again-test-and-next-step-combined}
13549 ;; @r{then}
13550 @var{recursive-call-returning-count}
13551 ;; @r{else}
13552 @var{return-zero})
13553@end group
13554@end smallexample
13555
13556How to incorporate the mechanism that counts?
13557
13558If you are not used to writing recursive functions, a question like
13559this can be troublesome. But it can and should be approached
13560systematically.
13561
13562We know that the counting mechanism should be associated in some way
13563with the recursive call. Indeed, since the next-step-expression moves
13564point forward by one word, and since a recursive call is made for
13565each word, the counting mechanism must be an expression that adds one
13566to the value returned by a call to @code{recursive-count-words}.
13567
13568Consider several cases:
13569
13570@itemize @bullet
13571@item
13572If there are two words in the region, the function should return
13573a value resulting from adding one to the value returned when it counts
13574the first word, plus the number returned when it counts the remaining
13575words in the region, which in this case is one.
13576
13577@item
13578If there is one word in the region, the function should return
13579a value resulting from adding one to the value returned when it counts
13580that word, plus the number returned when it counts the remaining
13581words in the region, which in this case is zero.
13582
13583@item
13584If there are no words in the region, the function should return zero.
13585@end itemize
13586
13587From the sketch we can see that the else-part of the @code{if} returns
13588zero for the case of no words. This means that the then-part of the
13589@code{if} must return a value resulting from adding one to the value
13590returned from a count of the remaining words.
13591
13592@need 1200
13593The expression will look like this, where @code{1+} is a function that
13594adds one to its argument.
13595
13596@smallexample
13597(1+ (recursive-count-words region-end))
13598@end smallexample
13599
13600@need 1200
13601The whole @code{recursive-count-words} function will then look like
13602this:
13603
13604@smallexample
13605@group
13606(defun recursive-count-words (region-end)
13607 "@var{documentation}@dots{}"
13608
13609;;; @r{1. do-again-test}
13610 (if (and (< (point) region-end)
13611 (re-search-forward "\\w+\\W*" region-end t))
13612@end group
13613
13614@group
13615;;; @r{2. then-part: the recursive call}
13616 (1+ (recursive-count-words region-end))
13617
13618;;; @r{3. else-part}
13619 0))
13620@end group
13621@end smallexample
13622
13623@need 1250
13624Let's examine how this works:
13625
13626If there are no words in the region, the else part of the @code{if}
13627expression is evaluated and consequently the function returns zero.
13628
13629If there is one word in the region, the value of point is less than
13630the value of @code{region-end} and the search succeeds. In this case,
13631the true-or-false-test of the @code{if} expression tests true, and the
13632then-part of the @code{if} expression is evaluated. The counting
13633expression is evaluated. This expression returns a value (which will
13634be the value returned by the whole function) that is the sum of one
13635added to the value returned by a recursive call.
13636
13637Meanwhile, the next-step-expression has caused point to jump over the
13638first (and in this case only) word in the region. This means that
13639when @code{(recursive-count-words region-end)} is evaluated a second
13640time, as a result of the recursive call, the value of point will be
13641equal to or greater than the value of region end. So this time,
13642@code{recursive-count-words} will return zero. The zero will be added
13643to one, and the original evaluation of @code{recursive-count-words}
13644will return one plus zero, which is one, which is the correct amount.
13645
13646Clearly, if there are two words in the region, the first call to
13647@code{recursive-count-words} returns one added to the value returned
13648by calling @code{recursive-count-words} on a region containing the
13649remaining word---that is, it adds one to one, producing two, which is
13650the correct amount.
13651
13652Similarly, if there are three words in the region, the first call to
13653@code{recursive-count-words} returns one added to the value returned
13654by calling @code{recursive-count-words} on a region containing the
13655remaining two words---and so on and so on.
13656
13657@need 1250
13658@noindent
13659With full documentation the two functions look like this:
13660
13661@need 1250
13662@noindent
13663The recursive function:
13664
13665@findex recursive-count-words
13666@smallexample
13667@group
13668(defun recursive-count-words (region-end)
13669 "Number of words between point and REGION-END."
13670@end group
13671
13672@group
13673;;; @r{1. do-again-test}
13674 (if (and (< (point) region-end)
13675 (re-search-forward "\\w+\\W*" region-end t))
13676@end group
13677
13678@group
13679;;; @r{2. then-part: the recursive call}
13680 (1+ (recursive-count-words region-end))
13681
13682;;; @r{3. else-part}
13683 0))
13684@end group
13685@end smallexample
13686
13687@need 800
13688@noindent
13689The wrapper:
13690
13691@smallexample
13692@group
13693;;; @r{Recursive version}
13694(defun count-words-region (beginning end)
13695 "Print number of words in the region.
13696@end group
13697
13698@group
13699Words are defined as at least one word-constituent
13700character followed by at least one character that is
13701not a word-constituent. The buffer's syntax table
13702determines which characters these are."
13703@end group
13704@group
13705 (interactive "r")
13706 (message "Counting words in region ... ")
13707 (save-excursion
13708 (goto-char beginning)
13709 (let ((count (recursive-count-words end)))
13710@end group
13711@group
13712 (cond ((zerop count)
13713 (message
13714 "The region does NOT have any words."))
13715@end group
13716@group
13717 ((= 1 count)
13718 (message "The region has 1 word."))
13719 (t
13720 (message
13721 "The region has %d words." count))))))
13722@end group
13723@end smallexample
13724
13725@node Counting Exercise, , recursive-count-words, Counting Words
13726@section Exercise: Counting Punctuation
13727
13728Using a @code{while} loop, write a function to count the number of
13729punctuation marks in a region---period, comma, semicolon, colon,
13730exclamation mark, and question mark. Do the same using recursion.
13731
13732@node Words in a defun, Readying a Graph, Counting Words, Top
13733@chapter Counting Words in a @code{defun}
13734@cindex Counting words in a @code{defun}
13735@cindex Word counting in a @code{defun}
13736
13737Our next project is to count the number of words in a function
13738definition. Clearly, this can be done using some variant of
13739@code{count-word-region}. @xref{Counting Words, , Counting Words:
13740Repetition and Regexps}. If we are just going to count the words in
13741one definition, it is easy enough to mark the definition with the
13742@kbd{C-M-h} (@code{mark-defun}) command, and then call
13743@code{count-word-region}.
13744
13745However, I am more ambitious: I want to count the words and symbols in
13746every definition in the Emacs sources and then print a graph that
13747shows how many functions there are of each length: how many contain 40
13748to 49 words or symbols, how many contain 50 to 59 words or symbols,
13749and so on. I have often been curious how long a typical function is,
13750and this will tell.
13751
13752@menu
13753* Divide and Conquer::
13754* Words and Symbols:: What to count?
13755* Syntax:: What constitutes a word or symbol?
13756* count-words-in-defun:: Very like @code{count-words}.
13757* Several defuns:: Counting several defuns in a file.
13758* Find a File:: Do you want to look at a file?
13759* lengths-list-file:: A list of the lengths of many definitions.
13760* Several files:: Counting in definitions in different files.
13761* Several files recursively:: Recursively counting in different files.
13762* Prepare the data:: Prepare the data for display in a graph.
13763@end menu
13764
13765@node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13766@ifnottex
13767@unnumberedsec Divide and Conquer
13768@end ifnottex
13769
13770Described in one phrase, the histogram project is daunting; but
13771divided into numerous small steps, each of which we can take one at a
13772time, the project becomes less fearsome. Let us consider what the
13773steps must be:
13774
13775@itemize @bullet
13776@item
13777First, write a function to count the words in one definition. This
13778includes the problem of handling symbols as well as words.
13779
13780@item
13781Second, write a function to list the numbers of words in each function
13782in a file. This function can use the @code{count-words-in-defun}
13783function.
13784
13785@item
13786Third, write a function to list the numbers of words in each function
13787in each of several files. This entails automatically finding the
13788various files, switching to them, and counting the words in the
13789definitions within them.
13790
13791@item
13792Fourth, write a function to convert the list of numbers that we
13793created in step three to a form that will be suitable for printing as
13794a graph.
13795
13796@item
13797Fifth, write a function to print the results as a graph.
13798@end itemize
13799
13800This is quite a project! But if we take each step slowly, it will not
13801be difficult.
13802
13803@node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13804@section What to Count?
13805@cindex Words and symbols in defun
13806
13807When we first start thinking about how to count the words in a
13808function definition, the first question is (or ought to be) what are
13809we going to count? When we speak of `words' with respect to a Lisp
13810function definition, we are actually speaking, in large part, of
13811`symbols'. For example, the following @code{multiply-by-seven}
13812function contains the five symbols @code{defun},
13813@code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
13814addition, in the documentation string, it contains the four words
13815@samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
13816symbol @samp{number} is repeated, so the definition contains a total
13817of ten words and symbols.
13818
13819@smallexample
13820@group
13821(defun multiply-by-seven (number)
13822 "Multiply NUMBER by seven."
13823 (* 7 number))
13824@end group
13825@end smallexample
13826
13827@noindent
13828However, if we mark the @code{multiply-by-seven} definition with
13829@kbd{C-M-h} (@code{mark-defun}), and then call
13830@code{count-words-region} on it, we will find that
13831@code{count-words-region} claims the definition has eleven words, not
13832ten! Something is wrong!
13833
13834The problem is twofold: @code{count-words-region} does not count the
13835@samp{*} as a word, and it counts the single symbol,
13836@code{multiply-by-seven}, as containing three words. The hyphens are
13837treated as if they were interword spaces rather than intraword
13838connectors: @samp{multiply-by-seven} is counted as if it were written
13839@samp{multiply by seven}.
13840
13841The cause of this confusion is the regular expression search within
13842the @code{count-words-region} definition that moves point forward word
13843by word. In the canonical version of @code{count-words-region}, the
13844regexp is:
13845
13846@smallexample
13847"\\w+\\W*"
13848@end smallexample
13849
13850@noindent
13851This regular expression is a pattern defining one or more word
13852constituent characters possibly followed by one or more characters
13853that are not word constituents. What is meant by `word constituent
13854characters' brings us to the issue of syntax, which is worth a section
13855of its own.
13856
13857@node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13858@section What Constitutes a Word or Symbol?
13859@cindex Syntax categories and tables
13860
13861Emacs treats different characters as belonging to different
13862@dfn{syntax categories}. For example, the regular expression,
13863@samp{\\w+}, is a pattern specifying one or more @emph{word
13864constituent} characters. Word constituent characters are members of
13865one syntax category. Other syntax categories include the class of
13866punctuation characters, such as the period and the comma, and the
13867class of whitespace characters, such as the blank space and the tab
13868character. (For more information, see @ref{Syntax, Syntax, The Syntax
13869Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13870Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13871
13872Syntax tables specify which characters belong to which categories.
13873Usually, a hyphen is not specified as a `word constituent character'.
13874Instead, it is specified as being in the `class of characters that are
13875part of symbol names but not words.' This means that the
13876@code{count-words-region} function treats it in the same way it treats
13877an interword white space, which is why @code{count-words-region}
13878counts @samp{multiply-by-seven} as three words.
13879
13880There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13881one symbol: modify the syntax table or modify the regular expression.
13882
13883We could redefine a hyphen as a word constituent character by
13884modifying the syntax table that Emacs keeps for each mode. This
13885action would serve our purpose, except that a hyphen is merely the
13886most common character within symbols that is not typically a word
13887constituent character; there are others, too.
13888
13889Alternatively, we can redefine the regular expression used in the
13890@code{count-words} definition so as to include symbols. This
13891procedure has the merit of clarity, but the task is a little tricky.
13892
13893@need 1200
13894The first part is simple enough: the pattern must match ``at least one
13895character that is a word or symbol constituent''. Thus:
13896
13897@smallexample
13898"\\(\\w\\|\\s_\\)+"
13899@end smallexample
13900
13901@noindent
13902The @samp{\\(} is the first part of the grouping construct that
13903includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13904by the @samp{\\|}. The @samp{\\w} matches any word-constituent
13905character and the @samp{\\s_} matches any character that is part of a
13906symbol name but not a word-constituent character. The @samp{+}
13907following the group indicates that the word or symbol constituent
13908characters must be matched at least once.
13909
13910However, the second part of the regexp is more difficult to design.
13911What we want is to follow the first part with ``optionally one or more
13912characters that are not constituents of a word or symbol''. At first,
13913I thought I could define this with the following:
13914
13915@smallexample
13916"\\(\\W\\|\\S_\\)*"
13917@end smallexample
13918
13919@noindent
13920The upper case @samp{W} and @samp{S} match characters that are
13921@emph{not} word or symbol constituents. Unfortunately, this
13922expression matches any character that is either not a word constituent
13923or not a symbol constituent. This matches any character!
13924
13925I then noticed that every word or symbol in my test region was
13926followed by white space (blank space, tab, or newline). So I tried
13927placing a pattern to match one or more blank spaces after the pattern
13928for one or more word or symbol constituents. This failed, too. Words
13929and symbols are often separated by whitespace, but in actual code
13930parentheses may follow symbols and punctuation may follow words. So
13931finally, I designed a pattern in which the word or symbol constituents
13932are followed optionally by characters that are not white space and
13933then followed optionally by white space.
13934
13935@need 800
13936Here is the full regular expression:
13937
13938@smallexample
13939"\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13940@end smallexample
13941
13942@node count-words-in-defun, Several defuns, Syntax, Words in a defun
13943@section The @code{count-words-in-defun} Function
13944@cindex Counting words in a @code{defun}
13945
13946We have seen that there are several ways to write a
13947@code{count-word-region} function. To write a
13948@code{count-words-in-defun}, we need merely adapt one of these
13949versions.
13950
13951The version that uses a @code{while} loop is easy to understand, so I
13952am going to adapt that. Because @code{count-words-in-defun} will be
13953part of a more complex program, it need not be interactive and it need
13954not display a message but just return the count. These considerations
13955simplify the definition a little.
13956
13957On the other hand, @code{count-words-in-defun} will be used within a
13958buffer that contains function definitions. Consequently, it is
13959reasonable to ask that the function determine whether it is called
13960when point is within a function definition, and if it is, to return
13961the count for that definition. This adds complexity to the
13962definition, but saves us from needing to pass arguments to the
13963function.
13964
13965@need 1250
13966These considerations lead us to prepare the following template:
13967
13968@smallexample
13969@group
13970(defun count-words-in-defun ()
13971 "@var{documentation}@dots{}"
13972 (@var{set up}@dots{}
13973 (@var{while loop}@dots{})
13974 @var{return count})
13975@end group
13976@end smallexample
13977
13978@noindent
13979As usual, our job is to fill in the slots.
13980
13981First, the set up.
13982
13983We are presuming that this function will be called within a buffer
13984containing function definitions. Point will either be within a
13985function definition or not. For @code{count-words-in-defun} to work,
13986point must move to the beginning of the definition, a counter must
13987start at zero, and the counting loop must stop when point reaches the
13988end of the definition.
13989
13990The @code{beginning-of-defun} function searches backwards for an
13991opening delimiter such as a @samp{(} at the beginning of a line, and
13992moves point to that position, or else to the limit of the search. In
13993practice, this means that @code{beginning-of-defun} moves point to the
13994beginning of an enclosing or preceding function definition, or else to
13995the beginning of the buffer. We can use @code{beginning-of-defun} to
13996place point where we wish to start.
13997
13998The @code{while} loop requires a counter to keep track of the words or
13999symbols being counted. A @code{let} expression can be used to create
14000a local variable for this purpose, and bind it to an initial value of zero.
14001
14002The @code{end-of-defun} function works like @code{beginning-of-defun}
14003except that it moves point to the end of the definition.
14004@code{end-of-defun} can be used as part of an expression that
14005determines the position of the end of the definition.
14006
14007The set up for @code{count-words-in-defun} takes shape rapidly: first
14008we move point to the beginning of the definition, then we create a
14009local variable to hold the count, and finally, we record the position
14010of the end of the definition so the @code{while} loop will know when to stop
14011looping.
14012
14013@need 1250
14014The code looks like this:
14015
14016@smallexample
14017@group
14018(beginning-of-defun)
14019(let ((count 0)
14020 (end (save-excursion (end-of-defun) (point))))
14021@end group
14022@end smallexample
14023
14024@noindent
14025The code is simple. The only slight complication is likely to concern
14026@code{end}: it is bound to the position of the end of the definition
14027by a @code{save-excursion} expression that returns the value of point
14028after @code{end-of-defun} temporarily moves it to the end of the
14029definition.
14030
14031The second part of the @code{count-words-in-defun}, after the set up,
14032is the @code{while} loop.
14033
14034The loop must contain an expression that jumps point forward word by
14035word and symbol by symbol, and another expression that counts the
14036jumps. The true-or-false-test for the @code{while} loop should test
14037true so long as point should jump forward, and false when point is at
14038the end of the definition. We have already redefined the regular
14039expression for this (@pxref{Syntax}), so the loop is straightforward:
14040
14041@smallexample
14042@group
14043(while (and (< (point) end)
14044 (re-search-forward
14045 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14046 (setq count (1+ count)))
14047@end group
14048@end smallexample
14049
14050The third part of the function definition returns the count of words
14051and symbols. This part is the last expression within the body of the
14052@code{let} expression, and can be, very simply, the local variable
14053@code{count}, which when evaluated returns the count.
14054
14055@need 1250
14056Put together, the @code{count-words-in-defun} definition looks like this:
14057
14058@findex count-words-in-defun
14059@smallexample
14060@group
14061(defun count-words-in-defun ()
14062 "Return the number of words and symbols in a defun."
14063 (beginning-of-defun)
14064 (let ((count 0)
14065 (end (save-excursion (end-of-defun) (point))))
14066@end group
14067@group
14068 (while
14069 (and (< (point) end)
14070 (re-search-forward
14071 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14072 end t))
14073 (setq count (1+ count)))
14074 count))
14075@end group
14076@end smallexample
14077
14078How to test this? The function is not interactive, but it is easy to
14079put a wrapper around the function to make it interactive; we can use
14080almost the same code as for the recursive version of
14081@code{count-words-region}:
14082
14083@smallexample
14084@group
14085;;; @r{Interactive version.}
14086(defun count-words-defun ()
14087 "Number of words and symbols in a function definition."
14088 (interactive)
14089 (message
14090 "Counting words and symbols in function definition ... ")
14091@end group
14092@group
14093 (let ((count (count-words-in-defun)))
14094 (cond
14095 ((zerop count)
14096 (message
14097 "The definition does NOT have any words or symbols."))
14098@end group
14099@group
14100 ((= 1 count)
14101 (message
14102 "The definition has 1 word or symbol."))
14103 (t
14104 (message
14105 "The definition has %d words or symbols." count)))))
14106@end group
14107@end smallexample
14108
14109@need 800
14110@noindent
14111Let's re-use @kbd{C-c =} as a convenient keybinding:
14112
14113@smallexample
14114(global-set-key "\C-c=" 'count-words-defun)
14115@end smallexample
14116
14117Now we can try out @code{count-words-defun}: install both
14118@code{count-words-in-defun} and @code{count-words-defun}, and set the
14119keybinding, and then place the cursor within the following definition:
14120
14121@smallexample
14122@group
14123(defun multiply-by-seven (number)
14124 "Multiply NUMBER by seven."
14125 (* 7 number))
14126 @result{} 10
14127@end group
14128@end smallexample
14129
14130@noindent
14131Success! The definition has 10 words and symbols.
14132
14133The next problem is to count the numbers of words and symbols in
14134several definitions within a single file.
14135
14136@node Several defuns, Find a File, count-words-in-defun, Words in a defun
14137@section Count Several @code{defuns} Within a File
14138
14139A file such as @file{simple.el} may have 80 or more function
14140definitions within it. Our long term goal is to collect statistics on
14141many files, but as a first step, our immediate goal is to collect
14142statistics on one file.
14143
14144The information will be a series of numbers, each number being the
14145length of a function definition. We can store the numbers in a list.
14146
14147We know that we will want to incorporate the information regarding one
14148file with information about many other files; this means that the
14149function for counting definition lengths within one file need only
14150return the list of lengths. It need not and should not display any
14151messages.
14152
14153The word count commands contain one expression to jump point forward
14154word by word and another expression to count the jumps. The function
14155to return the lengths of definitions can be designed to work the same
14156way, with one expression to jump point forward definition by
14157definition and another expression to construct the lengths' list.
14158
14159This statement of the problem makes it elementary to write the
14160function definition. Clearly, we will start the count at the
14161beginning of the file, so the first command will be @code{(goto-char
14162(point-min))}. Next, we start the @code{while} loop; and the
14163true-or-false test of the loop can be a regular expression search for
14164the next function definition---so long as the search succeeds, point
14165is moved forward and then the body of the loop is evaluated. The body
14166needs an expression that constructs the lengths' list. @code{cons},
14167the list construction command, can be used to create the list. That
14168is almost all there is to it.
14169
14170@need 800
14171Here is what this fragment of code looks like:
14172
14173@smallexample
14174@group
14175(goto-char (point-min))
14176(while (re-search-forward "^(defun" nil t)
14177 (setq lengths-list
14178 (cons (count-words-in-defun) lengths-list)))
14179@end group
14180@end smallexample
14181
14182What we have left out is the mechanism for finding the file that
14183contains the function definitions.
14184
14185In previous examples, we either used this, the Info file, or we
14186switched back and forth to some other buffer, such as the
14187@file{*scratch*} buffer.
14188
14189Finding a file is a new process that we have not yet discussed.
14190
14191@node Find a File, lengths-list-file, Several defuns, Words in a defun
14192@comment node-name, next, previous, up
14193@section Find a File
14194@cindex Find a File
14195
14196To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14197command. This command is almost, but not quite right for the lengths
14198problem.
14199
14200@need 1200
14201Let's look at the source for @code{find-file} (you can use the
14202@code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14203find the source of a function):
14204
14205@smallexample
14206@group
14207(defun find-file (filename)
14208 "Edit file FILENAME.
14209Switch to a buffer visiting file FILENAME,
14210creating one if none already exists."
14211 (interactive "FFind file: ")
14212 (switch-to-buffer (find-file-noselect filename)))
14213@end group
14214@end smallexample
14215
14216The definition possesses short but complete documentation and an
14217interactive specification that prompts you for a file name when you
14218use the command interactively. The body of the definition contains
14219two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14220
14221According to its documentation as shown by @kbd{C-h f} (the
14222@code{describe-function} command), the @code{find-file-noselect}
14223function reads the named file into a buffer and returns the buffer.
14224However, the buffer is not selected. Emacs does not switch its
14225attention (or yours if you are using @code{find-file-noselect}) to the
14226named buffer. That is what @code{switch-to-buffer} does: it switches
14227the buffer to which Emacs attention is directed; and it switches the
14228buffer displayed in the window to the new buffer. We have discussed
14229buffer switching elsewhere. (@xref{Switching Buffers}.)
14230
14231In this histogram project, we do not need to display each file on the
14232screen as the program determines the length of each definition within
14233it. Instead of employing @code{switch-to-buffer}, we can work with
14234@code{set-buffer}, which redirects the attention of the computer
14235program to a different buffer but does not redisplay it on the screen.
14236So instead of calling on @code{find-file} to do the job, we must write
14237our own expression.
14238
14239The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
14240
14241@node lengths-list-file, Several files, Find a File, Words in a defun
14242@section @code{lengths-list-file} in Detail
14243
14244The core of the @code{lengths-list-file} function is a @code{while}
14245loop containing a function to move point forward `defun by defun' and
14246a function to count the number of words and symbols in each defun.
14247This core must be surrounded by functions that do various other tasks,
14248including finding the file, and ensuring that point starts out at the
14249beginning of the file. The function definition looks like this:
14250@findex lengths-list-file
14251
14252@smallexample
14253@group
14254(defun lengths-list-file (filename)
14255 "Return list of definitions' lengths within FILE.
14256The returned list is a list of numbers.
14257Each number is the number of words or
14258symbols in one function definition."
14259@end group
14260@group
14261 (message "Working on `%s' ... " filename)
14262 (save-excursion
14263 (let ((buffer (find-file-noselect filename))
14264 (lengths-list))
14265 (set-buffer buffer)
14266 (setq buffer-read-only t)
14267 (widen)
14268 (goto-char (point-min))
14269 (while (re-search-forward "^(defun" nil t)
14270 (setq lengths-list
14271 (cons (count-words-in-defun) lengths-list)))
14272 (kill-buffer buffer)
14273 lengths-list)))
14274@end group
14275@end smallexample
14276
14277@noindent
14278The function is passed one argument, the name of the file on which it
14279will work. It has four lines of documentation, but no interactive
14280specification. Since people worry that a computer is broken if they
14281don't see anything going on, the first line of the body is a
14282message.
14283
14284The next line contains a @code{save-excursion} that returns Emacs'
14285attention to the current buffer when the function completes. This is
14286useful in case you embed this function in another function that
14287presumes point is restored to the original buffer.
14288
14289In the varlist of the @code{let} expression, Emacs finds the file and
14290binds the local variable @code{buffer} to the buffer containing the
14291file. At the same time, Emacs creates @code{lengths-list} as a local
14292variable.
14293
14294Next, Emacs switches its attention to the buffer.
14295
14296In the following line, Emacs makes the buffer read-only. Ideally,
14297this line is not necessary. None of the functions for counting words
14298and symbols in a function definition should change the buffer.
14299Besides, the buffer is not going to be saved, even if it were changed.
14300This line is entirely the consequence of great, perhaps excessive,
14301caution. The reason for the caution is that this function and those
14302it calls work on the sources for Emacs and it is very inconvenient if
14303they are inadvertently modified. It goes without saying that I did
14304not realize a need for this line until an experiment went awry and
14305started to modify my Emacs source files @dots{}
14306
14307Next comes a call to widen the buffer if it is narrowed. This
14308function is usually not needed---Emacs creates a fresh buffer if none
14309already exists; but if a buffer visiting the file already exists Emacs
14310returns that one. In this case, the buffer may be narrowed and must
14311be widened. If we wanted to be fully `user-friendly', we would
14312arrange to save the restriction and the location of point, but we
14313won't.
14314
14315The @code{(goto-char (point-min))} expression moves point to the
14316beginning of the buffer.
14317
14318Then comes a @code{while} loop in which the `work' of the function is
14319carried out. In the loop, Emacs determines the length of each
14320definition and constructs a lengths' list containing the information.
14321
14322Emacs kills the buffer after working through it. This is to save
14323space inside of Emacs. My version of Emacs 19 contained over 300
14324source files of interest; Emacs 21 contains over 800 source files.
14325Another function will apply @code{lengths-list-file} to each of the
14326files.
14327
14328Finally, the last expression within the @code{let} expression is the
14329@code{lengths-list} variable; its value is returned as the value of
14330the whole function.
14331
14332You can try this function by installing it in the usual fashion. Then
14333place your cursor after the following expression and type @kbd{C-x
14334C-e} (@code{eval-last-sexp}).
14335
14336@c !!! 21.0.100 lisp sources location here
14337@smallexample
14338(lengths-list-file
14339 "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14340@end smallexample
14341
14342@c was: (lengths-list-file "../lisp/debug.el")
14343@c !!! as of 21, Info file is in
14344@c /usr/share/info/emacs-lisp-intro.info.gz
14345@c but debug.el is in /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14346
14347@noindent
14348(You may need to change the pathname of the file; the one here worked
14349with GNU Emacs version 21.0.100. To change the expression, copy it to
14350the @file{*scratch*} buffer and edit it.
14351
14352@need 1200
14353@noindent
14354(Also, to see the full length of the list, rather than a truncated
14355version, you may have to evaluate the following:
14356
14357@smallexample
14358(custom-set-variables '(eval-expression-print-length nil))
14359@end smallexample
14360
14361@noindent
14362(@xref{defcustom, , Setting Variables with @code{defcustom}}.
14363Then evaluate the @code{lengths-list-file} expression.)
14364
14365@need 1200
14366The lengths' list for @file{debug.el} takes less than a second to
14367produce and looks like this:
14368
14369@smallexample
14370(77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14371@end smallexample
14372
14373@need 1500
14374(Using my old machine, the version 19 lengths' list for @file{debug.el}
14375took seven seconds to produce and looked like this:
14376
14377@smallexample
14378(75 41 80 62 20 45 44 68 45 12 34 235)
14379@end smallexample
14380
14381(The newer version of @file{debug.el} contains more defuns than the
14382earlier one; and my new machine is much faster than the old one.)
14383
14384Note that the length of the last definition in the file is first in
14385the list.
14386
14387@node Several files, Several files recursively, lengths-list-file, Words in a defun
14388@section Count Words in @code{defuns} in Different Files
14389
14390In the previous section, we created a function that returns a list of
14391the lengths of each definition in a file. Now, we want to define a
14392function to return a master list of the lengths of the definitions in
14393a list of files.
14394
14395Working on each of a list of files is a repetitious act, so we can use
14396either a @code{while} loop or recursion.
14397
14398@menu
14399* lengths-list-many-files:: Return a list of the lengths of defuns.
14400* append:: Attach one list to another.
14401@end menu
14402
14403@node lengths-list-many-files, append, Several files, Several files
14404@ifnottex
14405@unnumberedsubsec Determine the lengths of @code{defuns}
14406@end ifnottex
14407
14408The design using a @code{while} loop is routine. The argument passed
14409the function is a list of files. As we saw earlier (@pxref{Loop
14410Example}), you can write a @code{while} loop so that the body of the
14411loop is evaluated if such a list contains elements, but to exit the
14412loop if the list is empty. For this design to work, the body of the
14413loop must contain an expression that shortens the list each time the
14414body is evaluated, so that eventually the list is empty. The usual
14415technique is to set the value of the list to the value of the @sc{cdr}
14416of the list each time the body is evaluated.
14417
14418@need 800
14419The template looks like this:
14420
14421@smallexample
14422@group
14423(while @var{test-whether-list-is-empty}
14424 @var{body}@dots{}
14425 @var{set-list-to-cdr-of-list})
14426@end group
14427@end smallexample
14428
14429Also, we remember that a @code{while} loop returns @code{nil} (the
14430result of evaluating the true-or-false-test), not the result of any
14431evaluation within its body. (The evaluations within the body of the
14432loop are done for their side effects.) However, the expression that
14433sets the lengths' list is part of the body---and that is the value
14434that we want returned by the function as a whole. To do this, we
14435enclose the @code{while} loop within a @code{let} expression, and
14436arrange that the last element of the @code{let} expression contains
14437the value of the lengths' list. (@xref{Incrementing Example, , Loop
14438Example with an Incrementing Counter}.)
14439
14440@findex lengths-list-many-files
14441@need 1250
14442These considerations lead us directly to the function itself:
14443
14444@smallexample
14445@group
14446;;; @r{Use @code{while} loop.}
14447(defun lengths-list-many-files (list-of-files)
14448 "Return list of lengths of defuns in LIST-OF-FILES."
14449@end group
14450@group
14451 (let (lengths-list)
14452
14453;;; @r{true-or-false-test}
14454 (while list-of-files
14455 (setq lengths-list
14456 (append
14457 lengths-list
14458
14459;;; @r{Generate a lengths' list.}
14460 (lengths-list-file
14461 (expand-file-name (car list-of-files)))))
14462@end group
14463
14464@group
14465;;; @r{Make files' list shorter.}
14466 (setq list-of-files (cdr list-of-files)))
14467
14468;;; @r{Return final value of lengths' list.}
14469 lengths-list))
14470@end group
14471@end smallexample
14472
14473@code{expand-file-name} is a built-in function that converts a file
14474name to the absolute, long, path name form of the directory in which
14475the function is called.
14476
14477@c !!! 21.0.100 lisp sources location here
14478@need 1500
14479Thus, if @code{expand-file-name} is called on @code{debug.el} when
14480Emacs is visiting the
14481@file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14482
14483@smallexample
14484debug.el
14485@end smallexample
14486
14487@need 800
14488@noindent
14489becomes
14490
14491@c !!! 21.0.100 lisp sources location here
14492@smallexample
14493/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14494@end smallexample
14495
14496The only other new element of this function definition is the as yet
14497unstudied function @code{append}, which merits a short section for
14498itself.
14499
14500@node append, , lengths-list-many-files, Several files
14501@subsection The @code{append} Function
14502
14503@need 800
14504The @code{append} function attaches one list to another. Thus,
14505
14506@smallexample
14507(append '(1 2 3 4) '(5 6 7 8))
14508@end smallexample
14509
14510@need 800
14511@noindent
14512produces the list
14513
14514@smallexample
14515(1 2 3 4 5 6 7 8)
14516@end smallexample
14517
14518This is exactly how we want to attach two lengths' lists produced by
14519@code{lengths-list-file} to each other. The results contrast with
14520@code{cons},
14521
14522@smallexample
14523(cons '(1 2 3 4) '(5 6 7 8))
14524@end smallexample
14525
14526@need 1250
14527@noindent
14528which constructs a new list in which the first argument to @code{cons}
14529becomes the first element of the new list:
14530
14531@smallexample
14532((1 2 3 4) 5 6 7 8)
14533@end smallexample
14534
14535@node Several files recursively, Prepare the data, Several files, Words in a defun
14536@section Recursively Count Words in Different Files
14537
14538Besides a @code{while} loop, you can work on each of a list of files
14539with recursion. A recursive version of @code{lengths-list-many-files}
14540is short and simple.
14541
14542The recursive function has the usual parts: the `do-again-test', the
14543`next-step-expression', and the recursive call. The `do-again-test'
14544determines whether the function should call itself again, which it
14545will do if the @code{list-of-files} contains any remaining elements;
14546the `next-step-expression' resets the @code{list-of-files} to the
14547@sc{cdr} of itself, so eventually the list will be empty; and the
14548recursive call calls itself on the shorter list. The complete
14549function is shorter than this description!
14550@findex recursive-lengths-list-many-files
14551
14552@smallexample
14553@group
14554(defun recursive-lengths-list-many-files (list-of-files)
14555 "Return list of lengths of each defun in LIST-OF-FILES."
14556 (if list-of-files ; @r{do-again-test}
14557 (append
14558 (lengths-list-file
14559 (expand-file-name (car list-of-files)))
14560 (recursive-lengths-list-many-files
14561 (cdr list-of-files)))))
14562@end group
14563@end smallexample
14564
14565@noindent
14566In a sentence, the function returns the lengths' list for the first of
14567the @code{list-of-files} appended to the result of calling itself on
14568the rest of the @code{list-of-files}.
14569
14570Here is a test of @code{recursive-lengths-list-many-files}, along with
14571the results of running @code{lengths-list-file} on each of the files
14572individually.
14573
14574Install @code{recursive-lengths-list-many-files} and
14575@code{lengths-list-file}, if necessary, and then evaluate the
14576following expressions. You may need to change the files' pathnames;
14577those here work when this Info file and the Emacs sources are located
14578in their customary places. To change the expressions, copy them to
14579the @file{*scratch*} buffer, edit them, and then evaluate them.
14580
14581The results are shown after the @samp{@result{}}. (These results are
14582for files from Emacs Version 21.0.100; files from other versions of
14583Emacs may produce different results.)
14584
14585@c !!! 21.0.100 lisp sources location here
14586@smallexample
14587@group
14588(cd "/usr/local/share/emacs/21.0.100/")
14589
14590(lengths-list-file "./lisp/macros.el")
14591 @result{} (273 263 456 90)
14592@end group
14593
14594@group
14595(lengths-list-file "./lisp/mail/mailalias.el")
14596 @result{} (38 32 26 77 174 180 321 198 324)
14597@end group
14598
14599@group
14600(lengths-list-file "./lisp/makesum.el")
14601 @result{} (85 181)
14602@end group
14603
14604@group
14605(recursive-lengths-list-many-files
14606 '("./lisp/macros.el"
14607 "./lisp/mail/mailalias.el"
14608 "./lisp/makesum.el"))
14609 @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14610@end group
14611@end smallexample
14612
14613The @code{recursive-lengths-list-many-files} function produces the
14614output we want.
14615
14616The next step is to prepare the data in the list for display in a graph.
14617
14618@node Prepare the data, , Several files recursively, Words in a defun
14619@section Prepare the Data for Display in a Graph
14620
14621The @code{recursive-lengths-list-many-files} function returns a list
14622of numbers. Each number records the length of a function definition.
14623What we need to do now is transform this data into a list of numbers
14624suitable for generating a graph. The new list will tell how many
14625functions definitions contain less than 10 words and
14626symbols, how many contain between 10 and 19 words and symbols, how
14627many contain between 20 and 29 words and symbols, and so on.
14628
14629In brief, we need to go through the lengths' list produced by the
14630@code{recursive-lengths-list-many-files} function and count the number
14631of defuns within each range of lengths, and produce a list of those
14632numbers.
14633
14634Based on what we have done before, we can readily foresee that it
14635should not be too hard to write a function that `@sc{cdr}s' down the
14636lengths' list, looks at each element, determines which length range it
14637is in, and increments a counter for that range.
14638
14639However, before beginning to write such a function, we should consider
14640the advantages of sorting the lengths' list first, so the numbers are
14641ordered from smallest to largest. First, sorting will make it easier
14642to count the numbers in each range, since two adjacent numbers will
14643either be in the same length range or in adjacent ranges. Second, by
14644inspecting a sorted list, we can discover the highest and lowest
14645number, and thereby determine the largest and smallest length range
14646that we will need.
14647
14648@menu
14649* Sorting:: Sorting lists.
14650* Files List:: Making a list of files.
14651* Counting function definitions::
14652@end menu
14653
14654@node Sorting, Files List, Prepare the data, Prepare the data
14655@subsection Sorting Lists
14656@findex sort
14657
14658Emacs contains a function to sort lists, called (as you might guess)
14659@code{sort}. The @code{sort} function takes two arguments, the list
14660to be sorted, and a predicate that determines whether the first of
14661two list elements is ``less'' than the second.
14662
14663As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14664Type Object as an Argument}), a predicate is a function that
14665determines whether some property is true or false. The @code{sort}
14666function will reorder a list according to whatever property the
14667predicate uses; this means that @code{sort} can be used to sort
14668non-numeric lists by non-numeric criteria---it can, for example,
14669alphabetize a list.
14670
14671@need 1250
14672The @code{<} function is used when sorting a numeric list. For example,
14673
14674@smallexample
14675(sort '(4 8 21 17 33 7 21 7) '<)
14676@end smallexample
14677
14678@need 800
14679@noindent
14680produces this:
14681
14682@smallexample
14683(4 7 7 8 17 21 21 33)
14684@end smallexample
14685
14686@noindent
14687(Note that in this example, both the arguments are quoted so that the
14688symbols are not evaluated before being passed to @code{sort} as
14689arguments.)
14690
14691Sorting the list returned by the
14692@code{recursive-lengths-list-many-files} function is straightforward;
14693it uses the @code{<} function:
14694
14695@smallexample
14696@group
14697(sort
14698 (recursive-lengths-list-many-files
14699 '("../lisp/macros.el"
14700 "../lisp/mailalias.el"
14701 "../lisp/makesum.el"))
14702 '<
14703@end group
14704@end smallexample
14705
14706@need 800
14707@noindent
14708which produces:
14709
14710@smallexample
14711(85 86 116 122 154 176 179 265)
14712@end smallexample
14713
14714@noindent
14715(Note that in this example, the first argument to @code{sort} is not
14716quoted, since the expression must be evaluated so as to produce the
14717list that is passed to @code{sort}.)
14718
14719@node Files List, Counting function definitions, Sorting, Prepare the data
14720@subsection Making a List of Files
14721
14722The @code{recursive-lengths-list-many-files} function requires a list
14723of files as its argument. For our test examples, we constructed such
14724a list by hand; but the Emacs Lisp source directory is too large for
14725us to do for that. Instead, we will write a function to do the job
14726for us. In this function, we will use both a @code{while} loop and a
14727recursive call.
14728
14729@findex directory-files
14730We did not have to write a function like this for older versions of
14731GNU Emacs, since they placed all the @samp{.el} files in one
14732directory. Instead, we were able to use the @code{directory-files}
14733function, which lists the names of files that match a specified
14734pattern within a single directory.
14735
14736However, recent versions of Emacs place Emacs Lisp files in
14737sub-directories of the top level @file{lisp} directory. This
14738re-arrangement eases navigation. For example, all the mail related
14739files are in a @file{lisp} sub-directory called @file{mail}. But at
14740the same time, this arrangement forces us to create a file listing
14741function that descends into the sub-directories.
14742
14743@findex files-in-below-directory
14744We can create this function, called @code{files-in-below-directory},
14745using familiar functions such as @code{car}, @code{nthcdr}, and
14746@code{substring} in conjunction with an existing function called
14747@code{directory-files-and-attributes}. This latter function not only
14748lists all the filenames in a directory, including the names
14749of sub-directories, but also their attributes.
14750
14751To restate our goal: to create a function that will enable us
14752to feed filenames to @code{recursive-lengths-list-many-files}
14753as a list that looks like this (but with more elements):
14754
14755@smallexample
14756@group
14757("../lisp/macros.el"
14758 "../lisp/mail/rmail.el"
14759 "../lisp/makesum.el")
14760@end group
14761@end smallexample
14762
14763The @code{directory-files-and-attributes} function returns a list of
14764lists. Each of the lists within the main list consists of 13
14765elements. The first element is a string that contains the name of the
14766file -- which, in GNU/Linux, may be a `directory file', that is to
14767say, a file with the special attributes of a directory. The second
14768element of the list is @code{t} for a directory, a string
14769for symbolic link (the string is the name linked to), or @code{nil}.
14770
14771For example, the first @samp{.el} file in the @file{lisp/} directory
14772is @file{abbrev.el}. Its name is
14773@file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14774directory or a symbolic link.
14775
14776@need 1000
14777This is how @code{directory-files-and-attributes} lists that file and
14778its attributes:
14779
14780@smallexample
14781@group
14782("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14783nil
147841
147851000
14786100
14787@end group
14788@group
14789(15019 32380)
14790(14883 48041)
14791(15214 49336)
1479211583
14793"-rw-rw-r--"
14794@end group
14795@group
14796t
14797341385
14798776)
14799@end group
14800@end smallexample
14801
14802@need 1200
14803On the other hand, @file{mail/} is a directory within the @file{lisp/}
14804directory. The beginning of its listing looks like this:
14805
14806@smallexample
14807@group
14808("/usr/local/share/emacs/21.0.100/lisp/mail"
14809t
14810@dots{}
14811)
14812@end group
14813@end smallexample
14814
14815(Look at the documentation of @code{file-attributes} to learn about
14816the different attributes. Bear in mind that the
14817@code{file-attributes} function does not list the filename, so its
14818first element is @code{directory-files-and-attributes}'s second
14819element.)
14820
14821We will want our new function, @code{files-in-below-directory}, to
14822list the @samp{.el} files in the directory it is told to check, and in
14823any directories below that directory.
14824
14825This gives us a hint on how to construct
14826@code{files-in-below-directory}: within a directory, the function
14827should add @samp{.el} filenames to a list; and if, within a directory,
14828the function comes upon a sub-directory, it should go into that
14829sub-directory and repeat its actions.
14830
14831However, we should note that every directory contains a name that
14832refers to itself, called @file{.}, (``dot'') and a name that refers to
14833its parent directory, called @file{..} (``double dot''). (In
14834@file{/}, the root directory, @file{..} refers to itself, since
14835@file{/} has no parent.) Clearly, we do not want our
14836@code{files-in-below-directory} function to enter those directories,
14837since they always lead us, directly or indirectly, to the current
14838directory.
14839
14840Consequently, our @code{files-in-below-directory} function must do
14841several tasks:
14842
14843@itemize @bullet
14844@item
14845Check to see whether it is looking at a filename that ends in
14846@samp{.el}; and if so, add its name to a list.
14847
14848@item
14849Check to see whether it is looking at a filename that is the name of a
14850directory; and if so,
14851
14852@itemize @minus
14853@item
14854Check to see whether it is looking at @file{.} or @file{..}; and if
14855so skip it.
14856
14857@item
14858Or else, go into that directory and repeat the process.
14859@end itemize
14860@end itemize
14861
14862Let's write a function definition to do these tasks. We will use a
14863@code{while} loop to move from one filename to another within a
14864directory, checking what needs to be done; and we will use a recursive
14865call to repeat the actions on each sub-directory. The recursive
14866pattern is `accumulate'
14867(@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14868using @code{append} as the combiner.
14869
14870@ignore
14871(directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14872(shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14873@end ignore
14874
14875@c /usr/local/share/emacs/21.0.100/lisp/
14876
14877@need 800
14878Here is the function:
14879
14880@smallexample
14881@group
14882(defun files-in-below-directory (directory)
14883 "List the .el files in DIRECTORY and in its sub-directories."
14884 ;; Although the function will be used non-interactively,
14885 ;; it will be easier to test if we make it interactive.
14886 ;; The directory will have a name such as
14887 ;; "/usr/local/share/emacs/21.0.100/lisp/"
14888 (interactive "DDirectory name: ")
14889@end group
14890@group
14891 (let (el-files-list
14892 (current-directory-list
14893 (directory-files-and-attributes directory t)))
14894 ;; while we are in the current directory
14895 (while current-directory-list
14896@end group
14897@group
14898 (cond
14899 ;; check to see whether filename ends in `.el'
14900 ;; and if so, append its name to a list.
14901 ((equal ".el" (substring (car (car current-directory-list)) -3))
14902 (setq el-files-list
14903 (cons (car (car current-directory-list)) el-files-list)))
14904@end group
14905@group
14906 ;; check whether filename is that of a directory
14907 ((eq t (car (cdr (car current-directory-list))))
14908 ;; decide whether to skip or recurse
14909 (if
14910 (equal (or "." "..")
14911 (substring (car (car current-directory-list)) -1))
14912 ;; then do nothing if filename is that of
14913 ;; current directory or parent
14914 ()
14915@end group
14916@group
14917 ;; else descend into the directory and repeat the process
14918 (setq el-files-list
14919 (append
14920 (files-in-below-directory
14921 (car (car current-directory-list)))
14922 el-files-list)))))
14923 ;; move to the next filename in the list; this also
14924 ;; shortens the list so the while loop eventually comes to an end
14925 (setq current-directory-list (cdr current-directory-list)))
14926 ;; return the filenames
14927 el-files-list))
14928@end group
14929@end smallexample
14930
14931@c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14932
14933The @code{files-in-below-directory} @code{directory-files} function
14934takes one argument, the name of a directory.
14935
14936@need 1250
14937Thus, on my system,
14938
14939@c !!! 21.0.100 lisp sources location here
14940@smallexample
14941@group
14942(length
14943 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14944@end group
14945@end smallexample
14946
14947@noindent
14948tells me that my version 21.0.100 Lisp sources directory contains 754
14949@samp{.el} files.
14950
14951@code{files-in-below-directory} returns a list in reverse alphabetical
14952order. An expression to sort the list in alphabetical order looks
14953like this:
14954
14955@smallexample
14956@group
14957(sort
14958 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14959 'string-lessp)
14960@end group
14961@end smallexample
14962
14963@ignore
14964(defun test ()
14965 "Test how long it takes to find lengths of all elisp defuns."
14966 (insert "\n" (current-time-string) "\n")
14967 (sit-for 0)
14968 (sort
14969 (recursive-lengths-list-many-files
14970 '("../lisp/macros.el"
14971 "../lisp/mailalias.el"
14972 "../lisp/makesum.el"))
14973 '<)
14974 (insert (format "%s" (current-time-string))))
14975
14976@end ignore
14977
14978@node Counting function definitions, , Files List, Prepare the data
14979@subsection Counting function definitions
14980
14981Our immediate goal is to generate a list that tells us how many
14982function definitions contain fewer than 10 words and symbols, how many
14983contain between 10 and 19 words and symbols, how many contain between
1498420 and 29 words and symbols, and so on.
14985
14986With a sorted list of numbers, this is easy: count how many elements
14987of the list are smaller than 10, then, after moving past the numbers
14988just counted, count how many are smaller than 20, then, after moving
14989past the numbers just counted, count how many are smaller than 30, and
14990so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
14991larger than the top of that range. We can call the list of such
14992numbers the @code{top-of-ranges} list.
14993
14994@need 1200
14995If we wished, we could generate this list automatically, but it is
14996simpler to write a list manually. Here it is:
14997@vindex top-of-ranges
14998
14999@smallexample
15000@group
15001(defvar top-of-ranges
15002 '(10 20 30 40 50
15003 60 70 80 90 100
15004 110 120 130 140 150
15005 160 170 180 190 200
15006 210 220 230 240 250
15007 260 270 280 290 300)
15008 "List specifying ranges for `defuns-per-range'.")
15009@end group
15010@end smallexample
15011
15012To change the ranges, we edit this list.
15013
15014Next, we need to write the function that creates the list of the
15015number of definitions within each range. Clearly, this function must
15016take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15017as arguments.
15018
15019The @code{defuns-per-range} function must do two things again and
15020again: it must count the number of definitions within a range
15021specified by the current top-of-range value; and it must shift to the
15022next higher value in the @code{top-of-ranges} list after counting the
15023number of definitions in the current range. Since each of these
15024actions is repetitive, we can use @code{while} loops for the job.
15025One loop counts the number of definitions in the range defined by the
15026current top-of-range value, and the other loop selects each of the
15027top-of-range values in turn.
15028
15029Several entries of the @code{sorted-lengths} list are counted for each
15030range; this means that the loop for the @code{sorted-lengths} list
15031will be inside the loop for the @code{top-of-ranges} list, like a
15032small gear inside a big gear.
15033
15034The inner loop counts the number of definitions within the range. It
15035is a simple counting loop of the type we have seen before.
15036(@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15037The true-or-false test of the loop tests whether the value from the
15038@code{sorted-lengths} list is smaller than the current value of the
15039top of the range. If it is, the function increments the counter and
15040tests the next value from the @code{sorted-lengths} list.
15041
15042@need 1250
15043The inner loop looks like this:
15044
15045@smallexample
15046@group
15047(while @var{length-element-smaller-than-top-of-range}
15048 (setq number-within-range (1+ number-within-range))
15049 (setq sorted-lengths (cdr sorted-lengths)))
15050@end group
15051@end smallexample
15052
15053The outer loop must start with the lowest value of the
15054@code{top-of-ranges} list, and then be set to each of the succeeding
15055higher values in turn. This can be done with a loop like this:
15056
15057@smallexample
15058@group
15059(while top-of-ranges
15060 @var{body-of-loop}@dots{}
15061 (setq top-of-ranges (cdr top-of-ranges)))
15062@end group
15063@end smallexample
15064
15065@need 1200
15066Put together, the two loops look like this:
15067
15068@smallexample
15069@group
15070(while top-of-ranges
15071
15072 ;; @r{Count the number of elements within the current range.}
15073 (while @var{length-element-smaller-than-top-of-range}
15074 (setq number-within-range (1+ number-within-range))
15075 (setq sorted-lengths (cdr sorted-lengths)))
15076
15077 ;; @r{Move to next range.}
15078 (setq top-of-ranges (cdr top-of-ranges)))
15079@end group
15080@end smallexample
15081
15082In addition, in each circuit of the outer loop, Emacs should record
15083the number of definitions within that range (the value of
15084@code{number-within-range}) in a list. We can use @code{cons} for
15085this purpose. (@xref{cons, , @code{cons}}.)
15086
15087The @code{cons} function works fine, except that the list it
15088constructs will contain the number of definitions for the highest
15089range at its beginning and the number of definitions for the lowest
15090range at its end. This is because @code{cons} attaches new elements
15091of the list to the beginning of the list, and since the two loops are
15092working their way through the lengths' list from the lower end first,
15093the @code{defuns-per-range-list} will end up largest number first.
15094But we will want to print our graph with smallest values first and the
15095larger later. The solution is to reverse the order of the
15096@code{defuns-per-range-list}. We can do this using the
15097@code{nreverse} function, which reverses the order of a list.
15098@findex nreverse
15099
15100@need 800
15101For example,
15102
15103@smallexample
15104(nreverse '(1 2 3 4))
15105@end smallexample
15106
15107@need 800
15108@noindent
15109produces:
15110
15111@smallexample
15112(4 3 2 1)
15113@end smallexample
15114
15115Note that the @code{nreverse} function is ``destructive''---that is,
15116it changes the list to which it is applied; this contrasts with the
15117@code{car} and @code{cdr} functions, which are non-destructive. In
15118this case, we do not want the original @code{defuns-per-range-list},
15119so it does not matter that it is destroyed. (The @code{reverse}
15120function provides a reversed copy of a list, leaving the original list
15121as is.)
15122@findex reverse
15123
15124@need 1250
15125Put all together, the @code{defuns-per-range} looks like this:
15126
15127@smallexample
15128@group
15129(defun defuns-per-range (sorted-lengths top-of-ranges)
15130 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15131 (let ((top-of-range (car top-of-ranges))
15132 (number-within-range 0)
15133 defuns-per-range-list)
15134@end group
15135
15136@group
15137 ;; @r{Outer loop.}
15138 (while top-of-ranges
15139@end group
15140
15141@group
15142 ;; @r{Inner loop.}
15143 (while (and
15144 ;; @r{Need number for numeric test.}
15145 (car sorted-lengths)
15146 (< (car sorted-lengths) top-of-range))
15147@end group
15148
15149@group
15150 ;; @r{Count number of definitions within current range.}
15151 (setq number-within-range (1+ number-within-range))
15152 (setq sorted-lengths (cdr sorted-lengths)))
15153
15154 ;; @r{Exit inner loop but remain within outer loop.}
15155@end group
15156
15157@group
15158 (setq defuns-per-range-list
15159 (cons number-within-range defuns-per-range-list))
15160 (setq number-within-range 0) ; @r{Reset count to zero.}
15161@end group
15162
15163@group
15164 ;; @r{Move to next range.}
15165 (setq top-of-ranges (cdr top-of-ranges))
15166 ;; @r{Specify next top of range value.}
15167 (setq top-of-range (car top-of-ranges)))
15168@end group
15169
15170@group
15171 ;; @r{Exit outer loop and count the number of defuns larger than}
15172 ;; @r{ the largest top-of-range value.}
15173 (setq defuns-per-range-list
15174 (cons
15175 (length sorted-lengths)
15176 defuns-per-range-list))
15177@end group
15178
15179@group
15180 ;; @r{Return a list of the number of definitions within each range,}
15181 ;; @r{ smallest to largest.}
15182 (nreverse defuns-per-range-list)))
15183@end group
15184@end smallexample
15185
15186@need 1200
15187@noindent
15188The function is straightforward except for one subtle feature. The
15189true-or-false test of the inner loop looks like this:
15190
15191@smallexample
15192@group
15193(and (car sorted-lengths)
15194 (< (car sorted-lengths) top-of-range))
15195@end group
15196@end smallexample
15197
15198@need 800
15199@noindent
15200instead of like this:
15201
15202@smallexample
15203(< (car sorted-lengths) top-of-range)
15204@end smallexample
15205
15206The purpose of the test is to determine whether the first item in the
15207@code{sorted-lengths} list is less than the value of the top of the
15208range.
15209
15210The simple version of the test works fine unless the
15211@code{sorted-lengths} list has a @code{nil} value. In that case, the
15212@code{(car sorted-lengths)} expression function returns
15213@code{nil}. The @code{<} function cannot compare a number to
15214@code{nil}, which is an empty list, so Emacs signals an error and
15215stops the function from attempting to continue to execute.
15216
15217The @code{sorted-lengths} list always becomes @code{nil} when the
15218counter reaches the end of the list. This means that any attempt to
15219use the @code{defuns-per-range} function with the simple version of
15220the test will fail.
15221
15222We solve the problem by using the @code{(car sorted-lengths)}
15223expression in conjunction with the @code{and} expression. The
15224@code{(car sorted-lengths)} expression returns a non-@code{nil}
15225value so long as the list has at least one number within it, but
15226returns @code{nil} if the list is empty. The @code{and} expression
15227first evaluates the @code{(car sorted-lengths)} expression, and
15228if it is @code{nil}, returns false @emph{without} evaluating the
15229@code{<} expression. But if the @code{(car sorted-lengths)}
15230expression returns a non-@code{nil} value, the @code{and} expression
15231evaluates the @code{<} expression, and returns that value as the value
15232of the @code{and} expression.
15233
15234@c colon in printed section title causes problem in Info cross reference
15235This way, we avoid an error.
15236@iftex
15237@xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15238Functions}, for more information about @code{and}.
15239@end iftex
15240@ifinfo
15241@xref{forward-paragraph}, for more information about @code{and}.
15242@end ifinfo
15243
15244Here is a short test of the @code{defuns-per-range} function. First,
15245evaluate the expression that binds (a shortened)
15246@code{top-of-ranges} list to the list of values, then evaluate the
15247expression for binding the @code{sorted-lengths} list, and then
15248evaluate the @code{defuns-per-range} function.
15249
15250@smallexample
15251@group
15252;; @r{(Shorter list than we will use later.)}
15253(setq top-of-ranges
15254 '(110 120 130 140 150
15255 160 170 180 190 200))
15256
15257(setq sorted-lengths
15258 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15259
15260(defuns-per-range sorted-lengths top-of-ranges)
15261@end group
15262@end smallexample
15263
15264@need 800
15265@noindent
15266The list returned looks like this:
15267
15268@smallexample
15269(2 2 2 0 0 1 0 2 0 0 4)
15270@end smallexample
15271
15272@noindent
15273Indeed, there are two elements of the @code{sorted-lengths} list
15274smaller than 110, two elements between 110 and 119, two elements
15275between 120 and 129, and so on. There are four elements with a value
15276of 200 or larger.
15277
15278@c The next step is to turn this numbers' list into a graph.
15279
15280@node Readying a Graph, Emacs Initialization, Words in a defun, Top
15281@chapter Readying a Graph
15282@cindex Readying a graph
15283@cindex Graph prototype
15284@cindex Prototype graph
15285@cindex Body of graph
15286
15287Our goal is to construct a graph showing the numbers of function
15288definitions of various lengths in the Emacs lisp sources.
15289
15290As a practical matter, if you were creating a graph, you would
15291probably use a program such as @code{gnuplot} to do the job.
15292(@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
15293however, we create one from scratch, and in the process we will
15294re-acquaint ourselves with some of what we learned before and learn
15295more.
15296
15297In this chapter, we will first write a simple graph printing function.
15298This first definition will be a @dfn{prototype}, a rapidly written
15299function that enables us to reconnoiter this unknown graph-making
15300territory. We will discover dragons, or find that they are myth.
15301After scouting the terrain, we will feel more confident and enhance
15302the function to label the axes automatically.
15303
15304@menu
15305* Columns of a graph::
15306* graph-body-print:: How to print the body of a graph.
15307* recursive-graph-body-print::
15308* Printed Axes::
15309* Line Graph Exercise::
15310@end menu
15311
15312@node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15313@ifnottex
15314@unnumberedsec Printing the Columns of a Graph
15315@end ifnottex
15316
15317Since Emacs is designed to be flexible and work with all kinds of
15318terminals, including character-only terminals, the graph will need to
15319be made from one of the `typewriter' symbols. An asterisk will do; as
15320we enhance the graph-printing function, we can make the choice of
15321symbol a user option.
15322
15323We can call this function @code{graph-body-print}; it will take a
15324@code{numbers-list} as its only argument. At this stage, we will not
15325label the graph, but only print its body.
15326
15327The @code{graph-body-print} function inserts a vertical column of
15328asterisks for each element in the @code{numbers-list}. The height of
15329each line is determined by the value of that element of the
15330@code{numbers-list}.
15331
15332Inserting columns is a repetitive act; that means that this function can
15333be written either with a @code{while} loop or recursively.
15334
15335Our first challenge is to discover how to print a column of asterisks.
15336Usually, in Emacs, we print characters onto a screen horizontally,
15337line by line, by typing. We have two routes we can follow: write our
15338own column-insertion function or discover whether one exists in Emacs.
15339
15340To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15341command. This command is like the @kbd{C-h a} (command-apropos)
15342command, except that the latter finds only those functions that are
15343commands. The @kbd{M-x apropos} command lists all symbols that match
15344a regular expression, including functions that are not interactive.
15345@findex apropos
15346
15347What we want to look for is some command that prints or inserts
15348columns. Very likely, the name of the function will contain either
15349the word `print' or the word `insert' or the word `column'.
15350Therefore, we can simply type @kbd{M-x apropos RET
15351print\|insert\|column RET} and look at the result. On my system, this
15352command takes quite some time, and then produces a list of 79
15353functions and variables. Scanning down the list, the only function
15354that looks as if it might do the job is @code{insert-rectangle}.
15355
15356@need 1200
15357Indeed, this is the function we want; its documentation says:
15358
15359@smallexample
15360@group
15361insert-rectangle:
15362Insert text of RECTANGLE with upper left corner at point.
15363RECTANGLE's first line is inserted at point,
15364its second line is inserted at a point vertically under point, etc.
15365RECTANGLE should be a list of strings.
15366@end group
15367@end smallexample
15368
15369We can run a quick test, to make sure it does what we expect of it.
15370
15371Here is the result of placing the cursor after the
15372@code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15373(@code{eval-last-sexp}). The function inserts the strings
15374@samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15375point. Also the function returns @code{nil}.
15376
15377@smallexample
15378@group
15379(insert-rectangle '("first" "second" "third"))first
15380 second
15381 third
15382nil
15383@end group
15384@end smallexample
15385
15386@noindent
15387Of course, we won't be inserting the text of the
15388@code{insert-rectangle} expression itself into the buffer in which we
15389are making the graph, but will call the function from our program. We
15390shall, however, have to make sure that point is in the buffer at the
15391place where the @code{insert-rectangle} function will insert its
15392column of strings.
15393
15394If you are reading this in Info, you can see how this works by
15395switching to another buffer, such as the @file{*scratch*} buffer,
15396placing point somewhere in the buffer, typing @kbd{M-:},
15397typing the @code{insert-rectangle} expression into the minibuffer at
15398the prompt, and then typing @key{RET}. This causes Emacs to evaluate
15399the expression in the minibuffer, but to use as the value of point the
15400position of point in the @file{*scratch*} buffer. (@kbd{M-:}
15401is the keybinding for @code{eval-expression}.)
15402
15403We find when we do this that point ends up at the end of the last
15404inserted line---that is to say, this function moves point as a
15405side-effect. If we were to repeat the command, with point at this
15406position, the next insertion would be below and to the right of the
15407previous insertion. We don't want this! If we are going to make a
15408bar graph, the columns need to be beside each other.
15409
15410So we discover that each cycle of the column-inserting @code{while}
15411loop must reposition point to the place we want it, and that place
15412will be at the top, not the bottom, of the column. Moreover, we
15413remember that when we print a graph, we do not expect all the columns
15414to be the same height. This means that the top of each column may be
15415at a different height from the previous one. We cannot simply
15416reposition point to the same line each time, but moved over to the
15417right---or perhaps we can@dots{}
15418
15419We are planning to make the columns of the bar graph out of asterisks.
15420The number of asterisks in the column is the number specified by the
15421current element of the @code{numbers-list}. We need to construct a
15422list of asterisks of the right length for each call to
15423@code{insert-rectangle}. If this list consists solely of the requisite
15424number of asterisks, then we will have position point the right number
15425of lines above the base for the graph to print correctly. This could
15426be difficult.
15427
15428Alternatively, if we can figure out some way to pass
15429@code{insert-rectangle} a list of the same length each time, then we
15430can place point on the same line each time, but move it over one
15431column to the right for each new column. If we do this, however, some
15432of the entries in the list passed to @code{insert-rectangle} must be
15433blanks rather than asterisks. For example, if the maximum height of
15434the graph is 5, but the height of the column is 3, then
15435@code{insert-rectangle} requires an argument that looks like this:
15436
15437@smallexample
15438(" " " " "*" "*" "*")
15439@end smallexample
15440
15441This last proposal is not so difficult, so long as we can determine
15442the column height. There are two ways for us to specify the column
15443height: we can arbitrarily state what it will be, which would work
15444fine for graphs of that height; or we can search through the list of
15445numbers and use the maximum height of the list as the maximum height
15446of the graph. If the latter operation were difficult, then the former
15447procedure would be easiest, but there is a function built into Emacs
15448that determines the maximum of its arguments. We can use that
15449function. The function is called @code{max} and it returns the
15450largest of all its arguments, which must be numbers. Thus, for
15451example,
15452
15453@smallexample
15454(max 3 4 6 5 7 3)
15455@end smallexample
15456
15457@noindent
15458returns 7. (A corresponding function called @code{min} returns the
15459smallest of all its arguments.)
15460@findex max
15461@findex min
15462
15463However, we cannot simply call @code{max} on the @code{numbers-list};
15464the @code{max} function expects numbers as its argument, not a list of
15465numbers. Thus, the following expression,
15466
15467@smallexample
15468(max '(3 4 6 5 7 3))
15469@end smallexample
15470
15471@need 800
15472@noindent
15473produces the following error message;
15474
15475@smallexample
15476Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
15477@end smallexample
15478
15479@findex apply
15480We need a function that passes a list of arguments to a function.
15481This function is @code{apply}. This function `applies' its first
15482argument (a function) to its remaining arguments, the last of which
15483may be a list.
15484
15485@need 1250
15486For example,
15487
15488@smallexample
15489(apply 'max 3 4 7 3 '(4 8 5))
15490@end smallexample
15491
15492@noindent
15493returns 8.
15494
15495(Incidentally, I don't know how you would learn of this function
15496without a book such as this. It is possible to discover other
15497functions, like @code{search-forward} or @code{insert-rectangle}, by
15498guessing at a part of their names and then using @code{apropos}. Even
15499though its base in metaphor is clear---`apply' its first argument to
15500the rest---I doubt a novice would come up with that particular word
15501when using @code{apropos} or other aid. Of course, I could be wrong;
15502after all, the function was first named by someone who had to invent
15503it.)
15504
15505The second and subsequent arguments to @code{apply} are optional, so
15506we can use @code{apply} to call a function and pass the elements of a
15507list to it, like this, which also returns 8:
15508
15509@smallexample
15510(apply 'max '(4 8 5))
15511@end smallexample
15512
15513This latter way is how we will use @code{apply}. The
15514@code{recursive-lengths-list-many-files} function returns a numbers'
15515list to which we can apply @code{max} (we could also apply @code{max} to
15516the sorted numbers' list; it does not matter whether the list is
15517sorted or not.)
15518
15519@need 800
15520Hence, the operation for finding the maximum height of the graph is this:
15521
15522@smallexample
15523(setq max-graph-height (apply 'max numbers-list))
15524@end smallexample
15525
15526Now we can return to the question of how to create a list of strings
15527for a column of the graph. Told the maximum height of the graph
15528and the number of asterisks that should appear in the column, the
15529function should return a list of strings for the
15530@code{insert-rectangle} command to insert.
15531
15532Each column is made up of asterisks or blanks. Since the function is
15533passed the value of the height of the column and the number of
15534asterisks in the column, the number of blanks can be found by
15535subtracting the number of asterisks from the height of the column.
15536Given the number of blanks and the number of asterisks, two
15537@code{while} loops can be used to construct the list:
15538
15539@smallexample
15540@group
15541;;; @r{First version.}
15542(defun column-of-graph (max-graph-height actual-height)
15543 "Return list of strings that is one column of a graph."
15544 (let ((insert-list nil)
15545 (number-of-top-blanks
15546 (- max-graph-height actual-height)))
15547@end group
15548
15549@group
15550 ;; @r{Fill in asterisks.}
15551 (while (> actual-height 0)
15552 (setq insert-list (cons "*" insert-list))
15553 (setq actual-height (1- actual-height)))
15554@end group
15555
15556@group
15557 ;; @r{Fill in blanks.}
15558 (while (> number-of-top-blanks 0)
15559 (setq insert-list (cons " " insert-list))
15560 (setq number-of-top-blanks
15561 (1- number-of-top-blanks)))
15562@end group
15563
15564@group
15565 ;; @r{Return whole list.}
15566 insert-list))
15567@end group
15568@end smallexample
15569
15570If you install this function and then evaluate the following
15571expression you will see that it returns the list as desired:
15572
15573@smallexample
15574(column-of-graph 5 3)
15575@end smallexample
15576
15577@need 800
15578@noindent
15579returns
15580
15581@smallexample
15582(" " " " "*" "*" "*")
15583@end smallexample
15584
15585As written, @code{column-of-graph} contains a major flaw: the symbols
15586used for the blank and for the marked entries in the column are
15587`hard-coded' as a space and asterisk. This is fine for a prototype,
15588but you, or another user, may wish to use other symbols. For example,
15589in testing the graph function, you many want to use a period in place
15590of the space, to make sure the point is being repositioned properly
15591each time the @code{insert-rectangle} function is called; or you might
15592want to substitute a @samp{+} sign or other symbol for the asterisk.
15593You might even want to make a graph-column that is more than one
15594display column wide. The program should be more flexible. The way to
15595do that is to replace the blank and the asterisk with two variables
15596that we can call @code{graph-blank} and @code{graph-symbol} and define
15597those variables separately.
15598
15599Also, the documentation is not well written. These considerations
15600lead us to the second version of the function:
15601
15602@smallexample
15603@group
15604(defvar graph-symbol "*"
15605 "String used as symbol in graph, usually an asterisk.")
15606@end group
15607
15608@group
15609(defvar graph-blank " "
15610 "String used as blank in graph, usually a blank space.
15611graph-blank must be the same number of columns wide
15612as graph-symbol.")
15613@end group
15614@end smallexample
15615
15616@noindent
15617(For an explanation of @code{defvar}, see
15618@ref{defvar, , Initializing a Variable with @code{defvar}}.)
15619
15620@smallexample
15621@group
15622;;; @r{Second version.}
15623(defun column-of-graph (max-graph-height actual-height)
15624 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15625
15626@end group
15627@group
15628The graph-symbols are contiguous entries at the end
15629of the list.
15630The list will be inserted as one column of a graph.
15631The strings are either graph-blank or graph-symbol."
15632@end group
15633
15634@group
15635 (let ((insert-list nil)
15636 (number-of-top-blanks
15637 (- max-graph-height actual-height)))
15638@end group
15639
15640@group
15641 ;; @r{Fill in @code{graph-symbols}.}
15642 (while (> actual-height 0)
15643 (setq insert-list (cons graph-symbol insert-list))
15644 (setq actual-height (1- actual-height)))
15645@end group
15646
15647@group
15648 ;; @r{Fill in @code{graph-blanks}.}
15649 (while (> number-of-top-blanks 0)
15650 (setq insert-list (cons graph-blank insert-list))
15651 (setq number-of-top-blanks
15652 (1- number-of-top-blanks)))
15653
15654 ;; @r{Return whole list.}
15655 insert-list))
15656@end group
15657@end smallexample
15658
15659If we wished, we could rewrite @code{column-of-graph} a third time to
15660provide optionally for a line graph as well as for a bar graph. This
15661would not be hard to do. One way to think of a line graph is that it
15662is no more than a bar graph in which the part of each bar that is
15663below the top is blank. To construct a column for a line graph, the
15664function first constructs a list of blanks that is one shorter than
15665the value, then it uses @code{cons} to attach a graph symbol to the
15666list; then it uses @code{cons} again to attach the `top blanks' to
15667the list.
15668
15669It is easy to see how to write such a function, but since we don't
15670need it, we will not do it. But the job could be done, and if it were
15671done, it would be done with @code{column-of-graph}. Even more
15672important, it is worth noting that few changes would have to be made
15673anywhere else. The enhancement, if we ever wish to make it, is
15674simple.
15675
15676Now, finally, we come to our first actual graph printing function.
15677This prints the body of a graph, not the labels for the vertical and
15678horizontal axes, so we can call this @code{graph-body-print}.
15679
15680@node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15681@section The @code{graph-body-print} Function
15682@findex graph-body-print
15683
15684After our preparation in the preceding section, the
15685@code{graph-body-print} function is straightforward. The function
15686will print column after column of asterisks and blanks, using the
15687elements of a numbers' list to specify the number of asterisks in each
15688column. This is a repetitive act, which means we can use a
15689decrementing @code{while} loop or recursive function for the job. In
15690this section, we will write the definition using a @code{while} loop.
15691
15692The @code{column-of-graph} function requires the height of the graph
15693as an argument, so we should determine and record that as a local variable.
15694
15695This leads us to the following template for the @code{while} loop
15696version of this function:
15697
15698@smallexample
15699@group
15700(defun graph-body-print (numbers-list)
15701 "@var{documentation}@dots{}"
15702 (let ((height @dots{}
15703 @dots{}))
15704@end group
15705
15706@group
15707 (while numbers-list
15708 @var{insert-columns-and-reposition-point}
15709 (setq numbers-list (cdr numbers-list)))))
15710@end group
15711@end smallexample
15712
15713@noindent
15714We need to fill in the slots of the template.
15715
15716Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15717determine the height of the graph.
15718
15719The @code{while} loop will cycle through the @code{numbers-list} one
15720element at a time. As it is shortened by the @code{(setq numbers-list
15721(cdr numbers-list))} expression, the @sc{car} of each instance of the
15722list is the value of the argument for @code{column-of-graph}.
15723
15724At each cycle of the @code{while} loop, the @code{insert-rectangle}
15725function inserts the list returned by @code{column-of-graph}. Since
15726the @code{insert-rectangle} function moves point to the lower right of
15727the inserted rectangle, we need to save the location of point at the
15728time the rectangle is inserted, move back to that position after the
15729rectangle is inserted, and then move horizontally to the next place
15730from which @code{insert-rectangle} is called.
15731
15732If the inserted columns are one character wide, as they will be if
15733single blanks and asterisks are used, the repositioning command is
15734simply @code{(forward-char 1)}; however, the width of a column may be
15735greater than one. This means that the repositioning command should be
15736written @code{(forward-char symbol-width)}. The @code{symbol-width}
15737itself is the length of a @code{graph-blank} and can be found using
15738the expression @code{(length graph-blank)}. The best place to bind
15739the @code{symbol-width} variable to the value of the width of graph
15740column is in the varlist of the @code{let} expression.
15741
15742@need 1250
15743These considerations lead to the following function definition:
15744
15745@smallexample
15746@group
15747(defun graph-body-print (numbers-list)
15748 "Print a bar graph of the NUMBERS-LIST.
15749The numbers-list consists of the Y-axis values."
15750
15751 (let ((height (apply 'max numbers-list))
15752 (symbol-width (length graph-blank))
15753 from-position)
15754@end group
15755
15756@group
15757 (while numbers-list
15758 (setq from-position (point))
15759 (insert-rectangle
15760 (column-of-graph height (car numbers-list)))
15761 (goto-char from-position)
15762 (forward-char symbol-width)
15763@end group
15764@group
15765 ;; @r{Draw graph column by column.}
15766 (sit-for 0)
15767 (setq numbers-list (cdr numbers-list)))
15768@end group
15769@group
15770 ;; @r{Place point for X axis labels.}
15771 (forward-line height)
15772 (insert "\n")
15773))
15774@end group
15775@end smallexample
15776
15777@noindent
15778The one unexpected expression in this function is the
15779@w{@code{(sit-for 0)}} expression in the @code{while} loop. This
15780expression makes the graph printing operation more interesting to
15781watch than it would be otherwise. The expression causes Emacs to
15782`sit' or do nothing for a zero length of time and then redraw the
15783screen. Placed here, it causes Emacs to redraw the screen column by
15784column. Without it, Emacs would not redraw the screen until the
15785function exits.
15786
15787We can test @code{graph-body-print} with a short list of numbers.
15788
15789@enumerate
15790@item
15791Install @code{graph-symbol}, @code{graph-blank},
15792@code{column-of-graph}, which are in
475dc40a
EZ
15793@iftex
15794@ref{Readying a Graph, , Readying a Graph},
15795@end iftex
15796@ifinfo
15797@ref{Columns of a graph},
15798@end ifinfo
8b096dce
EZ
15799and @code{graph-body-print}.
15800
15801@need 800
15802@item
15803Copy the following expression:
15804
15805@smallexample
15806(graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15807@end smallexample
15808
15809@item
15810Switch to the @file{*scratch*} buffer and place the cursor where you
15811want the graph to start.
15812
15813@item
15814Type @kbd{M-:} (@code{eval-expression}).
15815
15816@item
15817Yank the @code{graph-body-print} expression into the minibuffer
15818with @kbd{C-y} (@code{yank)}.
15819
15820@item
15821Press @key{RET} to evaluate the @code{graph-body-print} expression.
15822@end enumerate
15823
15824@need 800
15825Emacs will print a graph like this:
15826
15827@smallexample
15828@group
15829 *
15830 * **
15831 * ****
15832 *** ****
15833 ********* *
15834 ************
15835 *************
15836@end group
15837@end smallexample
15838
15839@node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15840@section The @code{recursive-graph-body-print} Function
15841@findex recursive-graph-body-print
15842
15843The @code{graph-body-print} function may also be written recursively.
15844The recursive solution is divided into two parts: an outside `wrapper'
15845that uses a @code{let} expression to determine the values of several
15846variables that need only be found once, such as the maximum height of
15847the graph, and an inside function that is called recursively to print
15848the graph.
15849
15850@need 1250
15851The `wrapper' is uncomplicated:
15852
15853@smallexample
15854@group
15855(defun recursive-graph-body-print (numbers-list)
15856 "Print a bar graph of the NUMBERS-LIST.
15857The numbers-list consists of the Y-axis values."
15858 (let ((height (apply 'max numbers-list))
15859 (symbol-width (length graph-blank))
15860 from-position)
15861 (recursive-graph-body-print-internal
15862 numbers-list
15863 height
15864 symbol-width)))
15865@end group
15866@end smallexample
15867
15868The recursive function is a little more difficult. It has four parts:
15869the `do-again-test', the printing code, the recursive call, and the
15870`next-step-expression'. The `do-again-test' is an @code{if}
15871expression that determines whether the @code{numbers-list} contains
15872any remaining elements; if it does, the function prints one column of
15873the graph using the printing code and calls itself again. The
15874function calls itself again according to the value produced by the
15875`next-step-expression' which causes the call to act on a shorter
15876version of the @code{numbers-list}.
15877
15878@smallexample
15879@group
15880(defun recursive-graph-body-print-internal
15881 (numbers-list height symbol-width)
15882 "Print a bar graph.
15883Used within recursive-graph-body-print function."
15884@end group
15885
15886@group
15887 (if numbers-list
15888 (progn
15889 (setq from-position (point))
15890 (insert-rectangle
15891 (column-of-graph height (car numbers-list)))
15892@end group
15893@group
15894 (goto-char from-position)
15895 (forward-char symbol-width)
15896 (sit-for 0) ; @r{Draw graph column by column.}
15897 (recursive-graph-body-print-internal
15898 (cdr numbers-list) height symbol-width))))
15899@end group
15900@end smallexample
15901
15902@need 1250
15903After installation, this expression can be tested; here is a sample:
15904
15905@smallexample
15906(recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15907@end smallexample
15908
15909@need 800
15910Here is what @code{recursive-graph-body-print} produces:
15911
15912@smallexample
15913@group
15914 *
15915 ** *
15916 **** *
15917 **** ***
15918 * *********
15919 ************
15920 *************
15921@end group
15922@end smallexample
15923
15924Either of these two functions, @code{graph-body-print} or
15925@code{recursive-graph-body-print}, create the body of a graph.
15926
15927@node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15928@section Need for Printed Axes
15929
15930A graph needs printed axes, so you can orient yourself. For a do-once
15931project, it may be reasonable to draw the axes by hand using Emacs'
15932Picture mode; but a graph drawing function may be used more than once.
15933
15934For this reason, I have written enhancements to the basic
15935@code{print-graph-body} function that automatically print labels for
15936the horizontal and vertical axes. Since the label printing functions
15937do not contain much new material, I have placed their description in
15938an appendix. @xref{Full Graph, , A Graph with Labelled Axes}.
15939
15940@node Line Graph Exercise, , Printed Axes, Readying a Graph
15941@section Exercise
15942
15943Write a line graph version of the graph printing functions.
15944
15945@node Emacs Initialization, Debugging, Readying a Graph, Top
15946@chapter Your @file{.emacs} File
15947@cindex @file{.emacs} file
15948@cindex Customizing your @file{.emacs} file
15949@cindex Initialization file
15950
15951``You don't have to like Emacs to like it'' -- this seemingly
15952paradoxical statement is the secret of GNU Emacs. The plain, `out of
15953the box' Emacs is a generic tool. Most people who use it, customize
15954it to suit themselves.
15955
15956GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15957expressions in Emacs Lisp you can change or extend Emacs.
15958
15959@menu
15960* Default Configuration::
15961* Site-wide Init:: You can write site-wide init files.
15962* defcustom:: Emacs will write code for you.
15963* Beginning a .emacs File:: How to write a @code{.emacs file}.
15964* Text and Auto-fill:: Automatically wrap lines.
15965* Mail Aliases:: Use abbreviations for email addresses.
15966* Indent Tabs Mode:: Don't use tabs with @TeX{}
15967* Keybindings:: Create some personal keybindings.
15968* Keymaps:: More about key binding.
15969* Loading Files:: Load (i.e., evaluate) files automatically.
15970* Autoload:: Make functions available.
15971* Simple Extension:: Define a function; bind it to a key.
15972* X11 Colors:: Colors in version 19 in X.
15973* Miscellaneous::
15974* Mode Line:: How to customize your mode line.
15975@end menu
15976
15977@node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15978@ifnottex
15979@unnumberedsec Emacs' Default Configuration
15980@end ifnottex
15981
15982There are those who appreciate Emacs' default configuration. After
15983all, Emacs starts you in C mode when you edit a C file, starts you in
15984Fortran mode when you edit a Fortran file, and starts you in
15985Fundamental mode when you edit an unadorned file. This all makes
15986sense, if you do not know who is going to use Emacs. Who knows what a
15987person hopes to do with an unadorned file? Fundamental mode is the
15988right default for such a file, just as C mode is the right default for
15989editing C code. But when you do know who is going to use Emacs---you,
15990yourself---then it makes sense to customize Emacs.
15991
15992For example, I seldom want Fundamental mode when I edit an
15993otherwise undistinguished file; I want Text mode. This is why I
15994customize Emacs: so it suits me.
15995
15996You can customize and extend Emacs by writing or adapting a
15997@file{~/.emacs} file. This is your personal initialization file; its
15998contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
15999may also add @file{.el} to @file{~/.emacs} and call it a
16000@file{~/.emacs.el} file. In the past, you were forbidden to type the
16001extra keystrokes that the name @file{~/.emacs.el} requires, but now
16002you may. The new format is consistent with the Emacs Lisp file
16003naming conventions; the old format saves typing.}
16004
16005A @file{~/.emacs} file contains Emacs Lisp code. You can write this
16006code yourself; or you can use Emacs' @code{customize} feature to write
16007the code for you. You can combine your own expressions and
16008auto-written Customize expressions in your @file{.emacs} file.
16009
16010(I myself prefer to write my own expressions, except for those,
16011particularly fonts, that I find easier to manipulate using the
16012@code{customize} command. I combine the two methods.)
16013
16014Most of this chapter is about writing expressions yourself. It
16015describes a simple @file{.emacs} file; for more information, see
16016@ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16017@ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16018Manual}.
16019
16020@node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16021@section Site-wide Initialization Files
16022
16023@cindex @file{default.el} init file
16024@cindex @file{site-init.el} init file
16025@cindex @file{site-load.el} init file
16026In addition to your personal initialization file, Emacs automatically
16027loads various site-wide initialization files, if they exist. These
16028have the same form as your @file{.emacs} file, but are loaded by
16029everyone.
16030
16031Two site-wide initialization files, @file{site-load.el} and
16032@file{site-init.el}, are loaded into Emacs and then `dumped' if a
16033`dumped' version of Emacs is created, as is most common. (Dumped
16034copies of Emacs load more quickly. However, once a file is loaded and
16035dumped, a change to it does not lead to a change in Emacs unless you
16036load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16037Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16038@file{INSTALL} file.)
16039
16040Three other site-wide initialization files are loaded automatically
16041each time you start Emacs, if they exist. These are
16042@file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16043file, and @file{default.el}, and the terminal type file, which are both
16044loaded @emph{after} your @file{.emacs} file.
16045
16046Settings and definitions in your @file{.emacs} file will overwrite
16047conflicting settings and definitions in a @file{site-start.el} file,
16048if it exists; but the settings and definitions in a @file{default.el}
16049or terminal type file will overwrite those in your @file{.emacs} file.
16050(You can prevent interference from a terminal type file by setting
16051@code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16052Simple Extension}.)
16053
16054@c Rewritten to avoid overfull hbox.
16055The @file{INSTALL} file that comes in the distribution contains
16056descriptions of the @file{site-init.el} and @file{site-load.el} files.
16057
16058The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16059control loading. These files are in the @file{lisp} directory of the
16060Emacs distribution and are worth perusing.
16061
16062The @file{loaddefs.el} file contains a good many suggestions as to
16063what to put into your own @file{.emacs} file, or into a site-wide
16064initialization file.
16065
16066@node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16067@section Specifying Variables using @code{defcustom}
16068@findex defcustom
16069
16070You can specify variables using @code{defcustom} so that you and
16071others can then can use Emacs' @code{customize} feature to set their
16072values. (You cannot use @code{customize} to write function
16073definitions; but you can write @code{defuns} in your @file{.emacs}
16074file. Indeed, you can write any Lisp expression in your @file{.emacs}
16075file.)
16076
16077The @code{customize} feature depends on the @code{defcustom} special
16078form. Although you can use @code{defvar} or @code{setq} for variables
16079that users set, the @code{defcustom} special form is designed for the
16080job.
16081
16082You can use your knowledge of @code{defvar} for writing the
16083first three arguments for @code{defcustom}. The first argument to
16084@code{defcustom} is the name of the variable. The second argument is
16085the variable's initial value, if any; and this value is set only if
16086the value has not already been set. The third argument is the
16087documentation.
16088
16089The fourth and subsequent arguments to @code{defcustom} specify types
16090and options; these are not featured in @code{defvar}. (These
16091arguments are optional.)
16092
16093Each of these arguments consists of a keyword followed by a value.
16094Each keyword starts with the character @code{:}.
16095
16096@need 1250
16097For example, the customizable user option variable
16098@code{text-mode-hook} looks like this:
16099
16100@smallexample
16101@group
16102(defcustom text-mode-hook nil
16103 "Normal hook run when entering Text mode and many related modes."
16104 :type 'hook
16105 :options '(turn-on-auto-fill flyspell-mode)
16106 :group 'data)
16107@end group
16108@end smallexample
16109
16110@noindent
16111The name of the variable is @code{text-mode-hook}; it has no default
16112value; and its documentation string tells you what it does.
16113
16114The @code{:type} keyword tells Emacs what kind of data
16115@code{text-mode-hook} should be set to and how to display the value in
16116a Customization buffer.
16117
16118The @code{:options} keyword specifies a suggested list of values for
16119the variable. Currently, you can use @code{:options} only for a hook.
16120The list is only a suggestion; it is not exclusive; a person who sets
16121the variable may set it to other values; the list shown following the
16122@code{:options} keyword is intended to offer convenient choices to a
16123user.
16124
16125Finally, the @code{:group} keyword tells the Emacs Customization
16126command in which group the variable is located. This tells where to
16127find it.
16128
16129For more information, see @ref{Customization, , Writing Customization
16130Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16131
16132Consider @code{text-mode-hook} as an example.
16133
16134There are two ways to customize this variable. You can use the
16135customization command or write the appropriate expressions yourself.
16136
16137@need 800
16138Using the customization command, you can type:
16139
16140@smallexample
16141M-x customize
16142@end smallexample
16143
16144@noindent
16145and find that the group for editing files of data is called `data'.
16146Enter that group. Text Mode Hook is the first member. You can click
16147on its various options to set the values. After you click on the
16148button to
16149
16150@smallexample
16151Save for Future Sessions
16152@end smallexample
16153
16154@noindent
16155Emacs will write an expression into your @file{.emacs} file.
16156It will look like this:
16157
16158@smallexample
16159@group
16160(custom-set-variables
16161 ;; custom-set-variables was added by Custom --
16162 ;; don't edit or cut/paste it!
16163 ;; Your init file should contain only one such instance.
16164 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16165@end group
16166@end smallexample
16167
16168@noindent
16169(The @code{text-mode-hook-identify} function tells
16170@code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16171
16172In spite of the warning, you certainly may edit, cut, and paste the
16173expression! I do all time. The purpose of the warning is to scare
16174those who do not know what they are doing, so they do not
16175inadvertently generate an error.
16176
16177The @code{custom-set-variables} works somewhat differently than a
16178@code{setq}. While I have never learned the differences, I do modify
16179the @code{custom-set-variables} expressions in my @file{.emacs} file
16180by hand: I make the changes in what appears to me to be a reasonable
16181manner and have not had any problems. Others prefer to use the
16182Customization command and let Emacs do the work for them.
16183
16184Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16185This function sets the various font faces. Over time, I have set a
16186considerable number of faces. Some of the time, I re-set them using
16187@code{customize}; other times, I simply edit the
16188@code{custom-set-faces} expression in my @file{.emacs} file itself.
16189
16190The second way to customize your @code{text-mode-hook} is to set it
16191yourself in your @file{.emacs} file using code that has nothing to do
16192with the @code{custom-set-@dots{}} functions.
16193
16194@need 800
16195When you do this, and later use @code{customize}, you will see a
16196message that says
16197
16198@smallexample
16199this option has been changed outside the customize buffer.
16200@end smallexample
16201
16202@need 800
16203This message is only a warning. If you click on the button to
16204
16205@smallexample
16206Save for Future Sessions
16207@end smallexample
16208
16209@noindent
16210Emacs will write a @code{custom-set-@dots{}} expression near the end
16211of your @file{.emacs} file that will be evaluated after your
16212hand-written expression. It will, therefore, overrule your
16213hand-written expression. No harm will be done. When you do this,
16214however, be careful to remember which expression is active; if you
16215forget, you may confuse yourself.
16216
16217So long as you remember where the values are set, you will have no
16218trouble. In any event, the values are always set in your
16219initialization file, which is usually called @file{.emacs}.
16220
16221I myself use @code{customize} for hardly anything. Mostly, I write
16222expressions myself.
16223
16224@node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16225@section Beginning a @file{.emacs} File
16226@cindex @file{.emacs} file, beginning of
16227
16228When you start Emacs, it loads your @file{.emacs} file unless you tell
16229it not to by specifying @samp{-q} on the command line. (The
16230@code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16231
16232A @file{.emacs} file contains Lisp expressions. Often, these are no
16233more than expressions to set values; sometimes they are function
16234definitions.
16235
16236@xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16237Manual}, for a short description of initialization files.
16238
16239This chapter goes over some of the same ground, but is a walk among
16240extracts from a complete, long-used @file{.emacs} file---my own.
16241
16242The first part of the file consists of comments: reminders to myself.
16243By now, of course, I remember these things, but when I started, I did
16244not.
16245
16246@smallexample
16247@group
16248;;;; Bob's .emacs file
16249; Robert J. Chassell
16250; 26 September 1985
16251@end group
16252@end smallexample
16253
16254@noindent
16255Look at that date! I started this file a long time ago. I have been
16256adding to it ever since.
16257
16258@smallexample
16259@group
16260; Each section in this file is introduced by a
16261; line beginning with four semicolons; and each
16262; entry is introduced by a line beginning with
16263; three semicolons.
16264@end group
16265@end smallexample
16266
16267@noindent
16268This describes the usual conventions for comments in Emacs Lisp.
16269Everything on a line that follows a semicolon is a comment. Two,
16270three, and four semicolons are used as section and subsection
16271markers. (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16272Manual}, for more about comments.)
16273
16274@smallexample
16275@group
16276;;;; The Help Key
16277; Control-h is the help key;
16278; after typing control-h, type a letter to
16279; indicate the subject about which you want help.
16280; For an explanation of the help facility,
16281; type control-h two times in a row.
16282@end group
16283@end smallexample
16284
16285@noindent
16286Just remember: type @kbd{C-h} two times for help.
16287
16288@smallexample
16289@group
16290; To find out about any mode, type control-h m
16291; while in that mode. For example, to find out
16292; about mail mode, enter mail mode and then type
16293; control-h m.
16294@end group
16295@end smallexample
16296
16297@noindent
16298`Mode help', as I call this, is very helpful. Usually, it tells you
16299all you need to know.
16300
16301Of course, you don't need to include comments like these in your
16302@file{.emacs} file. I included them in mine because I kept forgetting
16303about Mode help or the conventions for comments---but I was able to
16304remember to look here to remind myself.
16305
16306@node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16307@section Text and Auto Fill Mode
16308
16309Now we come to the part that `turns on' Text mode and
16310Auto Fill mode.
16311
16312@smallexample
16313@group
16314;;; Text mode and Auto Fill mode
16315; The next three lines put Emacs into Text mode
16316; and Auto Fill mode, and are for writers who
16317; want to start writing prose rather than code.
16318
16319(setq default-major-mode 'text-mode)
16320(add-hook 'text-mode-hook 'text-mode-hook-identify)
16321(add-hook 'text-mode-hook 'turn-on-auto-fill)
16322@end group
16323@end smallexample
16324
16325Here is the first part of this @file{.emacs} file that does something
16326besides remind a forgetful human!
16327
16328The first of the two lines in parentheses tells Emacs to turn on Text
16329mode when you find a file, @emph{unless} that file should go into some
16330other mode, such as C mode.
16331
16332@cindex Per-buffer, local variables list
16333@cindex Local variables list, per-buffer,
16334@cindex Automatic mode selection
16335@cindex Mode selection, automatic
16336When Emacs reads a file, it looks at the extension to the file name,
16337if any. (The extension is the part that comes after a @samp{.}.) If
16338the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16339on C mode. Also, Emacs looks at first nonblank line of the file; if
16340the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
16341possesses a list of extensions and specifications that it uses
16342automatically. In addition, Emacs looks near the last page for a
16343per-buffer, ``local variables list'', if any.
16344
16345@ifinfo
16346@xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16347Emacs Manual}.
16348
16349@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16350Manual}.
16351@end ifinfo
16352@iftex
16353See sections ``How Major Modes are Chosen'' and ``Local Variables in
16354Files'' in @cite{The GNU Emacs Manual}.
16355@end iftex
16356
16357Now, back to the @file{.emacs} file.
16358
16359@need 800
16360Here is the line again; how does it work?
16361
16362@cindex Text Mode turned on
16363@smallexample
16364(setq default-major-mode 'text-mode)
16365@end smallexample
16366
16367@noindent
16368This line is a short, but complete Emacs Lisp expression.
16369
16370We are already familiar with @code{setq}. It sets the following variable,
16371@code{default-major-mode}, to the subsequent value, which is
16372@code{text-mode}. The single quote mark before @code{text-mode} tells
16373Emacs to deal directly with the @code{text-mode} variable, not with
16374whatever it might stand for. @xref{set & setq, , Setting the Value of
16375a Variable}, for a reminder of how @code{setq} works. The main point
16376is that there is no difference between the procedure you use to set
16377a value in your @file{.emacs} file and the procedure you use anywhere
16378else in Emacs.
16379
16380@need 800
16381Here are the next two lines:
16382
16383@cindex Auto Fill mode turned on
16384@findex add-hook
16385@smallexample
16386(add-hook 'text-mode-hook 'text-mode-hook-identify)
16387(add-hook 'text-mode-hook 'turn-on-auto-fill)
16388@end smallexample
16389
16390@noindent
16391In these two lines, the @code{add-hook} command first adds
16392@code{text-mode-hook-identify} to the variable called
16393@code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16394variable.
16395
16396@code{turn-on-auto-fill} is the name of a program, that, you guessed
16397it!, turns on Auto Fill mode. @code{text-mode-hook-identify} is a
16398function that tells @code{toggle-text-mode-auto-fill} which buffers
16399are in Text mode.
16400
16401Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16402onto Text mode. So every time Emacs turns on Text mode, Emacs also
16403turns on Auto Fill mode.
16404
16405In brief, the first line causes Emacs to enter Text mode when you edit
16406a file, unless the file name extension, first non-blank line, or local
16407variables tell Emacs otherwise.
16408
16409Text mode among other actions, sets the syntax table to work
16410conveniently for writers. In Text mode, Emacs considers an apostrophe
16411as part of a word like a letter; but Emacs does not consider a period
16412or a space as part of a word. Thus, @kbd{M-f} moves you over
16413@samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
16414the @samp{t} of @samp{it's}.
16415
16416The second and third lines causes Emacs to turn on Auto Fill mode when
16417it turns on Text mode. In Auto Fill mode, Emacs automatically breaks
16418a line that is too wide and brings the excessively wide part of the
16419line down to the next line. Emacs breaks lines between words, not
16420within them.
16421
16422When Auto Fill mode is turned off, lines continue to the right as you
16423type them. Depending on how you set the value of
16424@code{truncate-lines}, the words you type either disappear off the
16425right side of the screen, or else are shown, in a rather ugly and
16426unreadable manner, as a continuation line on the screen.
16427
16428@need 1250
16429In addition, in this part of my @file{.emacs} file, I tell the Emacs
16430fill commands to insert two spaces after a colon:
16431
16432@smallexample
16433(setq colon-double-space t)
16434@end smallexample
16435
16436@node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16437@section Mail Aliases
16438
16439Here is a @code{setq} that `turns on' mail aliases, along with more
16440reminders.
16441
16442@smallexample
16443@group
16444;;; Mail mode
16445; To enter mail mode, type `C-x m'
16446; To enter RMAIL (for reading mail),
16447; type `M-x rmail'
16448
16449(setq mail-aliases t)
16450@end group
16451@end smallexample
16452
16453@cindex Mail aliases
16454@noindent
16455This @code{setq} command sets the value of the variable
16456@code{mail-aliases} to @code{t}. Since @code{t} means true, the line
16457says, in effect, ``Yes, use mail aliases.''
16458
16459Mail aliases are convenient short names for long email addresses or
16460for lists of email addresses. The file where you keep your `aliases'
16461is @file{~/.mailrc}. You write an alias like this:
16462
16463@smallexample
16464alias geo george@@foobar.wiz.edu
16465@end smallexample
16466
16467@noindent
16468When you write a message to George, address it to @samp{geo}; the
16469mailer will automatically expand @samp{geo} to the full address.
16470
16471@node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16472@section Indent Tabs Mode
16473@cindex Tabs, preventing
16474@findex indent-tabs-mode
16475
16476By default, Emacs inserts tabs in place of multiple spaces when it
16477formats a region. (For example, you might indent many lines of text
16478all at once with the @code{indent-region} command.) Tabs look fine on
16479a terminal or with ordinary printing, but they produce badly indented
16480output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16481
16482@need 1250
16483The following turns off Indent Tabs mode:
16484
16485@smallexample
16486@group
16487;;; Prevent Extraneous Tabs
16488(setq-default indent-tabs-mode nil)
16489@end group
16490@end smallexample
16491
16492Note that this line uses @code{setq-default} rather than the
16493@code{setq} command that we have seen before. The @code{setq-default}
16494command sets values only in buffers that do not have their own local
16495values for the variable.
16496
16497@ifinfo
16498@xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16499
16500@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16501Manual}.
16502@end ifinfo
16503@iftex
16504See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16505Files'' in @cite{The GNU Emacs Manual}.
16506@end iftex
16507
16508@node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16509@section Some Keybindings
16510
16511Now for some personal keybindings:
16512
16513@smallexample
16514@group
16515;;; Compare windows
16516(global-set-key "\C-cw" 'compare-windows)
16517@end group
16518@end smallexample
16519
16520@findex compare-windows
16521@code{compare-windows} is a nifty command that compares the text in
16522your current window with text in the next window. It makes the
16523comparison by starting at point in each window, moving over text in
16524each window as far as they match. I use this command all the time.
16525
16526This also shows how to set a key globally, for all modes.
16527
16528@cindex Setting a key globally
16529@cindex Global set key
16530@cindex Key setting globally
16531@findex global-set-key
16532The command is @code{global-set-key}. It is followed by the
16533keybinding. In a @file{.emacs} file, the keybinding is written as
16534shown: @code{\C-c} stands for `control-c', which means `press the
16535control key and the @kbd{c} key at the same time'. The @code{w} means
16536`press the @kbd{w} key'. The keybinding is surrounded by double
16537quotation marks. In documentation, you would write this as @kbd{C-c
16538w}. (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16539than a @key{CTL} key, you would write @code{\M-c}. @xref{Init
16540Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16541Manual}, for details.)
16542
16543The command invoked by the keys is @code{compare-windows}. Note that
16544@code{compare-windows} is preceded by a single quote; otherwise, Emacs
16545would first try to evaluate the symbol to determine its value.
16546
16547These three things, the double quotation marks, the backslash before
16548the @samp{C}, and the single quote mark are necessary parts of
16549keybinding that I tend to forget. Fortunately, I have come to
16550remember that I should look at my existing @file{.emacs} file, and
16551adapt what is there.
16552
16553As for the keybinding itself: @kbd{C-c w}. This combines the prefix
16554key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
16555set of keys, @kbd{C-c} followed by a single character, is strictly
16556reserved for individuals' own use. (I call these `own' keys, since
16557these are for my own use.) You should always be able to create such a
16558keybinding for your own use without stomping on someone else's
16559keybinding. If you ever write an extension to Emacs, please avoid
16560taking any of these keys for public use. Create a key like @kbd{C-c
16561C-w} instead. Otherwise, we will run out of `own' keys.
16562
16563@need 1250
16564Here is another keybinding, with a comment:
16565
16566@smallexample
16567@group
16568;;; Keybinding for `occur'
16569; I use occur a lot, so let's bind it to a key:
16570(global-set-key "\C-co" 'occur)
16571@end group
16572@end smallexample
16573
16574@findex occur
16575The @code{occur} command shows all the lines in the current buffer
16576that contain a match for a regular expression. Matching lines are
16577shown in a buffer called @file{*Occur*}. That buffer serves as a menu
16578to jump to occurrences.
16579
16580@findex global-unset-key
16581@cindex Unbinding key
16582@cindex Key unbinding
16583@need 1250
16584Here is how to unbind a key, so it does not
16585work:
16586
16587@smallexample
16588@group
16589;;; Unbind `C-x f'
16590(global-unset-key "\C-xf")
16591@end group
16592@end smallexample
16593
16594There is a reason for this unbinding: I found I inadvertently typed
16595@w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
16596file, as I intended, I accidentally set the width for filled text,
16597almost always to a width I did not want. Since I hardly ever reset my
16598default width, I simply unbound the key.
16599
16600@findex list-buffers, @r{rebound}
16601@findex buffer-menu, @r{bound to key}
16602@need 1250
16603The following rebinds an existing key:
16604
16605@smallexample
16606@group
16607;;; Rebind `C-x C-b' for `buffer-menu'
16608(global-set-key "\C-x\C-b" 'buffer-menu)
16609@end group
16610@end smallexample
16611
16612By default, @kbd{C-x C-b} runs the
16613@code{list-buffers} command. This command lists
16614your buffers in @emph{another} window. Since I
16615almost always want to do something in that
16616window, I prefer the @code{buffer-menu}
16617command, which not only lists the buffers,
16618but moves point into that window.
16619
16620@node Keymaps, Loading Files, Keybindings, Emacs Initialization
16621@section Keymaps
16622@cindex Keymaps
16623@cindex Rebinding keys
16624
16625Emacs uses @dfn{keymaps} to record which keys call which commands.
16626When you use @code{global-set-key} to set the keybinding for a single
16627command in all parts of Emacs, you are specifying the keybinding in
16628@code{current-global-map}.
16629
16630Specific modes, such as C mode or Text mode, have their own keymaps;
16631the mode-specific keymaps override the global map that is shared by
16632all buffers.
16633
16634The @code{global-set-key} function binds, or rebinds, the global
16635keymap. For example, the following binds the key @kbd{C-x C-b} to the
16636function @code{buffer-menu}:
16637
16638@smallexample
16639(global-set-key "\C-x\C-b" 'buffer-menu)
16640@end smallexample
16641
16642Mode-specific keymaps are bound using the @code{define-key} function,
16643which takes a specific keymap as an argument, as well as the key and
16644the command. For example, my @file{.emacs} file contains the
16645following expression to bind the @code{texinfo-insert-@@group} command
16646to @kbd{C-c C-c g}:
16647
16648@smallexample
16649@group
16650(define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16651@end group
16652@end smallexample
16653
16654@noindent
16655The @code{texinfo-insert-@@group} function itself is a little extension
16656to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
16657use this command all the time and prefer to type the three strokes
16658@kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16659(@samp{@@group} and its matching @samp{@@end group} are commands that
16660keep all enclosed text together on one page; many multi-line examples
16661in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16662
16663@need 1250
16664Here is the @code{texinfo-insert-@@group} function definition:
16665
16666@smallexample
16667@group
16668(defun texinfo-insert-@@group ()
16669 "Insert the string @@group in a Texinfo buffer."
16670 (interactive)
16671 (beginning-of-line)
16672 (insert "@@group\n"))
16673@end group
16674@end smallexample
16675
16676(Of course, I could have used Abbrev mode to save typing, rather than
16677write a function to insert a word; but I prefer key strokes consistent
16678with other Texinfo mode key bindings.)
16679
16680You will see numerous @code{define-key} expressions in
16681@file{loaddefs.el} as well as in the various mode libraries, such as
16682@file{cc-mode.el} and @file{lisp-mode.el}.
16683
16684@xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16685Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16686Reference Manual}, for more information about keymaps.
16687
16688@node Loading Files, Autoload, Keymaps, Emacs Initialization
16689@section Loading Files
16690@cindex Loading files
16691@c findex load
16692
16693Many people in the GNU Emacs community have written extensions to
16694Emacs. As time goes by, these extensions are often included in new
16695releases. For example, the Calendar and Diary packages are now part
16696of the standard GNU Emacs.
16697
16698(Calc, which I consider a vital part of Emacs, would be part of the
16699standard distribution except that it was so large it was packaged
16700separately and no one has changed that.)
16701
16702You can use a @code{load} command to evaluate a complete file and
16703thereby install all the functions and variables in the file into Emacs.
16704For example:
16705
16706@c (auto-compression-mode t)
16707
16708@smallexample
16709(load "~/emacs/slowsplit")
16710@end smallexample
16711
16712This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16713exists, the faster, byte compiled @file{slowsplit.elc} file from the
16714@file{emacs} sub-directory of your home directory. The file contains
16715the function @code{split-window-quietly}, which John Robinson wrote in
167161989.
16717
16718The @code{split-window-quietly} function splits a window with the
16719minimum of redisplay. I installed it in 1989 because it worked well
16720with the slow 1200 baud terminals I was then using. Nowadays, I only
16721occasionally come across such a slow connection, but I continue to use
16722the function because I like the way it leaves the bottom half of a
16723buffer in the lower of the new windows and the top half in the upper
16724window.
16725
16726@need 1250
16727To replace the key binding for the default
16728@code{split-window-vertically}, you must also unset that key and bind
16729the keys to @code{split-window-quietly}, like this:
16730
16731@smallexample
16732@group
16733(global-unset-key "\C-x2")
16734(global-set-key "\C-x2" 'split-window-quietly)
16735@end group
16736@end smallexample
16737
16738@vindex load-path
16739If you load many extensions, as I do, then instead of specifying the
16740exact location of the extension file, as shown above, you can specify
16741that directory as part of Emacs' @code{load-path}. Then, when Emacs
16742loads a file, it will search that directory as well as its default
16743list of directories. (The default list is specified in @file{paths.h}
16744when Emacs is built.)
16745
16746@need 1250
16747The following command adds your @file{~/emacs} directory to the
16748existing load path:
16749
16750@smallexample
16751@group
16752;;; Emacs Load Path
16753(setq load-path (cons "~/emacs" load-path))
16754@end group
16755@end smallexample
16756
16757Incidentally, @code{load-library} is an interactive interface to the
16758@code{load} function. The complete function looks like this:
16759
16760@findex load-library
16761@smallexample
16762@group
16763(defun load-library (library)
16764 "Load the library named LIBRARY.
16765This is an interface to the function `load'."
16766 (interactive "sLoad library: ")
16767 (load library))
16768@end group
16769@end smallexample
16770
16771The name of the function, @code{load-library}, comes from the use of
16772`library' as a conventional synonym for `file'. The source for the
16773@code{load-library} command is in the @file{files.el} library.
16774
16775Another interactive command that does a slightly different job is
16776@code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
16777Emacs, emacs, The GNU Emacs Manual}, for information on the
16778distinction between @code{load-library} and this command.
16779
16780@node Autoload, Simple Extension, Loading Files, Emacs Initialization
16781@section Autoloading
16782@findex autoload
16783
16784Instead of installing a function by loading the file that contains it,
16785or by evaluating the function definition, you can make the function
16786available but not actually install it until it is first called. This
16787is called @dfn{autoloading}.
16788
16789When you execute an autoloaded function, Emacs automatically evaluates
16790the file that contains the definition, and then calls the function.
16791
16792Emacs starts quicker with autoloaded functions, since their libraries
16793are not loaded right away; but you need to wait a moment when you
16794first use such a function, while its containing file is evaluated.
16795
16796Rarely used functions are frequently autoloaded. The
16797@file{loaddefs.el} library contains hundreds of autoloaded functions,
16798from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
16799come to use a `rare' function frequently. When you do, you should
16800load that function's file with a @code{load} expression in your
16801@file{.emacs} file.
16802
16803In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16804that contain functions that would otherwise be autoloaded. (Actually,
16805it would have been better to include these files in my `dumped' Emacs
16806when I built it, but I forgot. @xref{Building Emacs, , Building
16807Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16808file for more about dumping.)
16809
16810You may also want to include autoloaded expressions in your @file{.emacs}
16811file. @code{autoload} is a built-in function that takes up to five
16812arguments, the final three of which are optional. The first argument
16813is the name of the function to be autoloaded; the second is the name
16814of the file to be loaded. The third argument is documentation for the
16815function, and the fourth tells whether the function can be called
16816interactively. The fifth argument tells what type of
16817object---@code{autoload} can handle a keymap or macro as well as a
16818function (the default is a function).
16819
16820@need 800
16821Here is a typical example:
16822
16823@smallexample
16824@group
16825(autoload 'html-helper-mode
16826 "html-helper-mode" "Edit HTML documents" t)
16827@end group
16828@end smallexample
16829
16830@noindent
16831(@code{html-helper-mode} is an alternative to @code{html-mode}, which
16832is a standard part of the distribution).
16833
16834@noindent
16835This expression autoloads the @code{html-helper-mode} function. It
16836takes it from the @file{html-helper-mode.el} file (or from the byte
16837compiled file @file{html-helper-mode.elc}, if it exists.) The file
16838must be located in a directory specified by @code{load-path}. The
16839documentation says that this is a mode to help you edit documents
16840written in the HyperText Markup Language. You can call this mode
16841interactively by typing @kbd{M-x html-helper-mode}. (You need to
16842duplicate the function's regular documentation in the autoload
16843expression because the regular function is not yet loaded, so its
16844documentation is not available.)
16845
16846@xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16847Manual}, for more information.
16848
16849@node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16850@section A Simple Extension: @code{line-to-top-of-window}
16851@findex line-to-top-of-window
16852@cindex Simple extension in @file{.emacs} file
16853
16854Here is a simple extension to Emacs that moves the line point is on to
16855the top of the window. I use this all the time, to make text easier
16856to read.
16857
16858You can put the following code into a separate file and then load it
16859from your @file{.emacs} file, or you can include it within your
16860@file{.emacs} file.
16861
16862@need 1250
16863Here is the definition:
16864
16865@smallexample
16866@group
16867;;; Line to top of window;
16868;;; replace three keystroke sequence C-u 0 C-l
16869(defun line-to-top-of-window ()
16870 "Move the line point is on to top of window."
16871 (interactive)
16872 (recenter 0))
16873@end group
16874@end smallexample
16875
16876@need 1250
16877Now for the keybinding.
16878
16879Nowadays, function keys as well as mouse button events and
16880non-@sc{ascii} characters are written within square brackets, without
16881quotation marks. (In Emacs version 18 and before, you had to write
16882different function key bindings for each different make of terminal.)
16883
16884I bind @code{line-to-top-of-window} to my @key{F6} function key like
16885this:
16886
16887@smallexample
16888(global-set-key [f6] 'line-to-top-of-window)
16889@end smallexample
16890
16891For more information, see @ref{Init Rebinding, , Rebinding Keys in
16892Your Init File, emacs, The GNU Emacs Manual}.
16893
16894@cindex Conditional 'twixt two versions of Emacs
16895@cindex Version of Emacs, choosing
16896@cindex Emacs version, choosing
16897If you run two versions of GNU Emacs, such as versions 20 and 21, and
16898use one @file{.emacs} file, you can select which code to evaluate with
16899the following conditional:
16900
16901@smallexample
16902@group
16903(cond
16904 ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16905 ;; evaluate version 20 code
16906 ( @dots{} ))
16907 ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16908 ;; evaluate version 21 code
16909 ( @dots{} )))
16910@end group
16911@end smallexample
16912
16913For example, in contrast to version 20, version 21 blinks its cursor
16914by default. I hate such blinking, as well as some other features in
16915version 21, so I placed the following in my @file{.emacs}
16916file@footnote{When I start instances of Emacs that do not load my
16917@file{.emacs} file or any site file, I also turn off blinking:
16918
16919@smallexample
16920emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16921@end smallexample
16922}:
16923
16924@smallexample
16925@group
16926(if (string-equal "21" (substring (emacs-version) 10 12))
16927 (progn
16928 (blink-cursor-mode 0)
16929 ;; Insert newline when you press `C-n' (next-line)
16930 ;; at the end of the buffer
16931 (setq next-line-add-newlines t)
16932@end group
16933@group
16934 ;; Turn on image viewing
16935 (auto-image-file-mode t)
16936@end group
16937@group
16938 ;; Turn on menu bar (this bar has text)
16939 ;; (Use numeric argument to turn on)
16940 (menu-bar-mode 1)
16941@end group
16942@group
16943 ;; Turn off tool bar (this bar has icons)
16944 ;; (Use numeric argument to turn on)
16945 (tool-bar-mode nil)
16946@end group
16947@group
16948 ;; Turn off tooltip mode for tool bar
16949 ;; (This mode causes icon explanations to pop up)
16950 ;; (Use numeric argument to turn on)
16951 (tooltip-mode nil)
16952 ;; If tooltips turned on, make tips appear promptly
16953 (setq tooltip-delay 0.1) ; default is one second
16954 ))
16955@end group
16956@end smallexample
16957
16958@noindent
16959(You will note that instead of typing @code{(number-to-string 21)}, I
16960decided to save typing and wrote `21' as a string, @code{"21"}, rather
16961than convert it from an integer to a string. In this instance, this
16962expression is better than the longer, but more general
16963@code{(number-to-string 21)}. However, if you do not know ahead of
16964time what type of information will be returned, then the
16965@code{number-to-string} function will be needed.)
16966
16967@node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16968@section X11 Colors
16969
16970You can specify colors when you use Emacs with the MIT X Windowing
16971system.
16972
16973I dislike the default colors and specify my own.
16974
16975@need 1250
16976Here are the expressions in my @file{.emacs}
16977file that set values:
16978
16979@smallexample
16980@group
16981;; Set cursor color
16982(set-cursor-color "white")
16983
16984;; Set mouse color
16985(set-mouse-color "white")
16986
16987;; Set foreground and background
16988(set-foreground-color "white")
16989(set-background-color "darkblue")
16990@end group
16991
16992@group
16993;;; Set highlighting colors for isearch and drag
16994(set-face-foreground 'highlight "white")
16995(set-face-background 'highlight "blue")
16996@end group
16997
16998@group
16999(set-face-foreground 'region "cyan")
17000(set-face-background 'region "blue")
17001@end group
17002
17003@group
17004(set-face-foreground 'secondary-selection "skyblue")
17005(set-face-background 'secondary-selection "darkblue")
17006@end group
17007
17008@group
17009;; Set calendar highlighting colors
17010(setq calendar-load-hook
17011 '(lambda ()
17012 (set-face-foreground 'diary-face "skyblue")
17013 (set-face-background 'holiday-face "slate blue")
17014 (set-face-foreground 'holiday-face "white")))
17015@end group
17016@end smallexample
17017
17018The various shades of blue soothe my eye and prevent me from seeing
17019the screen flicker.
17020
17021Alternatively, I could have set my specifications in various X
17022initialization files. For example, I could set the foreground,
17023background, cursor, and pointer (i.e., mouse) colors in my
17024@file{~/.Xresources} file like this:
17025
17026@smallexample
17027@group
17028Emacs*foreground: white
17029Emacs*background: darkblue
17030Emacs*cursorColor: white
17031Emacs*pointerColor: white
17032@end group
17033@end smallexample
17034
17035In any event, since it is not part of Emacs, I set the root color of
17036my X window in my @file{~/.xinitrc} file, like this@footnote{I
17037occasionally run more modern window managers, such as Sawfish with
17038GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17039image rather than a plain color.}:
17040
17041@smallexample
17042@group
17043# I use TWM for window manager.
17044xsetroot -solid Navy -fg white &
17045@end group
17046@end smallexample
17047
17048@node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17049@section Miscellaneous Settings for a @file{.emacs} File
17050
17051Here are a few miscellaneous settings:
17052@sp 1
17053
17054@itemize @minus
17055@item
17056Set the shape and color of the mouse cursor:
17057@smallexample
17058@group
17059; Cursor shapes are defined in
17060; `/usr/include/X11/cursorfont.h';
17061; for example, the `target' cursor is number 128;
17062; the `top_left_arrow' cursor is number 132.
17063@end group
17064
17065@group
17066(let ((mpointer (x-get-resource "*mpointer"
17067 "*emacs*mpointer")))
17068 ;; If you have not set your mouse pointer
17069 ;; then set it, otherwise leave as is:
17070 (if (eq mpointer nil)
17071 (setq mpointer "132")) ; top_left_arrow
17072@end group
17073@group
17074 (setq x-pointer-shape (string-to-int mpointer))
17075 (set-mouse-color "white"))
17076@end group
17077@end smallexample
17078@end itemize
17079
17080@node Mode Line, , Miscellaneous, Emacs Initialization
17081@section A Modified Mode Line
17082@vindex default-mode-line-format
17083@cindex Mode line format
17084
17085Finally, a feature I really like: a modified mode line.
17086
17087When I work over a network, I forget which machine I am using. Also,
17088I tend to I lose track of where I am, and which line point is on.
17089
17090So I reset my mode line to look like this:
17091
17092@smallexample
17093-:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
17094@end smallexample
17095
17096I am visiting a file called @file{foo.texi}, on my machine
17097@file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
17098Texinfo mode, and am at the top of the buffer.
17099
17100@need 1200
17101My @file{.emacs} file has a section that looks like this:
17102
17103@smallexample
17104@group
17105;; Set a Mode Line that tells me which machine, which directory,
17106;; and which line I am on, plus the other customary information.
17107(setq default-mode-line-format
17108 (quote
17109 (#("-" 0 1
17110 (help-echo
17111 "mouse-1: select window, mouse-2: delete others ..."))
17112 mode-line-mule-info
17113 mode-line-modified
17114 mode-line-frame-identification
17115 " "
17116@end group
17117@group
17118 mode-line-buffer-identification
17119 " "
17120 (:eval (substring
17121 (system-name) 0 (string-match "\\..+" (system-name))))
17122 ":"
17123 default-directory
17124 #(" " 0 1
17125 (help-echo
17126 "mouse-1: select window, mouse-2: delete others ..."))
17127 (line-number-mode " Line %l ")
17128 global-mode-string
17129@end group
17130@group
17131 #(" %[(" 0 6
17132 (help-echo
17133 "mouse-1: select window, mouse-2: delete others ..."))
17134 (:eval (mode-line-mode-name))
17135 mode-line-process
17136 minor-mode-alist
17137 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17138 ")%] "
17139 (-3 . "%P")
17140 ;; "-%-"
17141 )))
17142@end group
17143@end smallexample
17144
17145@noindent
17146Here, I redefine the default mode line. Most of the parts are from
17147the original; but I make a few changes. I set the @emph{default} mode
17148line format so as to permit various modes, such as Info, to override
17149it.
17150
17151Many elements in the list are self-explanatory:
17152@code{mode-line-modified} is a variable that tells whether the buffer
17153has been modified, @code{mode-name} tells the name of the mode, and so
17154on. However, the format looks complicated because of two features we
17155have not discussed.
17156
17157The first string in the mode line is a dash or hyphen, @samp{-}. In
17158the old days, it would have been specified simply as @code{"-"}. But
17159nowadays, Emacs can add properties to a string, such as highlighting
17160or, as in this case, a help feature. If you place your mouse cursor
17161over the hyphen, some help information appears (By default, you must
17162wait one second before the information appears. You can change that
17163timing by changing the value of @code{tooltip-delay}.)
17164
17165@need 1000
17166The new string format has a special syntax:
17167
17168@smallexample
17169#("-" 0 1 (help-echo "mouse-1: select window, ..."))
17170@end smallexample
17171
17172@noindent
17173The @code{#(} begins a list. The first element of the list is the
17174string itself, just one @samp{-}. The second and third
17175elements specify the range over which the fourth element applies. A
17176range starts @emph{after} a character, so a zero means the range
17177starts just before the first character; a 1 means that the range ends
17178just after the first character. The third element is the property for
17179the range. It consists of a property list, a
17180property name, in this case, @samp{help-echo}, followed by a value, in this
17181case, a string. The second, third, and fourth elements of this new
17182string format can be repeated.
17183
17184@xref{Text Props and Strings, , Text Properties in String, elisp, The
17185GNU Emacs Lisp Reference Manual}, and see @ref{Mode Line Format, , Mode
17186Line Format, elisp, The GNU Emacs Lisp Reference Manual}, for more
17187information.
17188
17189@code{mode-line-buffer-identification}
17190displays the current buffer name. It is a list
17191beginning @code{(#("%12b" 0 4 @dots{}}.
17192The @code{#(} begins the list.
17193
17194The @samp{"%12b"} displays the current buffer name, using the
17195@code{buffer-name} function with which we are familiar; the `12'
17196specifies the maximum number of characters that will be displayed.
17197When a name has fewer characters, whitespace is added to fill out to
17198this number. (Buffer names can and often should be longer than 12
17199characters; this length works well in a typical 80 column wide
17200window.)
17201
17202@code{:eval} is a new feature in GNU Emacs version 21. It says to
17203evaluate the following form and use the result as a string to display.
17204In this case, the expression displays the first component of the full
17205system name. The end of the first component is a @samp{.} (`period'),
17206so I use the @code{string-match} function to tell me the length of the
17207first component. The substring from the zeroth character to that
17208length is the name of the machine.
17209
17210@need 1250
17211This is the expression:
17212
17213@smallexample
17214@group
17215(:eval (substring
17216 (system-name) 0 (string-match "\\..+" (system-name))))
17217@end group
17218@end smallexample
17219
17220@samp{%[} and @samp{%]} cause a pair of square brackets
17221to appear for each recursive editing level. @samp{%n} says `Narrow'
17222when narrowing is in effect. @samp{%P} tells you the percentage of
17223the buffer that is above the bottom of the window, or `Top', `Bottom',
17224or `All'. (A lower case @samp{p} tell you the percentage above the
17225@emph{top} of the window.) @samp{%-} inserts enough dashes to fill
17226out the line.
17227
17228Remember, ``You don't have to like Emacs to like it'' --- your own
17229Emacs can have different colors, different commands, and different
17230keys than a default Emacs.
17231
17232On the other hand, if you want to bring up a plain `out of the box'
17233Emacs, with no customization, type:
17234
17235@smallexample
17236emacs -q
17237@end smallexample
17238
17239@noindent
17240This will start an Emacs that does @emph{not} load your
17241@file{~/.emacs} initialization file. A plain, default Emacs. Nothing
17242more.
17243
17244@node Debugging, Conclusion, Emacs Initialization, Top
17245@chapter Debugging
17246@cindex debugging
17247
17248GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
17249first is built into the internals of Emacs and is always with you;
17250the second requires that you instrument a function before you can use it.
17251
17252Both debuggers are described extensively in @ref{Debugging, ,
17253Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17254In this chapter, I will walk through a short example of each.
17255
17256@menu
17257* debug:: How to use the built-in debugger.
17258* debug-on-entry:: Start debugging when you call a function.
17259* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
17260* edebug:: How to use Edebug, a source level debugger.
17261* Debugging Exercises::
17262@end menu
17263
17264@node debug, debug-on-entry, Debugging, Debugging
17265@section @code{debug}
17266@findex debug
17267
17268Suppose you have written a function definition that is intended to
17269return the sum of the numbers 1 through a given number. (This is the
17270@code{triangle} function discussed earlier. @xref{Decrementing
17271Example, , Example with Decrementing Counter}, for a discussion.)
17272@c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17273
17274However, your function definition has a bug. You have mistyped
17275@samp{1=} for @samp{1-}. Here is the broken definition:
17276
17277@findex triangle-bugged
17278@smallexample
17279@group
17280(defun triangle-bugged (number)
17281 "Return sum of numbers 1 through NUMBER inclusive."
17282 (let ((total 0))
17283 (while (> number 0)
17284 (setq total (+ total number))
17285 (setq number (1= number))) ; @r{Error here.}
17286 total))
17287@end group
17288@end smallexample
17289
17290If you are reading this in Info, you can evaluate this definition in
17291the normal fashion. You will see @code{triangle-bugged} appear in the
17292echo area.
17293
17294@need 1250
17295Now evaluate the @code{triangle-bugged} function with an
17296argument of 4:
17297
17298@smallexample
17299(triangle-bugged 4)
17300@end smallexample
17301
17302@noindent
17303In GNU Emacs version 21, you will create and enter a
17304@file{*Backtrace*} buffer that says:
17305
17306@noindent
17307@smallexample
17308@group
17309---------- Buffer: *Backtrace* ----------
17310Debugger entered--Lisp error: (void-function 1=)
17311 (1= number)
17312 (setq number (1= number))
17313 (while (> number 0) (setq total (+ total number))
17314 (setq number (1= number)))
17315 (let ((total 0)) (while (> number 0) (setq total ...)
17316 (setq number ...)) total)
17317 triangle-bugged(4)
17318@end group
17319@group
17320 eval((triangle-bugged 4))
17321 eval-last-sexp-1(nil)
17322 eval-last-sexp(nil)
17323 call-interactively(eval-last-sexp)
17324---------- Buffer: *Backtrace* ----------
17325@end group
17326@end smallexample
17327
17328@noindent
17329(I have reformatted this example slightly; the debugger does not fold
17330long lines. As usual, you can quit the debugger by typing @kbd{q} in
17331the @file{*Backtrace*} buffer.)
17332
17333In practice, for a bug as simple as this, the `Lisp error' line will
17334tell you what you need to know to correct the definition. The
17335function @code{1=} is `void'.
17336
17337@need 800
17338In GNU Emacs 20 and before, you will see:
17339
17340@smallexample
17341Symbol's function definition is void:@: 1=
17342@end smallexample
17343
17344@noindent
17345which has the same meaning as the @file{*Backtrace*} buffer line in
17346version 21.
17347
17348However, suppose you are not quite certain what is going on?
17349You can read the complete backtrace.
17350
17351In this case, you need to run GNU Emacs 21, which automatically starts
17352the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17353you need to start the debugger manually as described below.
17354
17355Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17356what Emacs did that led to the error. Emacs made an interactive call
17357to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17358of the @code{triangle-bugged} expression. Each line above tells you
17359what the Lisp interpreter evaluated next.
17360
17361@need 1250
17362The third line from the top of the buffer is
17363
17364@smallexample
17365(setq number (1= number))
17366@end smallexample
17367
17368@noindent
17369Emacs tried to evaluate this expression; in order to do so, it tried
17370to evaluate the inner expression shown on the second line from the
17371top:
17372
17373@smallexample
17374(1= number)
17375@end smallexample
17376
17377@need 1250
17378@noindent
17379This is where the error occurred; as the top line says:
17380
17381@smallexample
17382Debugger entered--Lisp error: (void-function 1=)
17383@end smallexample
17384
17385@noindent
17386You can correct the mistake, re-evaluate the function definition, and
17387then run your test again.
17388
17389@node debug-on-entry, debug-on-quit, debug, Debugging
17390@section @code{debug-on-entry}
17391@findex debug-on-entry
17392
17393GNU Emacs 21 starts the debugger automatically when your function has
17394an error. GNU Emacs version 20 and before did not; it simply
17395presented you with an error message. You had to start the debugger
17396manually.
17397
17398You can start the debugger manually for all versions of Emacs; the
17399advantage is that the debugger runs even if you do not have a bug in
17400your code. Sometimes your code will be free of bugs!
17401
17402You can enter the debugger when you call the function by calling
17403@code{debug-on-entry}.
17404
17405@need 1250
17406@noindent
17407Type:
17408
17409@smallexample
17410M-x debug-on-entry RET triangle-bugged RET
17411@end smallexample
17412
17413@need 1250
17414@noindent
17415Now, evaluate the following:
17416
17417@smallexample
17418(triangle-bugged 5)
17419@end smallexample
17420
17421@noindent
17422All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17423you that it is beginning to evaluate the @code{triangle-bugged}
17424function:
17425
17426@smallexample
17427@group
17428---------- Buffer: *Backtrace* ----------
17429Debugger entered--entering a function:
17430* triangle-bugged(5)
17431 eval((triangle-bugged 5))
17432@end group
17433@group
17434 eval-last-sexp-1(nil)
17435 eval-last-sexp(nil)
17436 call-interactively(eval-last-sexp)
17437---------- Buffer: *Backtrace* ----------
17438@end group
17439@end smallexample
17440
17441In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
17442the first expression in @code{triangle-bugged}; the buffer will look
17443like this:
17444
17445@smallexample
17446@group
17447---------- Buffer: *Backtrace* ----------
17448Debugger entered--beginning evaluation of function call form:
17449* (let ((total 0)) (while (> number 0) (setq total ...)
17450 (setq number ...)) total)
17451* triangle-bugged(5)
17452 eval((triangle-bugged 5))
17453@end group
17454@group
17455 eval-last-sexp-1(nil)
17456 eval-last-sexp(nil)
17457 call-interactively(eval-last-sexp)
17458---------- Buffer: *Backtrace* ----------
17459@end group
17460@end smallexample
17461
17462@noindent
17463Now, type @kbd{d} again, eight times, slowly. Each time you type
17464@kbd{d}, Emacs will evaluate another expression in the function
17465definition.
17466
17467@need 1750
17468Eventually, the buffer will look like this:
17469
17470@smallexample
17471@group
17472---------- Buffer: *Backtrace* ----------
17473Debugger entered--beginning evaluation of function call form:
17474* (setq number (1= number))
17475* (while (> number 0) (setq total (+ total number))
17476 (setq number (1= number)))
17477@group
17478@end group
17479* (let ((total 0)) (while (> number 0) (setq total ...)
17480 (setq number ...)) total)
17481* triangle-bugged(5)
17482 eval((triangle-bugged 5))
17483@group
17484@end group
17485 eval-last-sexp-1(nil)
17486 eval-last-sexp(nil)
17487 call-interactively(eval-last-sexp)
17488---------- Buffer: *Backtrace* ----------
17489@end group
17490@end smallexample
17491
17492@noindent
17493Finally, after you type @kbd{d} two more times, Emacs will reach the
17494error, and the top two lines of the @file{*Backtrace*} buffer will look
17495like this:
17496
17497@smallexample
17498@group
17499---------- Buffer: *Backtrace* ----------
17500Debugger entered--Lisp error: (void-function 1=)
17501* (1= number)
17502@dots{}
17503---------- Buffer: *Backtrace* ----------
17504@end group
17505@end smallexample
17506
17507By typing @kbd{d}, you were able to step through the function.
17508
17509You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17510quits the trace, but does not cancel @code{debug-on-entry}.
17511
17512@findex cancel-debug-on-entry
17513To cancel the effect of @code{debug-on-entry}, call
17514@code{cancel-debug-on-entry} and the name of the function, like this:
17515
17516@smallexample
17517M-x cancel-debug-on-entry RET triangle-bugged RET
17518@end smallexample
17519
17520@noindent
17521(If you are reading this in Info, cancel @code{debug-on-entry} now.)
17522
17523@node debug-on-quit, edebug, debug-on-entry, Debugging
17524@section @code{debug-on-quit} and @code{(debug)}
17525
17526In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17527there are two other ways to start @code{debug}.
17528
17529@findex debug-on-quit
17530You can start @code{debug} whenever you type @kbd{C-g}
17531(@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17532@code{t}. This is useful for debugging infinite loops.
17533
17534@need 1500
17535@cindex @code{(debug)} in code
17536Or, you can insert a line that says @code{(debug)} into your code
17537where you want the debugger to start, like this:
17538
17539@smallexample
17540@group
17541(defun triangle-bugged (number)
17542 "Return sum of numbers 1 through NUMBER inclusive."
17543 (let ((total 0))
17544 (while (> number 0)
17545 (setq total (+ total number))
17546 (debug) ; @r{Start debugger.}
17547 (setq number (1= number))) ; @r{Error here.}
17548 total))
17549@end group
17550@end smallexample
17551
17552The @code{debug} function is described in detail in @ref{Debugger, ,
17553The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17554
17555@node edebug, Debugging Exercises, debug-on-quit, Debugging
17556@section The @code{edebug} Source Level Debugger
17557@cindex Source level debugger
17558@findex edebug
17559
17560Edebug is a source level debugger. Edebug normally displays the
17561source of the code you are debugging, with an arrow at the left that
17562shows which line you are currently executing.
17563
17564You can walk through the execution of a function, line by line, or run
17565quickly until reaching a @dfn{breakpoint} where execution stops.
17566
17567Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17568Lisp Reference Manual}.
17569
17570Here is a bugged function definition for @code{triangle-recursively}.
17571@xref{Recursive triangle function, , Recursion in place of a counter},
17572for a review of it.
17573
17574@smallexample
17575@group
17576(defun triangle-recursively-bugged (number)
17577 "Return sum of numbers 1 through NUMBER inclusive.
17578Uses recursion."
17579 (if (= number 1)
17580 1
17581 (+ number
17582 (triangle-recursively-bugged
17583 (1= number))))) ; @r{Error here.}
17584@end group
17585@end smallexample
17586
17587@noindent
17588Normally, you would install this definition by positioning your cursor
17589after the function's closing parenthesis and typing @kbd{C-x C-e}
17590(@code{eval-last-sexp}) or else by positioning your cursor within the
17591definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
17592the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17593Interactive mode.)
17594
17595@need 1500
17596However, to prepare this function definition for Edebug, you must
17597first @dfn{instrument} the code using a different command. You can do
17598this by positioning your cursor within the definition and typing
17599
17600@smallexample
17601M-x edebug-defun RET
17602@end smallexample
17603
17604@noindent
17605This will cause Emacs to load Edebug automatically if it is not
17606already loaded, and properly instrument the function.
17607
17608After instrumenting the function, place your cursor after the
17609following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17610
17611@smallexample
17612(triangle-recursively-bugged 3)
17613@end smallexample
17614
17615@noindent
17616You will be jumped back to the source for
17617@code{triangle-recursively-bugged} and the cursor positioned at the
17618beginning of the @code{if} line of the function. Also, you will see
17619an arrowhead at the left hand side of that line. The arrowhead marks
17620the line where the function is executing. (In the following examples,
17621we show the arrowhead with @samp{=>}; in a windowing system, you may
17622see the arrowhead as a solid triangle in the window `fringe'.)
17623
17624@smallexample
17625=>@point{}(if (= number 1)
17626@end smallexample
17627
17628@noindent
17629@iftex
17630In the example, the location of point is displayed with a star,
17631@samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17632@end iftex
17633@ifnottex
17634In the example, the location of point is displayed as @samp{@point{}}
17635(in a printed book, it is displayed with a five pointed star).
17636@end ifnottex
17637
17638If you now press @key{SPC}, point will move to the next expression to
17639be executed; the line will look like this:
17640
17641@smallexample
17642=>(if @point{}(= number 1)
17643@end smallexample
17644
17645@noindent
17646As you continue to press @key{SPC}, point will move from expression to
17647expression. At the same time, whenever an expression returns a value,
17648that value will be displayed in the echo area. For example, after you
17649move point past @code{number}, you will see the following:
17650
17651@smallexample
17652Result: 3 = C-c
17653@end smallexample
17654
17655@noindent
17656This means the value of @code{number} is 3, which is @sc{ascii}
17657`control-c' (the third letter of the alphabet).
17658
17659You can continue moving through the code until you reach the line with
17660the error. Before evaluation, that line looks like this:
17661
17662@smallexample
17663=> @point{}(1= number))))) ; @r{Error here.}
17664@end smallexample
17665
17666@need 1250
17667@noindent
17668When you press @key{SPC} once again, you will produce an error message
17669that says:
17670
17671@smallexample
17672Symbol's function definition is void:@: 1=
17673@end smallexample
17674
17675@noindent
17676This is the bug.
17677
17678Press @kbd{q} to quit Edebug.
17679
17680To remove instrumentation from a function definition, simply
17681re-evaluate it with a command that does not instrument it.
17682For example, you could place your cursor after the definition's
17683closing parenthesis and type @kbd{C-x C-e}.
17684
17685Edebug does a great deal more than walk with you through a function.
17686You can set it so it races through on its own, stopping only at an
17687error or at specified stopping points; you can cause it to display the
17688changing values of various expressions; you can find out how many
17689times a function is called, and more.
17690
17691Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17692Lisp Reference Manual}.
17693
17694@need 1500
17695@node Debugging Exercises, , edebug, Debugging
17696@section Debugging Exercises
17697
17698@itemize @bullet
17699@item
17700Install the @code{count-words-region} function and then cause it to
17701enter the built-in debugger when you call it. Run the command on a
17702region containing two words. You will need to press @kbd{d} a
17703remarkable number of times. On your system, is a `hook' called after
17704the command finishes? (For information on hooks, see @ref{Command
17705Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17706Manual}.)
17707
17708@item
17709Copy @code{count-words-region} into the @file{*scratch*} buffer,
17710instrument the function for Edebug, and walk through its execution.
17711The function does not need to have a bug, although you can introduce
17712one if you wish. If the function lacks a bug, the walk-through
17713completes without problems.
17714
17715@item
17716While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17717(The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17718@kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17719for commands made outside of the Edebug debugging buffer.)
17720
17721@item
17722In the Edebug debugging buffer, use the @kbd{p}
17723(@code{edebug-bounce-point}) command to see where in the region the
17724@code{count-words-region} is working.
17725
17726@item
17727Move point to some spot further down function and then type the
17728@kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17729
17730@item
17731Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17732walk through the function on its own; use an upper case @kbd{T} for
17733@code{edebug-Trace-fast-mode}.
17734
17735@item
17736Set a breakpoint, then run Edebug in Trace mode until it reaches the
17737stopping point.
17738@end itemize
17739
17740@node Conclusion, the-the, Debugging, Top
17741@chapter Conclusion
17742
17743We have now reached the end of this Introduction. You have now
17744learned enough about programming in Emacs Lisp to set values, to write
17745simple @file{.emacs} files for yourself and your friends, and write
17746simple customizations and extensions to Emacs.
17747
17748This is a place to stop. Or, if you wish, you can now go onward, and
17749teach yourself.
17750
17751You have learned some of the basic nuts and bolts of programming. But
17752only some. There are a great many more brackets and hinges that are
17753easy to use that we have not touched.
17754
17755A path you can follow right now lies among the sources to GNU Emacs
17756and in
17757@ifnotinfo
17758@cite{The GNU Emacs Lisp Reference Manual}.
17759@end ifnotinfo
17760@ifinfo
17761@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17762Emacs Lisp Reference Manual}.
17763@end ifinfo
17764
17765The Emacs Lisp sources are an adventure. When you read the sources and
17766come across a function or expression that is unfamiliar, you need to
17767figure out or find out what it does.
17768
17769Go to the Reference Manual. It is a thorough, complete, and fairly
17770easy-to-read description of Emacs Lisp. It is written not only for
17771experts, but for people who know what you know. (The @cite{Reference
17772Manual} comes with the standard GNU Emacs distribution. Like this
17773introduction, it comes as a Texinfo source file, so you can read it
17774on-line and as a typeset, printed book.)
17775
17776Go to the other on-line help that is part of GNU Emacs: the on-line
17777documentation for all functions, and @code{find-tags}, the program
17778that takes you to sources.
17779
17780Here is an example of how I explore the sources. Because of its name,
17781@file{simple.el} is the file I looked at first, a long time ago. As
17782it happens some of the functions in @file{simple.el} are complicated,
17783or at least look complicated at first sight. The @code{open-line}
17784function, for example, looks complicated.
17785
17786You may want to walk through this function slowly, as we did with the
17787@code{forward-sentence} function.
17788@ifnottex
17789(@xref{forward-sentence}.)
17790@end ifnottex
17791@iftex
17792(@xref{forward-sentence, , @code{forward-sentence}}.)
17793@end iftex
17794Or you may want to skip that function and look at another, such as
17795@code{split-line}. You don't need to read all the functions.
17796According to @code{count-words-in-defun}, the @code{split-line}
17797function contains 27 words and symbols.
17798
17799Even though it is short, @code{split-line} contains four expressions
17800we have not studied: @code{skip-chars-forward}, @code{indent-to},
17801@code{current-column} and @samp{?\n}.
17802
17803Consider the @code{skip-chars-forward} function. (It is part of the
17804function definition for @code{back-to-indentation}, which is shown in
17805@ref{Review, , Review}.)
17806
17807In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17808typing @kbd{C-h f} (@code{describe-function}) and the name of the
17809function. This gives you the function documentation.
17810
17811You may be able to guess what is done by a well named function such as
17812@code{indent-to}; or you can look it up, too. Incidentally, the
17813@code{describe-function} function itself is in @file{help.el}; it is
17814one of those long, but decipherable functions. You can look up
17815@code{describe-function} using the @kbd{C-h f} command!
17816
17817In this instance, since the code is Lisp, the @file{*Help*} buffer
17818contains the name of the library containing the function's source.
17819You can put point over the name of the library and press the RET key,
17820which in this situation is bound to @code{help-follow}, and be taken
17821directly to the source, in the same way as @kbd{M-.}
17822(@code{find-tag}).
17823
17824The definition for @code{describe-function} illustrates how to
17825customize the @code{interactive} expression without using the standard
17826character codes; and it shows how to create a temporary buffer.
17827
17828(The @code{indent-to} function is written in C rather than Emacs Lisp;
17829it is a `built-in' function. @code{help-follow} only provides you
17830with the documentation of a built-in function; it does not take you to
17831the source. But @code{find-tag} will take you to the source, if
17832properly set up.)
17833
17834You can look at a function's source using @code{find-tag}, which is
17835bound to @kbd{M-.} Finally, you can find out what the Reference
17836Manual has to say by visiting the manual in Info, and typing @kbd{i}
17837(@code{Info-index}) and the name of the function, or by looking up
17838@code{skip-chars-forward} in the index to a printed copy of the
17839manual.
17840
17841Similarly, you can find out what is meant by @samp{?\n}. You can try
17842using @code{Info-index} with @samp{?\n}. It turns out that this
17843action won't help; but don't give up. If you search the index for
17844@samp{\n} without the @samp{?}, you will be taken directly to the
17845relevant section of the manual. (@xref{Character Type, , Character
17846Type, elisp, The GNU Emacs Lisp Reference Manual}. @samp{?\n} stands
17847for the newline character.)
17848
17849Other interesting source files include @file{paragraphs.el},
17850@file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
17851file includes short, easily understood functions as well as longer
17852ones. The @file{loaddefs.el} file contains the many standard
17853autoloads and many keymaps. I have never looked at it all; only at
17854parts. @file{loadup.el} is the file that loads the standard parts of
17855Emacs; it tells you a great deal about how Emacs is built.
17856(@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17857Reference Manual}, for more about building.)
17858
17859As I said, you have learned some nuts and bolts; however, and very
17860importantly, we have hardly touched major aspects of programming; I
17861have said nothing about how to sort information, except to use the
17862predefined @code{sort} function; I have said nothing about how to store
17863information, except to use variables and lists; I have said nothing
17864about how to write programs that write programs. These are topics for
17865another, and different kind of book, a different kind of learning.
17866
17867What you have done is learn enough for much practical work with GNU
17868Emacs. What you have done is get started. This is the end of a
17869beginning.
17870
17871@c ================ Appendix ================
17872
17873@node the-the, Kill Ring, Conclusion, Top
17874@appendix The @code{the-the} Function
17875@findex the-the
17876@cindex Duplicated words function
17877@cindex Words, duplicated
17878
17879Sometimes when you you write text, you duplicate words---as with ``you
17880you'' near the beginning of this sentence. I find that most
17881frequently, I duplicate ``the'; hence, I call the function for
17882detecting duplicated words, @code{the-the}.
17883
17884@need 1250
17885As a first step, you could use the following regular expression to
17886search for duplicates:
17887
17888@smallexample
17889\\(\\w+[ \t\n]+\\)\\1
17890@end smallexample
17891
17892@noindent
17893This regexp matches one or more word-constituent characters followed
17894by one or more spaces, tabs, or newlines. However, it does not detect
17895duplicated words on different lines, since the ending of the first
17896word, the end of the line, is different from the ending of the second
17897word, a space. (For more information about regular expressions, see
17898@ref{Regexp Search, , Regular Expression Searches}, as well as
17899@ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
17900Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
17901The GNU Emacs Lisp Reference Manual}.)
17902
17903You might try searching just for duplicated word-constituent
17904characters but that does not work since the pattern detects doubles
17905such as the two occurrences of `th' in `with the'.
17906
17907Another possible regexp searches for word-constituent characters
17908followed by non-word-constituent characters, reduplicated. Here,
17909@w{@samp{\\w+}} matches one or more word-constituent characters and
17910@w{@samp{\\W*}} matches zero or more non-word-constituent characters.
17911
17912@smallexample
17913\\(\\(\\w+\\)\\W*\\)\\1
17914@end smallexample
17915
17916@noindent
17917Again, not useful.
17918
17919Here is the pattern that I use. It is not perfect, but good enough.
17920@w{@samp{\\b}} matches the empty string, provided it is at the beginning
17921or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
17922any characters that are @emph{not} an @@-sign, space, newline, or tab.
17923
17924@smallexample
17925\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
17926@end smallexample
17927
17928One can write more complicated expressions, but I found that this
17929expression is good enough, so I use it.
17930
17931Here is the @code{the-the} function, as I include it in my
17932@file{.emacs} file, along with a handy global key binding:
17933
17934@smallexample
17935@group
17936(defun the-the ()
17937 "Search forward for for a duplicated word."
17938 (interactive)
17939 (message "Searching for for duplicated words ...")
17940 (push-mark)
17941@end group
17942@group
17943 ;; This regexp is not perfect
17944 ;; but is fairly good over all:
17945 (if (re-search-forward
17946 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
17947 (message "Found duplicated word.")
17948 (message "End of buffer")))
17949@end group
17950
17951@group
17952;; Bind `the-the' to C-c \
17953(global-set-key "\C-c\\" 'the-the)
17954@end group
17955@end smallexample
17956
17957@sp 1
17958Here is test text:
17959
17960@smallexample
17961@group
17962one two two three four five
17963five six seven
17964@end group
17965@end smallexample
17966
17967You can substitute the other regular expressions shown above in the
17968function definition and try each of them on this list.
17969
17970@node Kill Ring, Full Graph, the-the, Top
17971@appendix Handling the Kill Ring
17972@cindex Kill ring handling
17973@cindex Handling the kill ring
17974@cindex Ring, making a list like a
17975
17976The kill ring is a list that is transformed into a ring by the
17977workings of the @code{rotate-yank-pointer} function. The @code{yank}
17978and @code{yank-pop} commands use the @code{rotate-yank-pointer}
17979function. This appendix describes the @code{rotate-yank-pointer}
17980function as well as both the @code{yank} and the @code{yank-pop}
17981commands.
17982
17983@menu
17984* rotate-yank-pointer:: Move a pointer along a list and around.
17985* yank:: Paste a copy of a clipped element.
17986* yank-pop:: Insert first element pointed to.
17987@end menu
17988
17989@node rotate-yank-pointer, yank, Kill Ring, Kill Ring
17990@comment node-name, next, previous, up
17991@appendixsec The @code{rotate-yank-pointer} Function
17992@findex rotate-yank-pointer
17993
17994The @code{rotate-yank-pointer} function changes the element in the kill
17995ring to which @code{kill-ring-yank-pointer} points. For example, it can
17996change @code{kill-ring-yank-pointer} from pointing to the second
17997element to point to the third element.
17998
17999@need 800
18000Here is the code for @code{rotate-yank-pointer}:
18001
18002@smallexample
18003@group
18004(defun rotate-yank-pointer (arg)
18005 "Rotate the yanking point in the kill ring."
18006 (interactive "p")
18007 (let ((length (length kill-ring)))
18008@end group
18009@group
18010 (if (zerop length)
18011 ;; @r{then-part}
18012 (error "Kill ring is empty")
18013@end group
18014@group
18015 ;; @r{else-part}
18016 (setq kill-ring-yank-pointer
18017 (nthcdr (% (+ arg
18018 (- length
18019 (length
18020 kill-ring-yank-pointer)))
18021 length)
18022 kill-ring)))))
18023@end group
18024@end smallexample
18025
18026@menu
18027* Understanding rotate-yk-ptr::
18028* rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
18029@end menu
18030
18031@node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18032@ifnottex
18033@unnumberedsubsec @code{rotate-yank-pointer} in Outline
18034@end ifnottex
18035
18036The @code{rotate-yank-pointer} function looks complex, but as usual,
18037it can be understood by taking it apart piece by piece. First look at
18038it in skeletal form:
18039
18040@smallexample
18041@group
18042(defun rotate-yank-pointer (arg)
18043 "Rotate the yanking point in the kill ring."
18044 (interactive "p")
18045 (let @var{varlist}
18046 @var{body}@dots{})
18047@end group
18048@end smallexample
18049
18050This function takes one argument, called @code{arg}. It has a brief
18051documentation string; and it is interactive with a small @samp{p}, which
18052means that the argument must be a processed prefix passed to the
18053function as a number.
18054
18055The body of the function definition is a @code{let} expression, which
18056itself has a body as well as a @var{varlist}.
18057
18058The @code{let} expression declares a variable that will be only usable
18059within the bounds of this function. This variable is called
18060@code{length} and is bound to a value that is equal to the number of
18061items in the kill ring. This is done by using the function called
18062@code{length}. (Note that this function has the same name as the
18063variable called @code{length}; but one use of the word is to name the
18064function and the other is to name the variable. The two are quite
18065distinct. Similarly, an English speaker will distinguish between the
18066meanings of the word @samp{ship} when he says: "I must ship this package
18067immediately." and "I must get aboard the ship immediately.")
18068
18069The function @code{length} tells the number of items there are in a list,
18070so @code{(length kill-ring)} returns the number of items there are in the
18071kill ring.
18072
18073@node rotate-yk-ptr body, , Understanding rotate-yk-ptr, rotate-yank-pointer
18074@comment node-name, next, previous, up
18075@appendixsubsec The Body of @code{rotate-yank-pointer}
18076
18077The body of @code{rotate-yank-pointer} is a @code{let} expression and
18078the body of the @code{let} expression is an @code{if} expression.
18079
18080The purpose of the @code{if} expression is to find out whether there is
18081anything in the kill ring. If the kill ring is empty, the @code{error}
18082function stops evaluation of the function and prints a message in the
18083echo area. On the other hand, if the kill ring has something in it, the
18084work of the function is done.
18085
18086Here is the if-part and then-part of the @code{if} expression:
18087
18088@findex zerop
18089@findex error
18090@smallexample
18091@group
18092(if (zerop length) ; @r{if-part}
18093 (error "Kill ring is empty") ; @r{then-part}
18094 @dots{}
18095@end group
18096@end smallexample
18097
18098@noindent
18099If there is not anything in the kill ring, its length must be zero and
18100an error message sent to the user: @samp{Kill ring is empty}. The
18101@code{if} expression uses the function @code{zerop} which returns true
18102if the value it is testing is zero. When @code{zerop} tests true, the
18103then-part of the @code{if} is evaluated. The then-part is a list
18104starting with the function @code{error}, which is a function that is
18105similar to the @code{message} function (@pxref{message}), in that it
18106prints a one-line message in the echo area. However, in addition to
18107printing a message, @code{error} also stops evaluation of the function
18108within which it is embedded. This means that the rest of the function
18109will not be evaluated if the length of the kill ring is zero.
18110
18111@menu
18112* Digression concerning error:: How to mislead humans, but not computers.
18113* rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
18114* Remainder Function:: The remainder, @code{%}, function.
18115* rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
18116* kill-rng-yk-ptr last elt:: Pointing to the last element.
18117@end menu
18118
18119@node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18120@ifnottex
18121@unnumberedsubsubsec Digression about the word `error'
18122@end ifnottex
18123
18124(In my opinion, it is slightly misleading, at least to humans, to use
18125the term `error' as the name of the @code{error} function. A better
18126term would be `cancel'. Strictly speaking, of course, you cannot
18127point to, much less rotate a pointer to a list that has no length, so
18128from the point of view of the computer, the word `error' is correct.
18129But a human expects to attempt this sort of thing, if only to find out
18130whether the kill ring is full or empty. This is an act of
18131exploration.
18132
18133(From the human point of view, the act of exploration and discovery is
18134not necessarily an error, and therefore should not be labelled as one,
18135even in the bowels of a computer. As it is, the code in Emacs implies
18136that a human who is acting virtuously, by exploring his or her
18137environment, is making an error. This is bad. Even though the computer
18138takes the same steps as it does when there is an `error', a term such as
18139`cancel' would have a clearer connotation.)
18140
18141@node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18142@unnumberedsubsubsec The else-part of the @code{if} expression
18143
18144The else-part of the @code{if} expression is dedicated to setting the
18145value of @code{kill-ring-yank-pointer} when the kill ring has something
18146in it. The code looks like this:
18147
18148@smallexample
18149@group
18150(setq kill-ring-yank-pointer
18151 (nthcdr (% (+ arg
18152 (- length
18153 (length kill-ring-yank-pointer)))
18154 length)
18155 kill-ring)))))
18156@end group
18157@end smallexample
18158
18159This needs some examination. Clearly, @code{kill-ring-yank-pointer}
18160is being set to be equal to some @sc{cdr} of the kill ring, using the
18161@code{nthcdr} function that is described in an earlier section.
18162(@xref{copy-region-as-kill}.) But exactly how does it do this?
18163
18164Before looking at the details of the code let's first consider the
18165purpose of the @code{rotate-yank-pointer} function.
18166
18167The @code{rotate-yank-pointer} function changes what
18168@code{kill-ring-yank-pointer} points to. If
18169@code{kill-ring-yank-pointer} starts by pointing to the first element
18170of a list, a call to @code{rotate-yank-pointer} causes it to point to
18171the second element; and if @code{kill-ring-yank-pointer} points to the
18172second element, a call to @code{rotate-yank-pointer} causes it to
18173point to the third element. (And if @code{rotate-yank-pointer} is
18174given an argument greater than 1, it jumps the pointer that many
18175elements.)
18176
18177The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18178the @code{kill-ring-yank-pointer} points to. If
18179@code{kill-ring-yank-pointer} points to the first element of the kill
18180ring, then, in the simplest case, the @code{rotate-yank-pointer}
18181function must cause it to point to the second element. Put another
18182way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18183to the @sc{cdr} of the kill ring.
18184
18185@need 1250
18186That is, under these circumstances,
18187
18188@smallexample
18189@group
18190(setq kill-ring-yank-pointer
18191 ("some text" "a different piece of text" "yet more text"))
18192
18193(setq kill-ring
18194 ("some text" "a different piece of text" "yet more text"))
18195@end group
18196@end smallexample
18197
18198@need 800
18199@noindent
18200the code should do this:
18201
18202@smallexample
18203(setq kill-ring-yank-pointer (cdr kill-ring))
18204@end smallexample
18205
18206@need 1000
18207@noindent
18208As a result, the @code{kill-ring-yank-pointer} will look like this:
18209
18210@smallexample
18211@group
18212kill-ring-yank-pointer
18213 @result{} ("a different piece of text" "yet more text"))
18214@end group
18215@end smallexample
18216
18217The actual @code{setq} expression uses the @code{nthcdr} function to do
18218the job.
18219
18220As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18221works by repeatedly taking the @sc{cdr} of a list---it takes the
18222@sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18223
18224@need 800
18225The two following expressions produce the same result:
18226
18227@smallexample
18228@group
18229(setq kill-ring-yank-pointer (cdr kill-ring))
18230
18231(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18232@end group
18233@end smallexample
18234
18235In the @code{rotate-yank-pointer} function, however, the first
18236argument to @code{nthcdr} is a rather complex looking expression with
18237lots of arithmetic inside of it:
18238
18239@smallexample
18240@group
18241(% (+ arg
18242 (- length
18243 (length kill-ring-yank-pointer)))
18244 length)
18245@end group
18246@end smallexample
18247
18248As usual, we need to look at the most deeply embedded expression first
18249and then work our way towards the light.
18250
18251The most deeply embedded expression is @code{(length
18252kill-ring-yank-pointer)}. This finds the length of the current value of
18253the @code{kill-ring-yank-pointer}. (Remember that the
18254@code{kill-ring-yank-pointer} is the name of a variable whose value is a
18255list.)
18256
18257@need 800
18258The measurement of the length is inside the expression:
18259
18260@smallexample
18261(- length (length kill-ring-yank-pointer))
18262@end smallexample
18263
18264@noindent
18265In this expression, the first @code{length} is the variable that was
18266assigned the length of the kill ring in the @code{let} statement at the
18267beginning of the function. (One might think this function would be
18268clearer if the variable @code{length} were named
18269@code{length-of-kill-ring} instead; but if you look at the text of the
18270whole function, you will see that it is so short that naming this
18271variable @code{length} is not a bother, unless you are pulling the
18272function apart into very tiny pieces as we are doing here.)
18273
18274So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18275difference between the length of the kill ring and the length of the list
18276whose name is @code{kill-ring-yank-pointer}.
18277
18278To see how all this fits into the @code{rotate-yank-pointer}
18279function, let's begin by analyzing the case where
18280@code{kill-ring-yank-pointer} points to the first element of the kill
18281ring, just as @code{kill-ring} does, and see what happens when
18282@code{rotate-yank-pointer} is called with an argument of 1.
18283
18284The variable @code{length} and the value of the expression
18285@code{(length kill-ring-yank-pointer)} will be the same since the
18286variable @code{length} is the length of the kill ring and the
18287@code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18288Consequently, the value of
18289
18290@smallexample
18291(- length (length kill-ring-yank-pointer))
18292@end smallexample
18293
18294@noindent
18295will be zero. Since the value of @code{arg} will be 1, this will mean
18296that the value of the whole expression
18297
18298@smallexample
18299(+ arg (- length (length kill-ring-yank-pointer)))
18300@end smallexample
18301
18302@noindent
18303will be 1.
18304
18305Consequently, the argument to @code{nthcdr} will be found as the result of
18306the expression
18307
18308@smallexample
18309(% 1 length)
18310@end smallexample
18311
18312@node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18313@unnumberedsubsubsec The @code{%} remainder function
18314
18315To understand @code{(% 1 length)}, we need to understand @code{%}.
18316According to its documentation (which I just found by typing @kbd{C-h
18317f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18318its first argument divided by its second argument. For example, the
18319remainder of 5 divided by 2 is 1. (2 goes into 5 twice with a
18320remainder of 1.)
18321
18322What surprises people who don't often do arithmetic is that a smaller
18323number can be divided by a larger number and have a remainder. In the
18324example we just used, 5 was divided by 2. We can reverse that and ask,
18325what is the result of dividing 2 by 5? If you can use fractions, the
18326answer is obviously 2/5 or .4; but if, as here, you can only use whole
18327numbers, the result has to be something different. Clearly, 5 can go into
183282 zero times, but what of the remainder? To see what the answer is,
18329consider a case that has to be familiar from childhood:
18330
18331@itemize @bullet
18332@item
183335 divided by 5 is 1 with a remainder of 0;
18334
18335@item
183366 divided by 5 is 1 with a remainder of 1;
18337
18338@item
183397 divided by 5 is 1 with a remainder of 2.
18340
18341@item
18342Similarly, 10 divided by 5 is 2 with a remainder of 0;
18343
18344@item
1834511 divided by 5 is 2 with a remainder of 1;
18346
18347@item
1834812 divided by 5 is 1 with a remainder of 2.
18349@end itemize
18350
18351@need 1250
18352@noindent
18353By considering the cases as parallel, we can see that
18354
18355@itemize @bullet
18356@item
18357zero divided by 5 must be zero with a remainder of zero;
18358
18359@item
183601 divided by 5 must be zero with a remainder of 1;
18361
18362@item
183632 divided by 5 must be zero with a remainder of 2;
18364@end itemize
18365
18366@noindent
18367and so on.
18368
18369@need 1250
18370So, in this code, if the value of @code{length} is 5, then the result of
18371evaluating
18372
18373@smallexample
18374(% 1 5)
18375@end smallexample
18376
18377@noindent
18378is 1. (I just checked this by placing the cursor after the expression
18379and typing @kbd{C-x C-e}. Indeed, 1 is printed in the echo area.)
18380
18381@node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18382@unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18383
18384When the @code{kill-ring-yank-pointer} points to the
18385beginning of the kill ring, and the argument passed to
18386@code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18387
18388@smallexample
18389@group
18390(- length (length kill-ring-yank-pointer))
18391 @result{} 0
18392@end group
18393@end smallexample
18394
18395@need 1250
18396@noindent
18397therefore,
18398
18399@smallexample
18400@group
18401(+ arg (- length (length kill-ring-yank-pointer)))
18402 @result{} 1
18403@end group
18404@end smallexample
18405
18406@need 1250
18407@noindent
18408and consequently:
18409
18410@smallexample
18411@group
18412(% (+ arg (- length (length kill-ring-yank-pointer)))
18413 length)
18414 @result{} 1
18415@end group
18416@end smallexample
18417
18418@noindent
18419regardless of the value of @code{length}.
18420
18421@need 1250
18422@noindent
18423As a result of this, the @code{setq kill-ring-yank-pointer} expression
18424simplifies to:
18425
18426@smallexample
18427(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18428@end smallexample
18429
18430@noindent
18431What it does is now easy to understand. Instead of pointing as it did
18432to the first element of the kill ring, the
18433@code{kill-ring-yank-pointer} is set to point to the second element.
18434
18435Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18436the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18437and so on for different values of the argument.
18438
18439Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18440the second element of the kill ring, its length is shorter than the
18441length of the kill ring by 1, so the computation of the remainder is
18442based on the expression @code{(% (+ arg 1) length)}. This means that
18443the @code{kill-ring-yank-pointer} is moved from the second element of
18444the kill ring to the third element if the argument passed to
18445@code{rotate-yank-pointer} is 1.
18446
18447@node kill-rng-yk-ptr last elt, , rotate-yk-ptr remainder, rotate-yk-ptr body
18448@unnumberedsubsubsec Pointing to the last element
18449
18450The final question is, what happens if the @code{kill-ring-yank-pointer}
18451is set to the @emph{last} element of the kill ring? Will a call to
18452@code{rotate-yank-pointer} mean that nothing more can be taken from the
18453kill ring? The answer is no. What happens is different and useful.
18454The @code{kill-ring-yank-pointer} is set to point to the beginning of
18455the kill ring instead.
18456
18457Let's see how this works by looking at the code, assuming the length of the
18458kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18459When the @code{kill-ring-yank-pointer} points to the last element of
18460the kill ring, its length is 1. The code looks like this:
18461
18462@smallexample
18463(% (+ arg (- length (length kill-ring-yank-pointer))) length)
18464@end smallexample
18465
18466@need 1250
18467When the variables are replaced by their numeric values, the expression
18468looks like this:
18469
18470@smallexample
18471(% (+ 1 (- 5 1)) 5)
18472@end smallexample
18473
18474@noindent
18475This expression can be evaluated by looking at the most embedded inner
18476expression first and working outwards: The value of @code{(- 5 1)} is 4;
18477the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18478zero. So what @code{rotate-yank-pointer} will do is
18479
18480@smallexample
18481(setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18482@end smallexample
18483
18484@noindent
18485which will set the @code{kill-ring-yank-pointer} to point to the beginning
18486of the kill ring.
18487
18488So what happens with successive calls to @code{rotate-yank-pointer} is that
18489it moves the @code{kill-ring-yank-pointer} from element to element in the
18490kill ring until it reaches the end; then it jumps back to the beginning.
18491And this is why the kill ring is called a ring, since by jumping back to
18492the beginning, it is as if the list has no end! (And what is a ring, but
18493an entity with no end?)
18494
18495@node yank, yank-pop, rotate-yank-pointer, Kill Ring
18496@comment node-name, next, previous, up
18497@appendixsec @code{yank}
18498@findex yank
18499
18500After learning about @code{rotate-yank-pointer}, the code for the
18501@code{yank} function is almost easy. It has only one tricky part, which is
18502the computation of the argument to be passed to @code{rotate-yank-pointer}.
18503
18504@need 1250
18505The code looks like this:
18506
18507@smallexample
18508@group
18509(defun yank (&optional arg)
18510 "Reinsert the last stretch of killed text.
18511More precisely, reinsert the stretch of killed text most
18512recently killed OR yanked.
18513With just C-U as argument, same but put point in front
18514(and mark at end). With argument n, reinsert the nth
18515most recently killed stretch of killed text.
18516See also the command \\[yank-pop]."
18517@end group
18518@group
18519
18520 (interactive "*P")
18521 (rotate-yank-pointer (if (listp arg) 0
18522 (if (eq arg '-) -1
18523 (1- arg))))
18524 (push-mark (point))
18525 (insert (car kill-ring-yank-pointer))
18526 (if (consp arg)
18527 (exchange-point-and-mark)))
18528@end group
18529@end smallexample
18530
18531Glancing over this code, we can understand the last few lines readily
18532enough. The mark is pushed, that is, remembered; then the first element
18533(the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18534inserted; and then, if the argument passed the function is a
18535@code{cons}, point and mark are exchanged so the point is put in the
18536front of the inserted text rather than at the end. This option is
18537explained in the documentation. The function itself is interactive with
18538@code{"*P"}. This means it will not work on a read-only buffer, and that
18539the unprocessed prefix argument is passed to the function.
18540
18541@menu
18542* rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
18543* rotate-yk-ptr negative arg:: Pass a negative argument.
18544@end menu
18545
18546@node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18547@unnumberedsubsubsec Passing the argument
18548
18549The hard part of @code{yank} is understanding the computation that
18550determines the value of the argument passed to
18551@code{rotate-yank-pointer}. Fortunately, it is not so difficult as it
18552looks at first sight.
18553
18554What happens is that the result of evaluating one or both of the
18555@code{if} expressions will be a number and that number will be the
18556argument passed to @code{rotate-yank-pointer}.
18557
18558@need 1250
18559Laid out with comments, the code looks like this:
18560
18561@smallexample
18562@group
18563(if (listp arg) ; @r{if-part}
18564 0 ; @r{then-part}
18565 (if (eq arg '-) ; @r{else-part, inner if}
18566 -1 ; @r{inner if's then-part}
18567 (1- arg)))) ; @r{inner if's else-part}
18568@end group
18569@end smallexample
18570
18571@noindent
18572This code consists of two @code{if} expression, one the else-part of
18573the other.
18574
18575The first or outer @code{if} expression tests whether the argument
18576passed to @code{yank} is a list. Oddly enough, this will be true if
18577@code{yank} is called without an argument---because then it will be
18578passed the value of @code{nil} for the optional argument and an
18579evaluation of @code{(listp nil)} returns true! So, if no argument is
18580passed to @code{yank}, the argument passed to
18581@code{rotate-yank-pointer} inside of @code{yank} is zero. This means
18582the pointer is not moved and the first element to which
18583@code{kill-ring-yank-pointer} points is inserted, as we expect.
18584Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18585read as a list, so again, a zero will be passed to
18586@code{rotate-yank-pointer}. (@kbd{C-u} produces an unprocessed prefix
18587argument of @code{(4)}, which is a list of one element.) At the same
18588time, later in the function, this argument will be read as a
18589@code{cons} so point will be put in the front and mark at the end of
18590the insertion. (The @code{P} argument to @code{interactive} is
18591designed to provide these values for the case when an optional
18592argument is not provided or when it is @kbd{C-u}.)
18593
18594The then-part of the outer @code{if} expression handles the case when
18595there is no argument or when it is @kbd{C-u}. The else-part handles the
18596other situations. The else-part is itself another @code{if} expression.
18597
18598The inner @code{if} expression tests whether the argument is a minus
18599sign. (This is done by pressing the @key{META} and @kbd{-} keys at the
18600same time, or the @key{ESC} key and then the @kbd{-} key). In this
18601case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18602argument. This moves the @code{kill-ring-yank-pointer} backwards, which
18603is what is desired.
18604
18605If the true-or-false-test of the inner @code{if} expression is false
18606(that is, if the argument is not a minus sign), the else-part of the
18607expression is evaluated. This is the expression @code{(1- arg)}.
18608Because of the two @code{if} expressions, it will only occur when the
18609argument is a positive number or when it is a negative number (not
18610just a minus sign on its own). What @code{(1- arg)} does is decrement
18611the number and return it. (The @code{1-} function subtracts one from
18612its argument.) This means that if the argument to
18613@code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18614the first element to which @code{kill-ring-yank-pointer} points is
18615yanked back, as you would expect.
18616
18617@node rotate-yk-ptr negative arg, , rotate-yk-ptr arg, yank
18618@unnumberedsubsubsec Passing a negative argument
18619
18620Finally, the question arises, what happens if either the remainder
18621function, @code{%}, or the @code{nthcdr} function is passed a negative
18622argument, as they quite well may?
18623
18624The answers can be found by a quick test. When @code{(% -1 5)} is
18625evaluated, a negative number is returned; and if @code{nthcdr} is
18626called with a negative number, it returns the same value as if it were
18627called with a first argument of zero. This can be seen be evaluating
18628the following code.
18629
18630Here the @samp{@result{}} points to the result of evaluating the code
18631preceding it. This was done by positioning the cursor after the code
18632and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18633You can do this if you are reading this in Info inside of GNU Emacs.
18634
18635@smallexample
18636@group
18637(% -1 5)
18638 @result{} -1
18639@end group
18640
18641@group
18642(setq animals '(cats dogs elephants))
18643 @result{} (cats dogs elephants)
18644@end group
18645
18646@group
18647(nthcdr 1 animals)
18648 @result{} (dogs elephants)
18649@end group
18650
18651@group
18652(nthcdr 0 animals)
18653 @result{} (cats dogs elephants)
18654@end group
18655
18656@group
18657(nthcdr -1 animals)
18658 @result{} (cats dogs elephants)
18659@end group
18660@end smallexample
18661
18662So, if a minus sign or a negative number is passed to @code{yank}, the
18663@code{kill-ring-yank-point} is rotated backwards until it reaches the
18664beginning of the list. Then it stays there. Unlike the other case,
18665when it jumps from the end of the list to the beginning of the list,
18666making a ring, it stops. This makes sense. You often want to get back
18667to the most recently clipped out piece of text, but you don't usually
18668want to insert text from as many as thirty kill commands ago. So you
18669need to work through the ring to get to the end, but won't cycle around
18670it inadvertently if you are trying to come back to the beginning.
18671
18672Incidentally, any number passed to @code{yank} with a minus sign
18673preceding it will be treated as @minus{}1. This is evidently a
18674simplification for writing the program. You don't need to jump back
18675towards the beginning of the kill ring more than one place at a time
18676and doing this is easier than writing a function to determine the
18677magnitude of the number that follows the minus sign.
18678
18679@node yank-pop, , yank, Kill Ring
18680@comment node-name, next, previous, up
18681@appendixsec @code{yank-pop}
18682@findex yank-pop
18683
18684After understanding @code{yank}, the @code{yank-pop} function is easy.
18685Leaving out the documentation to save space, it looks like this:
18686
18687@smallexample
18688@group
18689(defun yank-pop (arg)
18690 (interactive "*p")
18691 (if (not (eq last-command 'yank))
18692 (error "Previous command was not a yank"))
18693@end group
18694@group
18695 (setq this-command 'yank)
18696 (let ((before (< (point) (mark))))
18697 (delete-region (point) (mark))
18698 (rotate-yank-pointer arg)
18699@end group
18700@group
18701 (set-mark (point))
18702 (insert (car kill-ring-yank-pointer))
18703 (if before (exchange-point-and-mark))))
18704@end group
18705@end smallexample
18706
18707The function is interactive with a small @samp{p} so the prefix
18708argument is processed and passed to the function. The command can
18709only be used after a previous yank; otherwise an error message is
18710sent. This check uses the variable @code{last-command} which is
18711discussed elsewhere. (@xref{copy-region-as-kill}.)
18712
18713The @code{let} clause sets the variable @code{before} to true or false
18714depending whether point is before or after mark and then the region
18715between point and mark is deleted. This is the region that was just
18716inserted by the previous yank and it is this text that will be
18717replaced. Next the @code{kill-ring-yank-pointer} is rotated so that
18718the previously inserted text is not reinserted yet again. Mark is set
18719at the beginning of the place the new text will be inserted and then
18720the first element to which @code{kill-ring-yank-pointer} points is
18721inserted. This leaves point after the new text. If in the previous
18722yank, point was left before the inserted text, point and mark are now
18723exchanged so point is again left in front of the newly inserted text.
18724That is all there is to it!
18725
18726@node Full Graph, GNU Free Documentation License, Kill Ring, Top
18727@appendix A Graph with Labelled Axes
18728
18729Printed axes help you understand a graph. They convey scale. In an
18730earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
18731wrote the code to print the body of a graph. Here we write the code
18732for printing and labelling vertical and horizontal axes, along with the
18733body itself.
18734
18735@menu
18736* Labelled Example::
18737* print-graph Varlist:: @code{let} expression in @code{print-graph}.
18738* print-Y-axis:: Print a label for the vertical axis.
18739* print-X-axis:: Print a horizontal label.
18740* Print Whole Graph:: The function to print a complete graph.
18741@end menu
18742
18743@node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18744@ifnottex
18745@unnumberedsec Labelled Example Graph
18746@end ifnottex
18747
18748Since insertions fill a buffer to the right and below point, the new
18749graph printing function should first print the Y or vertical axis,
18750then the body of the graph, and finally the X or horizontal axis.
18751This sequence lays out for us the contents of the function:
18752
18753@enumerate
18754@item
18755Set up code.
18756
18757@item
18758Print Y axis.
18759
18760@item
18761Print body of graph.
18762
18763@item
18764Print X axis.
18765@end enumerate
18766
18767@need 800
18768Here is an example of how a finished graph should look:
18769
18770@smallexample
18771@group
18772 10 -
18773 *
18774 * *
18775 * **
18776 * ***
18777 5 - * *******
18778 * *** *******
18779 *************
18780 ***************
18781 1 - ****************
18782 | | | |
18783 1 5 10 15
18784@end group
18785@end smallexample
18786
18787@noindent
18788In this graph, both the vertical and the horizontal axes are labelled
18789with numbers. However, in some graphs, the horizontal axis is time
18790and would be better labelled with months, like this:
18791
18792@smallexample
18793@group
18794 5 - *
18795 * ** *
18796 *******
18797 ********** **
18798 1 - **************
18799 | ^ |
18800 Jan June Jan
18801@end group
18802@end smallexample
18803
18804Indeed, with a little thought, we can easily come up with a variety of
18805vertical and horizontal labelling schemes. Our task could become
18806complicated. But complications breed confusion. Rather than permit
18807this, it is better choose a simple labelling scheme for our first
18808effort, and to modify or replace it later.
18809
18810@need 1200
18811These considerations suggest the following outline for the
18812@code{print-graph} function:
18813
18814@smallexample
18815@group
18816(defun print-graph (numbers-list)
18817 "@var{documentation}@dots{}"
18818 (let ((height @dots{}
18819 @dots{}))
18820@end group
18821@group
18822 (print-Y-axis height @dots{} )
18823 (graph-body-print numbers-list)
18824 (print-X-axis @dots{} )))
18825@end group
18826@end smallexample
18827
18828We can work on each part of the @code{print-graph} function definition
18829in turn.
18830
18831@node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18832@comment node-name, next, previous, up
18833@appendixsec The @code{print-graph} Varlist
18834@cindex @code{print-graph} varlist
18835
18836In writing the @code{print-graph} function, the first task is to write
18837the varlist in the @code{let} expression. (We will leave aside for the
18838moment any thoughts about making the function interactive or about the
18839contents of its documentation string.)
18840
18841The varlist should set several values. Clearly, the top of the label
18842for the vertical axis must be at least the height of the graph, which
18843means that we must obtain this information here. Note that the
18844@code{print-graph-body} function also requires this information. There
18845is no reason to calculate the height of the graph in two different
18846places, so we should change @code{print-graph-body} from the way we
18847defined it earlier to take advantage of the calculation.
18848
18849Similarly, both the function for printing the X axis labels and the
18850@code{print-graph-body} function need to learn the value of the width of
18851each symbol. We can perform the calculation here and change the
18852definition for @code{print-graph-body} from the way we defined it in the
18853previous chapter.
18854
18855The length of the label for the horizontal axis must be at least as long
18856as the graph. However, this information is used only in the function
18857that prints the horizontal axis, so it does not need to be calculated here.
18858
18859These thoughts lead us directly to the following form for the varlist
18860in the @code{let} for @code{print-graph}:
18861
18862@smallexample
18863@group
18864(let ((height (apply 'max numbers-list)) ; @r{First version.}
18865 (symbol-width (length graph-blank)))
18866@end group
18867@end smallexample
18868
18869@noindent
18870As we shall see, this expression is not quite right.
18871
18872@node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
18873@comment node-name, next, previous, up
18874@appendixsec The @code{print-Y-axis} Function
18875@cindex Axis, print vertical
18876@cindex Y axis printing
18877@cindex Vertical axis printing
18878@cindex Print vertical axis
18879
18880The job of the @code{print-Y-axis} function is to print a label for
18881the vertical axis that looks like this:
18882
18883@smallexample
18884@group
18885 10 -
18886
18887
18888
18889
18890 5 -
18891
18892
18893
18894 1 -
18895@end group
18896@end smallexample
18897
18898@noindent
18899The function should be passed the height of the graph, and then should
18900construct and insert the appropriate numbers and marks.
18901
18902It is easy enough to see in the figure what the Y axis label should
18903look like; but to say in words, and then to write a function
18904definition to do the job is another matter. It is not quite true to
18905say that we want a number and a tic every five lines: there are only
18906three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
18907but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
18908and 9). It is better to say that we want a number and a tic mark on
18909the base line (number 1) and then that we want a number and a tic on
18910the fifth line from the bottom and on every line that is a multiple of
18911five.
18912
18913@menu
18914* Height of label:: What height for the Y axis?
18915* Compute a Remainder:: How to compute the remainder of a division.
18916* Y Axis Element:: Construct a line for the Y axis.
18917* Y-axis-column:: Generate a list of Y axis labels.
18918* print-Y-axis Penultimate:: A not quite final version.
18919@end menu
18920
18921@node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
18922@ifnottex
18923@unnumberedsubsec What height should the label be?
18924@end ifnottex
18925
18926The next issue is what height the label should be? Suppose the maximum
18927height of tallest column of the graph is seven. Should the highest
18928label on the Y axis be @samp{5 -}, and should the graph stick up above
18929the label? Or should the highest label be @samp{7 -}, and mark the peak
18930of the graph? Or should the highest label be @code{10 -}, which is a
18931multiple of five, and be higher than the topmost value of the graph?
18932
18933The latter form is preferred. Most graphs are drawn within rectangles
18934whose sides are an integral number of steps long---5, 10, 15, and so
18935on for a step distance of five. But as soon as we decide to use a
18936step height for the vertical axis, we discover that the simple
18937expression in the varlist for computing the height is wrong. The
18938expression is @code{(apply 'max numbers-list)}. This returns the
18939precise height, not the maximum height plus whatever is necessary to
18940round up to the nearest multiple of five. A more complex expression
18941is required.
18942
18943As usual in cases like this, a complex problem becomes simpler if it is
18944divided into several smaller problems.
18945
18946First, consider the case when the highest value of the graph is an
18947integral multiple of five---when it is 5, 10, 15 ,or some higher
18948multiple of five. We can use this value as the Y axis height.
18949
18950A fairly simply way to determine whether a number is a multiple of
18951five is to divide it by five and see if the division results in a
18952remainder. If there is no remainder, the number is a multiple of
18953five. Thus, seven divided by five has a remainder of two, and seven
18954is not an integral multiple of five. Put in slightly different
18955language, more reminiscent of the classroom, five goes into seven
18956once, with a remainder of two. However, five goes into ten twice,
18957with no remainder: ten is an integral multiple of five.
18958
18959@node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
18960@appendixsubsec Side Trip: Compute a Remainder
18961
18962@findex % @r{(remainder function)}
18963@cindex Remainder function, @code{%}
18964In Lisp, the function for computing a remainder is @code{%}. The
18965function returns the remainder of its first argument divided by its
18966second argument. As it happens, @code{%} is a function in Emacs Lisp
18967that you cannot discover using @code{apropos}: you find nothing if you
18968type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
18969learn of the existence of @code{%} is to read about it in a book such
18970as this or in the Emacs Lisp sources. The @code{%} function is used
18971in the code for @code{rotate-yank-pointer}, which is described in an
18972appendix. (@xref{rotate-yk-ptr body, , The Body of
18973@code{rotate-yank-pointer}}.)
18974
18975You can try the @code{%} function by evaluating the following two
18976expressions:
18977
18978@smallexample
18979@group
18980(% 7 5)
18981
18982(% 10 5)
18983@end group
18984@end smallexample
18985
18986@noindent
18987The first expression returns 2 and the second expression returns 0.
18988
18989To test whether the returned value is zero or some other number, we
18990can use the @code{zerop} function. This function returns @code{t} if
18991its argument, which must be a number, is zero.
18992
18993@smallexample
18994@group
18995(zerop (% 7 5))
18996 @result{} nil
18997
18998(zerop (% 10 5))
18999 @result{} t
19000@end group
19001@end smallexample
19002
19003Thus, the following expression will return @code{t} if the height
19004of the graph is evenly divisible by five:
19005
19006@smallexample
19007(zerop (% height 5))
19008@end smallexample
19009
19010@noindent
19011(The value of @code{height}, of course, can be found from @code{(apply
19012'max numbers-list)}.)
19013
19014On the other hand, if the value of @code{height} is not a multiple of
19015five, we want to reset the value to the next higher multiple of five.
19016This is straightforward arithmetic using functions with which we are
19017already familiar. First, we divide the value of @code{height} by five
19018to determine how many times five goes into the number. Thus, five
19019goes into twelve twice. If we add one to this quotient and multiply by
19020five, we will obtain the value of the next multiple of five that is
19021larger than the height. Five goes into twelve twice. Add one to two,
19022and multiply by five; the result is fifteen, which is the next multiple
19023of five that is higher than twelve. The Lisp expression for this is:
19024
19025@smallexample
19026(* (1+ (/ height 5)) 5)
19027@end smallexample
19028
19029@noindent
19030For example, if you evaluate the following, the result is 15:
19031
19032@smallexample
19033(* (1+ (/ 12 5)) 5)
19034@end smallexample
19035
19036All through this discussion, we have been using `five' as the value
19037for spacing labels on the Y axis; but we may want to use some other
19038value. For generality, we should replace `five' with a variable to
19039which we can assign a value. The best name I can think of for this
19040variable is @code{Y-axis-label-spacing}.
19041
19042@need 1250
19043Using this term, and an @code{if} expression, we produce the
19044following:
19045
19046@smallexample
19047@group
19048(if (zerop (% height Y-axis-label-spacing))
19049 height
19050 ;; @r{else}
19051 (* (1+ (/ height Y-axis-label-spacing))
19052 Y-axis-label-spacing))
19053@end group
19054@end smallexample
19055
19056@noindent
19057This expression returns the value of @code{height} itself if the height
19058is an even multiple of the value of the @code{Y-axis-label-spacing} or
19059else it computes and returns a value of @code{height} that is equal to
19060the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19061
19062We can now include this expression in the @code{let} expression of the
19063@code{print-graph} function (after first setting the value of
19064@code{Y-axis-label-spacing}):
19065@vindex Y-axis-label-spacing
19066
19067@smallexample
19068@group
19069(defvar Y-axis-label-spacing 5
19070 "Number of lines from one Y axis label to next.")
19071@end group
19072
19073@group
19074@dots{}
19075(let* ((height (apply 'max numbers-list))
19076 (height-of-top-line
19077 (if (zerop (% height Y-axis-label-spacing))
19078 height
19079@end group
19080@group
19081 ;; @r{else}
19082 (* (1+ (/ height Y-axis-label-spacing))
19083 Y-axis-label-spacing)))
19084 (symbol-width (length graph-blank))))
19085@dots{}
19086@end group
19087@end smallexample
19088
19089@noindent
19090(Note use of the @code{let*} function: the initial value of height is
19091computed once by the @code{(apply 'max numbers-list)} expression and
19092then the resulting value of @code{height} is used to compute its
19093final value. @xref{fwd-para let, , The @code{let*} expression}, for
19094more about @code{let*}.)
19095
19096@node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19097@appendixsubsec Construct a Y Axis Element
19098
19099When we print the vertical axis, we want to insert strings such as
19100@w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19101Moreover, we want the numbers and dashes to line up, so shorter
19102numbers must be padded with leading spaces. If some of the strings
19103use two digit numbers, the strings with single digit numbers must
19104include a leading blank space before the number.
19105
19106@findex number-to-string
19107To figure out the length of the number, the @code{length} function is
19108used. But the @code{length} function works only with a string, not with
19109a number. So the number has to be converted from being a number to
19110being a string. This is done with the @code{number-to-string} function.
19111For example,
19112
19113@smallexample
19114@group
19115(length (number-to-string 35))
19116 @result{} 2
19117
19118(length (number-to-string 100))
19119 @result{} 3
19120@end group
19121@end smallexample
19122
19123@noindent
19124(@code{number-to-string} is also called @code{int-to-string}; you will
19125see this alternative name in various sources.)
19126
19127In addition, in each label, each number is followed by a string such
19128as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19129This variable is defined with @code{defvar}:
19130
19131@vindex Y-axis-tic
19132@smallexample
19133@group
19134(defvar Y-axis-tic " - "
19135 "String that follows number in a Y axis label.")
19136@end group
19137@end smallexample
19138
19139The length of the Y label is the sum of the length of the Y axis tic
19140mark and the length of the number of the top of the graph.
19141
19142@smallexample
19143(length (concat (number-to-string height) Y-axis-tic)))
19144@end smallexample
19145
19146This value will be calculated by the @code{print-graph} function in
19147its varlist as @code{full-Y-label-width} and passed on. (Note that we
19148did not think to include this in the varlist when we first proposed it.)
19149
19150To make a complete vertical axis label, a tic mark is concatenated
19151with a number; and the two together may be preceded by one or more
19152spaces depending on how long the number is. The label consists of
19153three parts: the (optional) leading spaces, the number, and the tic
19154mark. The function is passed the value of the number for the specific
19155row, and the value of the width of the top line, which is calculated
19156(just once) by @code{print-graph}.
19157
19158@smallexample
19159@group
19160(defun Y-axis-element (number full-Y-label-width)
19161 "Construct a NUMBERed label element.
19162A numbered element looks like this ` 5 - ',
19163and is padded as needed so all line up with
19164the element for the largest number."
19165@end group
19166@group
19167 (let* ((leading-spaces
19168 (- full-Y-label-width
19169 (length
19170 (concat (number-to-string number)
19171 Y-axis-tic)))))
19172@end group
19173@group
19174 (concat
19175 (make-string leading-spaces ? )
19176 (number-to-string number)
19177 Y-axis-tic)))
19178@end group
19179@end smallexample
19180
19181The @code{Y-axis-element} function concatenates together the leading
19182spaces, if any; the number, as a string; and the tic mark.
19183
19184To figure out how many leading spaces the label will need, the
19185function subtracts the actual length of the label---the length of the
19186number plus the length of the tic mark---from the desired label width.
19187
19188@findex make-string
19189Blank spaces are inserted using the @code{make-string} function. This
19190function takes two arguments: the first tells it how long the string
19191will be and the second is a symbol for the character to insert, in a
19192special format. The format is a question mark followed by a blank
19193space, like this, @samp{? }. @xref{Character Type, , Character Type,
19194elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19195syntax for characters.
19196
19197The @code{number-to-string} function is used in the concatenation
19198expression, to convert the number to a string that is concatenated
19199with the leading spaces and the tic mark.
19200
19201@node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19202@appendixsubsec Create a Y Axis Column
19203
19204The preceding functions provide all the tools needed to construct a
19205function that generates a list of numbered and blank strings to insert
19206as the label for the vertical axis:
19207
19208@findex Y-axis-column
19209@smallexample
19210@group
19211(defun Y-axis-column (height width-of-label)
19212 "Construct list of Y axis labels and blank strings.
19213For HEIGHT of line above base and WIDTH-OF-LABEL."
19214 (let (Y-axis)
19215@group
19216@end group
19217 (while (> height 1)
19218 (if (zerop (% height Y-axis-label-spacing))
19219 ;; @r{Insert label.}
19220 (setq Y-axis
19221 (cons
19222 (Y-axis-element height width-of-label)
19223 Y-axis))
19224@group
19225@end group
19226 ;; @r{Else, insert blanks.}
19227 (setq Y-axis
19228 (cons
19229 (make-string width-of-label ? )
19230 Y-axis)))
19231 (setq height (1- height)))
19232 ;; @r{Insert base line.}
19233 (setq Y-axis
19234 (cons (Y-axis-element 1 width-of-label) Y-axis))
19235 (nreverse Y-axis)))
19236@end group
19237@end smallexample
19238
19239In this function, we start with the value of @code{height} and
19240repetitively subtract one from its value. After each subtraction, we
19241test to see whether the value is an integral multiple of the
19242@code{Y-axis-label-spacing}. If it is, we construct a numbered label
19243using the @code{Y-axis-element} function; if not, we construct a
19244blank label using the @code{make-string} function. The base line
19245consists of the number one followed by a tic mark.
19246
19247@node print-Y-axis Penultimate, , Y-axis-column, print-Y-axis
19248@appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19249
19250The list constructed by the @code{Y-axis-column} function is passed to
19251the @code{print-Y-axis} function, which inserts the list as a column.
19252
19253@findex print-Y-axis
19254@smallexample
19255@group
19256(defun print-Y-axis (height full-Y-label-width)
19257 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19258Height must be the maximum height of the graph.
19259Full width is the width of the highest label element."
19260;; Value of height and full-Y-label-width
19261;; are passed by `print-graph'.
19262@end group
19263@group
19264 (let ((start (point)))
19265 (insert-rectangle
19266 (Y-axis-column height full-Y-label-width))
19267 ;; @r{Place point ready for inserting graph.}
19268 (goto-char start)
19269 ;; @r{Move point forward by value of} full-Y-label-width
19270 (forward-char full-Y-label-width)))
19271@end group
19272@end smallexample
19273
19274The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19275insert the Y axis labels created by the @code{Y-axis-column} function.
19276In addition, it places point at the correct position for printing the body of
19277the graph.
19278
19279You can test @code{print-Y-axis}:
19280
19281@enumerate
19282@item
19283Install
19284
19285@smallexample
19286@group
19287Y-axis-label-spacing
19288Y-axis-tic
19289Y-axis-element
19290Y-axis-column
19291print-Y-axis
19292@end group
19293@end smallexample
19294
19295@item
19296Copy the following expression:
19297
19298@smallexample
19299(print-Y-axis 12 5)
19300@end smallexample
19301
19302@item
19303Switch to the @file{*scratch*} buffer and place the cursor where you
19304want the axis labels to start.
19305
19306@item
19307Type @kbd{M-:} (@code{eval-expression}).
19308
19309@item
19310Yank the @code{graph-body-print} expression into the minibuffer
19311with @kbd{C-y} (@code{yank)}.
19312
19313@item
19314Press @key{RET} to evaluate the expression.
19315@end enumerate
19316
19317Emacs will print labels vertically, the top one being
19318@w{@samp{10 -@w{ }}}. (The @code{print-graph} function
19319will pass the value of @code{height-of-top-line}, which
19320in this case would end up as 15.)
19321
19322@node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19323@appendixsec The @code{print-X-axis} Function
19324@cindex Axis, print horizontal
19325@cindex X axis printing
19326@cindex Print horizontal axis
19327@cindex Horizontal axis printing
19328
19329X axis labels are much like Y axis labels, except that the tics are on a
19330line above the numbers. Labels should look like this:
19331
19332@smallexample
19333@group
19334 | | | |
19335 1 5 10 15
19336@end group
19337@end smallexample
19338
19339The first tic is under the first column of the graph and is preceded by
19340several blank spaces. These spaces provide room in rows above for the Y
19341axis labels. The second, third, fourth, and subsequent tics are all
19342spaced equally, according to the value of @code{X-axis-label-spacing}.
19343
19344The second row of the X axis consists of numbers, preceded by several
19345blank spaces and also separated according to the value of the variable
19346@code{X-axis-label-spacing}.
19347
19348The value of the variable @code{X-axis-label-spacing} should itself be
19349measured in units of @code{symbol-width}, since you may want to change
19350the width of the symbols that you are using to print the body of the
19351graph without changing the ways the graph is labelled.
19352
19353@menu
19354* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
19355* X Axis Tic Marks:: Create tic marks for the horizontal axis.
19356@end menu
19357
19358@node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19359@ifnottex
19360@unnumberedsubsec Similarities and differences
19361@end ifnottex
19362
19363The @code{print-X-axis} function is constructed in more or less the
19364same fashion as the @code{print-Y-axis} function except that it has
19365two lines: the line of tic marks and the numbers. We will write a
19366separate function to print each line and then combine them within the
19367@code{print-X-axis} function.
19368
19369This is a three step process:
19370
19371@enumerate
19372@item
19373Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19374
19375@item
19376Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19377
19378@item
19379Write a function to print both lines, the @code{print-X-axis} function,
19380using @code{print-X-axis-tic-line} and
19381@code{print-X-axis-numbered-line}.
19382@end enumerate
19383
19384@node X Axis Tic Marks, , Similarities differences, print-X-axis
19385@appendixsubsec X Axis Tic Marks
19386
19387The first function should print the X axis tic marks. We must specify
19388the tic marks themselves and their spacing:
19389
19390@smallexample
19391@group
19392(defvar X-axis-label-spacing
19393 (if (boundp 'graph-blank)
19394 (* 5 (length graph-blank)) 5)
19395 "Number of units from one X axis label to next.")
19396@end group
19397@end smallexample
19398
19399@noindent
19400(Note that the value of @code{graph-blank} is set by another
19401@code{defvar}. The @code{boundp} predicate checks whether it has
19402already been set; @code{boundp} returns @code{nil} if it has not.
19403If @code{graph-blank} were unbound and we did not use this conditional
19404construction, in GNU Emacs 21, we would enter the debugger and see an
19405error message saying
19406@samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19407
19408@need 1200
19409Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19410
19411@smallexample
19412@group
19413(defvar X-axis-tic-symbol "|"
19414 "String to insert to point to a column in X axis.")
19415@end group
19416@end smallexample
19417
19418@need 1250
19419The goal is to make a line that looks like this:
19420
19421@smallexample
19422 | | | |
19423@end smallexample
19424
19425The first tic is indented so that it is under the first column, which is
19426indented to provide space for the Y axis labels.
19427
19428A tic element consists of the blank spaces that stretch from one tic to
19429the next plus a tic symbol. The number of blanks is determined by the
19430width of the tic symbol and the @code{X-axis-label-spacing}.
19431
19432@need 1250
19433The code looks like this:
19434
19435@smallexample
19436@group
19437;;; X-axis-tic-element
19438@dots{}
19439(concat
19440 (make-string
19441 ;; @r{Make a string of blanks.}
19442 (- (* symbol-width X-axis-label-spacing)
19443 (length X-axis-tic-symbol))
19444 ? )
19445 ;; @r{Concatenate blanks with tic symbol.}
19446 X-axis-tic-symbol)
19447@dots{}
19448@end group
19449@end smallexample
19450
19451Next, we determine how many blanks are needed to indent the first tic
19452mark to the first column of the graph. This uses the value of
19453@code{full-Y-label-width} passed it by the @code{print-graph} function.
19454
19455@need 1250
19456The code to make @code{X-axis-leading-spaces}
19457looks like this:
19458
19459@smallexample
19460@group
19461;; X-axis-leading-spaces
19462@dots{}
19463(make-string full-Y-label-width ? )
19464@dots{}
19465@end group
19466@end smallexample
19467
19468We also need to determine the length of the horizontal axis, which is
19469the length of the numbers list, and the number of tics in the horizontal
19470axis:
19471
19472@smallexample
19473@group
19474;; X-length
19475@dots{}
19476(length numbers-list)
19477@end group
19478
19479@group
19480;; tic-width
19481@dots{}
19482(* symbol-width X-axis-label-spacing)
19483@end group
19484
19485@group
19486;; number-of-X-tics
19487(if (zerop (% (X-length tic-width)))
19488 (/ (X-length tic-width))
19489 (1+ (/ (X-length tic-width))))
19490@end group
19491@end smallexample
19492
19493@need 1250
19494All this leads us directly to the function for printing the X axis tic line:
19495
19496@findex print-X-axis-tic-line
19497@smallexample
19498@group
19499(defun print-X-axis-tic-line
19500 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19501 "Print tics for X axis."
19502 (insert X-axis-leading-spaces)
19503 (insert X-axis-tic-symbol) ; @r{Under first column.}
19504@end group
19505@group
19506 ;; @r{Insert second tic in the right spot.}
19507 (insert (concat
19508 (make-string
19509 (- (* symbol-width X-axis-label-spacing)
19510 ;; @r{Insert white space up to second tic symbol.}
19511 (* 2 (length X-axis-tic-symbol)))
19512 ? )
19513 X-axis-tic-symbol))
19514@end group
19515@group
19516 ;; @r{Insert remaining tics.}
19517 (while (> number-of-X-tics 1)
19518 (insert X-axis-tic-element)
19519 (setq number-of-X-tics (1- number-of-X-tics))))
19520@end group
19521@end smallexample
19522
19523The line of numbers is equally straightforward:
19524
19525@need 1250
19526First, we create a numbered element with blank spaces before each number:
19527
19528@findex X-axis-element
19529@smallexample
19530@group
19531(defun X-axis-element (number)
19532 "Construct a numbered X axis element."
19533 (let ((leading-spaces
19534 (- (* symbol-width X-axis-label-spacing)
19535 (length (number-to-string number)))))
19536 (concat (make-string leading-spaces ? )
19537 (number-to-string number))))
19538@end group
19539@end smallexample
19540
19541Next, we create the function to print the numbered line, starting with
19542the number ``1'' under the first column:
19543
19544@findex print-X-axis-numbered-line
19545@smallexample
19546@group
19547(defun print-X-axis-numbered-line
19548 (number-of-X-tics X-axis-leading-spaces)
19549 "Print line of X-axis numbers"
19550 (let ((number X-axis-label-spacing))
19551 (insert X-axis-leading-spaces)
19552 (insert "1")
19553@end group
19554@group
19555 (insert (concat
19556 (make-string
19557 ;; @r{Insert white space up to next number.}
19558 (- (* symbol-width X-axis-label-spacing) 2)
19559 ? )
19560 (number-to-string number)))
19561@end group
19562@group
19563 ;; @r{Insert remaining numbers.}
19564 (setq number (+ number X-axis-label-spacing))
19565 (while (> number-of-X-tics 1)
19566 (insert (X-axis-element number))
19567 (setq number (+ number X-axis-label-spacing))
19568 (setq number-of-X-tics (1- number-of-X-tics)))))
19569@end group
19570@end smallexample
19571
19572Finally, we need to write the @code{print-X-axis} that uses
19573@code{print-X-axis-tic-line} and
19574@code{print-X-axis-numbered-line}.
19575
19576The function must determine the local values of the variables used by both
19577@code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19578then it must call them. Also, it must print the carriage return that
19579separates the two lines.
19580
19581The function consists of a varlist that specifies five local variables,
19582and calls to each of the two line printing functions:
19583
19584@findex print-X-axis
19585@smallexample
19586@group
19587(defun print-X-axis (numbers-list)
19588 "Print X axis labels to length of NUMBERS-LIST."
19589 (let* ((leading-spaces
19590 (make-string full-Y-label-width ? ))
19591@end group
19592@group
19593 ;; symbol-width @r{is provided by} graph-body-print
19594 (tic-width (* symbol-width X-axis-label-spacing))
19595 (X-length (length numbers-list))
19596@end group
19597@group
19598 (X-tic
19599 (concat
19600 (make-string
19601@end group
19602@group
19603 ;; @r{Make a string of blanks.}
19604 (- (* symbol-width X-axis-label-spacing)
19605 (length X-axis-tic-symbol))
19606 ? )
19607@end group
19608@group
19609 ;; @r{Concatenate blanks with tic symbol.}
19610 X-axis-tic-symbol))
19611@end group
19612@group
19613 (tic-number
19614 (if (zerop (% X-length tic-width))
19615 (/ X-length tic-width)
19616 (1+ (/ X-length tic-width)))))
19617@end group
19618@group
19619 (print-X-axis-tic-line tic-number leading-spaces X-tic)
19620 (insert "\n")
19621 (print-X-axis-numbered-line tic-number leading-spaces)))
19622@end group
19623@end smallexample
19624
19625@need 1250
19626You can test @code{print-X-axis}:
19627
19628@enumerate
19629@item
19630Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19631@code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19632@code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19633
19634@item
19635Copy the following expression:
19636
19637@smallexample
19638@group
19639(progn
19640 (let ((full-Y-label-width 5)
19641 (symbol-width 1))
19642 (print-X-axis
19643 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19644@end group
19645@end smallexample
19646
19647@item
19648Switch to the @file{*scratch*} buffer and place the cursor where you
19649want the axis labels to start.
19650
19651@item
19652Type @kbd{M-:} (@code{eval-expression}).
19653
19654@item
19655Yank the test expression into the minibuffer
19656with @kbd{C-y} (@code{yank)}.
19657
19658@item
19659Press @key{RET} to evaluate the expression.
19660@end enumerate
19661
19662@need 1250
19663Emacs will print the horizontal axis like this:
19664
19665@smallexample
19666@group
19667 | | | | |
19668 1 5 10 15 20
19669@end group
19670@end smallexample
19671
19672@node Print Whole Graph, , print-X-axis, Full Graph
19673@appendixsec Printing the Whole Graph
19674@cindex Printing the whole graph
19675@cindex Whole graph printing
19676@cindex Graph, printing all
19677
19678Now we are nearly ready to print the whole graph.
19679
19680The function to print the graph with the proper labels follows the
19681outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19682Axes}), but with additions.
19683
19684@need 1250
19685Here is the outline:
19686
19687@smallexample
19688@group
19689(defun print-graph (numbers-list)
19690 "@var{documentation}@dots{}"
19691 (let ((height @dots{}
19692 @dots{}))
19693@end group
19694@group
19695 (print-Y-axis height @dots{} )
19696 (graph-body-print numbers-list)
19697 (print-X-axis @dots{} )))
19698@end group
19699@end smallexample
19700
19701@menu
19702* The final version:: A few changes.
19703* Test print-graph:: Run a short test.
19704* Graphing words in defuns:: Executing the final code.
19705* lambda:: How to write an anonymous function.
19706* mapcar:: Apply a function to elements of a list.
19707* Another Bug:: Yet another bug @dots{} most insidious.
19708* Final printed graph:: The graph itself!
19709@end menu
19710
19711@node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19712@ifnottex
19713@unnumberedsubsec Changes for the Final Version
19714@end ifnottex
19715
19716The final version is different from what we planned in two ways:
19717first, it contains additional values calculated once in the varlist;
19718second, it carries an option to specify the labels' increment per row.
19719This latter feature turns out to be essential; otherwise, a graph may
19720have more rows than fit on a display or on a sheet of paper.
19721
19722@need 1500
19723This new feature requires a change to the @code{Y-axis-column}
19724function, to add @code{vertical-step} to it. The function looks like
19725this:
19726
19727@findex Y-axis-column @r{Final version.}
19728@smallexample
19729@group
19730;;; @r{Final version.}
19731(defun Y-axis-column
19732 (height width-of-label &optional vertical-step)
19733 "Construct list of labels for Y axis.
19734HEIGHT is maximum height of graph.
19735WIDTH-OF-LABEL is maximum width of label.
19736VERTICAL-STEP, an option, is a positive integer
19737that specifies how much a Y axis label increments
19738for each line. For example, a step of 5 means
19739that each line is five units of the graph."
19740@end group
19741@group
19742 (let (Y-axis
19743 (number-per-line (or vertical-step 1)))
19744 (while (> height 1)
19745 (if (zerop (% height Y-axis-label-spacing))
19746@end group
19747@group
19748 ;; @r{Insert label.}
19749 (setq Y-axis
19750 (cons
19751 (Y-axis-element
19752 (* height number-per-line)
19753 width-of-label)
19754 Y-axis))
19755@end group
19756@group
19757 ;; @r{Else, insert blanks.}
19758 (setq Y-axis
19759 (cons
19760 (make-string width-of-label ? )
19761 Y-axis)))
19762 (setq height (1- height)))
19763@end group
19764@group
19765 ;; @r{Insert base line.}
19766 (setq Y-axis (cons (Y-axis-element
19767 (or vertical-step 1)
19768 width-of-label)
19769 Y-axis))
19770 (nreverse Y-axis)))
19771@end group
19772@end smallexample
19773
19774The values for the maximum height of graph and the width of a symbol
19775are computed by @code{print-graph} in its @code{let} expression; so
19776@code{graph-body-print} must be changed to accept them.
19777
19778@findex graph-body-print @r{Final version.}
19779@smallexample
19780@group
19781;;; @r{Final version.}
19782(defun graph-body-print (numbers-list height symbol-width)
19783 "Print a bar graph of the NUMBERS-LIST.
19784The numbers-list consists of the Y-axis values.
19785HEIGHT is maximum height of graph.
19786SYMBOL-WIDTH is number of each column."
19787@end group
19788@group
19789 (let (from-position)
19790 (while numbers-list
19791 (setq from-position (point))
19792 (insert-rectangle
19793 (column-of-graph height (car numbers-list)))
19794 (goto-char from-position)
19795 (forward-char symbol-width)
19796@end group
19797@group
19798 ;; @r{Draw graph column by column.}
19799 (sit-for 0)
19800 (setq numbers-list (cdr numbers-list)))
19801 ;; @r{Place point for X axis labels.}
19802 (forward-line height)
19803 (insert "\n")))
19804@end group
19805@end smallexample
19806
19807@need 1250
19808Finally, the code for the @code{print-graph} function:
19809
19810@findex print-graph @r{Final version.}
19811@smallexample
19812@group
19813;;; @r{Final version.}
19814(defun print-graph
19815 (numbers-list &optional vertical-step)
19816 "Print labelled bar graph of the NUMBERS-LIST.
19817The numbers-list consists of the Y-axis values.
19818@end group
19819
19820@group
19821Optionally, VERTICAL-STEP, a positive integer,
19822specifies how much a Y axis label increments for
19823each line. For example, a step of 5 means that
19824each row is five units."
19825@end group
19826@group
19827 (let* ((symbol-width (length graph-blank))
19828 ;; @code{height} @r{is both the largest number}
19829 ;; @r{and the number with the most digits.}
19830 (height (apply 'max numbers-list))
19831@end group
19832@group
19833 (height-of-top-line
19834 (if (zerop (% height Y-axis-label-spacing))
19835 height
19836 ;; @r{else}
19837 (* (1+ (/ height Y-axis-label-spacing))
19838 Y-axis-label-spacing)))
19839@end group
19840@group
19841 (vertical-step (or vertical-step 1))
19842 (full-Y-label-width
19843 (length
19844@end group
19845@group
19846 (concat
19847 (number-to-string
19848 (* height-of-top-line vertical-step))
19849 Y-axis-tic))))
19850@end group
19851
19852@group
19853 (print-Y-axis
19854 height-of-top-line full-Y-label-width vertical-step)
19855@end group
19856@group
19857 (graph-body-print
19858 numbers-list height-of-top-line symbol-width)
19859 (print-X-axis numbers-list)))
19860@end group
19861@end smallexample
19862
19863@node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
19864@appendixsubsec Testing @code{print-graph}
19865
19866@need 1250
19867We can test the @code{print-graph} function with a short list of numbers:
19868
19869@enumerate
19870@item
19871Install the final versions of @code{Y-axis-column},
19872@code{graph-body-print}, and @code{print-graph} (in addition to the
19873rest of the code.)
19874
19875@item
19876Copy the following expression:
19877
19878@smallexample
19879(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
19880@end smallexample
19881
19882@item
19883Switch to the @file{*scratch*} buffer and place the cursor where you
19884want the axis labels to start.
19885
19886@item
19887Type @kbd{M-:} (@code{eval-expression}).
19888
19889@item
19890Yank the test expression into the minibuffer
19891with @kbd{C-y} (@code{yank)}.
19892
19893@item
19894Press @key{RET} to evaluate the expression.
19895@end enumerate
19896
19897@need 1250
19898Emacs will print a graph that looks like this:
19899
19900@smallexample
19901@group
1990210 -
19903
19904
19905 *
19906 ** *
19907 5 - **** *
19908 **** ***
19909 * *********
19910 ************
19911 1 - *************
19912
19913 | | | |
19914 1 5 10 15
19915@end group
19916@end smallexample
19917
19918On the other hand, if you pass @code{print-graph} a
19919@code{vertical-step} value of 2, by evaluating this expression:
19920
19921@smallexample
19922(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
19923@end smallexample
19924
19925@need 1250
19926@noindent
19927The graph looks like this:
19928
19929@smallexample
19930@group
1993120 -
19932
19933
19934 *
19935 ** *
1993610 - **** *
19937 **** ***
19938 * *********
19939 ************
19940 2 - *************
19941
19942 | | | |
19943 1 5 10 15
19944@end group
19945@end smallexample
19946
19947@noindent
19948(A question: is the `2' on the bottom of the vertical axis a bug or a
19949feature? If you think it is a bug, and should be a `1' instead, (or
19950even a `0'), you can modify the sources.)
19951
19952@node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
19953@appendixsubsec Graphing Numbers of Words and Symbols
19954
19955Now for the graph for which all this code was written: a graph that
19956shows how many function definitions contain fewer than 10 words and
19957symbols, how many contain between 10 and 19 words and symbols, how
19958many contain between 20 and 29 words and symbols, and so on.
19959
19960This is a multi-step process. First make sure you have loaded all the
19961requisite code.
19962
19963@need 1500
19964It is a good idea to reset the value of @code{top-of-ranges} in case
19965you have set it to some different value. You can evaluate the
19966following:
19967
19968@smallexample
19969@group
19970(setq top-of-ranges
19971 '(10 20 30 40 50
19972 60 70 80 90 100
19973 110 120 130 140 150
19974 160 170 180 190 200
19975 210 220 230 240 250
19976 260 270 280 290 300)
19977@end group
19978@end smallexample
19979
19980@noindent
19981Next create a list of the number of words and symbols in each range.
19982
19983@need 1500
19984@noindent
19985Evaluate the following:
19986
19987@smallexample
19988@group
19989(setq list-for-graph
19990 (defuns-per-range
19991 (sort
19992 (recursive-lengths-list-many-files
19993 (directory-files "/usr/local/emacs/lisp"
19994 t ".+el$"))
19995 '<)
19996 top-of-ranges))
19997@end group
19998@end smallexample
19999
20000@noindent
20001On my machine, this takes about an hour. It looks though 303 Lisp
20002files in my copy of Emacs version 19.23. After all that computing,
20003the @code{list-for-graph} has this value:
20004
20005@smallexample
20006@group
20007(537 1027 955 785 594 483 349 292 224 199 166 120 116 99
2000890 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20009@end group
20010@end smallexample
20011
20012@noindent
20013This means that my copy of Emacs has 537 function definitions with
20014fewer than 10 words or symbols in them, 1,027 function definitions
20015with 10 to 19 words or symbols in them, 955 function definitions with
2001620 to 29 words or symbols in them, and so on.
20017
20018Clearly, just by looking at this list we can see that most function
20019definitions contain ten to thirty words and symbols.
20020
20021Now for printing. We do @emph{not} want to print a graph that is
200221,030 lines high @dots{} Instead, we should print a graph that is
20023fewer than twenty-five lines high. A graph that height can be
20024displayed on almost any monitor, and easily printed on a sheet of paper.
20025
20026This means that each value in @code{list-for-graph} must be reduced to
20027one-fiftieth its present value.
20028
20029Here is a short function to do just that, using two functions we have
20030not yet seen, @code{mapcar} and @code{lambda}.
20031
20032@smallexample
20033@group
20034(defun one-fiftieth (full-range)
20035 "Return list, each number one-fiftieth of previous."
20036 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20037@end group
20038@end smallexample
20039
20040@node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20041@appendixsubsec A @code{lambda} Expression: Useful Anonymity
20042@cindex Anonymous function
20043@findex lambda
20044
20045@code{lambda} is the symbol for an anonymous function, a function
20046without a name. Every time you use an anonymous function, you need to
20047include its whole body.
20048
20049@need 1250
20050@noindent
20051Thus,
20052
20053@smallexample
20054(lambda (arg) (/ arg 50))
20055@end smallexample
20056
20057@noindent
20058is a function definition that says `return the value resulting from
20059dividing whatever is passed to me as @code{arg} by 50'.
20060
20061Earlier, for example, we had a function @code{multiply-by-seven}; it
20062multiplied its argument by 7. This function is similar, except it
20063divides its argument by 50; and, it has no name. The anonymous
20064equivalent of @code{multiply-by-seven} is:
20065
20066@smallexample
20067(lambda (number) (* 7 number))
20068@end smallexample
20069
20070@noindent
20071(@xref{defun, , The @code{defun} Special Form}.)
20072
20073@need 1250
20074@noindent
20075If we want to multiply 3 by 7, we can write:
20076
20077@c !!! Clear print-postscript-figures if the computer formatting this
20078@c document is too small and cannot handle all the diagrams and figures.
20079@c clear print-postscript-figures
20080@c set print-postscript-figures
20081@c lambda example diagram #1
20082@ifnottex
20083@smallexample
20084@group
20085(multiply-by-seven 3)
20086 \_______________/ ^
20087 | |
20088 function argument
20089@end group
20090@end smallexample
20091@end ifnottex
20092@ifset print-postscript-figures
20093@sp 1
20094@tex
20095@image{lambda-1}
20096%%%% old method of including an image
20097% \input /usr/local/lib/tex/inputs/psfig.tex
20098% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20099% \catcode`\@=0 %
20100@end tex
20101@sp 1
20102@end ifset
20103@ifclear print-postscript-figures
20104@iftex
20105@smallexample
20106@group
20107(multiply-by-seven 3)
20108 \_______________/ ^
20109 | |
20110 function argument
20111@end group
20112@end smallexample
20113@end iftex
20114@end ifclear
20115
20116@noindent
20117This expression returns 21.
20118
20119@need 1250
20120@noindent
20121Similarly, we can write:
20122
20123@c lambda example diagram #2
20124@ifnottex
20125@smallexample
20126@group
20127((lambda (number) (* 7 number)) 3)
20128 \____________________________/ ^
20129 | |
20130 anonymous function argument
20131@end group
20132@end smallexample
20133@end ifnottex
20134@ifset print-postscript-figures
20135@sp 1
20136@tex
20137@image{lambda-2}
20138%%%% old method of including an image
20139% \input /usr/local/lib/tex/inputs/psfig.tex
20140% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20141% \catcode`\@=0 %
20142@end tex
20143@sp 1
20144@end ifset
20145@ifclear print-postscript-figures
20146@iftex
20147@smallexample
20148@group
20149((lambda (number) (* 7 number)) 3)
20150 \____________________________/ ^
20151 | |
20152 anonymous function argument
20153@end group
20154@end smallexample
20155@end iftex
20156@end ifclear
20157
20158@need 1250
20159@noindent
20160If we want to divide 100 by 50, we can write:
20161
20162@c lambda example diagram #3
20163@ifnottex
20164@smallexample
20165@group
20166((lambda (arg) (/ arg 50)) 100)
20167 \______________________/ \_/
20168 | |
20169 anonymous function argument
20170@end group
20171@end smallexample
20172@end ifnottex
20173@ifset print-postscript-figures
20174@sp 1
20175@tex
20176@image{lambda-3}
20177%%%% old method of including an image
20178% \input /usr/local/lib/tex/inputs/psfig.tex
20179% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20180% \catcode`\@=0 %
20181@end tex
20182@sp 1
20183@end ifset
20184@ifclear print-postscript-figures
20185@iftex
20186@smallexample
20187@group
20188((lambda (arg) (/ arg 50)) 100)
20189 \______________________/ \_/
20190 | |
20191 anonymous function argument
20192@end group
20193@end smallexample
20194@end iftex
20195@end ifclear
20196
20197@noindent
20198This expression returns 2. The 100 is passed to the function, which
20199divides that number by 50.
20200
20201@xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20202Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
20203expressions derive from the Lambda Calculus.
20204
20205@node mapcar, Another Bug, lambda, Print Whole Graph
20206@appendixsubsec The @code{mapcar} Function
20207@findex mapcar
20208
20209@code{mapcar} is a function that calls its first argument with each
20210element of its second argument, in turn. The second argument must be
20211a sequence.
20212
20213The @samp{map} part of the name comes from the mathematical phrase,
20214`mapping over a domain', meaning to apply a function to each of the
20215elements in a domain. The mathematical phrase is based on the
20216metaphor of a surveyor walking, one step at a time, over an area he is
20217mapping. And @samp{car}, of course, comes from the Lisp notion of the
20218first of a list.
20219
20220@need 1250
20221@noindent
20222For example,
20223
20224@smallexample
20225@group
20226(mapcar '1+ '(2 4 6))
20227 @result{} (3 5 7)
20228@end group
20229@end smallexample
20230
20231@noindent
20232The function @code{1+} which adds one to its argument, is executed on
20233@emph{each} element of the list, and a new list is returned.
20234
20235Contrast this with @code{apply}, which applies its first argument to
20236all the remaining.
20237(@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20238@code{apply}.)
20239
20240@need 1250
20241In the definition of @code{one-fiftieth}, the first argument is the
20242anonymous function:
20243
20244@smallexample
20245(lambda (arg) (/ arg 50))
20246@end smallexample
20247
20248@noindent
20249and the second argument is @code{full-range}, which will be bound to
20250@code{list-for-graph}.
20251
20252@need 1250
20253The whole expression looks like this:
20254
20255@smallexample
20256(mapcar '(lambda (arg) (/ arg 50)) full-range))
20257@end smallexample
20258
20259@xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20260Lisp Reference Manual}, for more about @code{mapcar}.
20261
20262Using the @code{one-fiftieth} function, we can generate a list in
20263which each element is one-fiftieth the size of the corresponding
20264element in @code{list-for-graph}.
20265
20266@smallexample
20267@group
20268(setq fiftieth-list-for-graph
20269 (one-fiftieth list-for-graph))
20270@end group
20271@end smallexample
20272
20273@need 1250
20274The resulting list looks like this:
20275
20276@smallexample
20277@group
20278(10 20 19 15 11 9 6 5 4 3 3 2 2
202791 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20280@end group
20281@end smallexample
20282
20283@noindent
20284This, we are almost ready to print! (We also notice the loss of
20285information: many of the higher ranges are 0, meaning that fewer than
2028650 defuns had that many words or symbols---but not necessarily meaning
20287that none had that many words or symbols.)
20288
20289@node Another Bug, Final printed graph, mapcar, Print Whole Graph
20290@appendixsubsec Another Bug @dots{} Most Insidious
20291@cindex Bug, most insidious type
20292@cindex Insidious type of bug
20293
20294I said `almost ready to print'! Of course, there is a bug in the
20295@code{print-graph} function @dots{} It has a @code{vertical-step}
20296option, but not a @code{horizontal-step} option. The
20297@code{top-of-range} scale goes from 10 to 300 by tens. But the
20298@code{print-graph} function will print only by ones.
20299
20300This is a classic example of what some consider the most insidious
20301type of bug, the bug of omission. This is not the kind of bug you can
20302find by studying the code, for it is not in the code; it is an omitted
20303feature. Your best actions are to try your program early and often;
20304and try to arrange, as much as you can, to write code that is easy to
20305understand and easy to change. Try to be aware, whenever you can,
20306that whatever you have written, @emph{will} be rewritten, if not soon,
20307eventually. A hard maxim to follow.
20308
20309It is the @code{print-X-axis-numbered-line} function that needs the
20310work; and then the @code{print-X-axis} and the @code{print-graph}
20311functions need to be adapted. Not much needs to be done; there is one
20312nicety: the numbers ought to line up under the tic marks. This takes
20313a little thought.
20314
20315@need 1250
20316Here is the corrected @code{print-X-axis-numbered-line}:
20317
20318@smallexample
20319@group
20320(defun print-X-axis-numbered-line
20321 (number-of-X-tics X-axis-leading-spaces
20322 &optional horizontal-step)
20323 "Print line of X-axis numbers"
20324 (let ((number X-axis-label-spacing)
20325 (horizontal-step (or horizontal-step 1)))
20326@end group
20327@group
20328 (insert X-axis-leading-spaces)
20329 ;; @r{Delete extra leading spaces.}
20330 (delete-char
20331 (- (1-
20332 (length (number-to-string horizontal-step)))))
20333 (insert (concat
20334 (make-string
20335@end group
20336@group
20337 ;; @r{Insert white space.}
20338 (- (* symbol-width
20339 X-axis-label-spacing)
20340 (1-
20341 (length
20342 (number-to-string horizontal-step)))
20343 2)
20344 ? )
20345 (number-to-string
20346 (* number horizontal-step))))
20347@end group
20348@group
20349 ;; @r{Insert remaining numbers.}
20350 (setq number (+ number X-axis-label-spacing))
20351 (while (> number-of-X-tics 1)
20352 (insert (X-axis-element
20353 (* number horizontal-step)))
20354 (setq number (+ number X-axis-label-spacing))
20355 (setq number-of-X-tics (1- number-of-X-tics)))))
20356@end group
20357@end smallexample
20358
20359@need 1500
20360If you are reading this in Info, you can see the new versions of
20361@code{print-X-axis} @code{print-graph} and evaluate them. If you are
20362reading this in a printed book, you can see the changed lines here
20363(the full text is too much to print).
20364
20365@iftex
20366@smallexample
20367@group
20368(defun print-X-axis (numbers-list horizontal-step)
20369 @dots{}
20370 (print-X-axis-numbered-line
20371 tic-number leading-spaces horizontal-step))
20372@end group
20373@end smallexample
20374
20375@smallexample
20376@group
20377(defun print-graph
20378 (numbers-list
20379 &optional vertical-step horizontal-step)
20380 @dots{}
20381 (print-X-axis numbers-list horizontal-step))
20382@end group
20383@end smallexample
20384@end iftex
20385
20386@ifnottex
20387@smallexample
20388@group
20389(defun print-X-axis (numbers-list horizontal-step)
20390 "Print X axis labels to length of NUMBERS-LIST.
20391Optionally, HORIZONTAL-STEP, a positive integer,
20392specifies how much an X axis label increments for
20393each column."
20394@end group
20395@group
20396;; Value of symbol-width and full-Y-label-width
20397;; are passed by `print-graph'.
20398 (let* ((leading-spaces
20399 (make-string full-Y-label-width ? ))
20400 ;; symbol-width @r{is provided by} graph-body-print
20401 (tic-width (* symbol-width X-axis-label-spacing))
20402 (X-length (length numbers-list))
20403@end group
20404@group
20405 (X-tic
20406 (concat
20407 (make-string
20408 ;; @r{Make a string of blanks.}
20409 (- (* symbol-width X-axis-label-spacing)
20410 (length X-axis-tic-symbol))
20411 ? )
20412@end group
20413@group
20414 ;; @r{Concatenate blanks with tic symbol.}
20415 X-axis-tic-symbol))
20416 (tic-number
20417 (if (zerop (% X-length tic-width))
20418 (/ X-length tic-width)
20419 (1+ (/ X-length tic-width)))))
20420@end group
20421
20422@group
20423 (print-X-axis-tic-line
20424 tic-number leading-spaces X-tic)
20425 (insert "\n")
20426 (print-X-axis-numbered-line
20427 tic-number leading-spaces horizontal-step)))
20428@end group
20429@end smallexample
20430
20431@smallexample
20432@group
20433(defun print-graph
20434 (numbers-list &optional vertical-step horizontal-step)
20435 "Print labelled bar graph of the NUMBERS-LIST.
20436The numbers-list consists of the Y-axis values.
20437@end group
20438
20439@group
20440Optionally, VERTICAL-STEP, a positive integer,
20441specifies how much a Y axis label increments for
20442each line. For example, a step of 5 means that
20443each row is five units.
20444@end group
20445
20446@group
20447Optionally, HORIZONTAL-STEP, a positive integer,
20448specifies how much an X axis label increments for
20449each column."
20450 (let* ((symbol-width (length graph-blank))
20451 ;; @code{height} @r{is both the largest number}
20452 ;; @r{and the number with the most digits.}
20453 (height (apply 'max numbers-list))
20454@end group
20455@group
20456 (height-of-top-line
20457 (if (zerop (% height Y-axis-label-spacing))
20458 height
20459 ;; @r{else}
20460 (* (1+ (/ height Y-axis-label-spacing))
20461 Y-axis-label-spacing)))
20462@end group
20463@group
20464 (vertical-step (or vertical-step 1))
20465 (full-Y-label-width
20466 (length
20467 (concat
20468 (number-to-string
20469 (* height-of-top-line vertical-step))
20470 Y-axis-tic))))
20471@end group
20472@group
20473 (print-Y-axis
20474 height-of-top-line full-Y-label-width vertical-step)
20475 (graph-body-print
20476 numbers-list height-of-top-line symbol-width)
20477 (print-X-axis numbers-list horizontal-step)))
20478@end group
20479@end smallexample
20480@end ifnottex
20481
20482@ignore
20483Graphing Definitions Re-listed
20484
20485@need 1250
20486Here are all the graphing definitions in their final form:
20487
20488@smallexample
20489@group
20490(defvar top-of-ranges
20491 '(10 20 30 40 50
20492 60 70 80 90 100
20493 110 120 130 140 150
20494 160 170 180 190 200
20495 210 220 230 240 250)
20496 "List specifying ranges for `defuns-per-range'.")
20497@end group
20498
20499@group
20500(defvar graph-symbol "*"
20501 "String used as symbol in graph, usually an asterisk.")
20502@end group
20503
20504@group
20505(defvar graph-blank " "
20506 "String used as blank in graph, usually a blank space.
20507graph-blank must be the same number of columns wide
20508as graph-symbol.")
20509@end group
20510
20511@group
20512(defvar Y-axis-tic " - "
20513 "String that follows number in a Y axis label.")
20514@end group
20515
20516@group
20517(defvar Y-axis-label-spacing 5
20518 "Number of lines from one Y axis label to next.")
20519@end group
20520
20521@group
20522(defvar X-axis-tic-symbol "|"
20523 "String to insert to point to a column in X axis.")
20524@end group
20525
20526@group
20527(defvar X-axis-label-spacing
20528 (if (boundp 'graph-blank)
20529 (* 5 (length graph-blank)) 5)
20530 "Number of units from one X axis label to next.")
20531@end group
20532@end smallexample
20533
20534@smallexample
20535@group
20536(defun count-words-in-defun ()
20537 "Return the number of words and symbols in a defun."
20538 (beginning-of-defun)
20539 (let ((count 0)
20540 (end (save-excursion (end-of-defun) (point))))
20541@end group
20542
20543@group
20544 (while
20545 (and (< (point) end)
20546 (re-search-forward
20547 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20548 end t))
20549 (setq count (1+ count)))
20550 count))
20551@end group
20552@end smallexample
20553
20554@smallexample
20555@group
20556(defun lengths-list-file (filename)
20557 "Return list of definitions' lengths within FILE.
20558The returned list is a list of numbers.
20559Each number is the number of words or
20560symbols in one function definition."
20561@end group
20562
20563@group
20564 (message "Working on `%s' ... " filename)
20565 (save-excursion
20566 (let ((buffer (find-file-noselect filename))
20567 (lengths-list))
20568 (set-buffer buffer)
20569 (setq buffer-read-only t)
20570 (widen)
20571 (goto-char (point-min))
20572@end group
20573
20574@group
20575 (while (re-search-forward "^(defun" nil t)
20576 (setq lengths-list
20577 (cons (count-words-in-defun) lengths-list)))
20578 (kill-buffer buffer)
20579 lengths-list)))
20580@end group
20581@end smallexample
20582
20583@smallexample
20584@group
20585(defun lengths-list-many-files (list-of-files)
20586 "Return list of lengths of defuns in LIST-OF-FILES."
20587 (let (lengths-list)
20588;;; @r{true-or-false-test}
20589 (while list-of-files
20590 (setq lengths-list
20591 (append
20592 lengths-list
20593@end group
20594@group
20595;;; @r{Generate a lengths' list.}
20596 (lengths-list-file
20597 (expand-file-name (car list-of-files)))))
20598;;; @r{Make files' list shorter.}
20599 (setq list-of-files (cdr list-of-files)))
20600;;; @r{Return final value of lengths' list.}
20601 lengths-list))
20602@end group
20603@end smallexample
20604
20605@smallexample
20606@group
20607(defun defuns-per-range (sorted-lengths top-of-ranges)
20608 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20609 (let ((top-of-range (car top-of-ranges))
20610 (number-within-range 0)
20611 defuns-per-range-list)
20612@end group
20613
20614@group
20615 ;; @r{Outer loop.}
20616 (while top-of-ranges
20617
20618 ;; @r{Inner loop.}
20619 (while (and
20620 ;; @r{Need number for numeric test.}
20621 (car sorted-lengths)
20622 (< (car sorted-lengths) top-of-range))
20623
20624 ;; @r{Count number of definitions within current range.}
20625 (setq number-within-range (1+ number-within-range))
20626 (setq sorted-lengths (cdr sorted-lengths)))
20627@end group
20628
20629@group
20630 ;; @r{Exit inner loop but remain within outer loop.}
20631
20632 (setq defuns-per-range-list
20633 (cons number-within-range defuns-per-range-list))
20634 (setq number-within-range 0) ; @r{Reset count to zero.}
20635
20636 ;; @r{Move to next range.}
20637 (setq top-of-ranges (cdr top-of-ranges))
20638 ;; @r{Specify next top of range value.}
20639 (setq top-of-range (car top-of-ranges)))
20640@end group
20641
20642@group
20643 ;; @r{Exit outer loop and count the number of defuns larger than}
20644 ;; @r{ the largest top-of-range value.}
20645 (setq defuns-per-range-list
20646 (cons
20647 (length sorted-lengths)
20648 defuns-per-range-list))
20649
20650 ;; @r{Return a list of the number of definitions within each range,}
20651 ;; @r{ smallest to largest.}
20652 (nreverse defuns-per-range-list)))
20653@end group
20654@end smallexample
20655
20656@smallexample
20657@group
20658(defun column-of-graph (max-graph-height actual-height)
20659 "Return list of MAX-GRAPH-HEIGHT strings;
20660ACTUAL-HEIGHT are graph-symbols.
20661The graph-symbols are contiguous entries at the end
20662of the list.
20663The list will be inserted as one column of a graph.
20664The strings are either graph-blank or graph-symbol."
20665@end group
20666
20667@group
20668 (let ((insert-list nil)
20669 (number-of-top-blanks
20670 (- max-graph-height actual-height)))
20671
20672 ;; @r{Fill in @code{graph-symbols}.}
20673 (while (> actual-height 0)
20674 (setq insert-list (cons graph-symbol insert-list))
20675 (setq actual-height (1- actual-height)))
20676@end group
20677
20678@group
20679 ;; @r{Fill in @code{graph-blanks}.}
20680 (while (> number-of-top-blanks 0)
20681 (setq insert-list (cons graph-blank insert-list))
20682 (setq number-of-top-blanks
20683 (1- number-of-top-blanks)))
20684
20685 ;; @r{Return whole list.}
20686 insert-list))
20687@end group
20688@end smallexample
20689
20690@smallexample
20691@group
20692(defun Y-axis-element (number full-Y-label-width)
20693 "Construct a NUMBERed label element.
20694A numbered element looks like this ` 5 - ',
20695and is padded as needed so all line up with
20696the element for the largest number."
20697@end group
20698@group
20699 (let* ((leading-spaces
20700 (- full-Y-label-width
20701 (length
20702 (concat (number-to-string number)
20703 Y-axis-tic)))))
20704@end group
20705@group
20706 (concat
20707 (make-string leading-spaces ? )
20708 (number-to-string number)
20709 Y-axis-tic)))
20710@end group
20711@end smallexample
20712
20713@smallexample
20714@group
20715(defun print-Y-axis
20716 (height full-Y-label-width &optional vertical-step)
20717 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20718Height must be the maximum height of the graph.
20719Full width is the width of the highest label element.
20720Optionally, print according to VERTICAL-STEP."
20721@end group
20722@group
20723;; Value of height and full-Y-label-width
20724;; are passed by `print-graph'.
20725 (let ((start (point)))
20726 (insert-rectangle
20727 (Y-axis-column height full-Y-label-width vertical-step))
20728@end group
20729@group
20730 ;; @r{Place point ready for inserting graph.}
20731 (goto-char start)
20732 ;; @r{Move point forward by value of} full-Y-label-width
20733 (forward-char full-Y-label-width)))
20734@end group
20735@end smallexample
20736
20737@smallexample
20738@group
20739(defun print-X-axis-tic-line
20740 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20741 "Print tics for X axis."
20742 (insert X-axis-leading-spaces)
20743 (insert X-axis-tic-symbol) ; @r{Under first column.}
20744@end group
20745@group
20746 ;; @r{Insert second tic in the right spot.}
20747 (insert (concat
20748 (make-string
20749 (- (* symbol-width X-axis-label-spacing)
20750 ;; @r{Insert white space up to second tic symbol.}
20751 (* 2 (length X-axis-tic-symbol)))
20752 ? )
20753 X-axis-tic-symbol))
20754@end group
20755@group
20756 ;; @r{Insert remaining tics.}
20757 (while (> number-of-X-tics 1)
20758 (insert X-axis-tic-element)
20759 (setq number-of-X-tics (1- number-of-X-tics))))
20760@end group
20761@end smallexample
20762
20763@smallexample
20764@group
20765(defun X-axis-element (number)
20766 "Construct a numbered X axis element."
20767 (let ((leading-spaces
20768 (- (* symbol-width X-axis-label-spacing)
20769 (length (number-to-string number)))))
20770 (concat (make-string leading-spaces ? )
20771 (number-to-string number))))
20772@end group
20773@end smallexample
20774
20775@smallexample
20776@group
20777(defun graph-body-print (numbers-list height symbol-width)
20778 "Print a bar graph of the NUMBERS-LIST.
20779The numbers-list consists of the Y-axis values.
20780HEIGHT is maximum height of graph.
20781SYMBOL-WIDTH is number of each column."
20782@end group
20783@group
20784 (let (from-position)
20785 (while numbers-list
20786 (setq from-position (point))
20787 (insert-rectangle
20788 (column-of-graph height (car numbers-list)))
20789 (goto-char from-position)
20790 (forward-char symbol-width)
20791@end group
20792@group
20793 ;; @r{Draw graph column by column.}
20794 (sit-for 0)
20795 (setq numbers-list (cdr numbers-list)))
20796 ;; @r{Place point for X axis labels.}
20797 (forward-line height)
20798 (insert "\n")))
20799@end group
20800@end smallexample
20801
20802@smallexample
20803@group
20804(defun Y-axis-column
20805 (height width-of-label &optional vertical-step)
20806 "Construct list of labels for Y axis.
20807HEIGHT is maximum height of graph.
20808WIDTH-OF-LABEL is maximum width of label.
20809@end group
20810@group
20811VERTICAL-STEP, an option, is a positive integer
20812that specifies how much a Y axis label increments
20813for each line. For example, a step of 5 means
20814that each line is five units of the graph."
20815 (let (Y-axis
20816 (number-per-line (or vertical-step 1)))
20817@end group
20818@group
20819 (while (> height 1)
20820 (if (zerop (% height Y-axis-label-spacing))
20821 ;; @r{Insert label.}
20822 (setq Y-axis
20823 (cons
20824 (Y-axis-element
20825 (* height number-per-line)
20826 width-of-label)
20827 Y-axis))
20828@end group
20829@group
20830 ;; @r{Else, insert blanks.}
20831 (setq Y-axis
20832 (cons
20833 (make-string width-of-label ? )
20834 Y-axis)))
20835 (setq height (1- height)))
20836@end group
20837@group
20838 ;; @r{Insert base line.}
20839 (setq Y-axis (cons (Y-axis-element
20840 (or vertical-step 1)
20841 width-of-label)
20842 Y-axis))
20843 (nreverse Y-axis)))
20844@end group
20845@end smallexample
20846
20847@smallexample
20848@group
20849(defun print-X-axis-numbered-line
20850 (number-of-X-tics X-axis-leading-spaces
20851 &optional horizontal-step)
20852 "Print line of X-axis numbers"
20853 (let ((number X-axis-label-spacing)
20854 (horizontal-step (or horizontal-step 1)))
20855@end group
20856@group
20857 (insert X-axis-leading-spaces)
20858 ;; line up number
20859 (delete-char (- (1- (length (number-to-string horizontal-step)))))
20860 (insert (concat
20861 (make-string
20862 ;; @r{Insert white space up to next number.}
20863 (- (* symbol-width X-axis-label-spacing)
20864 (1- (length (number-to-string horizontal-step)))
20865 2)
20866 ? )
20867 (number-to-string (* number horizontal-step))))
20868@end group
20869@group
20870 ;; @r{Insert remaining numbers.}
20871 (setq number (+ number X-axis-label-spacing))
20872 (while (> number-of-X-tics 1)
20873 (insert (X-axis-element (* number horizontal-step)))
20874 (setq number (+ number X-axis-label-spacing))
20875 (setq number-of-X-tics (1- number-of-X-tics)))))
20876@end group
20877@end smallexample
20878
20879@smallexample
20880@group
20881(defun print-X-axis (numbers-list horizontal-step)
20882 "Print X axis labels to length of NUMBERS-LIST.
20883Optionally, HORIZONTAL-STEP, a positive integer,
20884specifies how much an X axis label increments for
20885each column."
20886@end group
20887@group
20888;; Value of symbol-width and full-Y-label-width
20889;; are passed by `print-graph'.
20890 (let* ((leading-spaces
20891 (make-string full-Y-label-width ? ))
20892 ;; symbol-width @r{is provided by} graph-body-print
20893 (tic-width (* symbol-width X-axis-label-spacing))
20894 (X-length (length numbers-list))
20895@end group
20896@group
20897 (X-tic
20898 (concat
20899 (make-string
20900 ;; @r{Make a string of blanks.}
20901 (- (* symbol-width X-axis-label-spacing)
20902 (length X-axis-tic-symbol))
20903 ? )
20904@end group
20905@group
20906 ;; @r{Concatenate blanks with tic symbol.}
20907 X-axis-tic-symbol))
20908 (tic-number
20909 (if (zerop (% X-length tic-width))
20910 (/ X-length tic-width)
20911 (1+ (/ X-length tic-width)))))
20912@end group
20913
20914@group
20915 (print-X-axis-tic-line
20916 tic-number leading-spaces X-tic)
20917 (insert "\n")
20918 (print-X-axis-numbered-line
20919 tic-number leading-spaces horizontal-step)))
20920@end group
20921@end smallexample
20922
20923@smallexample
20924@group
20925(defun one-fiftieth (full-range)
20926 "Return list, each number of which is 1/50th previous."
20927 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20928@end group
20929@end smallexample
20930
20931@smallexample
20932@group
20933(defun print-graph
20934 (numbers-list &optional vertical-step horizontal-step)
20935 "Print labelled bar graph of the NUMBERS-LIST.
20936The numbers-list consists of the Y-axis values.
20937@end group
20938
20939@group
20940Optionally, VERTICAL-STEP, a positive integer,
20941specifies how much a Y axis label increments for
20942each line. For example, a step of 5 means that
20943each row is five units.
20944@end group
20945
20946@group
20947Optionally, HORIZONTAL-STEP, a positive integer,
20948specifies how much an X axis label increments for
20949each column."
20950 (let* ((symbol-width (length graph-blank))
20951 ;; @code{height} @r{is both the largest number}
20952 ;; @r{and the number with the most digits.}
20953 (height (apply 'max numbers-list))
20954@end group
20955@group
20956 (height-of-top-line
20957 (if (zerop (% height Y-axis-label-spacing))
20958 height
20959 ;; @r{else}
20960 (* (1+ (/ height Y-axis-label-spacing))
20961 Y-axis-label-spacing)))
20962@end group
20963@group
20964 (vertical-step (or vertical-step 1))
20965 (full-Y-label-width
20966 (length
20967 (concat
20968 (number-to-string
20969 (* height-of-top-line vertical-step))
20970 Y-axis-tic))))
20971@end group
20972@group
20973
20974 (print-Y-axis
20975 height-of-top-line full-Y-label-width vertical-step)
20976 (graph-body-print
20977 numbers-list height-of-top-line symbol-width)
20978 (print-X-axis numbers-list horizontal-step)))
20979@end group
20980@end smallexample
20981@end ignore
20982
20983@page
20984@node Final printed graph, , Another Bug, Print Whole Graph
20985@appendixsubsec The Printed Graph
20986
20987When made and installed, you can call the @code{print-graph} command
20988like this:
20989
20990@smallexample
20991@group
20992(print-graph fiftieth-list-for-graph 50 10)
20993@end group
20994@end smallexample
20995
20996Here is the graph:
20997
20998@sp 2
20999
21000@smallexample
21001@group
210021000 - *
21003 **
21004 **
21005 **
21006 **
21007 750 - ***
21008 ***
21009 ***
21010 ***
21011 ****
21012 500 - *****
21013 ******
21014 ******
21015 ******
21016 *******
21017 250 - ********
21018 ********* *
21019 *********** *
21020 ************* *
21021 50 - ***************** * *
21022 | | | | | | | |
21023 10 50 100 150 200 250 300 350
21024@end group
21025@end smallexample
21026
21027@sp 2
21028
21029The largest group of functions contain 10 -- 19 words and symbols each.
21030
21031@node GNU Free Documentation License, Index, Full Graph, Top
21032@appendix GNU Free Documentation License
21033
21034@cindex FDL, GNU Free Documentation License
21035@center Version 1.1, March 2000
21036
21037@display
21038Copyright @copyright{} 2000 Free Software Foundation, Inc.
2103959 Temple Place, Suite 330, Boston, MA 02111-1307, USA
21040
21041Everyone is permitted to copy and distribute verbatim copies
21042of this license document, but changing it is not allowed.
21043@end display
21044
21045@enumerate 0
21046@item
21047PREAMBLE
21048
21049The purpose of this License is to make a manual, textbook, or other
21050written document @dfn{free} in the sense of freedom: to assure everyone
21051the effective freedom to copy and redistribute it, with or without
21052modifying it, either commercially or noncommercially. Secondarily,
21053this License preserves for the author and publisher a way to get
21054credit for their work, while not being considered responsible for
21055modifications made by others.
21056
21057This License is a kind of ``copyleft'', which means that derivative
21058works of the document must themselves be free in the same sense. It
21059complements the GNU General Public License, which is a copyleft
21060license designed for free software.
21061
21062We have designed this License in order to use it for manuals for free
21063software, because free software needs free documentation: a free
21064program should come with manuals providing the same freedoms that the
21065software does. But this License is not limited to software manuals;
21066it can be used for any textual work, regardless of subject matter or
21067whether it is published as a printed book. We recommend this License
21068principally for works whose purpose is instruction or reference.
21069
21070@item
21071APPLICABILITY AND DEFINITIONS
21072
21073This License applies to any manual or other work that contains a
21074notice placed by the copyright holder saying it can be distributed
21075under the terms of this License. The ``Document'', below, refers to any
21076such manual or work. Any member of the public is a licensee, and is
21077addressed as ``you''.
21078
21079A ``Modified Version'' of the Document means any work containing the
21080Document or a portion of it, either copied verbatim, or with
21081modifications and/or translated into another language.
21082
21083A ``Secondary Section'' is a named appendix or a front-matter section of
21084the Document that deals exclusively with the relationship of the
21085publishers or authors of the Document to the Document's overall subject
21086(or to related matters) and contains nothing that could fall directly
21087within that overall subject. (For example, if the Document is in part a
21088textbook of mathematics, a Secondary Section may not explain any
21089mathematics.) The relationship could be a matter of historical
21090connection with the subject or with related matters, or of legal,
21091commercial, philosophical, ethical or political position regarding
21092them.
21093
21094The ``Invariant Sections'' are certain Secondary Sections whose titles
21095are designated, as being those of Invariant Sections, in the notice
21096that says that the Document is released under this License.
21097
21098The ``Cover Texts'' are certain short passages of text that are listed,
21099as Front-Cover Texts or Back-Cover Texts, in the notice that says that
21100the Document is released under this License.
21101
21102A ``Transparent'' copy of the Document means a machine-readable copy,
21103represented in a format whose specification is available to the
21104general public, whose contents can be viewed and edited directly and
21105straightforwardly with generic text editors or (for images composed of
21106pixels) generic paint programs or (for drawings) some widely available
21107drawing editor, and that is suitable for input to text formatters or
21108for automatic translation to a variety of formats suitable for input
21109to text formatters. A copy made in an otherwise Transparent file
21110format whose markup has been designed to thwart or discourage
21111subsequent modification by readers is not Transparent. A copy that is
21112not ``Transparent'' is called ``Opaque''.
21113
21114Examples of suitable formats for Transparent copies include plain
21115@sc{ascii} without markup, Texinfo input format, La@TeX{} input format,
21116@acronym{SGML} or @acronym{XML} using a publicly available
21117@acronym{DTD}, and standard-conforming simple @acronym{HTML} designed
21118for human modification. Opaque formats include PostScript,
21119@acronym{PDF}, proprietary formats that can be read and edited only by
21120proprietary word processors, @acronym{SGML} or @acronym{XML} for which
21121the @acronym{DTD} and/or processing tools are not generally available,
21122and the machine-generated @acronym{HTML} produced by some word
21123processors for output purposes only.
21124
21125The ``Title Page'' means, for a printed book, the title page itself,
21126plus such following pages as are needed to hold, legibly, the material
21127this License requires to appear in the title page. For works in
21128formats which do not have any title page as such, ``Title Page'' means
21129the text near the most prominent appearance of the work's title,
21130preceding the beginning of the body of the text.
21131
21132@item
21133VERBATIM COPYING
21134
21135You may copy and distribute the Document in any medium, either
21136commercially or noncommercially, provided that this License, the
21137copyright notices, and the license notice saying this License applies
21138to the Document are reproduced in all copies, and that you add no other
21139conditions whatsoever to those of this License. You may not use
21140technical measures to obstruct or control the reading or further
21141copying of the copies you make or distribute. However, you may accept
21142compensation in exchange for copies. If you distribute a large enough
21143number of copies you must also follow the conditions in section 3.
21144
21145You may also lend copies, under the same conditions stated above, and
21146you may publicly display copies.
21147
21148@item
21149COPYING IN QUANTITY
21150
21151If you publish printed copies of the Document numbering more than 100,
21152and the Document's license notice requires Cover Texts, you must enclose
21153the copies in covers that carry, clearly and legibly, all these Cover
21154Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21155the back cover. Both covers must also clearly and legibly identify
21156you as the publisher of these copies. The front cover must present
21157the full title with all words of the title equally prominent and
21158visible. You may add other material on the covers in addition.
21159Copying with changes limited to the covers, as long as they preserve
21160the title of the Document and satisfy these conditions, can be treated
21161as verbatim copying in other respects.
21162
21163If the required texts for either cover are too voluminous to fit
21164legibly, you should put the first ones listed (as many as fit
21165reasonably) on the actual cover, and continue the rest onto adjacent
21166pages.
21167
21168If you publish or distribute Opaque copies of the Document numbering
21169more than 100, you must either include a machine-readable Transparent
21170copy along with each Opaque copy, or state in or with each Opaque copy
21171a publicly-accessible computer-network location containing a complete
21172Transparent copy of the Document, free of added material, which the
21173general network-using public has access to download anonymously at no
21174charge using public-standard network protocols. If you use the latter
21175option, you must take reasonably prudent steps, when you begin
21176distribution of Opaque copies in quantity, to ensure that this
21177Transparent copy will remain thus accessible at the stated location
21178until at least one year after the last time you distribute an Opaque
21179copy (directly or through your agents or retailers) of that edition to
21180the public.
21181
21182It is requested, but not required, that you contact the authors of the
21183Document well before redistributing any large number of copies, to give
21184them a chance to provide you with an updated version of the Document.
21185
21186@item
21187MODIFICATIONS
21188
21189You may copy and distribute a Modified Version of the Document under
21190the conditions of sections 2 and 3 above, provided that you release
21191the Modified Version under precisely this License, with the Modified
21192Version filling the role of the Document, thus licensing distribution
21193and modification of the Modified Version to whoever possesses a copy
21194of it. In addition, you must do these things in the Modified Version:
21195
21196@enumerate A
21197@item
21198Use in the Title Page (and on the covers, if any) a title distinct
21199from that of the Document, and from those of previous versions
21200(which should, if there were any, be listed in the History section
21201of the Document). You may use the same title as a previous version
21202if the original publisher of that version gives permission.
21203
21204@item
21205List on the Title Page, as authors, one or more persons or entities
21206responsible for authorship of the modifications in the Modified
21207Version, together with at least five of the principal authors of the
21208Document (all of its principal authors, if it has less than five).
21209
21210@item
21211State on the Title page the name of the publisher of the
21212Modified Version, as the publisher.
21213
21214@item
21215Preserve all the copyright notices of the Document.
21216
21217@item
21218Add an appropriate copyright notice for your modifications
21219adjacent to the other copyright notices.
21220
21221@item
21222Include, immediately after the copyright notices, a license notice
21223giving the public permission to use the Modified Version under the
21224terms of this License, in the form shown in the Addendum below.
21225
21226@item
21227Preserve in that license notice the full lists of Invariant Sections
21228and required Cover Texts given in the Document's license notice.
21229
21230@item
21231Include an unaltered copy of this License.
21232
21233@item
21234Preserve the section entitled ``History'', and its title, and add to
21235it an item stating at least the title, year, new authors, and
21236publisher of the Modified Version as given on the Title Page. If
21237there is no section entitled ``History'' in the Document, create one
21238stating the title, year, authors, and publisher of the Document as
21239given on its Title Page, then add an item describing the Modified
21240Version as stated in the previous sentence.
21241
21242@item
21243Preserve the network location, if any, given in the Document for
21244public access to a Transparent copy of the Document, and likewise
21245the network locations given in the Document for previous versions
21246it was based on. These may be placed in the ``History'' section.
21247You may omit a network location for a work that was published at
21248least four years before the Document itself, or if the original
21249publisher of the version it refers to gives permission.
21250
21251@item
21252In any section entitled ``Acknowledgments'' or ``Dedications'',
21253preserve the section's title, and preserve in the section all the
21254substance and tone of each of the contributor acknowledgments
21255and/or dedications given therein.
21256
21257@item
21258Preserve all the Invariant Sections of the Document,
21259unaltered in their text and in their titles. Section numbers
21260or the equivalent are not considered part of the section titles.
21261
21262@item
21263Delete any section entitled ``Endorsements''. Such a section
21264may not be included in the Modified Version.
21265
21266@item
21267Do not retitle any existing section as ``Endorsements''
21268or to conflict in title with any Invariant Section.
21269@end enumerate
21270
21271If the Modified Version includes new front-matter sections or
21272appendices that qualify as Secondary Sections and contain no material
21273copied from the Document, you may at your option designate some or all
21274of these sections as invariant. To do this, add their titles to the
21275list of Invariant Sections in the Modified Version's license notice.
21276These titles must be distinct from any other section titles.
21277
21278You may add a section entitled ``Endorsements'', provided it contains
21279nothing but endorsements of your Modified Version by various
21280parties---for example, statements of peer review or that the text has
21281been approved by an organization as the authoritative definition of a
21282standard.
21283
21284You may add a passage of up to five words as a Front-Cover Text, and a
21285passage of up to 25 words as a Back-Cover Text, to the end of the list
21286of Cover Texts in the Modified Version. Only one passage of
21287Front-Cover Text and one of Back-Cover Text may be added by (or
21288through arrangements made by) any one entity. If the Document already
21289includes a cover text for the same cover, previously added by you or
21290by arrangement made by the same entity you are acting on behalf of,
21291you may not add another; but you may replace the old one, on explicit
21292permission from the previous publisher that added the old one.
21293
21294The author(s) and publisher(s) of the Document do not by this License
21295give permission to use their names for publicity for or to assert or
21296imply endorsement of any Modified Version.
21297
21298@item
21299COMBINING DOCUMENTS
21300
21301You may combine the Document with other documents released under this
21302License, under the terms defined in section 4 above for modified
21303versions, provided that you include in the combination all of the
21304Invariant Sections of all of the original documents, unmodified, and
21305list them all as Invariant Sections of your combined work in its
21306license notice.
21307
21308The combined work need only contain one copy of this License, and
21309multiple identical Invariant Sections may be replaced with a single
21310copy. If there are multiple Invariant Sections with the same name but
21311different contents, make the title of each such section unique by
21312adding at the end of it, in parentheses, the name of the original
21313author or publisher of that section if known, or else a unique number.
21314Make the same adjustment to the section titles in the list of
21315Invariant Sections in the license notice of the combined work.
21316
21317In the combination, you must combine any sections entitled ``History''
21318in the various original documents, forming one section entitled
21319``History''; likewise combine any sections entitled ``Acknowledgments'',
21320and any sections entitled ``Dedications''. You must delete all sections
21321entitled ``Endorsements.''
21322
21323@item
21324COLLECTIONS OF DOCUMENTS
21325
21326You may make a collection consisting of the Document and other documents
21327released under this License, and replace the individual copies of this
21328License in the various documents with a single copy that is included in
21329the collection, provided that you follow the rules of this License for
21330verbatim copying of each of the documents in all other respects.
21331
21332You may extract a single document from such a collection, and distribute
21333it individually under this License, provided you insert a copy of this
21334License into the extracted document, and follow this License in all
21335other respects regarding verbatim copying of that document.
21336
21337@item
21338AGGREGATION WITH INDEPENDENT WORKS
21339
21340A compilation of the Document or its derivatives with other separate
21341and independent documents or works, in or on a volume of a storage or
21342distribution medium, does not as a whole count as a Modified Version
21343of the Document, provided no compilation copyright is claimed for the
21344compilation. Such a compilation is called an ``aggregate'', and this
21345License does not apply to the other self-contained works thus compiled
21346with the Document, on account of their being thus compiled, if they
21347are not themselves derivative works of the Document.
21348
21349If the Cover Text requirement of section 3 is applicable to these
21350copies of the Document, then if the Document is less than one quarter
21351of the entire aggregate, the Document's Cover Texts may be placed on
21352covers that surround only the Document within the aggregate.
21353Otherwise they must appear on covers around the whole aggregate.
21354
21355@item
21356TRANSLATION
21357
21358Translation is considered a kind of modification, so you may
21359distribute translations of the Document under the terms of section 4.
21360Replacing Invariant Sections with translations requires special
21361permission from their copyright holders, but you may include
21362translations of some or all Invariant Sections in addition to the
21363original versions of these Invariant Sections. You may include a
21364translation of this License provided that you also include the
21365original English version of this License. In case of a disagreement
21366between the translation and the original English version of this
21367License, the original English version will prevail.
21368
21369@item
21370TERMINATION
21371
21372You may not copy, modify, sublicense, or distribute the Document except
21373as expressly provided for under this License. Any other attempt to
21374copy, modify, sublicense or distribute the Document is void, and will
21375automatically terminate your rights under this License. However,
21376parties who have received copies, or rights, from you under this
21377License will not have their licenses terminated so long as such
21378parties remain in full compliance.
21379
21380@item
21381FUTURE REVISIONS OF THIS LICENSE
21382
21383The Free Software Foundation may publish new, revised versions
21384of the GNU Free Documentation License from time to time. Such new
21385versions will be similar in spirit to the present version, but may
21386differ in detail to address new problems or concerns. See
21387@uref{http://www.gnu.org/copyleft/}.
21388
21389Each version of the License is given a distinguishing version number.
21390If the Document specifies that a particular numbered version of this
21391License ``or any later version'' applies to it, you have the option of
21392following the terms and conditions either of that specified version or
21393of any later version that has been published (not as a draft) by the
21394Free Software Foundation. If the Document does not specify a version
21395number of this License, you may choose any version ever published (not
21396as a draft) by the Free Software Foundation.
21397@end enumerate
21398
21399@node Index, About the Author, GNU Free Documentation License, Top
21400@comment node-name, next, previous, up
21401@unnumbered Index
21402
d586ab6c 21403@ignore
8b096dce 21404MENU ENTRY: NODE NAME.
d586ab6c 21405@end ignore
8b096dce
EZ
21406
21407@printindex cp
21408
21409@iftex
21410@c Place biographical information on right-hand (verso) page
21411
21412@tex
21413\ifodd\pageno
21414 \par\vfill\supereject
21415 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21416 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21417 \page\hbox{}\page
21418\else
21419 \par\vfill\supereject
21420 \par\vfill\supereject
21421 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21422 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21423 \page\hbox{}\page
21424 \page\hbox{}\page
21425\fi
21426@end tex
21427
21428@page
21429@w{ }
21430
21431@c ================ Biographical information ================
21432
21433@w{ }
21434@sp 8
21435@center About the Author
21436@sp 1
21437@end iftex
21438
21439@ifnottex
21440@node About the Author, , Index, Top
21441@unnumbered About the Author
21442@end ifnottex
21443
21444@quotation
21445Robert J. Chassell has worked with GNU Emacs since 1985. He writes
21446and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21447world on software freedom. Chassell was a founding Director and
21448Treasurer of the Free Software Foundation, Inc. He is co-author of
21449the @cite{Texinfo} manual, and has edited more than a dozen other
21450books. He graduated from Cambridge University, in England. He has an
21451abiding interest in social and economic history and flies his own
21452airplane.
21453@end quotation
21454
21455@page
21456@w{ }
21457
21458@c Prevent page number on blank verso, so eject it first.
21459@tex
21460\par\vfill\supereject
21461@end tex
21462
21463@iftex
21464@headings off
21465@evenheading @thispage @| @| @thistitle
21466@oddheading @| @| @thispage
21467@end iftex
21468
8b096dce 21469@bye