(customize-changed-options): Undo last doc change.
[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 12@c <<<< For hard copy printing, this file is now
28be162e 13@c set for smallbook, which works for all sizes
475dc40a
EZ
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
b1bd267c
RC
24@set edition-number 2.07
25@set update-date 2002 Aug 23
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
b1bd267c
RC
43 ## DocBook output
44 makeinfo --docbook --no-split --paragraph-indent=0 \
45 --verbose emacs-lisp-intro.texi
46
47 ## XML output
48 makeinfo --xml --no-split --paragraph-indent=0 \
49 --verbose emacs-lisp-intro.texi
50
8b096dce
EZ
51@end ignore
52
53@c ================ Included Figures ================
54
55@c Set print-postscript-figures if you print PostScript figures.
56@c If you clear this, the ten figures will be printed as ASCII diagrams.
57@c (This is not relevant to Info, since Info only handles ASCII.)
58@c Your site may require editing changes to print PostScript; in this
59@c case, search for `print-postscript-figures' and make appropriate changes.
60
61
62@c ================ How to Create an Info file ================
63
64@c If you have `makeinfo' installed, run the following command
65
66@c makeinfo emacs-lisp-intro.texi
67
68@c or, if you want a single, large Info file, and no paragraph indents:
69@c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
70
71@c After creating the Info file, edit your Info `dir' file, if the
0860ed42 72@c `dircategory' section below does not enable your system to
8b096dce
EZ
73@c install the manual automatically.
74@c (The `dir' file is often in the `/usr/local/info/' directory.)
75
76@c ================ How to Create an HTML file ================
77
78@c To convert to HTML format
79@c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
80
81@c ================ How to Print a Book in Various Sizes ================
82
83@c This book can be printed in any of three different sizes.
84@c In the above header, set @-commands appropriately.
85
86@c 7 by 9.25 inches:
87@c @smallbook
88@c @clear largebook
89
90@c 8.5 by 11 inches:
91@c @c smallbook
92@c @set largebook
93
94@c European A4 size paper:
95@c @c smallbook
96@c @afourpaper
97@c @set largebook
98
99@c ================ How to Typeset and Print ================
100
101@c If you do not include PostScript figures, run either of the
102@c following command sequences, or similar commands suited to your
103@c system:
104
105@c texi2dvi emacs-lisp-intro.texi
106@c lpr -d emacs-lisp-intro.dvi
107
108@c or else:
109
110@c tex emacs-lisp-intro.texi
111@c texindex emacs-lisp-intro.??
112@c tex emacs-lisp-intro.texi
113@c lpr -d emacs-lisp-intro.dvi
114
475dc40a
EZ
115@c If you include the PostScript figures, and you have old software,
116@c you may need to convert the .dvi file to a .ps file before
117@c printing. Run either of the following command sequences, or one
118@c similar:
8b096dce
EZ
119@c
120@c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
121@c
122@c or else:
123@c
124@c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
125@c
126
127@c (Note: if you edit the book so as to change the length of the
128@c table of contents, you may have to change the value of `pageno' below.)
129
8b096dce
EZ
130@c ================ End of Formatting Sections ================
131
132@c For next or subsequent edition:
133@c create function using with-output-to-temp-buffer
134@c create a major mode, with keymaps
135@c run an asynchronous process, like grep or diff
136
8b096dce 137@c For 8.5 by 11 inch format: do not use such a small amount of
2ec6f00d 138@c whitespace between paragraphs as smallbook format
8b096dce
EZ
139@ifset largebook
140@tex
141\global\parskip 6pt plus 1pt
142@end tex
143@end ifset
144
145@c For all sized formats: print within-book cross
146@c reference with ``...'' rather than [...]
147@tex
148% Need following so comma appears after section numbers.
149\global\def\Ysectionnumberandtype{%
150\ifnum\secno=0 \putwordChapter\xreftie\the\chapno, \space %
151\else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno, \space %
152\else \ifnum \subsubsecno=0 %
153\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno, \space %
154\else %
155\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno, \space%
156\fi \fi \fi }
157
158\global\def\Yappendixletterandtype{%
159\ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}, \space%
160\else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno, \space %
161\else \ifnum \subsubsecno=0 %
162\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno, \space %
163\else %
164\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno, \space %
165\fi \fi \fi }
166
167\global\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
168 \def\printedmanual{\ignorespaces #5}%
169 \def\printednodename{\ignorespaces #3}%
170 \setbox1=\hbox{\printedmanual}%
171 \setbox0=\hbox{\printednodename}%
172 \ifdim \wd0 = 0pt
173 % No printed node name was explicitly given.
174 \ifx\SETxref-automatic-section-title\relax %
175 % Use the actual chapter/section title appear inside
176 % the square brackets. Use the real section title if we have it.
177 \ifdim \wd1>0pt%
178 % It is in another manual, so we don't have it.
179 \def\printednodename{\ignorespaces #1}%
180 \else
181 \ifhavexrefs
182 % We know the real title if we have the xref values.
183 \def\printednodename{\refx{#1-title}}%
184 \else
185 % Otherwise just copy the Info node name.
186 \def\printednodename{\ignorespaces #1}%
187 \fi%
188 \fi
189 \def\printednodename{#1-title}%
190 \else
191 % Use the node name inside the square brackets.
192 \def\printednodename{\ignorespaces #1}%
193 \fi
194 \fi
195 %
196 % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not
197 % insert empty discretionaries after hyphens, which means that it will
198 % not find a line break at a hyphen in a node names. Since some manuals
199 % are best written with fairly long node names, containing hyphens, this
200 % is a loss. Therefore, we give the text of the node name again, so it
201 % is as if TeX is seeing it for the first time.
202 \ifdim \wd1 > 0pt
203 \putwordsection{} ``\printednodename'' in \cite{\printedmanual}%
204 \else
205 % _ (for example) has to be the character _ for the purposes of the
206 % control sequence corresponding to the node, but it has to expand
207 % into the usual \leavevmode...\vrule stuff for purposes of
208 % printing. So we \turnoffactive for the \refx-snt, back on for the
209 % printing, back off for the \refx-pg.
210 {\turnoffactive \refx{#1-snt}{}}%
211% \space [\printednodename],\space % <= original
212% \putwordsection{} ``\printednodename'',\space
213 ``\printednodename'',\space
214 \turnoffactive \putwordpage\tie\refx{#1-pg}{}%
215 \fi
216\endgroup}
217@end tex
218
219@c ----------------------------------------------------
220
d586ab6c
EZ
221@dircategory Emacs
222@direntry
223* Emacs Lisp Intro: (eintr).
8b096dce 224 A simple introduction to Emacs Lisp programming.
d586ab6c 225@end direntry
8b096dce 226
b1bd267c 227@copying
8b096dce
EZ
228This is an introduction to @cite{Programming in Emacs Lisp}, for
229people who are not programmers.
230
231Edition @value{edition-number}, @value{update-date}
232
b1bd267c
RC
233Copyright @copyright{} 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002 Free Software Foundation, Inc.
234@sp 2
235
236Published by the Free Software Foundation, Inc.@*
23759 Temple Place, Suite 330@*
238Boston, MA 02111-1307 USA@*
239
b1bd267c
RC
240@c Printed copies are available for $30 each.@*
241ISBN 1-882114-43-4
8b096dce
EZ
242
243Permission is granted to copy, distribute and/or modify this document
244under the terms of the GNU Free Documentation License, Version 1.1 or
9a2ed8db
RC
245any later version published by the Free Software Foundation; there
246being no Invariant Section, with the Front-Cover Texts being ``A GNU
247Manual'', and with the Back-Cover Texts as in (a) below. A copy of
248the license is included in the section entitled ``GNU Free
28be162e
RC
249Documentation License''.
250
251(a) The FSF's Back-Cover Text is: ``You have freedom to copy and
252modify this GNU Manual, like GNU software. Copies published by the
253Free Software Foundation raise funds for GNU development.''
b1bd267c 254@end copying
8b096dce
EZ
255
256@c half title; two lines here, so do not use `shorttitlepage'
257@tex
258{\begingroup%
259 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
260 \endgroup}%
261{\begingroup\hbox{}\vskip 0.25in \chaprm%
262 \centerline{Programming in Emacs Lisp}%
263 \endgroup\page\hbox{}\page}
264@end tex
265
266@titlepage
267@sp 6
268@center @titlefont{An Introduction to}
269@sp 2
270@center @titlefont{Programming in Emacs Lisp}
271@sp 2
272@center Second Edition
273@sp 4
274@center by Robert J. Chassell
275
276@page
277@vskip 0pt plus 1filll
b1bd267c 278@insertcopying
8b096dce
EZ
279@end titlepage
280
281@iftex
282@headings off
283@evenheading @thispage @| @| @thischapter
284@oddheading @thissection @| @| @thispage
285@end iftex
286
475dc40a 287@ifnothtml
8b096dce 288
475dc40a
EZ
289@c Keep T.O.C. short by tightening up.
290@ifset largebook
291@tex
292\global\parskip 2pt plus 1pt
293\global\advance\baselineskip by -1pt
294@end tex
295@end ifset
8b096dce 296
475dc40a
EZ
297@shortcontents
298@contents
299
300@ifset largebook
301@tex
302\global\parskip 6pt plus 1pt
303\global\advance\baselineskip by 1pt
304@end tex
305@end ifset
306
307@end ifnothtml
8b096dce
EZ
308
309@c >>>> Set pageno appropriately <<<<
310
311@c The first page of the Preface is a roman numeral; it is the first
312@c right handed page after the Table of Contents; hence the following
313@c setting must be for an odd negative number.
314
315@c if largebook, there are 8 pages in Table of Contents
316@ifset largebook
317@iftex
318@pageno = -9
319@end iftex
320@end ifset
321
322@c if smallbook, there are 10 pages in Table of Contents
323@ifclear largebook
324@iftex
325@pageno = -11
326@end iftex
327@end ifclear
328
475dc40a
EZ
329@ifnottex
330@node Top, Preface, (dir), (dir)
331@top An Introduction to Programming in Emacs Lisp
332
b1bd267c 333@insertcopying
475dc40a
EZ
334
335This master menu first lists each chapter and index; then it lists
336every node in every chapter.
337@end ifnottex
338
8b096dce
EZ
339@menu
340* Preface:: What to look for.
341* List Processing:: What is Lisp?
342* Practicing Evaluation:: Running several programs.
343* Writing Defuns:: How to write function definitions.
344* Buffer Walk Through:: Exploring a few buffer-related functions.
345* More Complex:: A few, even more complex functions.
346* Narrowing & Widening:: Restricting your and Emacs attention to
347 a region.
348* car cdr & cons:: Fundamental functions in Lisp.
349* Cutting & Storing Text:: Removing text and saving it.
350* List Implementation:: How lists are implemented in the computer.
351* Yanking:: Pasting stored text.
352* Loops & Recursion:: How to repeat a process.
353* Regexp Search:: Regular expression searches.
354* Counting Words:: A review of repetition and regexps.
355* Words in a defun:: Counting words in a @code{defun}.
356* Readying a Graph:: A prototype graph printing function.
357* Emacs Initialization:: How to write a @file{.emacs} file.
358* Debugging:: How to run the Emacs Lisp debuggers.
359* Conclusion:: Now you have the basics.
360* the-the:: An appendix: how to find reduplicated words.
361* Kill Ring:: An appendix: how the kill ring works.
362* Full Graph:: How to create a graph with labelled axes.
363* GNU Free Documentation License::
364* Index::
365* About the Author::
366
367@detailmenu
368 --- The Detailed Node Listing ---
369
370Preface
371
372* Why:: Why learn Emacs Lisp?
373* On Reading this Text:: Read, gain familiarity, pick up habits....
374* Who You Are:: For whom this is written.
375* Lisp History::
376* Note for Novices:: You can read this as a novice.
377* Thank You::
378
379List Processing
380
381* Lisp Lists:: What are lists?
382* Run a Program:: Any list in Lisp is a program ready to run.
383* Making Errors:: Generating an error message.
384* Names & Definitions:: Names of symbols and function definitions.
385* Lisp Interpreter:: What the Lisp interpreter does.
386* Evaluation:: Running a program.
387* Variables:: Returning a value from a variable.
388* Arguments:: Passing information to a function.
389* set & setq:: Setting the value of a variable.
390* Summary:: The major points.
391* Error Message Exercises::
392
393Lisp Lists
394
395* Numbers Lists:: List have numbers, other lists, in them.
396* Lisp Atoms:: Elemental entities.
397* Whitespace in Lists:: Formating lists to be readable.
398* Typing Lists:: How GNU Emacs helps you type lists.
399
400The Lisp Interpreter
401
402* Complications:: Variables, Special forms, Lists within.
403* Byte Compiling:: Specially processing code for speed.
404
405Evaluation
406
407* Evaluating Inner Lists:: Lists within lists...
408
409Variables
410
411* fill-column Example::
412* Void Function:: The error message for a symbol
413 without a function.
414* Void Variable:: The error message for a symbol without a value.
415
416Arguments
417
418* Data types:: Types of data passed to a function.
419* Args as Variable or List:: An argument can be the value
420 of a variable or list.
421* Variable Number of Arguments:: Some functions may take a
422 variable number of arguments.
423* Wrong Type of Argument:: Passing an argument of the wrong type
424 to a function.
425* message:: A useful function for sending messages.
426
427Setting the Value of a Variable
428
429* Using set:: Setting values.
430* Using setq:: Setting a quoted value.
431* Counting:: Using @code{setq} to count.
432
433Practicing Evaluation
434
435* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
436 causes evaluation.
437* Buffer Names:: Buffers and files are different.
438* Getting Buffers:: Getting a buffer itself, not merely its name.
439* Switching Buffers:: How to change to another buffer.
440* Buffer Size & Locations:: Where point is located and the size of
441 the buffer.
442* Evaluation Exercise::
443
444How To Write Function Definitions
445
446* Primitive Functions::
447* defun:: The @code{defun} special form.
448* Install:: Install a function definition.
449* Interactive:: Making a function interactive.
450* Interactive Options:: Different options for @code{interactive}.
451* Permanent Installation:: Installing code permanently.
452* let:: Creating and initializing local variables.
453* if:: What if?
454* else:: If--then--else expressions.
455* Truth & Falsehood:: What Lisp considers false and true.
456* save-excursion:: Keeping track of point, mark, and buffer.
457* Review::
458* defun Exercises::
459
460Install a Function Definition
461
462* Effect of installation::
463* Change a defun:: How to change a function definition.
464
465Make a Function Interactive
466
467* Interactive multiply-by-seven:: An overview.
468* multiply-by-seven in detail:: The interactive version.
469
470@code{let}
471
472* Prevent confusion::
473* Parts of let Expression::
474* Sample let Expression::
475* Uninitialized let Variables::
476
477The @code{if} Special Form
478
479* if in more detail::
480* type-of-animal in detail:: An example of an @code{if} expression.
481
482Truth and Falsehood in Emacs Lisp
483
484* nil explained:: @code{nil} has two meanings.
485
486@code{save-excursion}
487
488* Point and mark:: A review of various locations.
489* Template for save-excursion::
490
491A Few Buffer--Related Functions
492
493* Finding More:: How to find more information.
494* simplified-beginning-of-buffer:: Shows @code{goto-char},
495 @code{point-min}, and @code{push-mark}.
496* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
497* append-to-buffer:: Uses @code{save-excursion} and
498 @code{insert-buffer-substring}.
499* Buffer Related Review:: Review.
500* Buffer Exercises::
501
502The Definition of @code{mark-whole-buffer}
503
504* mark-whole-buffer overview::
505* Body of mark-whole-buffer:: Only three lines of code.
506
507The Definition of @code{append-to-buffer}
508
509* append-to-buffer overview::
510* append interactive:: A two part interactive expression.
511* append-to-buffer body:: Incorporates a @code{let} expression.
512* append save-excursion:: How the @code{save-excursion} works.
513
514A Few More Complex Functions
515
516* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
517* insert-buffer:: Read-only, and with @code{or}.
518* beginning-of-buffer:: Shows @code{goto-char},
519 @code{point-min}, and @code{push-mark}.
520* Second Buffer Related Review::
521* optional Exercise::
522
523The Definition of @code{insert-buffer}
524
525* insert-buffer code::
526* insert-buffer interactive:: When you can read, but not write.
527* insert-buffer body:: The body has an @code{or} and a @code{let}.
528* if & or:: Using an @code{if} instead of an @code{or}.
529* Insert or:: How the @code{or} expression works.
530* Insert let:: Two @code{save-excursion} expressions.
531
532The Interactive Expression in @code{insert-buffer}
533
534* Read-only buffer:: When a buffer cannot be modified.
535* b for interactive:: An existing buffer or else its name.
536
537Complete Definition of @code{beginning-of-buffer}
538
539* Optional Arguments::
540* beginning-of-buffer opt arg:: Example with optional argument.
541* beginning-of-buffer complete::
542
543@code{beginning-of-buffer} with an Argument
544
545* Disentangle beginning-of-buffer::
546* Large buffer case::
547* Small buffer case::
548
549Narrowing and Widening
550
551* Narrowing advantages:: The advantages of narrowing
552* save-restriction:: The @code{save-restriction} special form.
553* what-line:: The number of the line that point is on.
554* narrow Exercise::
555
556@code{car}, @code{cdr}, @code{cons}: Fundamental Functions
557
558* Strange Names:: An historical aside: why the strange names?
559* car & cdr:: Functions for extracting part of a list.
560* cons:: Constructing a list.
561* nthcdr:: Calling @code{cdr} repeatedly.
562* nth::
563* setcar:: Changing the first element of a list.
564* setcdr:: Changing the rest of a list.
565* cons Exercise::
566
567@code{cons}
568
569* Build a list::
570* length:: How to find the length of a list.
571
572Cutting and Storing Text
573
574* Storing Text:: Text is stored in a list.
575* zap-to-char:: Cutting out text up to a character.
576* kill-region:: Cutting text out of a region.
577* Digression into C:: Minor note on C programming language macros.
578* defvar:: How to give a variable an initial value.
579* copy-region-as-kill:: A definition for copying text.
580* cons & search-fwd Review::
581* search Exercises::
582
583@code{zap-to-char}
584
585* Complete zap-to-char:: The complete implementation.
586* zap-to-char interactive:: A three part interactive expression.
587* zap-to-char body:: A short overview.
588* search-forward:: How to search for a string.
589* progn:: The @code{progn} special form.
590* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
591
592@code{kill-region}
593
594* Complete kill-region:: The function definition.
595* condition-case:: Dealing with a problem.
596* delete-and-extract-region:: Doing the work.
597
598Initializing a Variable with @code{defvar}
599
600* See variable current value::
601* defvar and asterisk:: An old-time convention.
602
603@code{copy-region-as-kill}
604
605* Complete copy-region-as-kill:: The complete function definition.
606* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
607
608The Body of @code{copy-region-as-kill}
609
610* last-command & this-command::
611* kill-append function::
612* kill-new function::
613
614How Lists are Implemented
615
616* Lists diagrammed::
617* Symbols as Chest:: Exploring a powerful metaphor.
618* List Exercise::
619
620Yanking Text Back
621
622* Kill Ring Overview:: The kill ring is a list.
623* kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
624* yank nthcdr Exercises::
625
626Loops and Recursion
627
628* while:: Causing a stretch of code to repeat.
629* dolist dotimes::
630* Recursion:: Causing a function to call itself.
631* Looping exercise::
632
633@code{while}
634
635* Looping with while:: Repeat so long as test returns true.
636* Loop Example:: A @code{while} loop that uses a list.
637* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
638* Incrementing Loop:: A loop with an incrementing counter.
639* Decrementing Loop:: A loop with a decrementing counter.
640
641A Loop with an Incrementing Counter
642
643* Incrementing Example:: Counting pebbles in a triangle.
644* Inc Example parts:: The parts of the function definition.
645* Inc Example altogether:: Putting the function definition together.
646
647Loop with a Decrementing Counter
648
649* Decrementing Example:: More pebbles on the beach.
650* Dec Example parts:: The parts of the function definition.
651* Dec Example altogether:: Putting the function definition together.
652
653Save your time: @code{dolist} and @code{dotimes}
654
655* dolist::
656* dotimes::
657
658Recursion
659
660* Building Robots:: Same model, different serial number ...
661* Recursive Definition Parts:: Walk until you stop ...
662* Recursion with list:: Using a list as the test whether to recurse.
663* Recursive triangle function::
664* Recursion with cond::
665* Recursive Patterns:: Often used templates.
666* No Deferment:: Don't store up work ...
667* No deferment solution::
668
669Recursion in Place of a Counter
670
671* Recursive Example arg of 1 or 2::
672* Recursive Example arg of 3 or 4::
673
674Recursive Patterns
675
676* Every::
677* Accumulate::
678* Keep::
679
680Regular Expression Searches
681
682* sentence-end:: The regular expression for @code{sentence-end}.
683* re-search-forward:: Very similar to @code{search-forward}.
684* forward-sentence:: A straightforward example of regexp search.
685* forward-paragraph:: A somewhat complex example.
686* etags:: How to create your own @file{TAGS} table.
687* Regexp Review::
688* re-search Exercises::
689
690@code{forward-sentence}
691
692* Complete forward-sentence::
693* fwd-sentence while loops:: Two @code{while} loops.
694* fwd-sentence re-search:: A regular expression search.
695
696@code{forward-paragraph}: a Goldmine of Functions
697
698* forward-paragraph in brief:: Key parts of the function definition.
699* fwd-para let:: The @code{let*} expression.
700* fwd-para while:: The forward motion @code{while} loop.
701* fwd-para between paragraphs:: Movement between paragraphs.
702* fwd-para within paragraph:: Movement within paragraphs.
703* fwd-para no fill prefix:: When there is no fill prefix.
704* fwd-para with fill prefix:: When there is a fill prefix.
705* fwd-para summary:: Summary of @code{forward-paragraph} code.
706
707Counting: Repetition and Regexps
708
709* Why Count Words::
710* count-words-region:: Use a regexp, but find a problem.
711* recursive-count-words:: Start with case of no words in region.
712* Counting Exercise::
713
714The @code{count-words-region} Function
715
716* Design count-words-region:: The definition using a @code{while} loop.
717* Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
718
719Counting Words in a @code{defun}
720
721* Divide and Conquer::
722* Words and Symbols:: What to count?
723* Syntax:: What constitutes a word or symbol?
724* count-words-in-defun:: Very like @code{count-words}.
725* Several defuns:: Counting several defuns in a file.
726* Find a File:: Do you want to look at a file?
727* lengths-list-file:: A list of the lengths of many definitions.
728* Several files:: Counting in definitions in different files.
729* Several files recursively:: Recursively counting in different files.
730* Prepare the data:: Prepare the data for display in a graph.
731
732Count Words in @code{defuns} in Different Files
733
734* lengths-list-many-files:: Return a list of the lengths of defuns.
735* append:: Attach one list to another.
736
737Prepare the Data for Display in a Graph
738
739* Sorting:: Sorting lists.
740* Files List:: Making a list of files.
741* Counting function definitions::
742
743Readying a Graph
744
745* Columns of a graph::
746* graph-body-print:: How to print the body of a graph.
747* recursive-graph-body-print::
748* Printed Axes::
749* Line Graph Exercise::
750
751Your @file{.emacs} File
752
753* Default Configuration::
754* Site-wide Init:: You can write site-wide init files.
755* defcustom:: Emacs will write code for you.
756* Beginning a .emacs File:: How to write a @code{.emacs file}.
757* Text and Auto-fill:: Automatically wrap lines.
758* Mail Aliases:: Use abbreviations for email addresses.
759* Indent Tabs Mode:: Don't use tabs with @TeX{}
760* Keybindings:: Create some personal keybindings.
761* Keymaps:: More about key binding.
762* Loading Files:: Load (i.e., evaluate) files automatically.
763* Autoload:: Make functions available.
764* Simple Extension:: Define a function; bind it to a key.
765* X11 Colors:: Colors in version 19 in X.
766* Miscellaneous::
767* Mode Line:: How to customize your mode line.
768
769Debugging
770
771* debug:: How to use the built-in debugger.
772* debug-on-entry:: Start debugging when you call a function.
773* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
774* edebug:: How to use Edebug, a source level debugger.
775* Debugging Exercises::
776
777Handling the Kill Ring
778
779* rotate-yank-pointer:: Move a pointer along a list and around.
780* yank:: Paste a copy of a clipped element.
781* yank-pop:: Insert first element pointed to.
782
783The @code{rotate-yank-pointer} Function
784
785* Understanding rotate-yk-ptr::
786* rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
787
788The Body of @code{rotate-yank-pointer}
789
790* Digression concerning error:: How to mislead humans, but not computers.
791* rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
792* Remainder Function:: The remainder, @code{%}, function.
793* rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
794* kill-rng-yk-ptr last elt:: Pointing to the last element.
795
796@code{yank}
797
798* rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
799* rotate-yk-ptr negative arg:: Pass a negative argument.
800
801A Graph with Labelled Axes
802
803* Labelled Example::
804* print-graph Varlist:: @code{let} expression in @code{print-graph}.
805* print-Y-axis:: Print a label for the vertical axis.
806* print-X-axis:: Print a horizontal label.
807* Print Whole Graph:: The function to print a complete graph.
808
809The @code{print-Y-axis} Function
810
811* Height of label:: What height for the Y axis?
812* Compute a Remainder:: How to compute the remainder of a division.
813* Y Axis Element:: Construct a line for the Y axis.
814* Y-axis-column:: Generate a list of Y axis labels.
815* print-Y-axis Penultimate:: A not quite final version.
816
817The @code{print-X-axis} Function
818
819* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
820* X Axis Tic Marks:: Create tic marks for the horizontal axis.
821
822Printing the Whole Graph
823
824* The final version:: A few changes.
825* Test print-graph:: Run a short test.
826* Graphing words in defuns:: Executing the final code.
827* lambda:: How to write an anonymous function.
828* mapcar:: Apply a function to elements of a list.
829* Another Bug:: Yet another bug @dots{} most insidious.
830* Final printed graph:: The graph itself!
831
832@end detailmenu
833@end menu
834
835@node Preface, List Processing, Top, Top
836@comment node-name, next, previous, up
837@unnumbered Preface
838
839Most of the GNU Emacs integrated environment is written in the programming
840language called Emacs Lisp. The code written in this programming
841language is the software---the sets of instructions---that tell the
842computer what to do when you give it commands. Emacs is designed so
843that you can write new code in Emacs Lisp and easily install it as an
844extension to the editor.
845
846(GNU Emacs is sometimes called an ``extensible editor'', but it does
847much more than provide editing capabilities. It is better to refer to
848Emacs as an ``extensible computing environment''. However, that
849phrase is quite a mouthful. It is easier to refer to Emacs simply as
850an editor. Moreover, everything you do in Emacs---find the Mayan date
851and phases of the moon, simplify polynomials, debug code, manage
852files, read letters, write books---all these activities are kinds of
853editing in the most general sense of the word.)
854
855@menu
856* Why:: Why learn Emacs Lisp?
857* On Reading this Text:: Read, gain familiarity, pick up habits....
858* Who You Are:: For whom this is written.
859* Lisp History::
860* Note for Novices:: You can read this as a novice.
861* Thank You::
862@end menu
863
864@node Why, On Reading this Text, Preface, Preface
865@ifnottex
866@unnumberedsec Why Study Emacs Lisp?
867@end ifnottex
868
869Although Emacs Lisp is usually thought of in association only with Emacs,
870it is a full computer programming language. You can use Emacs Lisp as
871you would any other programming language.
872
873Perhaps you want to understand programming; perhaps you want to extend
874Emacs; or perhaps you want to become a programmer. This introduction to
875Emacs Lisp is designed to get you started: to guide you in learning the
876fundamentals of programming, and more importantly, to show you how you
877can teach yourself to go further.
878
879@node On Reading this Text, Who You Are, Why, Preface
880@comment node-name, next, previous, up
881@unnumberedsec On Reading this Text
882
883All through this document, you will see little sample programs you can
884run inside of Emacs. If you read this document in Info inside of GNU
885Emacs, you can run the programs as they appear. (This is easy to do and
886is explained when the examples are presented.) Alternatively, you can
887read this introduction as a printed book while sitting beside a computer
888running Emacs. (This is what I like to do; I like printed books.) If
889you don't have a running Emacs beside you, you can still read this book,
890but in this case, it is best to treat it as a novel or as a travel guide
891to a country not yet visited: interesting, but not the same as being
892there.
893
894Much of this introduction is dedicated to walk-throughs or guided tours
895of code used in GNU Emacs. These tours are designed for two purposes:
896first, to give you familiarity with real, working code (code you use
897every day); and, second, to give you familiarity with the way Emacs
898works. It is interesting to see how a working environment is
899implemented.
900Also, I
901hope that you will pick up the habit of browsing through source code.
902You can learn from it and mine it for ideas. Having GNU Emacs is like
903having a dragon's cave of treasures.
904
905In addition to learning about Emacs as an editor and Emacs Lisp as a
906programming language, the examples and guided tours will give you an
907opportunity to get acquainted with Emacs as a Lisp programming
908environment. GNU Emacs supports programming and provides tools that
909you will want to become comfortable using, such as @kbd{M-.} (the key
910which invokes the @code{find-tag} command). You will also learn about
911buffers and other objects that are part of the environment.
912Learning about these features of Emacs is like learning new routes
913around your home town.
914
915@ignore
916In addition, I have written several programs as extended examples.
917Although these are examples, the programs are real. I use them.
918Other people use them. You may use them. Beyond the fragments of
919programs used for illustrations, there is very little in here that is
920`just for teaching purposes'; what you see is used. This is a great
921advantage of Emacs Lisp: it is easy to learn to use it for work.
922@end ignore
923
924Finally, I hope to convey some of the skills for using Emacs to
925learn aspects of programming that you don't know. You can often use
926Emacs to help you understand what puzzles you or to find out how to do
927something new. This self-reliance is not only a pleasure, but an
928advantage.
929
930@node Who You Are, Lisp History, On Reading this Text, Preface
931@comment node-name, next, previous, up
932@unnumberedsec For Whom This is Written
933
934This text is written as an elementary introduction for people who are
935not programmers. If you are a programmer, you may not be satisfied with
936this primer. The reason is that you may have become expert at reading
937reference manuals and be put off by the way this text is organized.
938
939An expert programmer who reviewed this text said to me:
940
941@quotation
942@i{I prefer to learn from reference manuals. I ``dive into'' each
943paragraph, and ``come up for air'' between paragraphs.}
944
945@i{When I get to the end of a paragraph, I assume that that subject is
946done, finished, that I know everything I need (with the
947possible exception of the case when the next paragraph starts talking
948about it in more detail). I expect that a well written reference manual
949will not have a lot of redundancy, and that it will have excellent
950pointers to the (one) place where the information I want is.}
951@end quotation
952
953This introduction is not written for this person!
954
955Firstly, I try to say everything at least three times: first, to
956introduce it; second, to show it in context; and third, to show it in a
957different context, or to review it.
958
959Secondly, I hardly ever put all the information about a subject in one
960place, much less in one paragraph. To my way of thinking, that imposes
961too heavy a burden on the reader. Instead I try to explain only what
962you need to know at the time. (Sometimes I include a little extra
963information so you won't be surprised later when the additional
964information is formally introduced.)
965
966When you read this text, you are not expected to learn everything the
967first time. Frequently, you need only make, as it were, a `nodding
968acquaintance' with some of the items mentioned. My hope is that I have
969structured the text and given you enough hints that you will be alert to
970what is important, and concentrate on it.
971
972You will need to ``dive into'' some paragraphs; there is no other way
973to read them. But I have tried to keep down the number of such
974paragraphs. This book is intended as an approachable hill, rather than
975as a daunting mountain.
976
977This introduction to @cite{Programming in Emacs Lisp} has a companion
978document,
979@iftex
980@cite{The GNU Emacs Lisp Reference Manual}.
981@end iftex
982@ifnottex
983@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
984Emacs Lisp Reference Manual}.
985@end ifnottex
986The reference manual has more detail than this introduction. In the
987reference manual, all the information about one topic is concentrated
988in one place. You should turn to it if you are like the programmer
989quoted above. And, of course, after you have read this
990@cite{Introduction}, you will find the @cite{Reference Manual} useful
991when you are writing your own programs.
992
993@node Lisp History, Note for Novices, Who You Are, Preface
994@unnumberedsec Lisp History
995@cindex Lisp history
996
997Lisp was first developed in the late 1950s at the Massachusetts
998Institute of Technology for research in artificial intelligence. The
999great power of the Lisp language makes it superior for other purposes as
1000well, such as writing editor commands and integrated environments.
1001
1002@cindex Maclisp
1003@cindex Common Lisp
1004GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1005in the 1960s. It is somewhat inspired by Common Lisp, which became a
1006standard in the 1980s. However, Emacs Lisp is much simpler than Common
1007Lisp. (The standard Emacs distribution contains an optional extensions
1008file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1009
1010@node Note for Novices, Thank You, Lisp History, Preface
1011@comment node-name, next, previous, up
1012@unnumberedsec A Note for Novices
1013
1014If you don't know GNU Emacs, you can still read this document
1015profitably. However, I recommend you learn Emacs, if only to learn to
1016move around your computer screen. You can teach yourself how to use
1017Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1018means you press and release the @key{CTRL} key and the @kbd{h} at the
1019same time, and then press and release @kbd{t}.)
1020
1021Also, I often refer to one of Emacs' standard commands by listing the
1022keys which you press to invoke the command and then giving the name of
1023the command in parentheses, like this: @kbd{M-C-\}
1024(@code{indent-region}). What this means is that the
1025@code{indent-region} command is customarily invoked by typing
1026@kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1027invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1028Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1029@key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1030(On many modern keyboards the @key{META} key is labelled
1031@key{ALT}.)
1032Sometimes a combination like this is called a keychord, since it is
1033similar to the way you play a chord on a piano. If your keyboard does
1034not have a @key{META} key, the @key{ESC} key prefix is used in place
1035of it. In this case, @kbd{M-C-\} means that you press and release your
1036@key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1037the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
1038along with the key that is labelled @key{ALT} and, at the same time,
1039press the @key{\} key.
1040
1041In addition to typing a lone keychord, you can prefix what you type
1042with @kbd{C-u}, which is called the `universal argument'. The
1043@kbd{C-u} keychord passes an argument to the subsequent command.
1044Thus, to indent a region of plain text by 6 spaces, mark the region,
1045and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1046Emacs either passes the number 4 to the command or otherwise runs the
1047command differently than it would otherwise.) @xref{Arguments, ,
1048Numeric Arguments, emacs, The GNU Emacs Manual}.
1049
1050If you are reading this in Info using GNU Emacs, you can read through
1051this whole document just by pressing the space bar, @key{SPC}.
1052(To learn about Info, type @kbd{C-h i} and then select Info.)
1053
1054A note on terminology: when I use the word Lisp alone, I often am
1055referring to the various dialects of Lisp in general, but when I speak
1056of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1057
1058@node Thank You, , Note for Novices, Preface
1059@comment node-name, next, previous, up
1060@unnumberedsec Thank You
1061
1062My thanks to all who helped me with this book. My especial thanks to
1063@r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1064McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1065Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1066@w{Philip Johnson} and @w{David Stampe} for their patient
1067encouragement. My mistakes are my own.
1068
1069@flushright
1070Robert J. Chassell
1071@end flushright
1072
1073@c ================ Beginning of main text ================
1074
1075@c Start main text on right-hand (verso) page
1076
1077@tex
1078\par\vfill\supereject
1079\headings off
1080\ifodd\pageno
1081 \par\vfill\supereject
1082\else
1083 \par\vfill\supereject
1084 \page\hbox{}\page
1085 \par\vfill\supereject
1086\fi
1087@end tex
1088
1089@iftex
1090@headings off
1091@evenheading @thispage @| @| @thischapter
1092@oddheading @thissection @| @| @thispage
1093@pageno = 1
1094@end iftex
1095
1096@node List Processing, Practicing Evaluation, Preface, Top
1097@comment node-name, next, previous, up
1098@chapter List Processing
1099
1100To the untutored eye, Lisp is a strange programming language. In Lisp
1101code there are parentheses everywhere. Some people even claim that the
1102name stands for `Lots of Isolated Silly Parentheses'. But the claim is
1103unwarranted. Lisp stands for LISt Processing, and the programming
1104language handles @emph{lists} (and lists of lists) by putting them
1105between parentheses. The parentheses mark the boundaries of the list.
1106Sometimes a list is preceded by a single apostrophe or quotation mark,
1107@samp{'}. Lists are the basis of Lisp.
1108
1109@menu
1110* Lisp Lists:: What are lists?
1111* Run a Program:: Any list in Lisp is a program ready to run.
1112* Making Errors:: Generating an error message.
1113* Names & Definitions:: Names of symbols and function definitions.
1114* Lisp Interpreter:: What the Lisp interpreter does.
1115* Evaluation:: Running a program.
1116* Variables:: Returning a value from a variable.
1117* Arguments:: Passing information to a function.
1118* set & setq:: Setting the value of a variable.
1119* Summary:: The major points.
1120* Error Message Exercises::
1121@end menu
1122
1123@node Lisp Lists, Run a Program, List Processing, List Processing
1124@comment node-name, next, previous, up
1125@section Lisp Lists
1126@cindex Lisp Lists
1127
1128In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1129This list is preceded by a single apostrophe. It could just as well be
1130written as follows, which looks more like the kind of list you are likely
1131to be familiar with:
1132
1133@smallexample
1134@group
1135'(rose
1136 violet
1137 daisy
1138 buttercup)
1139@end group
1140@end smallexample
1141
1142@noindent
1143The elements of this list are the names of the four different flowers,
1144separated from each other by whitespace and surrounded by parentheses,
1145like flowers in a field with a stone wall around them.
1146@cindex Flowers in a field
1147
1148@menu
1149* Numbers Lists:: List have numbers, other lists, in them.
1150* Lisp Atoms:: Elemental entities.
1151* Whitespace in Lists:: Formating lists to be readable.
1152* Typing Lists:: How GNU Emacs helps you type lists.
1153@end menu
1154
1155@node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1156@ifnottex
1157@unnumberedsubsec Numbers, Lists inside of Lists
1158@end ifnottex
1159
1160Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1161This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1162separated by whitespace.
1163
1164In Lisp, both data and programs are represented the same way; that is,
1165they are both lists of words, numbers, or other lists, separated by
1166whitespace and surrounded by parentheses. (Since a program looks like
1167data, one program may easily serve as data for another; this is a very
1168powerful feature of Lisp.) (Incidentally, these two parenthetical
1169remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1170@samp{.} as punctuation marks.)
1171
1172@need 1200
1173Here is another list, this time with a list inside of it:
1174
1175@smallexample
1176'(this list has (a list inside of it))
1177@end smallexample
1178
1179The components of this list are the words @samp{this}, @samp{list},
1180@samp{has}, and the list @samp{(a list inside of it)}. The interior
1181list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1182@samp{of}, @samp{it}.
1183
1184@node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1185@comment node-name, next, previous, up
1186@subsection Lisp Atoms
1187@cindex Lisp Atoms
1188
1189In Lisp, what we have been calling words are called @dfn{atoms}. This
1190term comes from the historical meaning of the word atom, which means
1191`indivisible'. As far as Lisp is concerned, the words we have been
1192using in the lists cannot be divided into any smaller parts and still
1193mean the same thing as part of a program; likewise with numbers and
1194single character symbols like @samp{+}. On the other hand, unlike an
1195atom, a list can be split into parts. (@xref{car cdr & cons, ,
1196@code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1197
1198In a list, atoms are separated from each other by whitespace. They can be
1199right next to a parenthesis.
1200
1201@cindex @samp{empty list} defined
1202Technically speaking, a list in Lisp consists of parentheses surrounding
1203atoms separated by whitespace or surrounding other lists or surrounding
1204both atoms and other lists. A list can have just one atom in it or
1205have nothing in it at all. A list with nothing in it looks like this:
1206@code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1207empty list is considered both an atom and a list at the same time.
1208
1209@cindex Symbolic expressions, introduced
1210@cindex @samp{expression} defined
1211@cindex @samp{form} defined
1212The printed representation of both atoms and lists are called
1213@dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1214The word @dfn{expression} by itself can refer to either the printed
1215representation, or to the atom or list as it is held internally in the
1216computer. Often, people use the term @dfn{expression}
1217indiscriminately. (Also, in many texts, the word @dfn{form} is used
1218as a synonym for expression.)
1219
1220Incidentally, the atoms that make up our universe were named such when
1221they were thought to be indivisible; but it has been found that physical
1222atoms are not indivisible. Parts can split off an atom or it can
1223fission into two parts of roughly equal size. Physical atoms were named
1224prematurely, before their truer nature was found. In Lisp, certain
1225kinds of atom, such as an array, can be separated into parts; but the
1226mechanism for doing this is different from the mechanism for splitting a
1227list. As far as list operations are concerned, the atoms of a list are
1228unsplittable.
1229
1230As in English, the meanings of the component letters of a Lisp atom
1231are different from the meaning the letters make as a word. For
1232example, the word for the South American sloth, the @samp{ai}, is
1233completely different from the two words, @samp{a}, and @samp{i}.
1234
1235There are many kinds of atom in nature but only a few in Lisp: for
1236example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1237as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1238listed in the examples above are all symbols. In everyday Lisp
1239conversation, the word ``atom'' is not often used, because programmers
1240usually try to be more specific about what kind of atom they are dealing
1241with. Lisp programming is mostly about symbols (and sometimes numbers)
1242within lists. (Incidentally, the preceding three word parenthetical
1243remark is a proper list in Lisp, since it consists of atoms, which in
1244this case are symbols, separated by whitespace and enclosed by
1245parentheses, without any non-Lisp punctuation.)
1246
1247@need 1250
1248In addition, text between double quotation marks---even sentences or
1249paragraphs---is an atom. Here is an example:
1250@cindex Text between double quotation marks
1251
1252@smallexample
1253'(this list includes "text between quotation marks.")
1254@end smallexample
1255
1256@cindex @samp{string} defined
1257@noindent
1258In Lisp, all of the quoted text including the punctuation mark and the
1259blank spaces is a single atom. This kind of atom is called a
1260@dfn{string} (for `string of characters') and is the sort of thing that
1261is used for messages that a computer can print for a human to read.
1262Strings are a different kind of atom than numbers or symbols and are
1263used differently.
1264
1265@node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1266@comment node-name, next, previous, up
1267@subsection Whitespace in Lists
1268@cindex Whitespace in lists
1269
1270@need 1200
1271The amount of whitespace in a list does not matter. From the point of view
1272of the Lisp language,
1273
1274@smallexample
1275@group
1276'(this list
1277 looks like this)
1278@end group
1279@end smallexample
1280
1281@need 800
1282@noindent
1283is exactly the same as this:
1284
1285@smallexample
1286'(this list looks like this)
1287@end smallexample
1288
1289Both examples show what to Lisp is the same list, the list made up of
1290the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1291@samp{this} in that order.
1292
1293Extra whitespace and newlines are designed to make a list more readable
1294by humans. When Lisp reads the expression, it gets rid of all the extra
1295whitespace (but it needs to have at least one space between atoms in
1296order to tell them apart.)
1297
1298Odd as it seems, the examples we have seen cover almost all of what Lisp
1299lists look like! Every other list in Lisp looks more or less like one
1300of these examples, except that the list may be longer and more complex.
1301In brief, a list is between parentheses, a string is between quotation
1302marks, a symbol looks like a word, and a number looks like a number.
1303(For certain situations, square brackets, dots and a few other special
1304characters may be used; however, we will go quite far without them.)
1305
1306@node Typing Lists, , Whitespace in Lists, Lisp Lists
1307@comment node-name, next, previous, up
1308@subsection GNU Emacs Helps You Type Lists
1309@cindex Help typing lists
1310@cindex Formatting help
1311
1312When you type a Lisp expression in GNU Emacs using either Lisp
1313Interaction mode or Emacs Lisp mode, you have available to you several
1314commands to format the Lisp expression so it is easy to read. For
1315example, pressing the @key{TAB} key automatically indents the line the
1316cursor is on by the right amount. A command to properly indent the
1317code in a region is customarily bound to @kbd{M-C-\}. Indentation is
e601d8fd 1318designed so that you can see which elements of a list belong to which
8b096dce
EZ
1319list---elements of a sub-list are indented more than the elements of
1320the enclosing list.
1321
1322In addition, when you type a closing parenthesis, Emacs momentarily
1323jumps the cursor back to the matching opening parenthesis, so you can
1324see which one it is. This is very useful, since every list you type
1325in Lisp must have its closing parenthesis match its opening
1326parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1327Manual}, for more information about Emacs' modes.)
1328
1329@node Run a Program, Making Errors, Lisp Lists, List Processing
1330@comment node-name, next, previous, up
1331@section Run a Program
1332@cindex Run a program
1333@cindex Program, running one
1334
1335@cindex @samp{evaluate} defined
1336A list in Lisp---any list---is a program ready to run. If you run it
1337(for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1338of three things: do nothing except return to you the list itself; send
1339you an error message; or, treat the first symbol in the list as a
1340command to do something. (Usually, of course, it is the last of these
1341three things that you really want!)
1342
1343@c use code for the single apostrophe, not samp.
1344The single apostrophe, @code{'}, that I put in front of some of the
1345example lists in preceding sections is called a @dfn{quote}; when it
1346precedes a list, it tells Lisp to do nothing with the list, other than
1347take it as it is written. But if there is no quote preceding a list,
1348the first item of the list is special: it is a command for the computer
1349to obey. (In Lisp, these commands are called @emph{functions}.) The list
1350@code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1351understands that the @code{+} is an instruction to do something with the
1352rest of the list: add the numbers that follow.
1353
1354@need 1250
1355If you are reading this inside of GNU Emacs in Info, here is how you can
1356evaluate such a list: place your cursor immediately after the right
1357hand parenthesis of the following list and then type @kbd{C-x C-e}:
1358
1359@smallexample
1360(+ 2 2)
1361@end smallexample
1362
1363@c use code for the number four, not samp.
1364@noindent
1365You will see the number @code{4} appear in the echo area. (In the
1366jargon, what you have just done is ``evaluate the list.'' The echo area
1367is the line at the bottom of the screen that displays or ``echoes''
1368text.) Now try the same thing with a quoted list: place the cursor
1369right after the following list and type @kbd{C-x C-e}:
1370
1371@smallexample
1372'(this is a quoted list)
1373@end smallexample
1374
1375@noindent
1376You will see @code{(this is a quoted list)} appear in the echo area.
1377
1378@cindex Lisp interpreter, explained
1379@cindex Interpreter, Lisp, explained
1380In both cases, what you are doing is giving a command to the program
1381inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1382interpreter a command to evaluate the expression. The name of the Lisp
1383interpreter comes from the word for the task done by a human who comes
1384up with the meaning of an expression---who ``interprets'' it.
1385
1386You can also evaluate an atom that is not part of a list---one that is
1387not surrounded by parentheses; again, the Lisp interpreter translates
1388from the humanly readable expression to the language of the computer.
1389But before discussing this (@pxref{Variables}), we will discuss what the
1390Lisp interpreter does when you make an error.
1391
1392@node Making Errors, Names & Definitions, Run a Program, List Processing
1393@comment node-name, next, previous, up
1394@section Generate an Error Message
1395@cindex Generate an error message
1396@cindex Error message generation
1397
1398Partly so you won't worry if you do it accidentally, we will now give
1399a command to the Lisp interpreter that generates an error message.
1400This is a harmless activity; and indeed, we will often try to generate
1401error messages intentionally. Once you understand the jargon, error
1402messages can be informative. Instead of being called ``error''
1403messages, they should be called ``help'' messages. They are like
1404signposts to a traveller in a strange country; deciphering them can be
1405hard, but once understood, they can point the way.
1406
1407The error message is generated by a built-in GNU Emacs debugger. We
1408will `enter the debugger'. You get out of the debugger by typing @code{q}.
1409
1410What we will do is evaluate a list that is not quoted and does not
1411have a meaningful command as its first element. Here is a list almost
1412exactly the same as the one we just used, but without the single-quote
1413in front of it. Position the cursor right after it and type @kbd{C-x
1414C-e}:
1415
1416@smallexample
1417(this is an unquoted list)
1418@end smallexample
1419
1420@noindent
1421What you see depends on which version of Emacs you are running. GNU
1422Emacs version 21 provides more information than version 20 and before.
1423First, the more recent result of generating an error; then the
1424earlier, version 20 result.
1425
1426@need 1250
1427@noindent
1428In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1429you will see the following in it:
1430
1431@smallexample
1432@group
1433---------- Buffer: *Backtrace* ----------
1434Debugger entered--Lisp error: (void-function this)
1435 (this is an unquoted list)
1436 eval((this is an unquoted list))
1437 eval-last-sexp-1(nil)
1438 eval-last-sexp(nil)
1439 call-interactively(eval-last-sexp)
1440---------- Buffer: *Backtrace* ----------
1441@end group
1442@end smallexample
1443
1444@need 1200
1445@noindent
1446Your cursor will be in this window (you may have to wait a few seconds
1447before it becomes visible). To quit the debugger and make the
1448debugger window go away, type:
1449
1450@smallexample
1451q
1452@end smallexample
1453
1454@noindent
1455Please type @kbd{q} right now, so you become confident that you can
1456get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1457it.
1458
1459@cindex @samp{function} defined
1460Based on what we already know, we can almost read this error message.
1461
1462You read the @file{*Backtrace*} buffer from the bottom up; it tells
1463you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1464interactive call to the command @code{eval-last-sexp}. @code{eval} is
1465an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1466`symbolic expression'. The command means `evaluate last symbolic
1467expression', which is the expression just before your cursor.
1468
1469Each line above tells you what the Lisp interpreter evaluated next.
1470The most recent action is at the top. The buffer is called the
1471@file{*Backtrace*} buffer because it enables you to track Emacs
1472backwards.
1473
1474@need 800
1475At the top of the @file{*Backtrace*} buffer, you see the line:
1476
1477@smallexample
1478Debugger entered--Lisp error: (void-function this)
1479@end smallexample
1480
1481@noindent
1482The Lisp interpreter tried to evaluate the first atom of the list, the
1483word @samp{this}. It is this action that generated the error message
1484@samp{void-function this}.
1485
1486The message contains the words @samp{void-function} and @samp{this}.
1487
1488@cindex @samp{function} defined
1489The word @samp{function} was mentioned once before. It is a very
1490important word. For our purposes, we can define it by saying that a
1491@dfn{function} is a set of instructions to the computer that tell the
1492computer to do something.
1493
1494Now we can begin to understand the error message: @samp{void-function
1495this}. The function (that is, the word @samp{this}) does not have a
1496definition of any set of instructions for the computer to carry out.
1497
1498The slightly odd word, @samp{void-function}, is designed to cover the
1499way Emacs Lisp is implemented, which is that when a symbol does not
1500have a function definition attached to it, the place that should
1501contain the instructions is `void'.
1502
1503On the other hand, since we were able to add 2 plus 2 successfully, by
1504evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1505have a set of instructions for the computer to obey and those
1506instructions must be to add the numbers that follow the @code{+}.
1507
1508@need 1250
1509In GNU Emacs version 20, and in earlier versions, you will see only
1510one line of error message; it will appear in the echo area and look
1511like this:
1512
1513@smallexample
1514Symbol's function definition is void:@: this
1515@end smallexample
1516
1517@noindent
1518(Also, your terminal may beep at you---some do, some don't; and others
1519blink. This is just a device to get your attention.) The message goes
1520away as soon as you type another key, even just to move the cursor.
1521
1522We know the meaning of the word @samp{Symbol}. It refers to the first
1523atom of the list, the word @samp{this}. The word @samp{function}
1524refers to the instructions that tell the computer what to do.
1525(Technically, the symbol tells the computer where to find the
1526instructions, but this is a complication we can ignore for the
1527moment.)
1528
1529The error message can be understood: @samp{Symbol's function
1530definition is void:@: this}. The symbol (that is, the word
1531@samp{this}) lacks instructions for the computer to carry out.
1532
1533@node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1534@comment node-name, next, previous, up
1535@section Symbol Names and Function Definitions
1536@cindex Symbol names
1537
1538We can articulate another characteristic of Lisp based on what we have
1539discussed so far---an important characteristic: a symbol, like
1540@code{+}, is not itself the set of instructions for the computer to
1541carry out. Instead, the symbol is used, perhaps temporarily, as a way
1542of locating the definition or set of instructions. What we see is the
1543name through which the instructions can be found. Names of people
1544work the same way. I can be referred to as @samp{Bob}; however, I am
1545not the letters @samp{B}, @samp{o}, @samp{b} but am the consciousness
1546consistently associated with a particular life-form. The name is not
1547me, but it can be used to refer to me.
1548
1549In Lisp, one set of instructions can be attached to several names.
1550For example, the computer instructions for adding numbers can be
1551linked to the symbol @code{plus} as well as to the symbol @code{+}
1552(and are in some dialects of Lisp). Among humans, I can be referred
1553to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1554
1555On the other hand, a symbol can have only one function definition
1556attached to it at a time. Otherwise, the computer would be confused as
1557to which definition to use. If this were the case among people, only
1558one person in the world could be named @samp{Bob}. However, the function
1559definition to which the name refers can be changed readily.
1560(@xref{Install, , Install a Function Definition}.)
1561
1562Since Emacs Lisp is large, it is customary to name symbols in a way
1563that identifies the part of Emacs to which the function belongs.
1564Thus, all the names for functions that deal with Texinfo start with
1565@samp{texinfo-} and those for functions that deal with reading mail
1566start with @samp{rmail-}.
1567
1568@node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1569@comment node-name, next, previous, up
1570@section The Lisp Interpreter
1571@cindex Lisp interpreter, what it does
1572@cindex Interpreter, what it does
1573
1574Based on what we have seen, we can now start to figure out what the
1575Lisp interpreter does when we command it to evaluate a list.
1576First, it looks to see whether there is a quote before the list; if
1577there is, the interpreter just gives us the list. On the other
1578hand, if there is no quote, the interpreter looks at the first element
1579in the list and sees whether it has a function definition. If it does,
1580the interpreter carries out the instructions in the function definition.
1581Otherwise, the interpreter prints an error message.
1582
1583This is how Lisp works. Simple. There are added complications which we
1584will get to in a minute, but these are the fundamentals. Of course, to
1585write Lisp programs, you need to know how to write function definitions
1586and attach them to names, and how to do this without confusing either
1587yourself or the computer.
1588
1589@menu
1590* Complications:: Variables, Special forms, Lists within.
1591* Byte Compiling:: Specially processing code for speed.
1592@end menu
1593
1594@node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1595@ifnottex
1596@unnumberedsubsec Complications
1597@end ifnottex
1598
1599Now, for the first complication. In addition to lists, the Lisp
1600interpreter can evaluate a symbol that is not quoted and does not have
1601parentheses around it. The Lisp interpreter will attempt to determine
1602the symbol's value as a @dfn{variable}. This situation is described
1603in the section on variables. (@xref{Variables}.)
1604
1605@cindex Special form
1606The second complication occurs because some functions are unusual and do
1607not work in the usual manner. Those that don't are called @dfn{special
1608forms}. They are used for special jobs, like defining a function, and
1609there are not many of them. In the next few chapters, you will be
1610introduced to several of the more important special forms.
1611
1612The third and final complication is this: if the function that the
1613Lisp interpreter is looking at is not a special form, and if it is part
1614of a list, the Lisp interpreter looks to see whether the list has a list
1615inside of it. If there is an inner list, the Lisp interpreter first
1616figures out what it should do with the inside list, and then it works on
1617the outside list. If there is yet another list embedded inside the
1618inner list, it works on that one first, and so on. It always works on
1619the innermost list first. The interpreter works on the innermost list
1620first, to evaluate the result of that list. The result may be
1621used by the enclosing expression.
1622
1623Otherwise, the interpreter works left to right, from one expression to
1624the next.
1625
1626@node Byte Compiling, , Complications, Lisp Interpreter
1627@subsection Byte Compiling
1628@cindex Byte compiling
1629
1630One other aspect of interpreting: the Lisp interpreter is able to
1631interpret two kinds of entity: humanly readable code, on which we will
1632focus exclusively, and specially processed code, called @dfn{byte
1633compiled} code, which is not humanly readable. Byte compiled code
1634runs faster than humanly readable code.
1635
1636You can transform humanly readable code into byte compiled code by
1637running one of the compile commands such as @code{byte-compile-file}.
1638Byte compiled code is usually stored in a file that ends with a
1639@file{.elc} extension rather than a @file{.el} extension. You will
1640see both kinds of file in the @file{emacs/lisp} directory; the files
1641to read are those with @file{.el} extensions.
1642
1643As a practical matter, for most things you might do to customize or
1644extend Emacs, you do not need to byte compile; and I will not discuss
1645the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1646The GNU Emacs Lisp Reference Manual}, for a full description of byte
1647compilation.
1648
1649@node Evaluation, Variables, Lisp Interpreter, List Processing
1650@comment node-name, next, previous, up
1651@section Evaluation
1652@cindex Evaluation
1653
1654When the Lisp interpreter works on an expression, the term for the
1655activity is called @dfn{evaluation}. We say that the interpreter
1656`evaluates the expression'. I've used this term several times before.
1657The word comes from its use in everyday language, `to ascertain the
1658value or amount of; to appraise', according to @cite{Webster's New
1659Collegiate Dictionary}.
1660
1661After evaluating an expression, the Lisp interpreter will most likely
1662@dfn{return} the value that the computer produces by carrying out the
1663instructions it found in the function definition, or perhaps it will
1664give up on that function and produce an error message. (The interpreter
1665may also find itself tossed, so to speak, to a different function or it
1666may attempt to repeat continually what it is doing for ever and ever in
1667what is called an `infinite loop'. These actions are less common; and
1668we can ignore them.) Most frequently, the interpreter returns a value.
1669
1670@cindex @samp{side effect} defined
1671At the same time the interpreter returns a value, it may do something
1672else as well, such as move a cursor or copy a file; this other kind of
1673action is called a @dfn{side effect}. Actions that we humans think are
1674important, such as printing results, are often ``side effects'' to the
1675Lisp interpreter. The jargon can sound peculiar, but it turns out that
1676it is fairly easy to learn to use side effects.
1677
1678In summary, evaluating a symbolic expression most commonly causes the
1679Lisp interpreter to return a value and perhaps carry out a side effect;
1680or else produce an error.
1681
1682@menu
1683* Evaluating Inner Lists:: Lists within lists...
1684@end menu
1685
1686@node Evaluating Inner Lists, , Evaluation, Evaluation
1687@comment node-name, next, previous, up
1688@subsection Evaluating Inner Lists
1689@cindex Inner list evaluation
1690@cindex Evaluating inner lists
1691
1692If evaluation applies to a list that is inside another list, the outer
1693list may use the value returned by the first evaluation as information
1694when the outer list is evaluated. This explains why inner expressions
1695are evaluated first: the values they return are used by the outer
1696expressions.
1697
1698@need 1250
1699We can investigate this process by evaluating another addition example.
1700Place your cursor after the following expression and type @kbd{C-x C-e}:
1701
1702@smallexample
1703(+ 2 (+ 3 3))
1704@end smallexample
1705
1706@noindent
1707The number 8 will appear in the echo area.
1708
1709What happens is that the Lisp interpreter first evaluates the inner
1710expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1711evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1712returns the value 8. Since there are no more enclosing expressions to
1713evaluate, the interpreter prints that value in the echo area.
1714
1715Now it is easy to understand the name of the command invoked by the
1716keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1717letters @code{sexp} are an abbreviation for `symbolic expression', and
1718@code{eval} is an abbreviation for `evaluate'. The command means
1719`evaluate last symbolic expression'.
1720
1721As an experiment, you can try evaluating the expression by putting the
1722cursor at the beginning of the next line immediately following the
1723expression, or inside the expression.
1724
1725@need 800
1726Here is another copy of the expression:
1727
1728@smallexample
1729(+ 2 (+ 3 3))
1730@end smallexample
1731
1732@noindent
1733If you place the cursor at the beginning of the blank line that
1734immediately follows the expression and type @kbd{C-x C-e}, you will
1735still get the value 8 printed in the echo area. Now try putting the
1736cursor inside the expression. If you put it right after the next to
1737last parenthesis (so it appears to sit on top of the last parenthesis),
1738you will get a 6 printed in the echo area! This is because the command
1739evaluates the expression @code{(+ 3 3)}.
1740
1741Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1742you will get the number itself. In Lisp, if you evaluate a number, you
1743get the number itself---this is how numbers differ from symbols. If you
1744evaluate a list starting with a symbol like @code{+}, you will get a
1745value returned that is the result of the computer carrying out the
1746instructions in the function definition attached to that name. If a
1747symbol by itself is evaluated, something different happens, as we will
1748see in the next section.
1749
1750@node Variables, Arguments, Evaluation, List Processing
1751@comment node-name, next, previous, up
1752@section Variables
1753@cindex Variables
1754
1755In Emacs Lisp, a symbol can have a value attached to it just as it can
1756have a function definition attached to it. The two are different.
1757The function definition is a set of instructions that a computer will
1758obey. A value, on the other hand, is something, such as number or a
1759name, that can vary (which is why such a symbol is called a variable).
1760The value of a symbol can be any expression in Lisp, such as a symbol,
1761number, list, or string. A symbol that has a value is often called a
1762@dfn{variable}.
1763
1764A symbol can have both a function definition and a value attached to
1765it at the same time. Or it can have just one or the other.
1766The two are separate. This is somewhat similar
1767to the way the name Cambridge can refer to the city in Massachusetts
1768and have some information attached to the name as well, such as
1769``great programming center''.
1770
1771@ignore
1772(Incidentally, in Emacs Lisp, a symbol can have two
1773other things attached to it, too: a property list and a documentation
1774string; these are discussed later.)
1775@end ignore
1776
1777Another way to think about this is to imagine a symbol as being a chest
1778of drawers. The function definition is put in one drawer, the value in
1779another, and so on. What is put in the drawer holding the value can be
1780changed without affecting the contents of the drawer holding the
1781function definition, and vice-versa.
1782
1783@menu
1784* fill-column Example::
1785* Void Function:: The error message for a symbol
1786 without a function.
1787* Void Variable:: The error message for a symbol without a value.
1788@end menu
1789
1790@node fill-column Example, Void Function, Variables, Variables
1791@ifnottex
1792@unnumberedsubsec @code{fill-column}, an Example Variable
1793@end ifnottex
1794
1795@findex fill-column, @r{an example variable}
1796@cindex Example variable, @code{fill-column}
1797@cindex Variable, example of, @code{fill-column}
1798The variable @code{fill-column} illustrates a symbol with a value
1799attached to it: in every GNU Emacs buffer, this symbol is set to some
1800value, usually 72 or 70, but sometimes to some other value. To find the
1801value of this symbol, evaluate it by itself. If you are reading this in
1802Info inside of GNU Emacs, you can do this by putting the cursor after
1803the symbol and typing @kbd{C-x C-e}:
1804
1805@smallexample
1806fill-column
1807@end smallexample
1808
1809@noindent
1810After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1811area. This is the value for which @code{fill-column} is set for me as I
1812write this. It may be different for you in your Info buffer. Notice
1813that the value returned as a variable is printed in exactly the same way
1814as the value returned by a function carrying out its instructions. From
1815the point of view of the Lisp interpreter, a value returned is a value
1816returned. What kind of expression it came from ceases to matter once
1817the value is known.
1818
1819A symbol can have any value attached to it or, to use the jargon, we can
1820@dfn{bind} the variable to a value: to a number, such as 72; to a
1821string, @code{"such as this"}; to a list, such as @code{(spruce pine
1822oak)}; we can even bind a variable to a function definition.
1823
1824A symbol can be bound to a value in several ways. @xref{set & setq, ,
1825Setting the Value of a Variable}, for information about one way to do
1826this.
1827
1828@node Void Function, Void Variable, fill-column Example, Variables
1829@comment node-name, next, previous, up
1830@subsection Error Message for a Symbol Without a Function
1831@cindex Symbol without function error
1832@cindex Error for symbol without function
1833
1834When we evaluated @code{fill-column} to find its value as a variable,
1835we did not place parentheses around the word. This is because we did
1836not intend to use it as a function name.
1837
1838If @code{fill-column} were the first or only element of a list, the
1839Lisp interpreter would attempt to find the function definition
1840attached to it. But @code{fill-column} has no function definition.
1841Try evaluating this:
1842
1843@smallexample
1844(fill-column)
1845@end smallexample
1846
1847@need 1250
1848@noindent
1849In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1850that says:
1851
1852@smallexample
1853@group
1854---------- Buffer: *Backtrace* ----------
1855Debugger entered--Lisp error: (void-function fill-column)
1856 (fill-column)
1857 eval((fill-column))
1858 eval-last-sexp-1(nil)
1859 eval-last-sexp(nil)
1860 call-interactively(eval-last-sexp)
1861---------- Buffer: *Backtrace* ----------
1862@end group
1863@end smallexample
1864
1865@noindent
1866(Remember, to quit the debugger and make the debugger window go away,
1867type @kbd{q} in the @file{*Backtrace*} buffer.)
1868
1869@need 800
1870In GNU Emacs 20 and before, you will produce an error message that says:
1871
1872@smallexample
1873Symbol's function definition is void:@: fill-column
1874@end smallexample
1875
1876@noindent
1877(The message will go away away as soon as you move the cursor or type
1878another key.)
1879
1880@node Void Variable, , Void Function, Variables
1881@comment node-name, next, previous, up
1882@subsection Error Message for a Symbol Without a Value
1883@cindex Symbol without value error
1884@cindex Error for symbol without value
1885
1886If you attempt to evaluate a symbol that does not have a value bound to
1887it, you will receive an error message. You can see this by
1888experimenting with our 2 plus 2 addition. In the following expression,
1889put your cursor right after the @code{+}, before the first number 2,
1890type @kbd{C-x C-e}:
1891
1892@smallexample
1893(+ 2 2)
1894@end smallexample
1895
1896@need 1500
1897@noindent
1898In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1899says:
1900
1901@smallexample
1902@group
1903---------- Buffer: *Backtrace* ----------
1904Debugger entered--Lisp error: (void-variable +)
1905 eval(+)
1906 eval-last-sexp-1(nil)
1907 eval-last-sexp(nil)
1908 call-interactively(eval-last-sexp)
1909---------- Buffer: *Backtrace* ----------
1910@end group
1911@end smallexample
1912
1913@noindent
1914(As with the other times we entered the debugger, you can quit by
1915typing @kbd{q} in the @file{*Backtrace*} buffer.)
1916
1917This backtrace is different from the very first error message we saw,
1918which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1919In this case, the function does not have a value as a variable; while
1920in the other error message, the function (the word `this') did not
1921have a definition.
1922
1923In this experiment with the @code{+}, what we did was cause the Lisp
1924interpreter to evaluate the @code{+} and look for the value of the
1925variable instead of the function definition. We did this by placing the
1926cursor right after the symbol rather than after the parenthesis of the
1927enclosing list as we did before. As a consequence, the Lisp interpreter
1928evaluated the preceding s-expression, which in this case was the
1929@code{+} by itself.
1930
1931Since @code{+} does not have a value bound to it, just the function
1932definition, the error message reported that the symbol's value as a
1933variable was void.
1934
1935@need 800
1936In GNU Emacs version 20 and before, your error message will say:
1937
1938@example
1939Symbol's value as variable is void:@: +
1940@end example
1941
1942@noindent
1943The meaning is the same as in GNU Emacs 21.
1944
1945@node Arguments, set & setq, Variables, List Processing
1946@comment node-name, next, previous, up
1947@section Arguments
1948@cindex Arguments
1949@cindex Passing information to functions
1950
1951To see how information is passed to functions, let's look again at
1952our old standby, the addition of two plus two. In Lisp, this is written
1953as follows:
1954
1955@smallexample
1956(+ 2 2)
1957@end smallexample
1958
1959If you evaluate this expression, the number 4 will appear in your echo
1960area. What the Lisp interpreter does is add the numbers that follow
1961the @code{+}.
1962
1963@cindex @samp{argument} defined
1964The numbers added by @code{+} are called the @dfn{arguments} of the
1965function @code{+}. These numbers are the information that is given to
1966or @dfn{passed} to the function.
1967
1968The word `argument' comes from the way it is used in mathematics and
1969does not refer to a disputation between two people; instead it refers to
1970the information presented to the function, in this case, to the
1971@code{+}. In Lisp, the arguments to a function are the atoms or lists
1972that follow the function. The values returned by the evaluation of
1973these atoms or lists are passed to the function. Different functions
1974require different numbers of arguments; some functions require none at
1975all.@footnote{It is curious to track the path by which the word `argument'
1976came to have two different meanings, one in mathematics and the other in
1977everyday English. According to the @cite{Oxford English Dictionary},
1978the word derives from the Latin for @samp{to make clear, prove}; thus it
1979came to mean, by one thread of derivation, `the evidence offered as
1980proof', which is to say, `the information offered', which led to its
1981meaning in Lisp. But in the other thread of derivation, it came to mean
1982`to assert in a manner against which others may make counter
1983assertions', which led to the meaning of the word as a disputation.
1984(Note here that the English word has two different definitions attached
1985to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1986have two different function definitions at the same time.)}
1987
1988@menu
1989* Data types:: Types of data passed to a function.
1990* Args as Variable or List:: An argument can be the value
1991 of a variable or list.
1992* Variable Number of Arguments:: Some functions may take a
1993 variable number of arguments.
1994* Wrong Type of Argument:: Passing an argument of the wrong type
1995 to a function.
1996* message:: A useful function for sending messages.
1997@end menu
1998
1999@node Data types, Args as Variable or List, Arguments, Arguments
2000@comment node-name, next, previous, up
2001@subsection Arguments' Data Types
2002@cindex Data types
2003@cindex Types of data
2004@cindex Arguments' data types
2005
2006The type of data that should be passed to a function depends on what
2007kind of information it uses. The arguments to a function such as
2008@code{+} must have values that are numbers, since @code{+} adds numbers.
2009Other functions use different kinds of data for their arguments.
2010
2011@findex concat
2012For example, the @code{concat} function links together or unites two or
2013more strings of text to produce a string. The arguments are strings.
2014Concatenating the two character strings @code{abc}, @code{def} produces
2015the single string @code{abcdef}. This can be seen by evaluating the
2016following:
2017
2018@smallexample
2019(concat "abc" "def")
2020@end smallexample
2021
2022@noindent
2023The value produced by evaluating this expression is @code{"abcdef"}.
2024
2025A function such as @code{substring} uses both a string and numbers as
2026arguments. The function returns a part of the string, a substring of
2027the first argument. This function takes three arguments. Its first
2028argument is the string of characters, the second and third arguments are
2029numbers that indicate the beginning and end of the substring. The
2030numbers are a count of the number of characters (including spaces and
2031punctuations) from the beginning of the string.
2032
2033@need 800
2034For example, if you evaluate the following:
2035
2036@smallexample
2037(substring "The quick brown fox jumped." 16 19)
2038@end smallexample
2039
2040@noindent
2041you will see @code{"fox"} appear in the echo area. The arguments are the
2042string and the two numbers.
2043
2044Note that the string passed to @code{substring} is a single atom even
2045though it is made up of several words separated by spaces. Lisp counts
2046everything between the two quotation marks as part of the string,
2047including the spaces. You can think of the @code{substring} function as
2048a kind of `atom smasher' since it takes an otherwise indivisible atom
2049and extracts a part. However, @code{substring} is only able to extract
2050a substring from an argument that is a string, not from another type of
2051atom such as a number or symbol.
2052
2053@node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2054@comment node-name, next, previous, up
2055@subsection An Argument as the Value of a Variable or List
2056
2057An argument can be a symbol that returns a value when it is evaluated.
2058For example, when the symbol @code{fill-column} by itself is evaluated,
2059it returns a number. This number can be used in an addition.
2060
2061@need 1250
2062Position the cursor after the following expression and type @kbd{C-x
2063C-e}:
2064
2065@smallexample
2066(+ 2 fill-column)
2067@end smallexample
2068
2069@noindent
2070The value will be a number two more than what you get by evaluating
2071@code{fill-column} alone. For me, this is 74, because the value of
2072@code{fill-column} is 72.
2073
2074As we have just seen, an argument can be a symbol that returns a value
2075when evaluated. In addition, an argument can be a list that returns a
2076value when it is evaluated. For example, in the following expression,
2077the arguments to the function @code{concat} are the strings
2078@w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2079@code{(number-to-string (+ 2 fill-column))}.
2080
2081@c For Emacs 21, need number-to-string
2082@smallexample
2083(concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2084@end smallexample
2085
2086@noindent
2087If you evaluate this expression---and if, as with my Emacs,
2088@code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2089appear in the echo area. (Note that you must put spaces after the
2090word @samp{The} and before the word @samp{red} so they will appear in
2091the final string. The function @code{number-to-string} converts the
2092integer that the addition function returns to a string.
2093@code{number-to-string} is also known as @code{int-to-string}.)
2094
2095@node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2096@comment node-name, next, previous, up
2097@subsection Variable Number of Arguments
2098@cindex Variable number of arguments
2099@cindex Arguments, variable number of
2100
2101Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2102number of arguments. (The @code{*} is the symbol for multiplication.)
2103This can be seen by evaluating each of the following expressions in
2104the usual way. What you will see in the echo area is printed in this
2105text after @samp{@result{}}, which you may read as `evaluates to'.
2106
2107@need 1250
2108In the first set, the functions have no arguments:
2109
2110@smallexample
2111@group
2112(+) @result{} 0
2113
2114(*) @result{} 1
2115@end group
2116@end smallexample
2117
2118@need 1250
2119In this set, the functions have one argument each:
2120
2121@smallexample
2122@group
2123(+ 3) @result{} 3
2124
2125(* 3) @result{} 3
2126@end group
2127@end smallexample
2128
2129@need 1250
2130In this set, the functions have three arguments each:
2131
2132@smallexample
2133@group
2134(+ 3 4 5) @result{} 12
2135
2136(* 3 4 5) @result{} 60
2137@end group
2138@end smallexample
2139
2140@node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2141@comment node-name, next, previous, up
2142@subsection Using the Wrong Type Object as an Argument
2143@cindex Wrong type of argument
2144@cindex Argument, wrong type of
2145
2146When a function is passed an argument of the wrong type, the Lisp
2147interpreter produces an error message. For example, the @code{+}
2148function expects the values of its arguments to be numbers. As an
2149experiment we can pass it the quoted symbol @code{hello} instead of a
2150number. Position the cursor after the following expression and type
2151@kbd{C-x C-e}:
2152
2153@smallexample
2154(+ 2 'hello)
2155@end smallexample
2156
2157@noindent
2158When you do this you will generate an error message. What has happened
2159is that @code{+} has tried to add the 2 to the value returned by
2160@code{'hello}, but the value returned by @code{'hello} is the symbol
2161@code{hello}, not a number. Only numbers can be added. So @code{+}
2162could not carry out its addition.
2163
2164@need 1250
2165In GNU Emacs version 21, you will create and enter a
2166@file{*Backtrace*} buffer that says:
2167
2168@noindent
2169@smallexample
2170@group
2171---------- Buffer: *Backtrace* ----------
2172Debugger entered--Lisp error:
2173 (wrong-type-argument number-or-marker-p hello)
2174 +(2 hello)
2175 eval((+ 2 (quote hello)))
2176 eval-last-sexp-1(nil)
2177 eval-last-sexp(nil)
2178 call-interactively(eval-last-sexp)
2179---------- Buffer: *Backtrace* ----------
2180@end group
2181@end smallexample
2182
2183@need 1250
2184As usual, the error message tries to be helpful and makes sense after you
2185learn how to read it.
2186
2187The first part of the error message is straightforward; it says
2188@samp{wrong type argument}. Next comes the mysterious jargon word
2189@w{@samp{number-or-marker-p}}. This word is trying to tell you what
2190kind of argument the @code{+} expected.
2191
2192The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2193trying to determine whether the information presented it (the value of
2194the argument) is a number or a marker (a special object representing a
2195buffer position). What it does is test to see whether the @code{+} is
2196being given numbers to add. It also tests to see whether the
2197argument is something called a marker, which is a specific feature of
2198Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2199When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2200its position is kept as a marker. The mark can be considered a
2201number---the number of characters the location is from the beginning
2202of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2203numeric value of marker positions as numbers.
2204
2205The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2206practice started in the early days of Lisp programming. The @samp{p}
2207stands for `predicate'. In the jargon used by the early Lisp
2208researchers, a predicate refers to a function to determine whether some
2209property is true or false. So the @samp{p} tells us that
2210@code{number-or-marker-p} is the name of a function that determines
2211whether it is true or false that the argument supplied is a number or
2212a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2213a function that tests whether its argument has the value of zero, and
2214@code{listp}, a function that tests whether its argument is a list.
2215
2216Finally, the last part of the error message is the symbol @code{hello}.
2217This is the value of the argument that was passed to @code{+}. If the
2218addition had been passed the correct type of object, the value passed
2219would have been a number, such as 37, rather than a symbol like
2220@code{hello}. But then you would not have got the error message.
2221
2222@need 1250
2223In GNU Emacs version 20 and before, the echo area displays an error
2224message that says:
2225
2226@smallexample
2227Wrong type argument:@: number-or-marker-p, hello
2228@end smallexample
2229
2230This says, in different words, the same as the top line of the
2231@file{*Backtrace*} buffer.
2232
2233@node message, , Wrong Type of Argument, Arguments
2234@comment node-name, next, previous, up
2235@subsection The @code{message} Function
2236@findex message
2237
2238Like @code{+}, the @code{message} function takes a variable number of
2239arguments. It is used to send messages to the user and is so useful
2240that we will describe it here.
2241
2242@need 1250
2243A message is printed in the echo area. For example, you can print a
2244message in your echo area by evaluating the following list:
2245
2246@smallexample
2247(message "This message appears in the echo area!")
2248@end smallexample
2249
2250The whole string between double quotation marks is a single argument
2251and is printed @i{in toto}. (Note that in this example, the message
2252itself will appear in the echo area within double quotes; that is
2253because you see the value returned by the @code{message} function. In
2254most uses of @code{message} in programs that you write, the text will
2255be printed in the echo area as a side-effect, without the quotes.
2256@xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2257detail}, for an example of this.)
2258
2259However, if there is a @samp{%s} in the quoted string of characters, the
2260@code{message} function does not print the @samp{%s} as such, but looks
2261to the argument that follows the string. It evaluates the second
2262argument and prints the value at the location in the string where the
2263@samp{%s} is.
2264
2265@need 1250
2266You can see this by positioning the cursor after the following
2267expression and typing @kbd{C-x C-e}:
2268
2269@smallexample
2270(message "The name of this buffer is: %s." (buffer-name))
2271@end smallexample
2272
2273@noindent
2274In Info, @code{"The name of this buffer is: *info*."} will appear in the
2275echo area. The function @code{buffer-name} returns the name of the
2276buffer as a string, which the @code{message} function inserts in place
2277of @code{%s}.
2278
2279To print a value as an integer, use @samp{%d} in the same way as
2280@samp{%s}. For example, to print a message in the echo area that
2281states the value of the @code{fill-column}, evaluate the following:
2282
2283@smallexample
2284(message "The value of fill-column is %d." fill-column)
2285@end smallexample
2286
2287@noindent
2288On my system, when I evaluate this list, @code{"The value of
2289fill-column is 72."} appears in my echo area@footnote{Actually, you
2290can use @code{%s} to print a number. It is non-specific. @code{%d}
2291prints only the part of a number left of a decimal point, and not
2292anything that is not a number.}.
2293
2294If there is more than one @samp{%s} in the quoted string, the value of
2295the first argument following the quoted string is printed at the
2296location of the first @samp{%s} and the value of the second argument is
2297printed at the location of the second @samp{%s}, and so on.
2298
2299@need 1250
2300For example, if you evaluate the following,
2301
2302@smallexample
2303@group
2304(message "There are %d %s in the office!"
2305 (- fill-column 14) "pink elephants")
2306@end group
2307@end smallexample
2308
2309@noindent
2310a rather whimsical message will appear in your echo area. On my system
2311it says, @code{"There are 58 pink elephants in the office!"}.
2312
2313The expression @code{(- fill-column 14)} is evaluated and the resulting
2314number is inserted in place of the @samp{%d}; and the string in double
2315quotes, @code{"pink elephants"}, is treated as a single argument and
2316inserted in place of the @samp{%s}. (That is to say, a string between
2317double quotes evaluates to itself, like a number.)
2318
2319Finally, here is a somewhat complex example that not only illustrates
2320the computation of a number, but also shows how you can use an
2321expression within an expression to generate the text that is substituted
2322for @samp{%s}:
2323
2324@smallexample
2325@group
2326(message "He saw %d %s"
2327 (- fill-column 34)
2328 (concat "red "
2329 (substring
2330 "The quick brown foxes jumped." 16 21)
2331 " leaping."))
2332@end group
2333@end smallexample
2334
2335In this example, @code{message} has three arguments: the string,
2336@code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2337the expression beginning with the function @code{concat}. The value
2338resulting from the evaluation of @code{(- fill-column 32)} is inserted
2339in place of the @samp{%d}; and the value returned by the expression
2340beginning with @code{concat} is inserted in place of the @samp{%s}.
2341
2342When I evaluate the expression, the message @code{"He saw 38 red
2343foxes leaping."} appears in my echo area.
2344
2345@node set & setq, Summary, Arguments, List Processing
2346@comment node-name, next, previous, up
2347@section Setting the Value of a Variable
2348@cindex Variable, setting value
2349@cindex Setting value of variable
2350
2351@cindex @samp{bind} defined
2352There are several ways by which a variable can be given a value. One of
2353the ways is to use either the function @code{set} or the function
2354@code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2355jargon for this process is to @dfn{bind} a variable to a value.)
2356
2357The following sections not only describe how @code{set} and @code{setq}
2358work but also illustrate how arguments are passed.
2359
2360@menu
2361* Using set:: Setting values.
2362* Using setq:: Setting a quoted value.
2363* Counting:: Using @code{setq} to count.
2364@end menu
2365
2366@node Using set, Using setq, set & setq, set & setq
2367@comment node-name, next, previous, up
2368@subsection Using @code{set}
2369@findex set
2370
2371To set the value of the symbol @code{flowers} to the list @code{'(rose
2372violet daisy buttercup)}, evaluate the following expression by
2373positioning the cursor after the expression and typing @kbd{C-x C-e}.
2374
2375@smallexample
2376(set 'flowers '(rose violet daisy buttercup))
2377@end smallexample
2378
2379@noindent
2380The list @code{(rose violet daisy buttercup)} will appear in the echo
2381area. This is what is @emph{returned} by the @code{set} function. As a
2382side effect, the symbol @code{flowers} is bound to the list ; that is,
2383the symbol @code{flowers}, which can be viewed as a variable, is given
2384the list as its value. (This process, by the way, illustrates how a
2385side effect to the Lisp interpreter, setting the value, can be the
2386primary effect that we humans are interested in. This is because every
2387Lisp function must return a value if it does not get an error, but it
2388will only have a side effect if it is designed to have one.)
2389
2390After evaluating the @code{set} expression, you can evaluate the symbol
2391@code{flowers} and it will return the value you just set. Here is the
2392symbol. Place your cursor after it and type @kbd{C-x C-e}.
2393
2394@smallexample
2395flowers
2396@end smallexample
2397
2398@noindent
2399When you evaluate @code{flowers}, the list
2400@code{(rose violet daisy buttercup)} appears in the echo area.
2401
2402Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2403in front of it, what you will see in the echo area is the symbol itself,
2404@code{flowers}. Here is the quoted symbol, so you can try this:
2405
2406@smallexample
2407'flowers
2408@end smallexample
2409
2410Note also, that when you use @code{set}, you need to quote both
2411arguments to @code{set}, unless you want them evaluated. Since we do
2412not want either argument evaluated, neither the variable
2413@code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2414are quoted. (When you use @code{set} without quoting its first
2415argument, the first argument is evaluated before anything else is
2416done. If you did this and @code{flowers} did not have a value
2417already, you would get an error message that the @samp{Symbol's value
2418as variable is void}; on the other hand, if @code{flowers} did return
2419a value after it was evaluated, the @code{set} would attempt to set
2420the value that was returned. There are situations where this is the
2421right thing for the function to do; but such situations are rare.)
2422
2423@node Using setq, Counting, Using set, set & setq
2424@comment node-name, next, previous, up
2425@subsection Using @code{setq}
2426@findex setq
2427
2428As a practical matter, you almost always quote the first argument to
2429@code{set}. The combination of @code{set} and a quoted first argument
2430is so common that it has its own name: the special form @code{setq}.
2431This special form is just like @code{set} except that the first argument
2432is quoted automatically, so you don't need to type the quote mark
2433yourself. Also, as an added convenience, @code{setq} permits you to set
2434several different variables to different values, all in one expression.
2435
2436To set the value of the variable @code{carnivores} to the list
2437@code{'(lion tiger leopard)} using @code{setq}, the following expression
2438is used:
2439
2440@smallexample
2441(setq carnivores '(lion tiger leopard))
2442@end smallexample
2443
2444@noindent
2445This is exactly the same as using @code{set} except the first argument
2446is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2447means @code{quote}.)
2448
2449@need 1250
2450With @code{set}, the expression would look like this:
2451
2452@smallexample
2453(set 'carnivores '(lion tiger leopard))
2454@end smallexample
2455
2456Also, @code{setq} can be used to assign different values to
2457different variables. The first argument is bound to the value
2458of the second argument, the third argument is bound to the value of the
2459fourth argument, and so on. For example, you could use the following to
2460assign a list of trees to the symbol @code{trees} and a list of herbivores
2461to the symbol @code{herbivores}:
2462
2463@smallexample
2464@group
2465(setq trees '(pine fir oak maple)
2466 herbivores '(gazelle antelope zebra))
2467@end group
2468@end smallexample
2469
2470@noindent
2471(The expression could just as well have been on one line, but it might
2472not have fit on a page; and humans find it easier to read nicely
2473formatted lists.)
2474
2475Although I have been using the term `assign', there is another way of
2476thinking about the workings of @code{set} and @code{setq}; and that is to
2477say that @code{set} and @code{setq} make the symbol @emph{point} to the
2478list. This latter way of thinking is very common and in forthcoming
2479chapters we shall come upon at least one symbol that has `pointer' as
2480part of its name. The name is chosen because the symbol has a value,
2481specifically a list, attached to it; or, expressed another way,
2482the symbol is set to ``point'' to the list.
2483
2484@node Counting, , Using setq, set & setq
2485@comment node-name, next, previous, up
2486@subsection Counting
2487@cindex Counting
2488
2489Here is an example that shows how to use @code{setq} in a counter. You
2490might use this to count how many times a part of your program repeats
2491itself. First set a variable to zero; then add one to the number each
2492time the program repeats itself. To do this, you need a variable that
2493serves as a counter, and two expressions: an initial @code{setq}
2494expression that sets the counter variable to zero; and a second
2495@code{setq} expression that increments the counter each time it is
2496evaluated.
2497
2498@smallexample
2499@group
2500(setq counter 0) ; @r{Let's call this the initializer.}
2501
2502(setq counter (+ counter 1)) ; @r{This is the incrementer.}
2503
2504counter ; @r{This is the counter.}
2505@end group
2506@end smallexample
2507
2508@noindent
2509(The text following the @samp{;} are comments. @xref{Change a
2510defun, , Change a Function Definition}.)
2511
2512If you evaluate the first of these expressions, the initializer,
2513@code{(setq counter 0)}, and then evaluate the third expression,
2514@code{counter}, the number @code{0} will appear in the echo area. If
2515you then evaluate the second expression, the incrementer, @code{(setq
2516counter (+ counter 1))}, the counter will get the value 1. So if you
2517again evaluate @code{counter}, the number @code{1} will appear in the
2518echo area. Each time you evaluate the second expression, the value of
2519the counter will be incremented.
2520
2521When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2522the Lisp interpreter first evaluates the innermost list; this is the
2523addition. In order to evaluate this list, it must evaluate the variable
2524@code{counter} and the number @code{1}. When it evaluates the variable
2525@code{counter}, it receives its current value. It passes this value and
2526the number @code{1} to the @code{+} which adds them together. The sum
2527is then returned as the value of the inner list and passed to the
2528@code{setq} which sets the variable @code{counter} to this new value.
2529Thus, the value of the variable, @code{counter}, is changed.
2530
2531@node Summary, Error Message Exercises, set & setq, List Processing
2532@comment node-name, next, previous, up
2533@section Summary
2534
2535Learning Lisp is like climbing a hill in which the first part is the
2536steepest. You have now climbed the most difficult part; what remains
2537becomes easier as you progress onwards.
2538
2539In summary,
2540
2541@itemize @bullet
2542
2543@item
2544Lisp programs are made up of expressions, which are lists or single atoms.
2545
2546@item
2547Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2548surrounded by parentheses. A list can be empty.
2549
2550@item
2551Atoms are multi-character symbols, like @code{forward-paragraph}, single
2552character symbols like @code{+}, strings of characters between double
2553quotation marks, or numbers.
2554
2555@item
2556A number evaluates to itself.
2557
2558@item
2559A string between double quotes also evaluates to itself.
2560
2561@item
2562When you evaluate a symbol by itself, its value is returned.
2563
2564@item
2565When you evaluate a list, the Lisp interpreter looks at the first symbol
2566in the list and then at the function definition bound to that symbol.
2567Then the instructions in the function definition are carried out.
2568
2569@item
2570A single-quote, @code{'}, tells the Lisp interpreter that it should
2571return the following expression as written, and not evaluate it as it
2572would if the quote were not there.
2573
2574@item
2575Arguments are the information passed to a function. The arguments to a
2576function are computed by evaluating the rest of the elements of the list
2577of which the function is the first element.
2578
2579@item
2580A function always returns a value when it is evaluated (unless it gets
2581an error); in addition, it may also carry out some action called a
2582``side effect''. In many cases, a function's primary purpose is to
2583create a side effect.
2584@end itemize
2585
2586@node Error Message Exercises, , Summary, List Processing
2587@comment node-name, next, previous, up
2588@section Exercises
2589
2590A few simple exercises:
2591
2592@itemize @bullet
2593@item
2594Generate an error message by evaluating an appropriate symbol that is
2595not within parentheses.
2596
2597@item
2598Generate an error message by evaluating an appropriate symbol that is
2599between parentheses.
2600
2601@item
2602Create a counter that increments by two rather than one.
2603
2604@item
2605Write an expression that prints a message in the echo area when
2606evaluated.
2607@end itemize
2608
2609@node Practicing Evaluation, Writing Defuns, List Processing, Top
2610@comment node-name, next, previous, up
2611@chapter Practicing Evaluation
2612@cindex Practicing evaluation
2613@cindex Evaluation practice
2614
2615Before learning how to write a function definition in Emacs Lisp, it is
2616useful to spend a little time evaluating various expressions that have
2617already been written. These expressions will be lists with the
2618functions as their first (and often only) element. Since some of the
2619functions associated with buffers are both simple and interesting, we
2620will start with those. In this section, we will evaluate a few of
2621these. In another section, we will study the code of several other
2622buffer-related functions, to see how they were written.
2623
2624@menu
2625* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2626 causes evaluation.
2627* Buffer Names:: Buffers and files are different.
2628* Getting Buffers:: Getting a buffer itself, not merely its name.
2629* Switching Buffers:: How to change to another buffer.
2630* Buffer Size & Locations:: Where point is located and the size of
2631 the buffer.
2632* Evaluation Exercise::
2633@end menu
2634
2635@node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2636@ifnottex
2637@unnumberedsec How to Evaluate
2638@end ifnottex
2639
2640@i{Whenever you give an editing command} to Emacs Lisp, such as the
2641command to move the cursor or to scroll the screen, @i{you are evaluating
2642an expression,} the first element of which is a function. @i{This is
2643how Emacs works.}
2644
2645@cindex @samp{interactive function} defined
2646@cindex @samp{command} defined
2647When you type keys, you cause the Lisp interpreter to evaluate an
2648expression and that is how you get your results. Even typing plain text
2649involves evaluating an Emacs Lisp function, in this case, one that uses
2650@code{self-insert-command}, which simply inserts the character you
2651typed. The functions you evaluate by typing keystrokes are called
2652@dfn{interactive} functions, or @dfn{commands}; how you make a function
2653interactive will be illustrated in the chapter on how to write function
2654definitions. @xref{Interactive, , Making a Function Interactive}.
2655
2656In addition to typing keyboard commands, we have seen a second way to
2657evaluate an expression: by positioning the cursor after a list and
2658typing @kbd{C-x C-e}. This is what we will do in the rest of this
2659section. There are other ways to evaluate an expression as well; these
2660will be described as we come to them.
2661
2662Besides being used for practicing evaluation, the functions shown in the
2663next few sections are important in their own right. A study of these
2664functions makes clear the distinction between buffers and files, how to
2665switch to a buffer, and how to determine a location within it.
2666
2667@node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2668@comment node-name, next, previous, up
2669@section Buffer Names
2670@findex buffer-name
2671@findex buffer-file-name
2672
2673The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2674the difference between a file and a buffer. When you evaluate the
2675following expression, @code{(buffer-name)}, the name of the buffer
2676appears in the echo area. When you evaluate @code{(buffer-file-name)},
2677the name of the file to which the buffer refers appears in the echo
2678area. Usually, the name returned by @code{(buffer-name)} is the same as
2679the name of the file to which it refers, and the name returned by
2680@code{(buffer-file-name)} is the full path-name of the file.
2681
2682A file and a buffer are two different entities. A file is information
2683recorded permanently in the computer (unless you delete it). A buffer,
2684on the other hand, is information inside of Emacs that will vanish at
2685the end of the editing session (or when you kill the buffer). Usually,
2686a buffer contains information that you have copied from a file; we say
2687the buffer is @dfn{visiting} that file. This copy is what you work on
2688and modify. Changes to the buffer do not change the file, until you
2689save the buffer. When you save the buffer, the buffer is copied to the file
2690and is thus saved permanently.
2691
2692@need 1250
2693If you are reading this in Info inside of GNU Emacs, you can evaluate
2694each of the following expressions by positioning the cursor after it and
2695typing @kbd{C-x C-e}.
2696
2697@smallexample
2698@group
2699(buffer-name)
2700
2701(buffer-file-name)
2702@end group
2703@end smallexample
2704
2705@noindent
2706When I do this, @file{"introduction.texinfo"} is the value returned by
2707evaluating @code{(buffer-name)}, and
2708@file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2709evaluating @code{(buffer-file-name)}. The former is the name of the
2710buffer and the latter is the name of the file. (In the expressions, the
2711parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2712@code{buffer-file-name} as functions; without the parentheses, the
2713interpreter would attempt to evaluate the symbols as variables.
2714@xref{Variables}.)
2715
2716In spite of the distinction between files and buffers, you will often
2717find that people refer to a file when they mean a buffer and vice-versa.
2718Indeed, most people say, ``I am editing a file,'' rather than saying,
2719``I am editing a buffer which I will soon save to a file.'' It is
2720almost always clear from context what people mean. When dealing with
2721computer programs, however, it is important to keep the distinction in mind,
2722since the computer is not as smart as a person.
2723
2724@cindex Buffer, history of word
2725The word `buffer', by the way, comes from the meaning of the word as a
2726cushion that deadens the force of a collision. In early computers, a
2727buffer cushioned the interaction between files and the computer's
2728central processing unit. The drums or tapes that held a file and the
2729central processing unit were pieces of equipment that were very
2730different from each other, working at their own speeds, in spurts. The
2731buffer made it possible for them to work together effectively.
2732Eventually, the buffer grew from being an intermediary, a temporary
2733holding place, to being the place where work is done. This
2734transformation is rather like that of a small seaport that grew into a
2735great city: once it was merely the place where cargo was warehoused
2736temporarily before being loaded onto ships; then it became a business
2737and cultural center in its own right.
2738
2739Not all buffers are associated with files. For example, when you start
2740an Emacs session by typing the command @code{emacs} alone, without
2741naming any files, Emacs will start with the @file{*scratch*} buffer on
2742the screen. This buffer is not visiting any file. Similarly, a
2743@file{*Help*} buffer is not associated with any file.
2744
2745@cindex @code{nil}, history of word
2746If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2747position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2748expression, the name @code{"*scratch*"} is returned and will appear in
2749the echo area. @code{"*scratch*"} is the name of the buffer. However,
2750if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2751evaluate that, @code{nil} will appear in the echo area. @code{nil} is
2752from the Latin word for `nothing'; in this case, it means that the
2753@file{*scratch*} buffer is not associated with any file. (In Lisp,
2754@code{nil} is also used to mean `false' and is a synonym for the empty
2755list, @code{()}.)
2756
2757Incidentally, if you are in the @file{*scratch*} buffer and want the
2758value returned by an expression to appear in the @file{*scratch*}
2759buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2760instead of @kbd{C-x C-e}. This causes the value returned to appear
2761after the expression. The buffer will look like this:
2762
2763@smallexample
2764(buffer-name)"*scratch*"
2765@end smallexample
2766
2767@noindent
2768You cannot do this in Info since Info is read-only and it will not allow
2769you to change the contents of the buffer. But you can do this in any
2770buffer you can edit; and when you write code or documentation (such as
2771this book), this feature is very useful.
2772
2773@node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2774@comment node-name, next, previous, up
2775@section Getting Buffers
2776@findex current-buffer
2777@findex other-buffer
2778@cindex Getting a buffer
2779
2780The @code{buffer-name} function returns the @emph{name} of the buffer;
2781to get the buffer @emph{itself}, a different function is needed: the
2782@code{current-buffer} function. If you use this function in code, what
2783you get is the buffer itself.
2784
2785A name and the object or entity to which the name refers are different
2786from each other. You are not your name. You are a person to whom
2787others refer by name. If you ask to speak to George and someone hands you
2788a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2789@samp{g}, and @samp{e} written on it, you might be amused, but you would
2790not be satisfied. You do not want to speak to the name, but to the
2791person to whom the name refers. A buffer is similar: the name of the
2792scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2793get a buffer itself, you need to use a function such as
2794@code{current-buffer}.
2795
2796However, there is a slight complication: if you evaluate
2797@code{current-buffer} in an expression on its own, as we will do here,
2798what you see is a printed representation of the name of the buffer
2799without the contents of the buffer. Emacs works this way for two
2800reasons: the buffer may be thousands of lines long---too long to be
2801conveniently displayed; and, another buffer may have the same contents
2802but a different name, and it is important to distinguish between them.
2803
2804@need 800
2805Here is an expression containing the function:
2806
2807@smallexample
2808(current-buffer)
2809@end smallexample
2810
2811@noindent
2812If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2813appears in the echo area. The special format indicates that the
2814buffer itself is being returned, rather than just its name.
2815
2816Incidentally, while you can type a number or symbol into a program, you
2817cannot do that with the printed representation of a buffer: the only way
2818to get a buffer itself is with a function such as @code{current-buffer}.
2819
2820A related function is @code{other-buffer}. This returns the most
2821recently selected buffer other than the one you are in currently. If
2822you have recently switched back and forth from the @file{*scratch*}
2823buffer, @code{other-buffer} will return that buffer.
2824
2825@need 800
2826You can see this by evaluating the expression:
2827
2828@smallexample
2829(other-buffer)
2830@end smallexample
2831
2832@noindent
2833You should see @file{#<buffer *scratch*>} appear in the echo area, or
2834the name of whatever other buffer you switched back from most
2835recently@footnote{Actually, by default, if the buffer from which you
2836just switched is visible to you in another window, @code{other-buffer}
2837will choose the most recent buffer that you cannot see; this is a
2838subtlety that I often forget.}.
2839
2840@node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2841@comment node-name, next, previous, up
2842@section Switching Buffers
2843@findex switch-to-buffer
2844@findex set-buffer
2845@cindex Switching to a buffer
2846
2847The @code{other-buffer} function actually provides a buffer when it is
2848used as an argument to a function that requires one. We can see this
2849by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2850different buffer.
2851
2852But first, a brief introduction to the @code{switch-to-buffer}
2853function. When you switched back and forth from Info to the
2854@file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2855likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2856rather, to save typing, you probably typed just part of the name, such
2857as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2858expand to the full name; and then typed your @kbd{RET} key.} when
2859prompted in the minibuffer for the name of the buffer to which you
2860wanted to switch. The keystrokes, @kbd{C-x b}, cause the Lisp
2861interpreter to evaluate the interactive function
2862@code{switch-to-buffer}. As we said before, this is how Emacs works:
2863different keystrokes call or run different functions. For example,
2864@kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2865@code{forward-sentence}, and so on.
2866
2867By writing @code{switch-to-buffer} in an expression, and giving it a
2868buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2869does.
2870
2871@need 1000
2872Here is the Lisp expression:
2873
2874@smallexample
2875(switch-to-buffer (other-buffer))
2876@end smallexample
2877
2878@noindent
2879The symbol @code{switch-to-buffer} is the first element of the list,
2880so the Lisp interpreter will treat it as a function and carry out the
2881instructions that are attached to it. But before doing that, the
2882interpreter will note that @code{other-buffer} is inside parentheses
2883and work on that symbol first. @code{other-buffer} is the first (and
2884in this case, the only) element of this list, so the Lisp interpreter
2885calls or runs the function. It returns another buffer. Next, the
2886interpreter runs @code{switch-to-buffer}, passing to it, as an
2887argument, the other buffer, which is what Emacs will switch to. If
2888you are reading this in Info, try this now. Evaluate the expression.
2889(To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2890expression will move you to your most recent other buffer that you
2891cannot see. If you really want to go to your most recently selected
2892buffer, even if you can still see it, you need to evaluate the
2893following more complex expression:
2894
2895@smallexample
2896(switch-to-buffer (other-buffer (current-buffer) t))
2897@end smallexample
2898
28be162e 2899@c noindent
8b096dce
EZ
2900In this case, the first argument to @code{other-buffer} tells it which
2901buffer to skip---the current one---and the second argument tells
2902@code{other-buffer} it is OK to switch to a visible buffer.
2903In regular use, @code{switch-to-buffer} takes you to an invisible
2904window since you would most likely use @kbd{C-x o} (@code{other-window})
2905to go to another visible buffer.}
2906
2907In the programming examples in later sections of this document, you will
2908see the function @code{set-buffer} more often than
2909@code{switch-to-buffer}. This is because of a difference between
2910computer programs and humans: humans have eyes and expect to see the
2911buffer on which they are working on their computer terminals. This is
2912so obvious, it almost goes without saying. However, programs do not
2913have eyes. When a computer program works on a buffer, that buffer does
2914not need to be visible on the screen.
2915
2916@code{switch-to-buffer} is designed for humans and does two different
2917things: it switches the buffer to which Emacs' attention is directed; and
2918it switches the buffer displayed in the window to the new buffer.
2919@code{set-buffer}, on the other hand, does only one thing: it switches
2920the attention of the computer program to a different buffer. The buffer
2921on the screen remains unchanged (of course, normally nothing happens
2922there until the command finishes running).
2923
2924@cindex @samp{call} defined
2925Also, we have just introduced another jargon term, the word @dfn{call}.
2926When you evaluate a list in which the first symbol is a function, you
2927are calling that function. The use of the term comes from the notion of
2928the function as an entity that can do something for you if you `call'
2929it---just as a plumber is an entity who can fix a leak if you call him
2930or her.
2931
2932@node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2933@comment node-name, next, previous, up
2934@section Buffer Size and the Location of Point
2935@cindex Size of buffer
2936@cindex Buffer size
2937@cindex Point location
2938@cindex Location of point
2939
2940Finally, let's look at several rather simple functions,
2941@code{buffer-size}, @code{point}, @code{point-min}, and
2942@code{point-max}. These give information about the size of a buffer and
2943the location of point within it.
2944
2945The function @code{buffer-size} tells you the size of the current
2946buffer; that is, the function returns a count of the number of
2947characters in the buffer.
2948
2949@smallexample
2950(buffer-size)
2951@end smallexample
2952
2953@noindent
2954You can evaluate this in the usual way, by positioning the
2955cursor after the expression and typing @kbd{C-x C-e}.
2956
2957@cindex @samp{point} defined
2958In Emacs, the current position of the cursor is called @dfn{point}.
2959The expression @code{(point)} returns a number that tells you where the
2960cursor is located as a count of the number of characters from the
2961beginning of the buffer up to point.
2962
2963@need 1250
2964You can see the character count for point in this buffer by evaluating
2965the following expression in the usual way:
2966
2967@smallexample
2968(point)
2969@end smallexample
2970
2971@noindent
2972As I write this, the value of @code{point} is 65724. The @code{point}
2973function is frequently used in some of the examples later in this
2974book.
2975
2976@need 1250
2977The value of point depends, of course, on its location within the
2978buffer. If you evaluate point in this spot, the number will be larger:
2979
2980@smallexample
2981(point)
2982@end smallexample
2983
2984@noindent
2985For me, the value of point in this location is 66043, which means that
2986there are 319 characters (including spaces) between the two expressions.
2987
2988@cindex @samp{narrowing} defined
2989The function @code{point-min} is somewhat similar to @code{point}, but
2990it returns the value of the minimum permissible value of point in the
2991current buffer. This is the number 1 unless @dfn{narrowing} is in
2992effect. (Narrowing is a mechanism whereby you can restrict yourself,
2993or a program, to operations on just a part of a buffer.
2994@xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
2995function @code{point-max} returns the value of the maximum permissible
2996value of point in the current buffer.
2997
2998@node Evaluation Exercise, , Buffer Size & Locations, Practicing Evaluation
2999@section Exercise
3000
3001Find a file with which you are working and move towards its middle.
3002Find its buffer name, file name, length, and your position in the file.
3003
3004@node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
3005@comment node-name, next, previous, up
3006@chapter How To Write Function Definitions
3007@cindex Definition writing
3008@cindex Function definition writing
3009@cindex Writing a function definition
3010
3011When the Lisp interpreter evaluates a list, it looks to see whether the
3012first symbol on the list has a function definition attached to it; or,
3013put another way, whether the symbol points to a function definition. If
3014it does, the computer carries out the instructions in the definition. A
3015symbol that has a function definition is called, simply, a function
3016(although, properly speaking, the definition is the function and the
3017symbol refers to it.)
3018
3019@menu
3020* Primitive Functions::
3021* defun:: The @code{defun} special form.
3022* Install:: Install a function definition.
3023* Interactive:: Making a function interactive.
3024* Interactive Options:: Different options for @code{interactive}.
3025* Permanent Installation:: Installing code permanently.
3026* let:: Creating and initializing local variables.
3027* if:: What if?
3028* else:: If--then--else expressions.
3029* Truth & Falsehood:: What Lisp considers false and true.
3030* save-excursion:: Keeping track of point, mark, and buffer.
3031* Review::
3032* defun Exercises::
3033@end menu
3034
3035@node Primitive Functions, defun, Writing Defuns, Writing Defuns
3036@ifnottex
3037@unnumberedsec An Aside about Primitive Functions
3038@end ifnottex
3039@cindex Primitive functions
3040@cindex Functions, primitive
3041
3042@cindex C language primitives
3043@cindex Primitives written in C
3044All functions are defined in terms of other functions, except for a few
3045@dfn{primitive} functions that are written in the C programming
3046language. When you write functions' definitions, you will write them in
3047Emacs Lisp and use other functions as your building blocks. Some of the
3048functions you will use will themselves be written in Emacs Lisp (perhaps
3049by you) and some will be primitives written in C. The primitive
3050functions are used exactly like those written in Emacs Lisp and behave
3051like them. They are written in C so we can easily run GNU Emacs on any
3052computer that has sufficient power and can run C.
3053
3054Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3055distinguish between the use of functions written in C and the use of
3056functions written in Emacs Lisp. The difference is irrelevant. I
3057mention the distinction only because it is interesting to know. Indeed,
3058unless you investigate, you won't know whether an already-written
3059function is written in Emacs Lisp or C.
3060
3061@node defun, Install, Primitive Functions, Writing Defuns
3062@comment node-name, next, previous, up
3063@section The @code{defun} Special Form
3064@findex defun
3065@cindex Special form of @code{defun}
3066
3067@cindex @samp{function definition} defined
3068In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3069it that tells the computer what to do when the function is called.
3070This code is called the @dfn{function definition} and is created by
3071evaluating a Lisp expression that starts with the symbol @code{defun}
3072(which is an abbreviation for @emph{define function}). Because
3073@code{defun} does not evaluate its arguments in the usual way, it is
3074called a @dfn{special form}.
3075
3076In subsequent sections, we will look at function definitions from the
3077Emacs source code, such as @code{mark-whole-buffer}. In this section,
3078we will describe a simple function definition so you can see how it
3079looks. This function definition uses arithmetic because it makes for a
3080simple example. Some people dislike examples using arithmetic; however,
3081if you are such a person, do not despair. Hardly any of the code we
3082will study in the remainder of this introduction involves arithmetic or
3083mathematics. The examples mostly involve text in one way or another.
3084
3085A function definition has up to five parts following the word
3086@code{defun}:
3087
3088@enumerate
3089@item
3090The name of the symbol to which the function definition should be
3091attached.
3092
3093@item
3094A list of the arguments that will be passed to the function. If no
3095arguments will be passed to the function, this is an empty list,
3096@code{()}.
3097
3098@item
3099Documentation describing the function. (Technically optional, but
3100strongly recommended.)
3101
3102@item
3103Optionally, an expression to make the function interactive so you can
3104use it by typing @kbd{M-x} and then the name of the function; or by
3105typing an appropriate key or keychord.
3106
3107@cindex @samp{body} defined
3108@item
3109The code that instructs the computer what to do: the @dfn{body} of the
3110function definition.
3111@end enumerate
3112
3113It is helpful to think of the five parts of a function definition as
3114being organized in a template, with slots for each part:
3115
3116@smallexample
3117@group
3118(defun @var{function-name} (@var{arguments}@dots{})
3119 "@var{optional-documentation}@dots{}"
3120 (interactive @var{argument-passing-info}) ; @r{optional}
3121 @var{body}@dots{})
3122@end group
3123@end smallexample
3124
3125As an example, here is the code for a function that multiplies its
3126argument by 7. (This example is not interactive. @xref{Interactive,
3127, Making a Function Interactive}, for that information.)
3128
3129@smallexample
3130@group
3131(defun multiply-by-seven (number)
3132 "Multiply NUMBER by seven."
3133 (* 7 number))
3134@end group
3135@end smallexample
3136
3137This definition begins with a parenthesis and the symbol @code{defun},
3138followed by the name of the function.
3139
3140@cindex @samp{argument list} defined
3141The name of the function is followed by a list that contains the
3142arguments that will be passed to the function. This list is called
3143the @dfn{argument list}. In this example, the list has only one
3144element, the symbol, @code{number}. When the function is used, the
3145symbol will be bound to the value that is used as the argument to the
3146function.
3147
3148Instead of choosing the word @code{number} for the name of the argument,
3149I could have picked any other name. For example, I could have chosen
3150the word @code{multiplicand}. I picked the word `number' because it
3151tells what kind of value is intended for this slot; but I could just as
3152well have chosen the word `multiplicand' to indicate the role that the
3153value placed in this slot will play in the workings of the function. I
3154could have called it @code{foogle}, but that would have been a bad
3155choice because it would not tell humans what it means. The choice of
3156name is up to the programmer and should be chosen to make the meaning of
3157the function clear.
3158
3159Indeed, you can choose any name you wish for a symbol in an argument
3160list, even the name of a symbol used in some other function: the name
3161you use in an argument list is private to that particular definition.
3162In that definition, the name refers to a different entity than any use
3163of the same name outside the function definition. Suppose you have a
3164nick-name `Shorty' in your family; when your family members refer to
3165`Shorty', they mean you. But outside your family, in a movie, for
3166example, the name `Shorty' refers to someone else. Because a name in an
3167argument list is private to the function definition, you can change the
3168value of such a symbol inside the body of a function without changing
3169its value outside the function. The effect is similar to that produced
3170by a @code{let} expression. (@xref{let, , @code{let}}.)
3171
3172@ignore
3173Note also that we discuss the word `number' in two different ways: as a
3174symbol that appears in the code, and as the name of something that will
3175be replaced by a something else during the evaluation of the function.
3176In the first case, @code{number} is a symbol, not a number; it happens
3177that within the function, it is a variable who value is the number in
3178question, but our primary interest in it is as a symbol. On the other
3179hand, when we are talking about the function, our interest is that we
3180will substitute a number for the word @var{number}. To keep this
3181distinction clear, we use different typography for the two
3182circumstances. When we talk about this function, or about how it works,
3183we refer to this number by writing @var{number}. In the function
3184itself, we refer to it by writing @code{number}.
3185@end ignore
3186
3187The argument list is followed by the documentation string that
3188describes the function. This is what you see when you type
3189@w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3190write a documentation string like this, you should make the first line
3191a complete sentence since some commands, such as @code{apropos}, print
3192only the first line of a multi-line documentation string. Also, you
3193should not indent the second line of a documentation string, if you
3194have one, because that looks odd when you use @kbd{C-h f}
3195(@code{describe-function}). The documentation string is optional, but
3196it is so useful, it should be included in almost every function you
3197write.
3198
3199@findex * @r{(multiplication)}
3200The third line of the example consists of the body of the function
3201definition. (Most functions' definitions, of course, are longer than
3202this.) In this function, the body is the list, @code{(* 7 number)}, which
3203says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3204@code{*} is the function for multiplication, just as @code{+} is the
3205function for addition.)
3206
3207When you use the @code{multiply-by-seven} function, the argument
3208@code{number} evaluates to the actual number you want used. Here is an
3209example that shows how @code{multiply-by-seven} is used; but don't try
3210to evaluate this yet!
3211
3212@smallexample
3213(multiply-by-seven 3)
3214@end smallexample
3215
3216@noindent
3217The symbol @code{number}, specified in the function definition in the
3218next section, is given or ``bound to'' the value 3 in the actual use of
3219the function. Note that although @code{number} was inside parentheses
3220in the function definition, the argument passed to the
3221@code{multiply-by-seven} function is not in parentheses. The
3222parentheses are written in the function definition so the computer can
3223figure out where the argument list ends and the rest of the function
3224definition begins.
3225
3226If you evaluate this example, you are likely to get an error message.
3227(Go ahead, try it!) This is because we have written the function
3228definition, but not yet told the computer about the definition---we have
3229not yet installed (or `loaded') the function definition in Emacs.
3230Installing a function is the process that tells the Lisp interpreter the
3231definition of the function. Installation is described in the next
3232section.
3233
3234@node Install, Interactive, defun, Writing Defuns
3235@comment node-name, next, previous, up
3236@section Install a Function Definition
3237@cindex Install a Function Definition
3238@cindex Definition installation
3239@cindex Function definition installation
3240
3241If you are reading this inside of Info in Emacs, you can try out the
3242@code{multiply-by-seven} function by first evaluating the function
3243definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3244the function definition follows. Place the cursor after the last
3245parenthesis of the function definition and type @kbd{C-x C-e}. When you
3246do this, @code{multiply-by-seven} will appear in the echo area. (What
3247this means is that when a function definition is evaluated, the value it
3248returns is the name of the defined function.) At the same time, this
3249action installs the function definition.
3250
3251@smallexample
3252@group
3253(defun multiply-by-seven (number)
3254 "Multiply NUMBER by seven."
3255 (* 7 number))
3256@end group
3257@end smallexample
3258
3259@noindent
3260By evaluating this @code{defun}, you have just installed
3261@code{multiply-by-seven} in Emacs. The function is now just as much a
3262part of Emacs as @code{forward-word} or any other editing function you
3263use. (@code{multiply-by-seven} will stay installed until you quit
3264Emacs. To reload code automatically whenever you start Emacs, see
3265@ref{Permanent Installation, , Installing Code Permanently}.)
3266
3267
3268@menu
3269* Effect of installation::
3270* Change a defun:: How to change a function definition.
3271@end menu
3272
3273@node Effect of installation, Change a defun, Install, Install
3274@ifnottex
3275@unnumberedsubsec The effect of installation
3276@end ifnottex
3277
3278
3279You can see the effect of installing @code{multiply-by-seven} by
3280evaluating the following sample. Place the cursor after the following
3281expression and type @kbd{C-x C-e}. The number 21 will appear in the
3282echo area.
3283
3284@smallexample
3285(multiply-by-seven 3)
3286@end smallexample
3287
3288If you wish, you can read the documentation for the function by typing
3289@kbd{C-h f} (@code{describe-function}) and then the name of the
3290function, @code{multiply-by-seven}. When you do this, a
3291@file{*Help*} window will appear on your screen that says:
3292
3293@smallexample
3294@group
3295multiply-by-seven:
3296Multiply NUMBER by seven.
3297@end group
3298@end smallexample
3299
3300@noindent
3301(To return to a single window on your screen, type @kbd{C-x 1}.)
3302
3303@node Change a defun, , Effect of installation, Install
3304@comment node-name, next, previous, up
3305@subsection Change a Function Definition
3306@cindex Changing a function definition
3307@cindex Function definition, how to change
3308@cindex Definition, how to change
3309
3310If you want to change the code in @code{multiply-by-seven}, just rewrite
3311it. To install the new version in place of the old one, evaluate the
3312function definition again. This is how you modify code in Emacs. It is
3313very simple.
3314
3315As an example, you can change the @code{multiply-by-seven} function to
3316add the number to itself seven times instead of multiplying the number
3317by seven. It produces the same answer, but by a different path. At
3318the same time, we will add a comment to the code; a comment is text
3319that the Lisp interpreter ignores, but that a human reader may find
3320useful or enlightening. The comment is that this is the ``second
3321version''.
3322
3323@smallexample
3324@group
3325(defun multiply-by-seven (number) ; @r{Second version.}
3326 "Multiply NUMBER by seven."
3327 (+ number number number number number number number))
3328@end group
3329@end smallexample
3330
3331@cindex Comments in Lisp code
3332The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3333line that follows a semicolon is a comment. The end of the line is the
3334end of the comment. To stretch a comment over two or more lines, begin
3335each line with a semicolon.
3336
3337@xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3338File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3339Reference Manual}, for more about comments.
3340
3341You can install this version of the @code{multiply-by-seven} function by
3342evaluating it in the same way you evaluated the first function: place
3343the cursor after the last parenthesis and type @kbd{C-x C-e}.
3344
3345In summary, this is how you write code in Emacs Lisp: you write a
3346function; install it; test it; and then make fixes or enhancements and
3347install it again.
3348
3349@node Interactive, Interactive Options, Install, Writing Defuns
3350@comment node-name, next, previous, up
3351@section Make a Function Interactive
3352@cindex Interactive functions
3353@findex interactive
3354
3355You make a function interactive by placing a list that begins with
3356the special form @code{interactive} immediately after the
3357documentation. A user can invoke an interactive function by typing
3358@kbd{M-x} and then the name of the function; or by typing the keys to
3359which it is bound, for example, by typing @kbd{C-n} for
3360@code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3361
3362Interestingly, when you call an interactive function interactively,
3363the value returned is not automatically displayed in the echo area.
3364This is because you often call an interactive function for its side
3365effects, such as moving forward by a word or line, and not for the
3366value returned. If the returned value were displayed in the echo area
3367each time you typed a key, it would be very distracting.
3368
3369@menu
3370* Interactive multiply-by-seven:: An overview.
3371* multiply-by-seven in detail:: The interactive version.
3372@end menu
3373
3374@node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3375@ifnottex
3376@unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3377@end ifnottex
3378
3379Both the use of the special form @code{interactive} and one way to
3380display a value in the echo area can be illustrated by creating an
3381interactive version of @code{multiply-by-seven}.
3382
3383@need 1250
3384Here is the code:
3385
3386@smallexample
3387@group
3388(defun multiply-by-seven (number) ; @r{Interactive version.}
3389 "Multiply NUMBER by seven."
3390 (interactive "p")
3391 (message "The result is %d" (* 7 number)))
3392@end group
3393@end smallexample
3394
3395@noindent
3396You can install this code by placing your cursor after it and typing
3397@kbd{C-x C-e}. The name of the function will appear in your echo area.
3398Then, you can use this code by typing @kbd{C-u} and a number and then
3399typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3400@samp{The result is @dots{}} followed by the product will appear in the
3401echo area.
3402
3403Speaking more generally, you invoke a function like this in either of two
3404ways:
3405
3406@enumerate
3407@item
3408By typing a prefix argument that contains the number to be passed, and
3409then typing @kbd{M-x} and the name of the function, as with
3410@kbd{C-u 3 M-x forward-sentence}; or,
3411
3412@item
3413By typing whatever key or keychord the function is bound to, as with
3414@kbd{C-u 3 M-e}.
3415@end enumerate
3416
3417@noindent
3418Both the examples just mentioned work identically to move point forward
3419three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3420it could not be used as an example of key binding.)
3421
3422(@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3423to a key.)
3424
3425A prefix argument is passed to an interactive function by typing the
3426@key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3427typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3428type @kbd{C-u} without a number, it defaults to 4).
3429
3430@node multiply-by-seven in detail, , Interactive multiply-by-seven, Interactive
3431@comment node-name, next, previous, up
3432@subsection An Interactive @code{multiply-by-seven}
3433
3434Let's look at the use of the special form @code{interactive} and then at
3435the function @code{message} in the interactive version of
3436@code{multiply-by-seven}. You will recall that the function definition
3437looks like this:
3438
3439@smallexample
3440@group
3441(defun multiply-by-seven (number) ; @r{Interactive version.}
3442 "Multiply NUMBER by seven."
3443 (interactive "p")
3444 (message "The result is %d" (* 7 number)))
3445@end group
3446@end smallexample
3447
3448In this function, the expression, @code{(interactive "p")}, is a list of
3449two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3450the function and use its value for the argument of the function.
3451
3452@need 1000
3453The argument will be a number. This means that the symbol
3454@code{number} will be bound to a number in the line:
3455
3456@smallexample
3457(message "The result is %d" (* 7 number))
3458@end smallexample
3459
3460@need 1250
3461@noindent
3462For example, if your prefix argument is 5, the Lisp interpreter will
3463evaluate the line as if it were:
3464
3465@smallexample
3466(message "The result is %d" (* 7 5))
3467@end smallexample
3468
3469@noindent
3470(If you are reading this in GNU Emacs, you can evaluate this expression
3471yourself.) First, the interpreter will evaluate the inner list, which
3472is @code{(* 7 5)}. This returns a value of 35. Next, it
3473will evaluate the outer list, passing the values of the second and
3474subsequent elements of the list to the function @code{message}.
3475
3476As we have seen, @code{message} is an Emacs Lisp function especially
3477designed for sending a one line message to a user. (@xref{message, , The
3478@code{message} function}.)
3479In summary, the @code{message} function prints its first argument in the
3480echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3481@samp{%c}. When it sees one of these control sequences, the function
3482looks to the second and subsequent arguments and prints the value of the
3483argument in the location in the string where the control sequence is
3484located.
3485
3486In the interactive @code{multiply-by-seven} function, the control string
3487is @samp{%d}, which requires a number, and the value returned by
3488evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3489is printed in place of the @samp{%d} and the message is @samp{The result
3490is 35}.
3491
3492(Note that when you call the function @code{multiply-by-seven}, the
3493message is printed without quotes, but when you call @code{message}, the
3494text is printed in double quotes. This is because the value returned by
3495@code{message} is what appears in the echo area when you evaluate an
3496expression whose first element is @code{message}; but when embedded in a
3497function, @code{message} prints the text as a side effect without
3498quotes.)
3499
3500@node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3501@comment node-name, next, previous, up
3502@section Different Options for @code{interactive}
3503@cindex Options for @code{interactive}
3504@cindex Interactive options
3505
3506In the example, @code{multiply-by-seven} used @code{"p"} as the
3507argument to @code{interactive}. This argument told Emacs to interpret
3508your typing either @kbd{C-u} followed by a number or @key{META}
3509followed by a number as a command to pass that number to the function
3510as its argument. Emacs has more than twenty characters predefined for
3511use with @code{interactive}. In almost every case, one of these
3512options will enable you to pass the right information interactively to
3513a function. (@xref{Interactive Codes, , Code Characters for
3514@code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3515
3516@need 1250
3517For example, the character @samp{r} causes Emacs to pass the beginning
3518and end of the region (the current values of point and mark) to the
3519function as two separate arguments. It is used as follows:
3520
3521@smallexample
3522(interactive "r")
3523@end smallexample
3524
3525On the other hand, a @samp{B} tells Emacs to ask for the name of a
3526buffer that will be passed to the function. When it sees a @samp{B},
3527Emacs will ask for the name by prompting the user in the minibuffer,
3528using a string that follows the @samp{B}, as in @code{"BAppend to
3529buffer:@: "}. Not only will Emacs prompt for the name, but Emacs will
3530complete the name if you type enough of it and press @key{TAB}.
3531
3532A function with two or more arguments can have information passed to
3533each argument by adding parts to the string that follows
3534@code{interactive}. When you do this, the information is passed to
3535each argument in the same order it is specified in the
3536@code{interactive} list. In the string, each part is separated from
3537the next part by a @samp{\n}, which is a newline. For example, you
3538could follow @code{"BAppend to buffer:@: "} with a @samp{\n}) and an
3539@samp{r}. This would cause Emacs to pass the values of point and mark
3540to the function as well as prompt you for the buffer---three arguments
3541in all.
3542
3543In this case, the function definition would look like the following,
3544where @code{buffer}, @code{start}, and @code{end} are the symbols to
3545which @code{interactive} binds the buffer and the current values of the
3546beginning and ending of the region:
3547
3548@smallexample
3549@group
3550(defun @var{name-of-function} (buffer start end)
3551 "@var{documentation}@dots{}"
3552 (interactive "BAppend to buffer:@: \nr")
3553 @var{body-of-function}@dots{})
3554@end group
3555@end smallexample
3556
3557@noindent
3558(The space after the colon in the prompt makes it look better when you
3559are prompted. The @code{append-to-buffer} function looks exactly like
3560this. @xref{append-to-buffer, , The Definition of
3561@code{append-to-buffer}}.)
3562
3563If a function does not have arguments, then @code{interactive} does not
3564require any. Such a function contains the simple expression
3565@code{(interactive)}. The @code{mark-whole-buffer} function is like
3566this.
3567
3568Alternatively, if the special letter-codes are not right for your
3569application, you can pass your own arguments to @code{interactive} as
3570a list. @xref{interactive, , Using @code{Interactive}, elisp, The
3571GNU Emacs Lisp Reference Manual}, for more information about this advanced
3572technique.
3573
3574@node Permanent Installation, let, Interactive Options, Writing Defuns
3575@comment node-name, next, previous, up
3576@section Install Code Permanently
3577@cindex Install code permanently
3578@cindex Permanent code installation
3579@cindex Code installation
3580
3581When you install a function definition by evaluating it, it will stay
3582installed until you quit Emacs. The next time you start a new session
3583of Emacs, the function will not be installed unless you evaluate the
3584function definition again.
3585
3586At some point, you may want to have code installed automatically
3587whenever you start a new session of Emacs. There are several ways of
3588doing this:
3589
3590@itemize @bullet
3591@item
3592If you have code that is just for yourself, you can put the code for the
3593function definition in your @file{.emacs} initialization file. When you
3594start Emacs, your @file{.emacs} file is automatically evaluated and all
3595the function definitions within it are installed.
3596@xref{Emacs Initialization, , Your @file{.emacs} File}.
3597
3598@item
3599Alternatively, you can put the function definitions that you want
3600installed in one or more files of their own and use the @code{load}
3601function to cause Emacs to evaluate and thereby install each of the
3602functions in the files.
3603@xref{Loading Files, , Loading Files}.
3604
3605@item
3606On the other hand, if you have code that your whole site will use, it
3607is usual to put it in a file called @file{site-init.el} that is loaded
3608when Emacs is built. This makes the code available to everyone who
3609uses your machine. (See the @file{INSTALL} file that is part of the
3610Emacs distribution.)
3611@end itemize
3612
3613Finally, if you have code that everyone who uses Emacs may want, you
3614can post it on a computer network or send a copy to the Free Software
3615Foundation. (When you do this, please license the code and its
3616documentation under a license that permits other people to run, copy,
3617study, modify, and redistribute the code and which protects you from
3618having your work taken from you.) If you send a copy of your code to
3619the Free Software Foundation, and properly protect yourself and
3620others, it may be included in the next release of Emacs. In large
3621part, this is how Emacs has grown over the past years, by donations.
3622
3623@node let, if, Permanent Installation, Writing Defuns
3624@comment node-name, next, previous, up
3625@section @code{let}
3626@findex let
3627
3628The @code{let} expression is a special form in Lisp that you will need
3629to use in most function definitions.
3630
3631@code{let} is used to attach or bind a symbol to a value in such a way
3632that the Lisp interpreter will not confuse the variable with a
3633variable of the same name that is not part of the function.
3634
3635To understand why the @code{let} special form is necessary, consider
3636the situation in which you own a home that you generally refer to as
3637`the house', as in the sentence, ``The house needs painting.'' If you
3638are visiting a friend and your host refers to `the house', he is
3639likely to be referring to @emph{his} house, not yours, that is, to a
3640different house.
3641
3642If your friend is referring to his house and you think he is referring
3643to your house, you may be in for some confusion. The same thing could
3644happen in Lisp if a variable that is used inside of one function has
3645the same name as a variable that is used inside of another function,
3646and the two are not intended to refer to the same value. The
3647@code{let} special form prevents this kind of confusion.
3648
3649@menu
3650* Prevent confusion::
3651* Parts of let Expression::
3652* Sample let Expression::
3653* Uninitialized let Variables::
3654@end menu
3655
3656@node Prevent confusion, Parts of let Expression, let, let
3657@ifnottex
3658@unnumberedsubsec @code{let} Prevents Confusion
3659@end ifnottex
3660
3661@cindex @samp{local variable} defined
3662The @code{let} special form prevents confusion. @code{let} creates a
3663name for a @dfn{local variable} that overshadows any use of the same
3664name outside the @code{let} expression. This is like understanding
3665that whenever your host refers to `the house', he means his house, not
3666yours. (Symbols used in argument lists work the same way.
3667@xref{defun, , The @code{defun} Special Form}.)
3668
3669Local variables created by a @code{let} expression retain their value
3670@emph{only} within the @code{let} expression itself (and within
3671expressions called within the @code{let} expression); the local
3672variables have no effect outside the @code{let} expression.
3673
3674Another way to think about @code{let} is that it is like a @code{setq}
3675that is temporary and local. The values set by @code{let} are
3676automatically undone when the @code{let} is finished. The setting
e601d8fd 3677only affects expressions that are inside the bounds of the @code{let}
8b096dce
EZ
3678expression. In computer science jargon, we would say ``the binding of
3679a symbol is visible only in functions called in the @code{let} form;
3680in Emacs Lisp, scoping is dynamic, not lexical.''
3681
3682@code{let} can create more than one variable at once. Also,
3683@code{let} gives each variable it creates an initial value, either a
3684value specified by you, or @code{nil}. (In the jargon, this is called
3685`binding the variable to the value'.) After @code{let} has created
3686and bound the variables, it executes the code in the body of the
3687@code{let}, and returns the value of the last expression in the body,
3688as the value of the whole @code{let} expression. (`Execute' is a jargon
3689term that means to evaluate a list; it comes from the use of the word
3690meaning `to give practical effect to' (@cite{Oxford English
3691Dictionary}). Since you evaluate an expression to perform an action,
3692`execute' has evolved as a synonym to `evaluate'.)
3693
3694@node Parts of let Expression, Sample let Expression, Prevent confusion, let
3695@comment node-name, next, previous, up
3696@subsection The Parts of a @code{let} Expression
3697@cindex @code{let} expression, parts of
3698@cindex Parts of @code{let} expression
3699
3700@cindex @samp{varlist} defined
3701A @code{let} expression is a list of three parts. The first part is
3702the symbol @code{let}. The second part is a list, called a
3703@dfn{varlist}, each element of which is either a symbol by itself or a
3704two-element list, the first element of which is a symbol. The third
3705part of the @code{let} expression is the body of the @code{let}. The
3706body usually consists of one or more lists.
3707
3708@need 800
3709A template for a @code{let} expression looks like this:
3710
3711@smallexample
3712(let @var{varlist} @var{body}@dots{})
3713@end smallexample
3714
3715@noindent
3716The symbols in the varlist are the variables that are given initial
3717values by the @code{let} special form. Symbols by themselves are given
3718the initial value of @code{nil}; and each symbol that is the first
3719element of a two-element list is bound to the value that is returned
3720when the Lisp interpreter evaluates the second element.
3721
3722Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3723this case, in a @code{let} expression, Emacs binds the symbol
3724@code{thread} to an initial value of @code{nil}, and binds the symbol
3725@code{needles} to an initial value of 3.
3726
3727When you write a @code{let} expression, what you do is put the
3728appropriate expressions in the slots of the @code{let} expression
3729template.
3730
3731If the varlist is composed of two-element lists, as is often the case,
3732the template for the @code{let} expression looks like this:
3733
3734@smallexample
3735@group
3736(let ((@var{variable} @var{value})
3737 (@var{variable} @var{value})
3738 @dots{})
3739 @var{body}@dots{})
3740@end group
3741@end smallexample
3742
3743@node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3744@comment node-name, next, previous, up
3745@subsection Sample @code{let} Expression
3746@cindex Sample @code{let} expression
3747@cindex @code{let} expression sample
3748
3749The following expression creates and gives initial values
3750to the two variables @code{zebra} and @code{tiger}. The body of the
3751@code{let} expression is a list which calls the @code{message} function.
3752
3753@smallexample
3754@group
3755(let ((zebra 'stripes)
3756 (tiger 'fierce))
3757 (message "One kind of animal has %s and another is %s."
3758 zebra tiger))
3759@end group
3760@end smallexample
3761
3762Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3763
3764The two variables are @code{zebra} and @code{tiger}. Each variable is
3765the first element of a two-element list and each value is the second
3766element of its two-element list. In the varlist, Emacs binds the
3767variable @code{zebra} to the value @code{stripes}, and binds the
3768variable @code{tiger} to the value @code{fierce}. In this example,
3769both values are symbols preceded by a quote. The values could just as
3770well have been another list or a string. The body of the @code{let}
3771follows after the list holding the variables. In this example, the body
3772is a list that uses the @code{message} function to print a string in
3773the echo area.
3774
3775@need 1500
3776You may evaluate the example in the usual fashion, by placing the
3777cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3778this, the following will appear in the echo area:
3779
3780@smallexample
3781"One kind of animal has stripes and another is fierce."
3782@end smallexample
3783
3784As we have seen before, the @code{message} function prints its first
3785argument, except for @samp{%s}. In this example, the value of the variable
3786@code{zebra} is printed at the location of the first @samp{%s} and the
3787value of the variable @code{tiger} is printed at the location of the
3788second @samp{%s}.
3789
3790@node Uninitialized let Variables, , Sample let Expression, let
3791@comment node-name, next, previous, up
3792@subsection Uninitialized Variables in a @code{let} Statement
3793@cindex Uninitialized @code{let} variables
3794@cindex @code{let} variables uninitialized
3795
3796If you do not bind the variables in a @code{let} statement to specific
3797initial values, they will automatically be bound to an initial value of
3798@code{nil}, as in the following expression:
3799
3800@smallexample
3801@group
3802(let ((birch 3)
3803 pine
3804 fir
3805 (oak 'some))
3806 (message
3807 "Here are %d variables with %s, %s, and %s value."
3808 birch pine fir oak))
3809@end group
3810@end smallexample
3811
3812@noindent
3813Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3814
3815@need 1250
3816If you evaluate this expression in the usual way, the following will
3817appear in your echo area:
3818
3819@smallexample
3820"Here are 3 variables with nil, nil, and some value."
3821@end smallexample
3822
3823@noindent
3824In this example, Emacs binds the symbol @code{birch} to the number 3,
3825binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3826the symbol @code{oak} to the value @code{some}.
3827
3828Note that in the first part of the @code{let}, the variables @code{pine}
3829and @code{fir} stand alone as atoms that are not surrounded by
3830parentheses; this is because they are being bound to @code{nil}, the
3831empty list. But @code{oak} is bound to @code{some} and so is a part of
3832the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3833number 3 and so is in a list with that number. (Since a number
3834evaluates to itself, the number does not need to be quoted. Also, the
3835number is printed in the message using a @samp{%d} rather than a
3836@samp{%s}.) The four variables as a group are put into a list to
3837delimit them from the body of the @code{let}.
3838
3839@node if, else, let, Writing Defuns
3840@comment node-name, next, previous, up
3841@section The @code{if} Special Form
3842@findex if
3843@cindex Conditional with @code{if}
3844
3845A third special form, in addition to @code{defun} and @code{let}, is the
3846conditional @code{if}. This form is used to instruct the computer to
3847make decisions. You can write function definitions without using
3848@code{if}, but it is used often enough, and is important enough, to be
3849included here. It is used, for example, in the code for the
3850function @code{beginning-of-buffer}.
3851
3852The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3853@emph{then} an expression is evaluated.'' If the test is not true, the
3854expression is not evaluated. For example, you might make a decision
3855such as, ``if it is warm and sunny, then go to the beach!''
3856
3857@menu
3858* if in more detail::
3859* type-of-animal in detail:: An example of an @code{if} expression.
3860@end menu
3861
3862@node if in more detail, type-of-animal in detail, if, if
3863@ifnottex
3864@unnumberedsubsec @code{if} in more detail
3865@end ifnottex
3866
3867@cindex @samp{if-part} defined
3868@cindex @samp{then-part} defined
3869An @code{if} expression written in Lisp does not use the word `then';
3870the test and the action are the second and third elements of the list
3871whose first element is @code{if}. Nonetheless, the test part of an
3872@code{if} expression is often called the @dfn{if-part} and the second
3873argument is often called the @dfn{then-part}.
3874
3875Also, when an @code{if} expression is written, the true-or-false-test
3876is usually written on the same line as the symbol @code{if}, but the
3877action to carry out if the test is true, the ``then-part'', is written
3878on the second and subsequent lines. This makes the @code{if}
3879expression easier to read.
3880
3881@smallexample
3882@group
3883(if @var{true-or-false-test}
3884 @var{action-to-carry-out-if-test-is-true})
3885@end group
3886@end smallexample
3887
3888@noindent
3889The true-or-false-test will be an expression that
3890is evaluated by the Lisp interpreter.
3891
3892Here is an example that you can evaluate in the usual manner. The test
3893is whether the number 5 is greater than the number 4. Since it is, the
3894message @samp{5 is greater than 4!} will be printed.
3895
3896@smallexample
3897@group
3898(if (> 5 4) ; @r{if-part}
3899 (message "5 is greater than 4!")) ; @r{then-part}
3900@end group
3901@end smallexample
3902
3903@noindent
3904(The function @code{>} tests whether its first argument is greater than
3905its second argument and returns true if it is.)
3906@findex > (greater than)
3907
3908Of course, in actual use, the test in an @code{if} expression will not
3909be fixed for all time as it is by the expression @code{(> 5 4)}.
3910Instead, at least one of the variables used in the test will be bound to
3911a value that is not known ahead of time. (If the value were known ahead
3912of time, we would not need to run the test!)
3913
3914For example, the value may be bound to an argument of a function
3915definition. In the following function definition, the character of the
3916animal is a value that is passed to the function. If the value bound to
3917@code{characteristic} is @code{fierce}, then the message, @samp{It's a
3918tiger!} will be printed; otherwise, @code{nil} will be returned.
3919
3920@smallexample
3921@group
3922(defun type-of-animal (characteristic)
3923 "Print message in echo area depending on CHARACTERISTIC.
3924If the CHARACTERISTIC is the symbol `fierce',
3925then warn of a tiger."
3926 (if (equal characteristic 'fierce)
3927 (message "It's a tiger!")))
3928@end group
3929@end smallexample
3930
3931@need 1500
3932@noindent
3933If you are reading this inside of GNU Emacs, you can evaluate the
3934function definition in the usual way to install it in Emacs, and then you
3935can evaluate the following two expressions to see the results:
3936
3937@smallexample
3938@group
3939(type-of-animal 'fierce)
3940
3941(type-of-animal 'zebra)
3942
3943@end group
3944@end smallexample
3945
3946@c Following sentences rewritten to prevent overfull hbox.
3947@noindent
3948When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3949following message printed in the echo area: @code{"It's a tiger!"}; and
3950when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3951printed in the echo area.
3952
3953@node type-of-animal in detail, , if in more detail, if
3954@comment node-name, next, previous, up
3955@subsection The @code{type-of-animal} Function in Detail
3956
3957Let's look at the @code{type-of-animal} function in detail.
3958
3959The function definition for @code{type-of-animal} was written by filling
3960the slots of two templates, one for a function definition as a whole, and
3961a second for an @code{if} expression.
3962
3963@need 1250
3964The template for every function that is not interactive is:
3965
3966@smallexample
3967@group
3968(defun @var{name-of-function} (@var{argument-list})
3969 "@var{documentation}@dots{}"
3970 @var{body}@dots{})
3971@end group
3972@end smallexample
3973
3974@need 800
3975The parts of the function that match this template look like this:
3976
3977@smallexample
3978@group
3979(defun type-of-animal (characteristic)
3980 "Print message in echo area depending on CHARACTERISTIC.
3981If the CHARACTERISTIC is the symbol `fierce',
3982then warn of a tiger."
3983 @var{body: the} @code{if} @var{expression})
3984@end group
3985@end smallexample
3986
3987The name of function is @code{type-of-animal}; it is passed the value
3988of one argument. The argument list is followed by a multi-line
3989documentation string. The documentation string is included in the
3990example because it is a good habit to write documentation string for
3991every function definition. The body of the function definition
3992consists of the @code{if} expression.
3993
3994@need 800
3995The template for an @code{if} expression looks like this:
3996
3997@smallexample
3998@group
3999(if @var{true-or-false-test}
4000 @var{action-to-carry-out-if-the-test-returns-true})
4001@end group
4002@end smallexample
4003
4004@need 1250
4005In the @code{type-of-animal} function, the code for the @code{if}
4006looks like this:
4007
4008@smallexample
4009@group
4010(if (equal characteristic 'fierce)
4011 (message "It's a tiger!")))
4012@end group
4013@end smallexample
4014
4015@need 800
4016Here, the true-or-false-test is the expression:
4017
4018@smallexample
4019(equal characteristic 'fierce)
4020@end smallexample
4021
4022@noindent
4023In Lisp, @code{equal} is a function that determines whether its first
4024argument is equal to its second argument. The second argument is the
4025quoted symbol @code{'fierce} and the first argument is the value of the
4026symbol @code{characteristic}---in other words, the argument passed to
4027this function.
4028
4029In the first exercise of @code{type-of-animal}, the argument
4030@code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4031is equal to @code{fierce}, the expression, @code{(equal characteristic
4032'fierce)}, returns a value of true. When this happens, the @code{if}
4033evaluates the second argument or then-part of the @code{if}:
4034@code{(message "It's tiger!")}.
4035
4036On the other hand, in the second exercise of @code{type-of-animal}, the
4037argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4038is not equal to @code{fierce}, so the then-part is not evaluated and
4039@code{nil} is returned by the @code{if} expression.
4040
4041@node else, Truth & Falsehood, if, Writing Defuns
4042@comment node-name, next, previous, up
4043@section If--then--else Expressions
4044@cindex Else
4045
4046An @code{if} expression may have an optional third argument, called
4047the @dfn{else-part}, for the case when the true-or-false-test returns
4048false. When this happens, the second argument or then-part of the
4049overall @code{if} expression is @emph{not} evaluated, but the third or
4050else-part @emph{is} evaluated. You might think of this as the cloudy
4051day alternative for the decision `if it is warm and sunny, then go to
4052the beach, else read a book!''.
4053
4054The word ``else'' is not written in the Lisp code; the else-part of an
4055@code{if} expression comes after the then-part. In the written Lisp, the
4056else-part is usually written to start on a line of its own and is
4057indented less than the then-part:
4058
4059@smallexample
4060@group
4061(if @var{true-or-false-test}
4062 @var{action-to-carry-out-if-the-test-returns-true}
4063 @var{action-to-carry-out-if-the-test-returns-false})
4064@end group
4065@end smallexample
4066
4067For example, the following @code{if} expression prints the message @samp{4
4068is not greater than 5!} when you evaluate it in the usual way:
4069
4070@smallexample
4071@group
4072(if (> 4 5) ; @r{if-part}
4073 (message "5 is greater than 4!") ; @r{then-part}
4074 (message "4 is not greater than 5!")) ; @r{else-part}
4075@end group
4076@end smallexample
4077
4078@noindent
4079Note that the different levels of indentation make it easy to
4080distinguish the then-part from the else-part. (GNU Emacs has several
4081commands that automatically indent @code{if} expressions correctly.
4082@xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4083
4084We can extend the @code{type-of-animal} function to include an
4085else-part by simply incorporating an additional part to the @code{if}
4086expression.
4087
4088@need 1500
4089You can see the consequences of doing this if you evaluate the following
4090version of the @code{type-of-animal} function definition to install it
4091and then evaluate the two subsequent expressions to pass different
4092arguments to the function.
4093
4094@smallexample
4095@group
4096(defun type-of-animal (characteristic) ; @r{Second version.}
4097 "Print message in echo area depending on CHARACTERISTIC.
4098If the CHARACTERISTIC is the symbol `fierce',
4099then warn of a tiger;
4100else say it's not fierce."
4101 (if (equal characteristic 'fierce)
4102 (message "It's a tiger!")
4103 (message "It's not fierce!")))
4104@end group
4105@end smallexample
4106@sp 1
4107
4108@smallexample
4109@group
4110(type-of-animal 'fierce)
4111
4112(type-of-animal 'zebra)
4113
4114@end group
4115@end smallexample
4116
4117@c Following sentence rewritten to prevent overfull hbox.
4118@noindent
4119When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4120following message printed in the echo area: @code{"It's a tiger!"}; but
4121when you evaluate @code{(type-of-animal 'zebra)}, you will see
4122@code{"It's not fierce!"}.
4123
4124(Of course, if the @var{characteristic} were @code{ferocious}, the
4125message @code{"It's not fierce!"} would be printed; and it would be
4126misleading! When you write code, you need to take into account the
4127possibility that some such argument will be tested by the @code{if} and
4128write your program accordingly.)
4129
4130@node Truth & Falsehood, save-excursion, else, Writing Defuns
4131@comment node-name, next, previous, up
4132@section Truth and Falsehood in Emacs Lisp
4133@cindex Truth and falsehood in Emacs Lisp
4134@cindex Falsehood and truth in Emacs Lisp
4135@findex nil
4136
4137There is an important aspect to the truth test in an @code{if}
4138expression. So far, we have spoken of `true' and `false' as values of
4139predicates as if they were new kinds of Emacs Lisp objects. In fact,
4140`false' is just our old friend @code{nil}. Anything else---anything
4141at all---is `true'.
4142
4143The expression that tests for truth is interpreted as @dfn{true}
4144if the result of evaluating it is a value that is not @code{nil}. In
4145other words, the result of the test is considered true if the value
4146returned is a number such as 47, a string such as @code{"hello"}, or a
4147symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4148even a buffer!
4149
4150@menu
4151* nil explained:: @code{nil} has two meanings.
4152@end menu
4153
4154@node nil explained, , Truth & Falsehood, Truth & Falsehood
4155@ifnottex
4156@unnumberedsubsec An explanation of @code{nil}
4157@end ifnottex
4158
4159Before illustrating a test for truth, we need an explanation of @code{nil}.
4160
4161In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4162empty list. Second, it means false and is the value returned when a
4163true-or-false-test tests false. @code{nil} can be written as an empty
4164list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4165concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4166to use @code{nil} for false and @code{()} for the empty list.
4167
4168In Emacs Lisp, any value that is not @code{nil}---is not the empty
4169list---is considered true. This means that if an evaluation returns
4170something that is not an empty list, an @code{if} expression will test
4171true. For example, if a number is put in the slot for the test, it
4172will be evaluated and will return itself, since that is what numbers
4173do when evaluated. In this conditional, the @code{if} expression will
4174test true. The expression tests false only when @code{nil}, an empty
4175list, is returned by evaluating the expression.
4176
4177You can see this by evaluating the two expressions in the following examples.
4178
4179In the first example, the number 4 is evaluated as the test in the
4180@code{if} expression and returns itself; consequently, the then-part
4181of the expression is evaluated and returned: @samp{true} appears in
4182the echo area. In the second example, the @code{nil} indicates false;
4183consequently, the else-part of the expression is evaluated and
4184returned: @samp{false} appears in the echo area.
4185
4186@smallexample
4187@group
4188(if 4
4189 'true
4190 'false)
4191@end group
4192
4193@group
4194(if nil
4195 'true
4196 'false)
4197@end group
4198@end smallexample
4199
4200@need 1250
4201Incidentally, if some other useful value is not available for a test that
4202returns true, then the Lisp interpreter will return the symbol @code{t}
4203for true. For example, the expression @code{(> 5 4)} returns @code{t}
4204when evaluated, as you can see by evaluating it in the usual way:
4205
4206@smallexample
4207(> 5 4)
4208@end smallexample
4209
4210@need 1250
4211@noindent
4212On the other hand, this function returns @code{nil} if the test is false.
4213
4214@smallexample
4215(> 4 5)
4216@end smallexample
4217
4218@node save-excursion, Review, Truth & Falsehood, Writing Defuns
4219@comment node-name, next, previous, up
4220@section @code{save-excursion}
4221@findex save-excursion
4222@cindex Region, what it is
4223@cindex Preserving point, mark, and buffer
4224@cindex Point, mark, buffer preservation
4225@findex point
4226@findex mark
4227
4228The @code{save-excursion} function is the fourth and final special form
4229that we will discuss in this chapter.
4230
4231In Emacs Lisp programs used for editing, the @code{save-excursion}
4232function is very common. It saves the location of point and mark,
4233executes the body of the function, and then restores point and mark to
4234their previous positions if their locations were changed. Its primary
4235purpose is to keep the user from being surprised and disturbed by
4236unexpected movement of point or mark.
4237
4238@menu
4239* Point and mark:: A review of various locations.
4240* Template for save-excursion::
4241@end menu
4242
4243@node Point and mark, Template for save-excursion, save-excursion, save-excursion
4244@ifnottex
4245@unnumberedsubsec Point and Mark
4246@end ifnottex
4247
4248Before discussing @code{save-excursion}, however, it may be useful
4249first to review what point and mark are in GNU Emacs. @dfn{Point} is
4250the current location of the cursor. Wherever the cursor
4251is, that is point. More precisely, on terminals where the cursor
4252appears to be on top of a character, point is immediately before the
4253character. In Emacs Lisp, point is an integer. The first character in
4254a buffer is number one, the second is number two, and so on. The
4255function @code{point} returns the current position of the cursor as a
4256number. Each buffer has its own value for point.
4257
4258The @dfn{mark} is another position in the buffer; its value can be set
4259with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4260a mark has been set, you can use the command @kbd{C-x C-x}
4261(@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4262and set the mark to be the previous position of point. In addition, if
4263you set another mark, the position of the previous mark is saved in the
4264mark ring. Many mark positions can be saved this way. You can jump the
4265cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4266times.
4267
4268The part of the buffer between point and mark is called @dfn{the
4269region}. Numerous commands work on the region, including
4270@code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4271@code{print-region}.
4272
4273The @code{save-excursion} special form saves the locations of point and
4274mark and restores those positions after the code within the body of the
4275special form is evaluated by the Lisp interpreter. Thus, if point were
4276in the beginning of a piece of text and some code moved point to the end
4277of the buffer, the @code{save-excursion} would put point back to where
4278it was before, after the expressions in the body of the function were
4279evaluated.
4280
4281In Emacs, a function frequently moves point as part of its internal
4282workings even though a user would not expect this. For example,
4283@code{count-lines-region} moves point. To prevent the user from being
4284bothered by jumps that are both unexpected and (from the user's point of
4285view) unnecessary, @code{save-excursion} is often used to keep point and
4286mark in the location expected by the user. The use of
4287@code{save-excursion} is good housekeeping.
4288
4289To make sure the house stays clean, @code{save-excursion} restores the
4290values of point and mark even if something goes wrong in the code inside
4291of it (or, to be more precise and to use the proper jargon, ``in case of
4292abnormal exit''). This feature is very helpful.
4293
4294In addition to recording the values of point and mark,
4295@code{save-excursion} keeps track of the current buffer, and restores
4296it, too. This means you can write code that will change the buffer and
4297have @code{save-excursion} switch you back to the original buffer. This
4298is how @code{save-excursion} is used in @code{append-to-buffer}.
4299(@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4300
4301@node Template for save-excursion, , Point and mark, save-excursion
4302@comment node-name, next, previous, up
4303@subsection Template for a @code{save-excursion} Expression
4304
4305@need 800
4306The template for code using @code{save-excursion} is simple:
4307
4308@smallexample
4309@group
4310(save-excursion
4311 @var{body}@dots{})
4312@end group
4313@end smallexample
4314
4315@noindent
4316The body of the function is one or more expressions that will be
4317evaluated in sequence by the Lisp interpreter. If there is more than
4318one expression in the body, the value of the last one will be returned
4319as the value of the @code{save-excursion} function. The other
4320expressions in the body are evaluated only for their side effects; and
4321@code{save-excursion} itself is used only for its side effect (which
4322is restoring the positions of point and mark).
4323
4324@need 1250
4325In more detail, the template for a @code{save-excursion} expression
4326looks like this:
4327
4328@smallexample
4329@group
4330(save-excursion
4331 @var{first-expression-in-body}
4332 @var{second-expression-in-body}
4333 @var{third-expression-in-body}
4334 @dots{}
4335 @var{last-expression-in-body})
4336@end group
4337@end smallexample
4338
4339@noindent
4340An expression, of course, may be a symbol on its own or a list.
4341
4342In Emacs Lisp code, a @code{save-excursion} expression often occurs
4343within the body of a @code{let} expression. It looks like this:
4344
4345@smallexample
4346@group
4347(let @var{varlist}
4348 (save-excursion
4349 @var{body}@dots{}))
4350@end group
4351@end smallexample
4352
4353@node Review, defun Exercises, save-excursion, Writing Defuns
4354@comment node-name, next, previous, up
4355@section Review
4356
4357In the last few chapters we have introduced a fair number of functions
4358and special forms. Here they are described in brief, along with a few
4359similar functions that have not been mentioned yet.
4360
4361@table @code
4362@item eval-last-sexp
4363Evaluate the last symbolic expression before the current location of
4364point. The value is printed in the echo area unless the function is
4365invoked with an argument; in that case, the output is printed in the
4366current buffer. This command is normally bound to @kbd{C-x C-e}.
4367
4368@item defun
4369Define function. This special form has up to five parts: the name,
4370a template for the arguments that will be passed to the function,
4371documentation, an optional interactive declaration, and the body of the
4372definition.
4373
4374@need 1250
4375For example:
4376
4377@smallexample
4378@group
4379(defun back-to-indentation ()
4380 "Move point to first visible character on line."
4381 (interactive)
4382 (beginning-of-line 1)
4383 (skip-chars-forward " \t"))
4384@end group
4385@end smallexample
4386
4387@item interactive
4388Declare to the interpreter that the function can be used
4389interactively. This special form may be followed by a string with one
4390or more parts that pass the information to the arguments of the
4391function, in sequence. These parts may also tell the interpreter to
4392prompt for information. Parts of the string are separated by
4393newlines, @samp{\n}.
4394
4395Common code characters are:
4396
4397@table @code
4398@item b
4399The name of an existing buffer.
4400
4401@item f
4402The name of an existing file.
4403
4404@item p
4405The numeric prefix argument. (Note that this `p' is lower case.)
4406
4407@item r
4408Point and the mark, as two numeric arguments, smallest first. This
4409is the only code letter that specifies two successive arguments
4410rather than one.
4411@end table
4412
4413@xref{Interactive Codes, , Code Characters for @samp{interactive},
4414elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4415code characters.
4416
4417@item let
4418Declare that a list of variables is for use within the body of the
4419@code{let} and give them an initial value, either @code{nil} or a
4420specified value; then evaluate the rest of the expressions in the body
4421of the @code{let} and return the value of the last one. Inside the
4422body of the @code{let}, the Lisp interpreter does not see the values of
4423the variables of the same names that are bound outside of the
4424@code{let}.
4425
4426@need 1250
4427For example,
4428
4429@smallexample
4430@group
4431(let ((foo (buffer-name))
4432 (bar (buffer-size)))
4433 (message
4434 "This buffer is %s and has %d characters."
4435 foo bar))
4436@end group
4437@end smallexample
4438
4439@item save-excursion
4440Record the values of point and mark and the current buffer before
4441evaluating the body of this special form. Restore the values of point
4442and mark and buffer afterward.
4443
4444@need 1250
4445For example,
4446
4447@smallexample
4448@group
4449(message "We are %d characters into this buffer."
4450 (- (point)
4451 (save-excursion
4452 (goto-char (point-min)) (point))))
4453@end group
4454@end smallexample
4455
4456@item if
4457Evaluate the first argument to the function; if it is true, evaluate
4458the second argument; else evaluate the third argument, if there is one.
4459
4460The @code{if} special form is called a @dfn{conditional}. There are
4461other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4462commonly used.
4463
4464@need 1250
4465For example,
4466
4467@smallexample
4468@group
4469(if (string-equal
4470 (number-to-string 21)
4471 (substring (emacs-version) 10 12))
4472 (message "This is version 21 Emacs")
4473 (message "This is not version 21 Emacs"))
4474@end group
4475@end smallexample
4476
4477@item equal
4478@itemx eq
4479Test whether two objects are the same. @code{equal} uses one meaning
4480of the word `same' and @code{eq} uses another: @code{equal} returns
4481true if the two objects have a similar structure and contents, such as
4482two copies of the same book. On the other hand, @code{eq}, returns
4483true if both arguments are actually the same object.
4484@findex equal
4485@findex eq
4486
4487@need 1250
4488@item <
4489@itemx >
4490@itemx <=
4491@itemx >=
4492The @code{<} function tests whether its first argument is smaller than
4493its second argument. A corresponding function, @code{>}, tests whether
4494the first argument is greater than the second. Likewise, @code{<=}
4495tests whether the first argument is less than or equal to the second and
4496@code{>=} tests whether the first argument is greater than or equal to
4497the second. In all cases, both arguments must be numbers or markers
4498(markers indicate positions in buffers).
4499
4500@item string<
4501@itemx string-lessp
4502@itemx string=
4503@itemx string-equal
4504The @code{string-lessp} function tests whether its first argument is
4505smaller than the second argument. A shorter, alternative name for the
4506same function (a @code{defalias}) is @code{string<}.
4507
4508The arguments to @code{string-lessp} must be strings or symbols; the
4509ordering is lexicographic, so case is significant. The print names of
4510symbols are used instead of the symbols themselves.
4511
4540f8f8 4512@cindex @samp{empty string} defined
1dcb89ad
RC
4513An empty string, @samp{""}, a string with no characters in it, is
4514smaller than any string of characters.
4515
8b096dce
EZ
4516@code{string-equal} provides the corresponding test for equality. Its
4517shorter, alternative name is @code{string=}. There are no string test
4518functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4519
4520@item message
4521Print a message in the echo area. The first argument is a string that
4522can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4523arguments that follow the string. The argument used by @samp{%s} must
4524be a string or a symbol; the argument used by @samp{%d} must be a
4525number. The argument used by @samp{%c} must be an ascii code number;
4526it will be printed as the character with that @sc{ascii} code.
4527
4528@item setq
4529@itemx set
4530The @code{setq} function sets the value of its first argument to the
4531value of the second argument. The first argument is automatically
4532quoted by @code{setq}. It does the same for succeeding pairs of
4533arguments. Another function, @code{set}, takes only two arguments and
4534evaluates both of them before setting the value returned by its first
4535argument to the value returned by its second argument.
4536
4537@item buffer-name
4538Without an argument, return the name of the buffer, as a string.
4539
4540@itemx buffer-file-name
4541Without an argument, return the name of the file the buffer is
4542visiting.
4543
4544@item current-buffer
4545Return the buffer in which Emacs is active; it may not be
4546the buffer that is visible on the screen.
4547
4548@item other-buffer
4549Return the most recently selected buffer (other than the buffer passed
4550to @code{other-buffer} as an argument and other than the current
4551buffer).
4552
4553@item switch-to-buffer
4554Select a buffer for Emacs to be active in and display it in the current
4555window so users can look at it. Usually bound to @kbd{C-x b}.
4556
4557@item set-buffer
4558Switch Emacs' attention to a buffer on which programs will run. Don't
4559alter what the window is showing.
4560
4561@item buffer-size
4562Return the number of characters in the current buffer.
4563
4564@item point
4565Return the value of the current position of the cursor, as an
4566integer counting the number of characters from the beginning of the
4567buffer.
4568
4569@item point-min
4570Return the minimum permissible value of point in
4571the current buffer. This is 1, unless narrowing is in effect.
4572
4573@item point-max
4574Return the value of the maximum permissible value of point in the
4575current buffer. This is the end of the buffer, unless narrowing is in
4576effect.
4577@end table
4578
4579@need 1500
4580@node defun Exercises, , Review, Writing Defuns
4581@section Exercises
4582
4583@itemize @bullet
4584@item
4585Write a non-interactive function that doubles the value of its
4586argument, a number. Make that function interactive.
4587
4588@item
4589Write a function that tests whether the current value of
4590@code{fill-column} is greater than the argument passed to the function,
4591and if so, prints an appropriate message.
4592@end itemize
4593
4594@node Buffer Walk Through, More Complex, Writing Defuns, Top
4595@comment node-name, next, previous, up
4596@chapter A Few Buffer--Related Functions
4597
4598In this chapter we study in detail several of the functions used in GNU
4599Emacs. This is called a ``walk-through''. These functions are used as
4600examples of Lisp code, but are not imaginary examples; with the
4601exception of the first, simplified function definition, these functions
4602show the actual code used in GNU Emacs. You can learn a great deal from
4603these definitions. The functions described here are all related to
4604buffers. Later, we will study other functions.
4605
4606@menu
4607* Finding More:: How to find more information.
4608* simplified-beginning-of-buffer:: Shows @code{goto-char},
4609 @code{point-min}, and @code{push-mark}.
4610* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4611* append-to-buffer:: Uses @code{save-excursion} and
4612 @code{insert-buffer-substring}.
4613* Buffer Related Review:: Review.
4614* Buffer Exercises::
4615@end menu
4616
4617@node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4618@section Finding More Information
4619
4620@findex describe-function, @r{introduced}
4621@cindex Find function documentation
4622In this walk-through, I will describe each new function as we come to
4623it, sometimes in detail and sometimes briefly. If you are interested,
4624you can get the full documentation of any Emacs Lisp function at any
4625time by typing @kbd{C-h f} and then the name of the function (and then
4626@key{RET}). Similarly, you can get the full documentation for a
4627variable by typing @kbd{C-h v} and then the name of the variable (and
4628then @key{RET}).
4629
4630@cindex Find source of function
4631In versions 20 and higher, when a function is written in Emacs Lisp,
4632@code{describe-function} will also tell you the location of the
4633function definition. If you move point over the file name and press
4634the @key{RET} key, which is this case means @code{help-follow} rather
4635than `return' or `enter', Emacs will take you directly to the function
4636definition.
4637
4638More generally, if you want to see a function in its original source
4639file, you can use the @code{find-tags} function to jump to it.
4640@code{find-tags} works with a wide variety of languages, not just
4641Lisp, and C, and it works with non-programming text as well. For
4642example, @code{find-tags} will jump to the various nodes in the
4643Texinfo source file of this document.
4644
4645The @code{find-tags} function depends on `tags tables' that record
4646the locations of the functions, variables, and other items to which
4647@code{find-tags} jumps.
4648
4649To use the @code{find-tags} command, type @kbd{M-.} (i.e., type the
4650@key{META} key and the period key at the same time, or else type the
4651@key{ESC} key and then type the period key), and then, at the prompt,
4652type in the name of the function whose source code you want to see,
4653such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4654switch buffers and display the source code for the function on your
4655screen. To switch back to your current buffer, type @kbd{C-x b
4656@key{RET}}. (On some keyboards, the @key{META} key is labelled
4657@key{ALT}.)
4658
4659@c !!! 21.0.100 tags table location in this paragraph
4660@cindex TAGS table, specifying
4661@findex find-tags
4662Depending on how the initial default values of your copy of Emacs are
4663set, you may also need to specify the location of your `tags table',
4664which is a file called @file{TAGS}. For example, if you are
4665interested in Emacs sources, the tags table you will most likely want,
4666if it has already been created for you, will be in a subdirectory of
4667the @file{/usr/local/share/emacs/} directory; thus you would use the
4668@code{M-x visit-tags-table} command and specify a pathname such as
4669@file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
4670@file{/usr/local/src/emacs/lisp/TAGS}. If the tags table has
4671not already been created, you will have to create it yourself.
4672
4673@need 1250
4674To create a @file{TAGS} file in a specific directory, switch to that
4675directory in Emacs using @kbd{M-x cd} command, or list the directory
4676with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4677@w{@code{etags *.el}} as the command to execute
4678
4679@smallexample
4680M-x compile RET etags *.el RET
4681@end smallexample
4682
4683For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4684
4685After you become more familiar with Emacs Lisp, you will find that you will
4686frequently use @code{find-tags} to navigate your way around source code;
4687and you will create your own @file{TAGS} tables.
4688
4689@cindex Library, as term for `file'
4690Incidentally, the files that contain Lisp code are conventionally
4691called @dfn{libraries}. The metaphor is derived from that of a
4692specialized library, such as a law library or an engineering library,
4693rather than a general library. Each library, or file, contains
4694functions that relate to a particular topic or activity, such as
4695@file{abbrev.el} for handling abbreviations and other typing
4696shortcuts, and @file{help.el} for on-line help. (Sometimes several
4697libraries provide code for a single activity, as the various
4698@file{rmail@dots{}} files provide code for reading electronic mail.)
4699In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4700@kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4701by topic keywords.''
4702
4703@node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4704@comment node-name, next, previous, up
4705@section A Simplified @code{beginning-of-buffer} Definition
4706@findex simplified-beginning-of-buffer
4707
4708The @code{beginning-of-buffer} command is a good function to start with
4709since you are likely to be familiar with it and it is easy to
4710understand. Used as an interactive command, @code{beginning-of-buffer}
4711moves the cursor to the beginning of the buffer, leaving the mark at the
4712previous position. It is generally bound to @kbd{M-<}.
4713
4714In this section, we will discuss a shortened version of the function
4715that shows how it is most frequently used. This shortened function
4716works as written, but it does not contain the code for a complex option.
4717In another section, we will describe the entire function.
4718(@xref{beginning-of-buffer, , Complete Definition of
4719@code{beginning-of-buffer}}.)
4720
4721Before looking at the code, let's consider what the function
4722definition has to contain: it must include an expression that makes
4723the function interactive so it can be called by typing @kbd{M-x
e601d8fd 4724beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
8b096dce
EZ
4725must include code to leave a mark at the original position in the
4726buffer; and it must include code to move the cursor to the beginning
4727of the buffer.
4728
4729@need 1250
4730Here is the complete text of the shortened version of the function:
4731
4732@smallexample
4733@group
4734(defun simplified-beginning-of-buffer ()
4735 "Move point to the beginning of the buffer;
4736leave mark at previous position."
4737 (interactive)
4738 (push-mark)
4739 (goto-char (point-min)))
4740@end group
4741@end smallexample
4742
4743Like all function definitions, this definition has five parts following
4744the special form @code{defun}:
4745
4746@enumerate
4747@item
4748The name: in this example, @code{simplified-beginning-of-buffer}.
4749
4750@item
4751A list of the arguments: in this example, an empty list, @code{()},
4752
4753@item
4754The documentation string.
4755
4756@item
4757The interactive expression.
4758
4759@item
4760The body.
4761@end enumerate
4762
4763@noindent
4764In this function definition, the argument list is empty; this means that
4765this function does not require any arguments. (When we look at the
4766definition for the complete function, we will see that it may be passed
4767an optional argument.)
4768
4769The interactive expression tells Emacs that the function is intended to
4770be used interactively. In this example, @code{interactive} does not have
4771an argument because @code{simplified-beginning-of-buffer} does not
4772require one.
4773
4774@need 800
4775The body of the function consists of the two lines:
4776
4777@smallexample
4778@group
4779(push-mark)
4780(goto-char (point-min))
4781@end group
4782@end smallexample
4783
4784The first of these lines is the expression, @code{(push-mark)}. When
4785this expression is evaluated by the Lisp interpreter, it sets a mark at
4786the current position of the cursor, wherever that may be. The position
4787of this mark is saved in the mark ring.
4788
4789The next line is @code{(goto-char (point-min))}. This expression
4790jumps the cursor to the minimum point in the buffer, that is, to the
4791beginning of the buffer (or to the beginning of the accessible portion
4792of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4793Narrowing and Widening}.)
4794
4795The @code{push-mark} command sets a mark at the place where the cursor
4796was located before it was moved to the beginning of the buffer by the
4797@code{(goto-char (point-min))} expression. Consequently, you can, if
4798you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4799
4800That is all there is to the function definition!
4801
4802@findex describe-function
4803When you are reading code such as this and come upon an unfamiliar
4804function, such as @code{goto-char}, you can find out what it does by
4805using the @code{describe-function} command. To use this command, type
4806@kbd{C-h f} and then type in the name of the function and press
4807@key{RET}. The @code{describe-function} command will print the
4808function's documentation string in a @file{*Help*} window. For
4809example, the documentation for @code{goto-char} is:
4810
4811@smallexample
4812@group
4813One arg, a number. Set point to that number.
4814Beginning of buffer is position (point-min),
4815end is (point-max).
4816@end group
4817@end smallexample
4818
4819@noindent
4820(The prompt for @code{describe-function} will offer you the symbol
4821under or preceding the cursor, so you can save typing by positioning
4822the cursor right over or after the function and then typing @kbd{C-h f
4823@key{RET}}.)
4824
4825The @code{end-of-buffer} function definition is written in the same way as
4826the @code{beginning-of-buffer} definition except that the body of the
4827function contains the expression @code{(goto-char (point-max))} in place
4828of @code{(goto-char (point-min))}.
4829
4830@node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4831@comment node-name, next, previous, up
4832@section The Definition of @code{mark-whole-buffer}
4833@findex mark-whole-buffer
4834
4835The @code{mark-whole-buffer} function is no harder to understand than the
4836@code{simplified-beginning-of-buffer} function. In this case, however,
4837we will look at the complete function, not a shortened version.
4838
4839The @code{mark-whole-buffer} function is not as commonly used as the
4840@code{beginning-of-buffer} function, but is useful nonetheless: it
4841marks a whole buffer as a region by putting point at the beginning and
4842a mark at the end of the buffer. It is generally bound to @kbd{C-x
4843h}.
4844
4845
4846@menu
4847* mark-whole-buffer overview::
4848* Body of mark-whole-buffer:: Only three lines of code.
4849@end menu
4850
4851
4852@node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4853@ifnottex
4854@unnumberedsubsec An overview of @code{mark-whole-buffer}
4855@end ifnottex
4856
4857@need 1250
4858In GNU Emacs 20, the code for the complete function looks like this:
4859
4860@smallexample
4861@group
4862(defun mark-whole-buffer ()
4863 "Put point at beginning and mark at end of buffer."
4864 (interactive)
4865 (push-mark (point))
4866 (push-mark (point-max))
4867 (goto-char (point-min)))
4868@end group
4869@end smallexample
4870
4871@need 1250
4872Like all other functions, the @code{mark-whole-buffer} function fits
4873into the template for a function definition. The template looks like
4874this:
4875
4876@smallexample
4877@group
4878(defun @var{name-of-function} (@var{argument-list})
4879 "@var{documentation}@dots{}"
4880 (@var{interactive-expression}@dots{})
4881 @var{body}@dots{})
4882@end group
4883@end smallexample
4884
4885Here is how the function works: the name of the function is
4886@code{mark-whole-buffer}; it is followed by an empty argument list,
4887@samp{()}, which means that the function does not require arguments.
4888The documentation comes next.
4889
4890The next line is an @code{(interactive)} expression that tells Emacs
4891that the function will be used interactively. These details are similar
4892to the @code{simplified-beginning-of-buffer} function described in the
4893previous section.
4894
4895@node Body of mark-whole-buffer, , mark-whole-buffer overview, mark-whole-buffer
4896@comment node-name, next, previous, up
4897@subsection Body of @code{mark-whole-buffer}
4898
4899The body of the @code{mark-whole-buffer} function consists of three
4900lines of code:
4901
4902@smallexample
4903@group
4904(push-mark (point))
4905(push-mark (point-max))
4906(goto-char (point-min))
4907@end group
4908@end smallexample
4909
4910The first of these lines is the expression, @code{(push-mark (point))}.
4911
4912This line does exactly the same job as the first line of the body of
4913the @code{simplified-beginning-of-buffer} function, which is written
4914@code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4915at the current position of the cursor.
4916
4917I don't know why the expression in @code{mark-whole-buffer} is written
4918@code{(push-mark (point))} and the expression in
4919@code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4920whoever wrote the code did not know that the arguments for
4921@code{push-mark} are optional and that if @code{push-mark} is not
4922passed an argument, the function automatically sets mark at the
4923location of point by default. Or perhaps the expression was written
4924so as to parallel the structure of the next line. In any case, the
4925line causes Emacs to determine the position of point and set a mark
4926there.
4927
4928The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4929This expression sets a mark at the point in the buffer
4930that has the highest number. This will be the end of the buffer (or,
4931if the buffer is narrowed, the end of the accessible portion of the
4932buffer. @xref{Narrowing & Widening, , Narrowing and Widening}, for
4933more about narrowing.) After this mark has been set, the previous
4934mark, the one set at point, is no longer set, but Emacs remembers its
4935position, just as all other recent marks are always remembered. This
4936means that you can, if you wish, go back to that position by typing
4937@kbd{C-u C-@key{SPC}} twice.
4938
4939(In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4940complicated than shown here. The line reads
4941
4942@smallexample
4943(push-mark (point-max) nil t)
4944@end smallexample
4945
4946@noindent
4947(The expression works nearly the same as before. It sets a mark at
4948the highest numbered place in the buffer that it can. However, in
6964db14
RC
4949this version, @code{push-mark} has two additional arguments. The
4950second argument to @code{push-mark} is @code{nil}. This tells the
4951function it @emph{should} display a message that says `Mark set' when
4952it pushes the mark. The third argument is @code{t}. This tells
8b096dce
EZ
4953@code{push-mark} to activate the mark when Transient Mark mode is
4954turned on. Transient Mark mode highlights the currently active
4955region. It is usually turned off.)
4956
4957Finally, the last line of the function is @code{(goto-char
4958(point-min)))}. This is written exactly the same way as it is written
4959in @code{beginning-of-buffer}. The expression moves the cursor to
4960the minimum point in the buffer, that is, to the beginning of the buffer
4961(or to the beginning of the accessible portion of the buffer). As a
4962result of this, point is placed at the beginning of the buffer and mark
4963is set at the end of the buffer. The whole buffer is, therefore, the
4964region.
4965
4966@node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4967@comment node-name, next, previous, up
4968@section The Definition of @code{append-to-buffer}
4969@findex append-to-buffer
4970
4971The @code{append-to-buffer} command is very nearly as simple as the
4972@code{mark-whole-buffer} command. What it does is copy the region (that
4973is, the part of the buffer between point and mark) from the current
4974buffer to a specified buffer.
4975
4976@menu
4977* append-to-buffer overview::
4978* append interactive:: A two part interactive expression.
4979* append-to-buffer body:: Incorporates a @code{let} expression.
4980* append save-excursion:: How the @code{save-excursion} works.
4981@end menu
4982
4983@node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4984@ifnottex
4985@unnumberedsubsec An Overview of @code{append-to-buffer}
4986@end ifnottex
4987
4988@findex insert-buffer-substring
4989The @code{append-to-buffer} command uses the
4990@code{insert-buffer-substring} function to copy the region.
4991@code{insert-buffer-substring} is described by its name: it takes a
4992string of characters from part of a buffer, a ``substring'', and
4993inserts them into another buffer. Most of @code{append-to-buffer} is
4994concerned with setting up the conditions for
4995@code{insert-buffer-substring} to work: the code must specify both the
4996buffer to which the text will go and the region that will be copied.
4997Here is the complete text of the function:
4998
4999@smallexample
5000@group
5001(defun append-to-buffer (buffer start end)
5002 "Append to specified buffer the text of the region.
5003It is inserted into that buffer before its point.
5004@end group
5005
5006@group
5007When calling from a program, give three arguments:
5008a buffer or the name of one, and two character numbers
5009specifying the portion of the current buffer to be copied."
5010 (interactive "BAppend to buffer:@: \nr")
5011 (let ((oldbuf (current-buffer)))
5012 (save-excursion
5013 (set-buffer (get-buffer-create buffer))
5014 (insert-buffer-substring oldbuf start end))))
5015@end group
5016@end smallexample
5017
5018The function can be understood by looking at it as a series of
5019filled-in templates.
5020
5021The outermost template is for the function definition. In this
5022function, it looks like this (with several slots filled in):
5023
5024@smallexample
5025@group
5026(defun append-to-buffer (buffer start end)
5027 "@var{documentation}@dots{}"
5028 (interactive "BAppend to buffer:@: \nr")
5029 @var{body}@dots{})
5030@end group
5031@end smallexample
5032
5033The first line of the function includes its name and three arguments.
5034The arguments are the @code{buffer} to which the text will be copied, and
5035the @code{start} and @code{end} of the region in the current buffer that
5036will be copied.
5037
5038The next part of the function is the documentation, which is clear and
5039complete.
5040
5041@node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
5042@comment node-name, next, previous, up
5043@subsection The @code{append-to-buffer} Interactive Expression
5044
5045Since the @code{append-to-buffer} function will be used interactively,
5046the function must have an @code{interactive} expression. (For a
5047review of @code{interactive}, see @ref{Interactive, , Making a
5048Function Interactive}.) The expression reads as follows:
5049
5050@smallexample
5051(interactive "BAppend to buffer:@: \nr")
5052@end smallexample
5053
5054@noindent
5055This expression has an argument inside of quotation marks and that
5056argument has two parts, separated by @samp{\n}.
5057
5058The first part is @samp{BAppend to buffer:@: }. Here, the @samp{B}
5059tells Emacs to ask for the name of the buffer that will be passed to the
5060function. Emacs will ask for the name by prompting the user in the
5061minibuffer, using the string following the @samp{B}, which is the string
5062@samp{Append to buffer:@: }. Emacs then binds the variable @code{buffer}
5063in the function's argument list to the specified buffer.
5064
5065The newline, @samp{\n}, separates the first part of the argument from
5066the second part. It is followed by an @samp{r} that tells Emacs to bind
5067the two arguments that follow the symbol @code{buffer} in the function's
5068argument list (that is, @code{start} and @code{end}) to the values of
5069point and mark.
5070
5071@node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5072@comment node-name, next, previous, up
5073@subsection The Body of @code{append-to-buffer}
5074
5075The body of the @code{append-to-buffer} function begins with @code{let}.
5076
5077As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5078@code{let} expression is to create and give initial values to one or
5079more variables that will only be used within the body of the
5080@code{let}. This means that such a variable will not be confused with
5081any variable of the same name outside the @code{let} expression.
5082
5083We can see how the @code{let} expression fits into the function as a
5084whole by showing a template for @code{append-to-buffer} with the
5085@code{let} expression in outline:
5086
5087@smallexample
5088@group
5089(defun append-to-buffer (buffer start end)
5090 "@var{documentation}@dots{}"
5091 (interactive "BAppend to buffer:@: \nr")
5092 (let ((@var{variable} @var{value}))
5093 @var{body}@dots{})
5094@end group
5095@end smallexample
5096
5097The @code{let} expression has three elements:
5098
5099@enumerate
5100@item
5101The symbol @code{let};
5102
5103@item
5104A varlist containing, in this case, a single two-element list,
5105@code{(@var{variable} @var{value})};
5106
5107@item
5108The body of the @code{let} expression.
5109@end enumerate
5110
5111@need 800
5112In the @code{append-to-buffer} function, the varlist looks like this:
5113
5114@smallexample
5115(oldbuf (current-buffer))
5116@end smallexample
5117
5118@noindent
5119In this part of the @code{let} expression, the one variable,
5120@code{oldbuf}, is bound to the value returned by the
5121@code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5122used to keep track of the buffer in which you are working and from
5123which you will copy.
5124
5125The element or elements of a varlist are surrounded by a set of
5126parentheses so the Lisp interpreter can distinguish the varlist from
5127the body of the @code{let}. As a consequence, the two-element list
5128within the varlist is surrounded by a circumscribing set of parentheses.
5129The line looks like this:
5130
5131@smallexample
5132@group
5133(let ((oldbuf (current-buffer)))
5134 @dots{} )
5135@end group
5136@end smallexample
5137
5138@noindent
5139The two parentheses before @code{oldbuf} might surprise you if you did
5140not realize that the first parenthesis before @code{oldbuf} marks the
5141boundary of the varlist and the second parenthesis marks the beginning
5142of the two-element list, @code{(oldbuf (current-buffer))}.
5143
5144@node append save-excursion, , append-to-buffer body, append-to-buffer
5145@comment node-name, next, previous, up
5146@subsection @code{save-excursion} in @code{append-to-buffer}
5147
5148The body of the @code{let} expression in @code{append-to-buffer}
5149consists of a @code{save-excursion} expression.
5150
5151The @code{save-excursion} function saves the locations of point and
5152mark, and restores them to those positions after the expressions in the
5153body of the @code{save-excursion} complete execution. In addition,
5154@code{save-excursion} keeps track of the original buffer, and
5155restores it. This is how @code{save-excursion} is used in
5156@code{append-to-buffer}.
5157
5158@need 1500
5159@cindex Indentation for formatting
5160@cindex Formatting convention
5161Incidentally, it is worth noting here that a Lisp function is normally
5162formatted so that everything that is enclosed in a multi-line spread is
5163indented more to the right than the first symbol. In this function
5164definition, the @code{let} is indented more than the @code{defun}, and
5165the @code{save-excursion} is indented more than the @code{let}, like
5166this:
5167
5168@smallexample
5169@group
5170(defun @dots{}
5171 @dots{}
5172 @dots{}
5173 (let@dots{}
5174 (save-excursion
5175 @dots{}
5176@end group
5177@end smallexample
5178
5179@need 1500
5180@noindent
5181This formatting convention makes it easy to see that the two lines in
5182the body of the @code{save-excursion} are enclosed by the parentheses
5183associated with @code{save-excursion}, just as the
5184@code{save-excursion} itself is enclosed by the parentheses associated
5185with the @code{let}:
5186
5187@smallexample
5188@group
5189(let ((oldbuf (current-buffer)))
5190 (save-excursion
5191 (set-buffer (get-buffer-create buffer))
5192 (insert-buffer-substring oldbuf start end))))
5193@end group
5194@end smallexample
5195
5196@need 1200
5197The use of the @code{save-excursion} function can be viewed as a process
5198of filling in the slots of a template:
5199
5200@smallexample
5201@group
5202(save-excursion
5203 @var{first-expression-in-body}
5204 @var{second-expression-in-body}
5205 @dots{}
5206 @var{last-expression-in-body})
5207@end group
5208@end smallexample
5209
5210@need 1200
5211@noindent
5212In this function, the body of the @code{save-excursion} contains only
5213two expressions. The body looks like this:
5214
5215@smallexample
5216@group
5217(set-buffer (get-buffer-create buffer))
5218(insert-buffer-substring oldbuf start end)
5219@end group
5220@end smallexample
5221
5222When the @code{append-to-buffer} function is evaluated, the two
5223expressions in the body of the @code{save-excursion} are evaluated in
5224sequence. The value of the last expression is returned as the value of
5225the @code{save-excursion} function; the other expression is evaluated
5226only for its side effects.
5227
5228The first line in the body of the @code{save-excursion} uses the
5229@code{set-buffer} function to change the current buffer to the one
5230specified in the first argument to @code{append-to-buffer}. (Changing
5231the buffer is the side effect; as we have said before, in Lisp, a side
5232effect is often the primary thing we want.) The second line does the
5233primary work of the function.
5234
5235The @code{set-buffer} function changes Emacs' attention to the buffer to
5236which the text will be copied and from which @code{save-excursion} will
5237return.
5238
5239@need 800
5240The line looks like this:
5241
5242@smallexample
5243(set-buffer (get-buffer-create buffer))
5244@end smallexample
5245
5246The innermost expression of this list is @code{(get-buffer-create
5247buffer)}. This expression uses the @code{get-buffer-create} function,
5248which either gets the named buffer, or if it does not exist, creates one
5249with the given name. This means you can use @code{append-to-buffer} to
5250put text into a buffer that did not previously exist.
5251
5252@code{get-buffer-create} also keeps @code{set-buffer} from getting an
5253unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5254were to specify a buffer that does not exist, Emacs would baulk.
5255Since @code{get-buffer-create} will create a buffer if none exists,
5256@code{set-buffer} is always provided with a buffer.
5257
5258@need 1250
5259The last line of @code{append-to-buffer} does the work of appending
5260the text:
5261
5262@smallexample
5263(insert-buffer-substring oldbuf start end)
5264@end smallexample
5265
5266@noindent
5267The @code{insert-buffer-substring} function copies a string @emph{from}
5268the buffer specified as its first argument and inserts the string into
5269the present buffer. In this case, the argument to
5270@code{insert-buffer-substring} is the value of the variable created and
5271bound by the @code{let}, namely the value of @code{oldbuf}, which was
5272the current buffer when you gave the @code{append-to-buffer} command.
5273
5274After @code{insert-buffer-substring} has done its work,
5275@code{save-excursion} will restore the action to the original buffer and
5276@code{append-to-buffer} will have done its job.
5277
5278@need 800
5279Written in skeletal form, the workings of the body look like this:
5280
5281@smallexample
5282@group
5283(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5284 (save-excursion ; @r{Keep track of buffer.}
5285 @var{change-buffer}
5286 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5287
5288 @var{change-back-to-original-buffer-when-finished}
5289@var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5290
5291@end group
5292@end smallexample
5293
5294In summary, @code{append-to-buffer} works as follows: it saves the value
5295of the current buffer in the variable called @code{oldbuf}. It gets the
5296new buffer, creating one if need be, and switches Emacs to it. Using
5297the value of @code{oldbuf}, it inserts the region of text from the old
5298buffer into the new buffer; and then using @code{save-excursion}, it
5299brings you back to your original buffer.
5300
5301In looking at @code{append-to-buffer}, you have explored a fairly
5302complex function. It shows how to use @code{let} and
5303@code{save-excursion}, and how to change to and come back from another
5304buffer. Many function definitions use @code{let},
5305@code{save-excursion}, and @code{set-buffer} this way.
5306
5307@node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5308@comment node-name, next, previous, up
5309@section Review
5310
5311Here is a brief summary of the various functions discussed in this chapter.
5312
5313@table @code
5314@item describe-function
5315@itemx describe-variable
5316Print the documentation for a function or variable.
5317Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5318
5319@item find-tag
5320Find the file containing the source for a function or variable and
5321switch buffers to it, positioning point at the beginning of the item.
5322Conventionally bound to @kbd{M-.} (that's a period following the
5323@key{META} key).
5324
5325@item save-excursion
5326Save the location of point and mark and restore their values after the
5327arguments to @code{save-excursion} have been evaluated. Also, remember
5328the current buffer and return to it.
5329
5330@item push-mark
5331Set mark at a location and record the value of the previous mark on the
5332mark ring. The mark is a location in the buffer that will keep its
5333relative position even if text is added to or removed from the buffer.
5334
5335@item goto-char
5336Set point to the location specified by the value of the argument, which
5337can be a number, a marker, or an expression that returns the number of
5338a position, such as @code{(point-min)}.
5339
5340@item insert-buffer-substring
5341Copy a region of text from a buffer that is passed to the function as
5342an argument and insert the region into the current buffer.
5343
5344@item mark-whole-buffer
5345Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5346
5347@item set-buffer
5348Switch the attention of Emacs to another buffer, but do not change the
5349window being displayed. Used when the program rather than a human is
5350to work on a different buffer.
5351
5352@item get-buffer-create
5353@itemx get-buffer
5354Find a named buffer or create one if a buffer of that name does not
5355exist. The @code{get-buffer} function returns @code{nil} if the named
5356buffer does not exist.
5357@end table
5358
5359@need 1500
5360@node Buffer Exercises, , Buffer Related Review, Buffer Walk Through
5361@section Exercises
5362
5363@itemize @bullet
5364@item
5365Write your own @code{simplified-end-of-buffer} function definition;
5366then test it to see whether it works.
5367
5368@item
5369Use @code{if} and @code{get-buffer} to write a function that prints a
5370message telling you whether a buffer exists.
5371
5372@item
5373Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5374function.
5375@end itemize
5376
5377@node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5378@comment node-name, next, previous, up
5379@chapter A Few More Complex Functions
5380
5381In this chapter, we build on what we have learned in previous chapters
5382by looking at more complex functions. The @code{copy-to-buffer}
5383function illustrates use of two @code{save-excursion} expressions in
5384one definition, while the @code{insert-buffer} function illustrates
5385use of an asterisk in an @code{interactive} expression, use of
5386@code{or}, and the important distinction between a name and the object
5387to which the name refers.
5388
5389@menu
5390* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5391* insert-buffer:: Read-only, and with @code{or}.
5392* beginning-of-buffer:: Shows @code{goto-char},
5393 @code{point-min}, and @code{push-mark}.
5394* Second Buffer Related Review::
5395* optional Exercise::
5396@end menu
5397
5398@node copy-to-buffer, insert-buffer, More Complex, More Complex
5399@comment node-name, next, previous, up
5400@section The Definition of @code{copy-to-buffer}
5401@findex copy-to-buffer
5402
5403After understanding how @code{append-to-buffer} works, it is easy to
5404understand @code{copy-to-buffer}. This function copies text into a
5405buffer, but instead of adding to the second buffer, it replaces the
5406previous text in the second buffer. The code for the
5407@code{copy-to-buffer} function is almost the same as the code for
5408@code{append-to-buffer}, except that @code{erase-buffer} and a second
5409@code{save-excursion} are used. (@xref{append-to-buffer, , The
5410Definition of @code{append-to-buffer}}, for the description of
5411@code{append-to-buffer}.)
5412
5413@need 800
5414The body of @code{copy-to-buffer} looks like this
5415
5416@smallexample
5417@group
5418@dots{}
5419(interactive "BCopy to buffer:@: \nr")
5420 (let ((oldbuf (current-buffer)))
5421 (save-excursion
5422 (set-buffer (get-buffer-create buffer))
5423 (erase-buffer)
5424 (save-excursion
5425 (insert-buffer-substring oldbuf start end)))))
5426@end group
5427@end smallexample
5428
5429This code is similar to the code in @code{append-to-buffer}: it is
5430only after changing to the buffer to which the text will be copied
5431that the definition for this function diverges from the definition for
5432@code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5433buffer's former contents. (This is what is meant by `replacement'; to
5434replace text, Emacs erases the previous text and then inserts new
5435text.) After erasing the previous contents of the buffer,
5436@code{save-excursion} is used for a second time and the new text is
5437inserted.
5438
5439Why is @code{save-excursion} used twice? Consider again what the
5440function does.
5441
5442@need 1250
5443In outline, the body of @code{copy-to-buffer} looks like this:
5444
5445@smallexample
5446@group
5447(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5448 (save-excursion ; @r{First use of @code{save-excursion}.}
5449 @var{change-buffer}
5450 (erase-buffer)
5451 (save-excursion ; @r{Second use of @code{save-excursion}.}
5452 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5453@end group
5454@end smallexample
5455
5456The first use of @code{save-excursion} returns Emacs to the buffer from
5457which the text is being copied. That is clear, and is just like its use
5458in @code{append-to-buffer}. Why the second use? The reason is that
5459@code{insert-buffer-substring} always leaves point at the @emph{end} of
5460the region being inserted. The second @code{save-excursion} causes
5461Emacs to leave point at the beginning of the text being inserted. In
5462most circumstances, users prefer to find point at the beginning of
5463inserted text. (Of course, the @code{copy-to-buffer} function returns
5464the user to the original buffer when done---but if the user @emph{then}
5465switches to the copied-to buffer, point will go to the beginning of the
5466text. Thus, this use of a second @code{save-excursion} is a little
5467nicety.)
5468
5469@node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5470@comment node-name, next, previous, up
5471@section The Definition of @code{insert-buffer}
5472@findex insert-buffer
5473
5474@code{insert-buffer} is yet another buffer-related function. This
5475command copies another buffer @emph{into} the current buffer. It is the
5476reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5477copy a region of text @emph{from} the current buffer to another buffer.
5478
5479In addition, this code illustrates the use of @code{interactive} with a
5480buffer that might be @dfn{read-only} and the important distinction
5481between the name of an object and the object actually referred to.
5482
5483@menu
5484* insert-buffer code::
5485* insert-buffer interactive:: When you can read, but not write.
5486* insert-buffer body:: The body has an @code{or} and a @code{let}.
5487* if & or:: Using an @code{if} instead of an @code{or}.
5488* Insert or:: How the @code{or} expression works.
5489* Insert let:: Two @code{save-excursion} expressions.
5490@end menu
5491
5492@node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5493@ifnottex
5494@unnumberedsubsec The Code for @code{insert-buffer}
5495@end ifnottex
5496
5497@need 800
5498Here is the code:
5499
5500@smallexample
5501@group
5502(defun insert-buffer (buffer)
5503 "Insert after point the contents of BUFFER.
5504Puts mark after the inserted text.
5505BUFFER may be a buffer or a buffer name."
5506 (interactive "*bInsert buffer:@: ")
5507@end group
5508@group
5509 (or (bufferp buffer)
5510 (setq buffer (get-buffer buffer)))
5511 (let (start end newmark)
5512 (save-excursion
5513 (save-excursion
5514 (set-buffer buffer)
5515 (setq start (point-min) end (point-max)))
5516@end group
5517@group
5518 (insert-buffer-substring buffer start end)
5519 (setq newmark (point)))
5520 (push-mark newmark)))
5521@end group
5522@end smallexample
5523
5524@need 1200
5525As with other function definitions, you can use a template to see an
5526outline of the function:
5527
5528@smallexample
5529@group
5530(defun insert-buffer (buffer)
5531 "@var{documentation}@dots{}"
5532 (interactive "*bInsert buffer:@: ")
5533 @var{body}@dots{})
5534@end group
5535@end smallexample
5536
5537@node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5538@comment node-name, next, previous, up
5539@subsection The Interactive Expression in @code{insert-buffer}
5540@findex interactive, @r{example use of}
5541
5542In @code{insert-buffer}, the argument to the @code{interactive}
5543declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5544buffer:@: }.
5545
5546@menu
5547* Read-only buffer:: When a buffer cannot be modified.
5548* b for interactive:: An existing buffer or else its name.
5549@end menu
5550
5551@node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5552@comment node-name, next, previous, up
5553@unnumberedsubsubsec A Read-only Buffer
5554@cindex Read-only buffer
5555@cindex Asterisk for read-only buffer
5556@findex * @r{for read-only buffer}
5557
e601d8fd
RC
5558The asterisk is for the situation when the current buffer is a
5559read-only buffer---a buffer that cannot be modified. If
5560@code{insert-buffer} is called when the current buffer is read-only, a
5561message to this effect is printed in the echo area and the terminal
5562may beep or blink at you; you will not be permitted to insert anything
5563into current buffer. The asterisk does not need to be followed by a
5564newline to separate it from the next argument.
8b096dce
EZ
5565
5566@node b for interactive, , Read-only buffer, insert-buffer interactive
5567@comment node-name, next, previous, up
5568@unnumberedsubsubsec @samp{b} in an Interactive Expression
5569
5570The next argument in the interactive expression starts with a lower
5571case @samp{b}. (This is different from the code for
5572@code{append-to-buffer}, which uses an upper-case @samp{B}.
5573@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5574The lower-case @samp{b} tells the Lisp interpreter that the argument
5575for @code{insert-buffer} should be an existing buffer or else its
5576name. (The upper-case @samp{B} option provides for the possibility
5577that the buffer does not exist.) Emacs will prompt you for the name
5578of the buffer, offering you a default buffer, with name completion
5579enabled. If the buffer does not exist, you receive a message that
5580says ``No match''; your terminal may beep at you as well.
5581
5582@node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5583@comment node-name, next, previous, up
5584@subsection The Body of the @code{insert-buffer} Function
5585
5586The body of the @code{insert-buffer} function has two major parts: an
5587@code{or} expression and a @code{let} expression. The purpose of the
5588@code{or} expression is to ensure that the argument @code{buffer} is
5589bound to a buffer and not just the name of a buffer. The body of the
5590@code{let} expression contains the code which copies the other buffer
5591into the current buffer.
5592
5593@need 1250
5594In outline, the two expressions fit into the @code{insert-buffer}
5595function like this:
5596
5597@smallexample
5598@group
5599(defun insert-buffer (buffer)
5600 "@var{documentation}@dots{}"
5601 (interactive "*bInsert buffer:@: ")
5602 (or @dots{}
5603 @dots{}
5604@end group
5605@group
5606 (let (@var{varlist})
5607 @var{body-of-}@code{let}@dots{} )
5608@end group
5609@end smallexample
5610
5611To understand how the @code{or} expression ensures that the argument
5612@code{buffer} is bound to a buffer and not to the name of a buffer, it
5613is first necessary to understand the @code{or} function.
5614
5615Before doing this, let me rewrite this part of the function using
5616@code{if} so that you can see what is done in a manner that will be familiar.
5617
5618@node if & or, Insert or, insert-buffer body, insert-buffer
5619@comment node-name, next, previous, up
5620@subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5621
5622The job to be done is to make sure the value of @code{buffer} is a
5623buffer itself and not the name of a buffer. If the value is the name,
5624then the buffer itself must be got.
5625
5626You can imagine yourself at a conference where an usher is wandering
5627around holding a list with your name on it and looking for you: the
5628usher is ``bound'' to your name, not to you; but when the usher finds
5629you and takes your arm, the usher becomes ``bound'' to you.
5630
5631@need 800
5632In Lisp, you might describe this situation like this:
5633
5634@smallexample
5635@group
5636(if (not (holding-on-to-guest))
5637 (find-and-take-arm-of-guest))
5638@end group
5639@end smallexample
5640
5641We want to do the same thing with a buffer---if we do not have the
5642buffer itself, we want to get it.
5643
5644@need 1200
5645Using a predicate called @code{bufferp} that tells us whether we have a
5646buffer (rather than its name), we can write the code like this:
5647
5648@smallexample
5649@group
5650(if (not (bufferp buffer)) ; @r{if-part}
5651 (setq buffer (get-buffer buffer))) ; @r{then-part}
5652@end group
5653@end smallexample
5654
5655@noindent
5656Here, the true-or-false-test of the @code{if} expression is
5657@w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5658@w{@code{(setq buffer (get-buffer buffer))}}.
5659
5660In the test, the function @code{bufferp} returns true if its argument is
5661a buffer---but false if its argument is the name of the buffer. (The
5662last character of the function name @code{bufferp} is the character
5663@samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5664indicates that the function is a predicate, which is a term that means
5665that the function will determine whether some property is true or false.
5666@xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5667Argument}.)
5668
5669@need 1200
5670The function @code{not} precedes the expression @code{(bufferp buffer)},
5671so the true-or-false-test looks like this:
5672
5673@smallexample
5674(not (bufferp buffer))
5675@end smallexample
5676
5677@noindent
5678@code{not} is a function that returns true if its argument is false
5679and false if its argument is true. So if @code{(bufferp buffer)}
5680returns true, the @code{not} expression returns false and vice-versa:
5681what is ``not true'' is false and what is ``not false'' is true.
5682
5683Using this test, the @code{if} expression works as follows: when the
5684value of the variable @code{buffer} is actually a buffer rather then
5685its name, the true-or-false-test returns false and the @code{if}
5686expression does not evaluate the then-part. This is fine, since we do
5687not need to do anything to the variable @code{buffer} if it really is
5688a buffer.
5689
5690On the other hand, when the value of @code{buffer} is not a buffer
5691itself, but the name of a buffer, the true-or-false-test returns true
5692and the then-part of the expression is evaluated. In this case, the
5693then-part is @code{(setq buffer (get-buffer buffer))}. This
5694expression uses the @code{get-buffer} function to return an actual
5695buffer itself, given its name. The @code{setq} then sets the variable
5696@code{buffer} to the value of the buffer itself, replacing its previous
5697value (which was the name of the buffer).
5698
5699@node Insert or, Insert let, if & or, insert-buffer
5700@comment node-name, next, previous, up
5701@subsection The @code{or} in the Body
5702
5703The purpose of the @code{or} expression in the @code{insert-buffer}
5704function is to ensure that the argument @code{buffer} is bound to a
5705buffer and not just to the name of a buffer. The previous section shows
5706how the job could have been done using an @code{if} expression.
5707However, the @code{insert-buffer} function actually uses @code{or}.
5708To understand this, it is necessary to understand how @code{or} works.
5709
5710@findex or
5711An @code{or} function can have any number of arguments. It evaluates
5712each argument in turn and returns the value of the first of its
5713arguments that is not @code{nil}. Also, and this is a crucial feature
5714of @code{or}, it does not evaluate any subsequent arguments after
5715returning the first non-@code{nil} value.
5716
5717@need 800
5718The @code{or} expression looks like this:
5719
5720@smallexample
5721@group
5722(or (bufferp buffer)
5723 (setq buffer (get-buffer buffer)))
5724@end group
5725@end smallexample
5726
5727@noindent
5728The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5729This expression returns true (a non-@code{nil} value) if the buffer is
5730actually a buffer, and not just the name of a buffer. In the @code{or}
5731expression, if this is the case, the @code{or} expression returns this
5732true value and does not evaluate the next expression---and this is fine
5733with us, since we do not want to do anything to the value of
5734@code{buffer} if it really is a buffer.
5735
5736On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5737which it will be if the value of @code{buffer} is the name of a buffer,
5738the Lisp interpreter evaluates the next element of the @code{or}
5739expression. This is the expression @code{(setq buffer (get-buffer
5740buffer))}. This expression returns a non-@code{nil} value, which
5741is the value to which it sets the variable @code{buffer}---and this
5742value is a buffer itself, not the name of a buffer.
5743
5744The result of all this is that the symbol @code{buffer} is always
5745bound to a buffer itself rather than to the name of a buffer. All
5746this is necessary because the @code{set-buffer} function in a
5747following line only works with a buffer itself, not with the name to a
5748buffer.
5749
5750@need 1250
5751Incidentally, using @code{or}, the situation with the usher would be
5752written like this:
5753
5754@smallexample
5755(or (holding-on-to-guest) (find-and-take-arm-of-guest))
5756@end smallexample
5757
5758@node Insert let, , Insert or, insert-buffer
5759@comment node-name, next, previous, up
5760@subsection The @code{let} Expression in @code{insert-buffer}
5761
5762After ensuring that the variable @code{buffer} refers to a buffer itself
5763and not just to the name of a buffer, the @code{insert-buffer function}
5764continues with a @code{let} expression. This specifies three local
5765variables, @code{start}, @code{end}, and @code{newmark} and binds them
5766to the initial value @code{nil}. These variables are used inside the
5767remainder of the @code{let} and temporarily hide any other occurrence of
5768variables of the same name in Emacs until the end of the @code{let}.
5769
5770@need 1200
5771The body of the @code{let} contains two @code{save-excursion}
5772expressions. First, we will look at the inner @code{save-excursion}
5773expression in detail. The expression looks like this:
5774
5775@smallexample
5776@group
5777(save-excursion
5778 (set-buffer buffer)
5779 (setq start (point-min) end (point-max)))
5780@end group
5781@end smallexample
5782
5783@noindent
5784The expression @code{(set-buffer buffer)} changes Emacs' attention
5785from the current buffer to the one from which the text will copied.
5786In that buffer, the variables @code{start} and @code{end} are set to
5787the beginning and end of the buffer, using the commands
5788@code{point-min} and @code{point-max}. Note that we have here an
5789illustration of how @code{setq} is able to set two variables in the
5790same expression. The first argument of @code{setq} is set to the
5791value of its second, and its third argument is set to the value of its
5792fourth.
5793
5794After the body of the inner @code{save-excursion} is evaluated, the
5795@code{save-excursion} restores the original buffer, but @code{start} and
5796@code{end} remain set to the values of the beginning and end of the
5797buffer from which the text will be copied.
5798
5799@need 1250
5800The outer @code{save-excursion} expression looks like this:
5801
5802@smallexample
5803@group
5804(save-excursion
5805 (@var{inner-}@code{save-excursion}@var{-expression}
5806 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5807 (insert-buffer-substring buffer start end)
5808 (setq newmark (point)))
5809@end group
5810@end smallexample
5811
5812@noindent
5813The @code{insert-buffer-substring} function copies the text
5814@emph{into} the current buffer @emph{from} the region indicated by
5815@code{start} and @code{end} in @code{buffer}. Since the whole of the
5816second buffer lies between @code{start} and @code{end}, the whole of
5817the second buffer is copied into the buffer you are editing. Next,
5818the value of point, which will be at the end of the inserted text, is
5819recorded in the variable @code{newmark}.
5820
5821After the body of the outer @code{save-excursion} is evaluated, point
5822and mark are relocated to their original places.
5823
5824However, it is convenient to locate a mark at the end of the newly
5825inserted text and locate point at its beginning. The @code{newmark}
5826variable records the end of the inserted text. In the last line of
5827the @code{let} expression, the @code{(push-mark newmark)} expression
5828function sets a mark to this location. (The previous location of the
5829mark is still accessible; it is recorded on the mark ring and you can
5830go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5831located at the beginning of the inserted text, which is where it was
5832before you called the insert function.
5833
5834@need 1250
5835The whole @code{let} expression looks like this:
5836
5837@smallexample
5838@group
5839(let (start end newmark)
5840 (save-excursion
5841 (save-excursion
5842 (set-buffer buffer)
5843 (setq start (point-min) end (point-max)))
5844 (insert-buffer-substring buffer start end)
5845 (setq newmark (point)))
5846 (push-mark newmark))
5847@end group
5848@end smallexample
5849
5850Like the @code{append-to-buffer} function, the @code{insert-buffer}
5851function uses @code{let}, @code{save-excursion}, and
5852@code{set-buffer}. In addition, the function illustrates one way to
5853use @code{or}. All these functions are building blocks that we will
5854find and use again and again.
5855
5856@node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5857@comment node-name, next, previous, up
5858@section Complete Definition of @code{beginning-of-buffer}
5859@findex beginning-of-buffer
5860
5861The basic structure of the @code{beginning-of-buffer} function has
5862already been discussed. (@xref{simplified-beginning-of-buffer, , A
5863Simplified @code{beginning-of-buffer} Definition}.)
5864This section describes the complex part of the definition.
5865
5866As previously described, when invoked without an argument,
5867@code{beginning-of-buffer} moves the cursor to the beginning of the
5868buffer, leaving the mark at the previous position. However, when the
5869command is invoked with a number between one and ten, the function
5870considers that number to be a fraction of the length of the buffer,
5871measured in tenths, and Emacs moves the cursor that fraction of the way
5872from the beginning of the buffer. Thus, you can either call this
5873function with the key command @kbd{M-<}, which will move the cursor to
5874the beginning of the buffer, or with a key command such as @kbd{C-u 7
5875M-<} which will move the cursor to a point 70% of the way through the
5876buffer. If a number bigger than ten is used for the argument, it moves
5877to the end of the buffer.
5878
5879The @code{beginning-of-buffer} function can be called with or without an
5880argument. The use of the argument is optional.
5881
5882@menu
5883* Optional Arguments::
5884* beginning-of-buffer opt arg:: Example with optional argument.
5885* beginning-of-buffer complete::
5886@end menu
5887
5888@node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5889@subsection Optional Arguments
5890
5891Unless told otherwise, Lisp expects that a function with an argument in
5892its function definition will be called with a value for that argument.
5893If that does not happen, you get an error and a message that says
5894@samp{Wrong number of arguments}.
5895
5896@cindex Optional arguments
5897@cindex Keyword
5898@findex optional
5899However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5900be used to tell the Lisp interpreter that an argument is optional.
5901The keyword is @code{&optional}. (The @samp{&} in front of
5902@samp{optional} is part of the keyword.) In a function definition, if
5903an argument follows the keyword @code{&optional}, a value does not
5904need to be passed to that argument when the function is called.
5905
5906@need 1200
5907The first line of the function definition of @code{beginning-of-buffer}
5908therefore looks like this:
5909
5910@smallexample
5911(defun beginning-of-buffer (&optional arg)
5912@end smallexample
5913
5914@need 1250
5915In outline, the whole function looks like this:
5916
5917@smallexample
5918@group
5919(defun beginning-of-buffer (&optional arg)
5920 "@var{documentation}@dots{}"
5921 (interactive "P")
5922 (push-mark)
5923 (goto-char
5924 (@var{if-there-is-an-argument}
5925 @var{figure-out-where-to-go}
5926 @var{else-go-to}
5927 (point-min))))
5928@end group
5929@end smallexample
5930
5931The function is similar to the @code{simplified-beginning-of-buffer}
5932function except that the @code{interactive} expression has @code{"P"}
5933as an argument and the @code{goto-char} function is followed by an
5934if-then-else expression that figures out where to put the cursor if
5935there is an argument.
5936
5937The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5938a prefix argument, if there is one, to the function. A prefix argument
5939is made by typing the @key{META} key followed by a number, or by typing
5940@kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5941defaults to 4).
5942
5943The true-or-false-test of the @code{if} expression is simple: it is
5944simply the argument @code{arg}. If @code{arg} has a value that is not
5945@code{nil}, which will be the case if @code{beginning-of-buffer} is
5946called with an argument, then this true-or-false-test will return true
5947and the then-part of the @code{if} expression will be evaluated. On the
5948other hand, if @code{beginning-of-buffer} is not called with an
5949argument, the value of @code{arg} will be @code{nil} and the else-part
5950of the @code{if} expression will be evaluated. The else-part is simply
5951@code{point-min}, and when this is the outcome, the whole
5952@code{goto-char} expression is @code{(goto-char (point-min))}, which is
5953how we saw the @code{beginning-of-buffer} function in its simplified
5954form.
5955
5956@node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5957@subsection @code{beginning-of-buffer} with an Argument
5958
5959When @code{beginning-of-buffer} is called with an argument, an
5960expression is evaluated which calculates what value to pass to
5961@code{goto-char}. This expression is rather complicated at first sight.
5962It includes an inner @code{if} expression and much arithmetic. It looks
5963like this:
5964
5965@smallexample
5966@group
5967(if (> (buffer-size) 10000)
5968 ;; @r{Avoid overflow for large buffer sizes!}
5969 (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5970 (/
5971 (+ 10
5972 (*
5973 (buffer-size) (prefix-numeric-value arg))) 10))
5974@end group
5975@end smallexample
5976
5977@menu
5978* Disentangle beginning-of-buffer::
5979* Large buffer case::
5980* Small buffer case::
5981@end menu
5982
5983@node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5984@ifnottex
5985@unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5986@end ifnottex
5987
5988Like other complex-looking expressions, the conditional expression
5989within @code{beginning-of-buffer} can be disentangled by looking at it
5990as parts of a template, in this case, the template for an if-then-else
5991expression. In skeletal form, the expression looks like this:
5992
5993@smallexample
5994@group
5995(if (@var{buffer-is-large}
5996 @var{divide-buffer-size-by-10-and-multiply-by-arg}
5997 @var{else-use-alternate-calculation}
5998@end group
5999@end smallexample
6000
6001The true-or-false-test of this inner @code{if} expression checks the
6002size of the buffer. The reason for this is that the old Version 18
6003Emacs used numbers that are no bigger than eight million or so
6004and in the computation that followed, the programmer feared that Emacs
6005might try to use over-large numbers if the buffer were large. The
6006term `overflow', mentioned in the comment, means numbers that are over
6007large. Version 21 Emacs uses larger numbers, but this code has not
6008been touched, if only because people now look at buffers that are far,
6009far larger than ever before.
6010
6011There are two cases: if the buffer is large and if it is not.
6012
6013@node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
6014@comment node-name, next, previous, up
6015@unnumberedsubsubsec What happens in a large buffer
6016
6017In @code{beginning-of-buffer}, the inner @code{if} expression tests
6018whether the size of the buffer is greater than 10,000 characters. To do
6019this, it uses the @code{>} function and the @code{buffer-size} function.
6020
6021@need 800
6022The line looks like this:
6023
6024@smallexample
6025(if (> (buffer-size) 10000)
6026@end smallexample
6027
6028@need 1200
6029@noindent
6030When the buffer is large, the then-part of the @code{if} expression is
6031evaluated. It reads like this (after formatting for easy reading):
6032
6033@smallexample
6034@group
6035(*
6036 (prefix-numeric-value arg)
6037 (/ (buffer-size) 10))
6038@end group
6039@end smallexample
6040
6041@noindent
6042This expression is a multiplication, with two arguments to the function
6043@code{*}.
6044
6045The first argument is @code{(prefix-numeric-value arg)}. When
6046@code{"P"} is used as the argument for @code{interactive}, the value
6047passed to the function as its argument is passed a ``raw prefix
6048argument'', and not a number. (It is a number in a list.) To perform
6049the arithmetic, a conversion is necessary, and
6050@code{prefix-numeric-value} does the job.
6051
6052@findex / @r{(division)}
6053@cindex Division
6054The second argument is @code{(/ (buffer-size) 10)}. This expression
6055divides the numeric value of the buffer by ten. This produces a number
6056that tells how many characters make up one tenth of the buffer size.
6057(In Lisp, @code{/} is used for division, just as @code{*} is
6058used for multiplication.)
6059
6060@need 1200
6061In the multiplication expression as a whole, this amount is multiplied
6062by the value of the prefix argument---the multiplication looks like this:
6063
6064@smallexample
6065@group
6066(* @var{numeric-value-of-prefix-arg}
6067 @var{number-of-characters-in-one-tenth-of-the-buffer})
6068@end group
6069@end smallexample
6070
6071@noindent
6072If, for example, the prefix argument is @samp{7}, the one-tenth value
6073will be multiplied by 7 to give a position 70% of the way through the
6074buffer.
6075
6076@need 1200
6077The result of all this is that if the buffer is large, the
6078@code{goto-char} expression reads like this:
6079
6080@smallexample
6081@group
6082(goto-char (* (prefix-numeric-value arg)
6083 (/ (buffer-size) 10)))
6084@end group
6085@end smallexample
6086
6087This puts the cursor where we want it.
6088
6089@node Small buffer case, , Large buffer case, beginning-of-buffer opt arg
6090@comment node-name, next, previous, up
6091@unnumberedsubsubsec What happens in a small buffer
6092
6093If the buffer contains fewer than 10,000 characters, a slightly
6094different computation is performed. You might think this is not
6095necessary, since the first computation could do the job. However, in
6096a small buffer, the first method may not put the cursor on exactly the
6097desired line; the second method does a better job.
6098
6099@need 800
6100The code looks like this:
6101
6102@c Keep this on one line.
6103@smallexample
6104(/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6105@end smallexample
6106
6107@need 1200
6108@noindent
6109This is code in which you figure out what happens by discovering how the
6110functions are embedded in parentheses. It is easier to read if you
6111reformat it with each expression indented more deeply than its
6112enclosing expression:
6113
6114@smallexample
6115@group
6116 (/
6117 (+ 10
6118 (*
6119 (buffer-size)
6120 (prefix-numeric-value arg)))
6121 10))
6122@end group
6123@end smallexample
6124
6125@need 1200
6126@noindent
6127Looking at parentheses, we see that the innermost operation is
6128@code{(prefix-numeric-value arg)}, which converts the raw argument to a
6129number. This number is multiplied by the buffer size in the following
6130expression:
6131
6132@smallexample
6133(* (buffer-size) (prefix-numeric-value arg)
6134@end smallexample
6135
6136@noindent
6137This multiplication creates a number that may be larger than the size of
6138the buffer---seven times larger if the argument is 7, for example. Ten
6139is then added to this number and finally the large number is divided by
6140ten to provide a value that is one character larger than the percentage
6141position in the buffer.
6142
6143The number that results from all this is passed to @code{goto-char} and
6144the cursor is moved to that point.
6145
6146@node beginning-of-buffer complete, , beginning-of-buffer opt arg, beginning-of-buffer
6147@comment node-name, next, previous, up
6148@subsection The Complete @code{beginning-of-buffer}
6149
6150@need 800
6151Here is the complete text of the @code{beginning-of-buffer} function:
6152
6153@smallexample
6154@group
6155(defun beginning-of-buffer (&optional arg)
6156 "Move point to the beginning of the buffer;
6157leave mark at previous position.
6158With arg N, put point N/10 of the way
6159from the true beginning.
6160Don't use this in Lisp programs!
6161\(goto-char (point-min)) is faster
6162and does not set the mark."
6163 (interactive "P")
6164 (push-mark)
6165@end group
6166@group
6167 (goto-char
6168 (if arg
6169 (if (> (buffer-size) 10000)
6170 ;; @r{Avoid overflow for large buffer sizes!}
6171 (* (prefix-numeric-value arg)
6172 (/ (buffer-size) 10))
6173@end group
6174@group
6175 (/ (+ 10 (* (buffer-size)
6176 (prefix-numeric-value arg)))
6177 10))
6178 (point-min)))
6179 (if arg (forward-line 1)))
6180@end group
6181@end smallexample
6182
6183@noindent
6184Except for two small points, the previous discussion shows how this
6185function works. The first point deals with a detail in the
6186documentation string, and the second point concerns the last line of
6187the function.
6188
6189@need 800
6190In the documentation string, there is reference to an expression:
6191
6192@smallexample
6193\(goto-char (point-min))
6194@end smallexample
6195
6196@noindent
6197A @samp{\} is used before the first parenthesis of this expression.
6198This @samp{\} tells the Lisp interpreter that the expression should be
6199printed as shown in the documentation rather than evaluated as a
6200symbolic expression, which is what it looks like.
6201
6202@need 1200
6203Finally, the last line of the @code{beginning-of-buffer} command says to
6204move point to the beginning of the next line if the command is
6205invoked with an argument:
6206
6207@smallexample
6208(if arg (forward-line 1)))
6209@end smallexample
6210
6211@noindent
6212This puts the cursor at the beginning of the first line after the
6213appropriate tenths position in the buffer. This is a flourish that
6214means that the cursor is always located @emph{at least} the requested
6215tenths of the way through the buffer, which is a nicety that is,
6216perhaps, not necessary, but which, if it did not occur, would be sure to
6217draw complaints.
6218
6219@node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6220@comment node-name, next, previous, up
6221@section Review
6222
6223Here is a brief summary of some of the topics covered in this chapter.
6224
6225@table @code
6226@item or
6227Evaluate each argument in sequence, and return the value of the first
6228argument that is not @code{nil}; if none return a value that is not
6229@code{nil}, return @code{nil}. In brief, return the first true value
6230of the arguments; return a true value if one @emph{or} any of the
6231other are true.
6232
6233@item and
6234Evaluate each argument in sequence, and if any are @code{nil}, return
6235@code{nil}; if none are @code{nil}, return the value of the last
6236argument. In brief, return a true value only if all the arguments are
6237true; return a true value if one @emph{and} each of the others is
6238true.
6239
6240@item &optional
6241A keyword used to indicate that an argument to a function definition
6242is optional; this means that the function can be evaluated without the
6243argument, if desired.
6244
6245@item prefix-numeric-value
6246Convert the `raw prefix argument' produced by @code{(interactive
6247"P")} to a numeric value.
6248
6249@item forward-line
6250Move point forward to the beginning of the next line, or if the argument
6251is greater than one, forward that many lines. If it can't move as far
6252forward as it is supposed to, @code{forward-line} goes forward as far as
6253it can and then returns a count of the number of additional lines it was
6254supposed to move but couldn't.
6255
6256@item erase-buffer
6257Delete the entire contents of the current buffer.
6258
6259@item bufferp
6260Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6261@end table
6262
6263@node optional Exercise, , Second Buffer Related Review, More Complex
6264@section @code{optional} Argument Exercise
6265
6266Write an interactive function with an optional argument that tests
6267whether its argument, a number, is greater or less than the value of
6268@code{fill-column}, and tells you which, in a message. However, if you
6269do not pass an argument to the function, use 56 as a default value.
6270
6271@node Narrowing & Widening, car cdr & cons, More Complex, Top
6272@comment node-name, next, previous, up
6273@chapter Narrowing and Widening
6274@cindex Focusing attention (narrowing)
6275@cindex Narrowing
6276@cindex Widening
6277
6278Narrowing is a feature of Emacs that makes it possible for you to focus
6279on a specific part of a buffer, and work without accidentally changing
6280other parts. Narrowing is normally disabled since it can confuse
6281novices.
6282
6283@menu
6284* Narrowing advantages:: The advantages of narrowing
6285* save-restriction:: The @code{save-restriction} special form.
6286* what-line:: The number of the line that point is on.
6287* narrow Exercise::
6288@end menu
6289
6290@node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6291@ifnottex
6292@unnumberedsec The Advantages of Narrowing
6293@end ifnottex
6294
6295With narrowing, the rest of a buffer is made invisible, as if it weren't
6296there. This is an advantage if, for example, you want to replace a word
6297in one part of a buffer but not in another: you narrow to the part you want
6298and the replacement is carried out only in that section, not in the rest
6299of the buffer. Searches will only work within a narrowed region, not
6300outside of one, so if you are fixing a part of a document, you can keep
6301yourself from accidentally finding parts you do not need to fix by
6302narrowing just to the region you want.
6303(The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6304
6305However, narrowing does make the rest of the buffer invisible, which
6306can scare people who inadvertently invoke narrowing and think they
6307have deleted a part of their file. Moreover, the @code{undo} command
6308(which is usually bound to @kbd{C-x u}) does not turn off narrowing
6309(nor should it), so people can become quite desperate if they do not
6310know that they can return the rest of a buffer to visibility with the
6311@code{widen} command.
6312(The key binding for @code{widen} is @kbd{C-x n w}.)
6313
6314Narrowing is just as useful to the Lisp interpreter as to a human.
6315Often, an Emacs Lisp function is designed to work on just part of a
6316buffer; or conversely, an Emacs Lisp function needs to work on all of a
6317buffer that has been narrowed. The @code{what-line} function, for
6318example, removes the narrowing from a buffer, if it has any narrowing
6319and when it has finished its job, restores the narrowing to what it was.
6320On the other hand, the @code{count-lines} function, which is called by
6321@code{what-line}, uses narrowing to restrict itself to just that portion
6322of the buffer in which it is interested and then restores the previous
6323situation.
6324
6325@node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6326@comment node-name, next, previous, up
6327@section The @code{save-restriction} Special Form
6328@findex save-restriction
6329
6330In Emacs Lisp, you can use the @code{save-restriction} special form to
6331keep track of whatever narrowing is in effect, if any. When the Lisp
6332interpreter meets with @code{save-restriction}, it executes the code
6333in the body of the @code{save-restriction} expression, and then undoes
6334any changes to narrowing that the code caused. If, for example, the
6335buffer is narrowed and the code that follows @code{save-restriction}
6336gets rid of the narrowing, @code{save-restriction} returns the buffer
6337to its narrowed region afterwards. In the @code{what-line} command,
6338any narrowing the buffer may have is undone by the @code{widen}
6339command that immediately follows the @code{save-restriction} command.
6340Any original narrowing is restored just before the completion of the
6341function.
6342
6343@need 1250
6344The template for a @code{save-restriction} expression is simple:
6345
6346@smallexample
6347@group
6348(save-restriction
6349 @var{body}@dots{} )
6350@end group
6351@end smallexample
6352
6353@noindent
6354The body of the @code{save-restriction} is one or more expressions that
6355will be evaluated in sequence by the Lisp interpreter.
6356
6357Finally, a point to note: when you use both @code{save-excursion} and
6358@code{save-restriction}, one right after the other, you should use
6359@code{save-excursion} outermost. If you write them in reverse order,
6360you may fail to record narrowing in the buffer to which Emacs switches
6361after calling @code{save-excursion}. Thus, when written together,
6362@code{save-excursion} and @code{save-restriction} should be written
6363like this:
6364
6365@smallexample
6366@group
6367(save-excursion
6368 (save-restriction
6369 @var{body}@dots{}))
6370@end group
6371@end smallexample
6372
6373In other circumstances, when not written together, the
6374@code{save-excursion} and @code{save-restriction} special forms must
6375be written in the order appropriate to the function.
6376
6377@need 1250
6378For example,
6379
6380@smallexample
6381@group
6382 (save-restriction
6383 (widen)
6384 (save-excursion
6385 @var{body}@dots{}))
6386@end group
6387@end smallexample
6388
6389@node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6390@comment node-name, next, previous, up
6391@section @code{what-line}
6392@findex what-line
6393@cindex Widening, example of
6394
6395The @code{what-line} command tells you the number of the line in which
6396the cursor is located. The function illustrates the use of the
6397@code{save-restriction} and @code{save-excursion} commands. Here is the
6398text of the function in full:
6399
6400@smallexample
6401@group
6402(defun what-line ()
6403 "Print the current line number (in the buffer) of point."
6404 (interactive)
6405 (save-restriction
6406 (widen)
6407 (save-excursion
6408 (beginning-of-line)
6409 (message "Line %d"
6410 (1+ (count-lines 1 (point)))))))
6411@end group
6412@end smallexample
6413
6414The function has a documentation line and is interactive, as you would
6415expect. The next two lines use the functions @code{save-restriction} and
6416@code{widen}.
6417
6418The @code{save-restriction} special form notes whatever narrowing is in
6419effect, if any, in the current buffer and restores that narrowing after
6420the code in the body of the @code{save-restriction} has been evaluated.
6421
6422The @code{save-restriction} special form is followed by @code{widen}.
6423This function undoes any narrowing the current buffer may have had
6424when @code{what-line} was called. (The narrowing that was there is
6425the narrowing that @code{save-restriction} remembers.) This widening
6426makes it possible for the line counting commands to count from the
6427beginning of the buffer. Otherwise, they would have been limited to
6428counting within the accessible region. Any original narrowing is
6429restored just before the completion of the function by the
6430@code{save-restriction} special form.
6431
6432The call to @code{widen} is followed by @code{save-excursion}, which
6433saves the location of the cursor (i.e., of point) and of the mark, and
6434restores them after the code in the body of the @code{save-excursion}
6435uses the @code{beginning-of-line} function to move point.
6436
6437(Note that the @code{(widen)} expression comes between the
6438@code{save-restriction} and @code{save-excursion} special forms. When
6439you write the two @code{save- @dots{}} expressions in sequence, write
6440@code{save-excursion} outermost.)
6441
6442@need 1200
6443The last two lines of the @code{what-line} function are functions to
6444count the number of lines in the buffer and then print the number in the
6445echo area.
6446
6447@smallexample
6448@group
6449(message "Line %d"
6450 (1+ (count-lines 1 (point)))))))
6451@end group
6452@end smallexample
6453
6454The @code{message} function prints a one-line message at the bottom of the
6455Emacs screen. The first argument is inside of quotation marks and is
6456printed as a string of characters. However, it may contain @samp{%d},
6457@samp{%s}, or @samp{%c} to print arguments that follow the string.
6458@samp{%d} prints the argument as a decimal, so the message will say
6459something such as @samp{Line 243}.
6460
6461@need 1200
6462The number that is printed in place of the @samp{%d} is computed by the
6463last line of the function:
6464
6465@smallexample
6466(1+ (count-lines 1 (point)))
6467@end smallexample
6468
6469@noindent
6470What this does is count the lines from the first position of the
6471buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6472one to that number. (The @code{1+} function adds one to its
6473argument.) We add one to it because line 2 has only one line before
6474it, and @code{count-lines} counts only the lines @emph{before} the
6475current line.
6476
6477After @code{count-lines} has done its job, and the message has been
6478printed in the echo area, the @code{save-excursion} restores point and
6479mark to their original positions; and @code{save-restriction} restores
6480the original narrowing, if any.
6481
6482@node narrow Exercise, , what-line, Narrowing & Widening
6483@section Exercise with Narrowing
6484
6485Write a function that will display the first 60 characters of the
6486current buffer, even if you have narrowed the buffer to its latter
6487half so that the first line is inaccessible. Restore point, mark,
6488and narrowing. For this exercise, you need to use
6489@code{save-restriction}, @code{widen}, @code{goto-char},
6490@code{point-min}, @code{buffer-substring}, @code{message}, and other
6491functions, a whole potpourri.
6492
6493@node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6494@comment node-name, next, previous, up
6495@chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6496@findex car, @r{introduced}
6497@findex cdr, @r{introduced}
6498
6499In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6500functions. The @code{cons} function is used to construct lists, and
6501the @code{car} and @code{cdr} functions are used to take them apart.
6502
6503In the walk through of the @code{copy-region-as-kill} function, we
6504will see @code{cons} as well as two variants on @code{cdr},
6505namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6506
6507@menu
6508* Strange Names:: An historical aside: why the strange names?
6509* car & cdr:: Functions for extracting part of a list.
6510* cons:: Constructing a list.
6511* nthcdr:: Calling @code{cdr} repeatedly.
6512* nth::
6513* setcar:: Changing the first element of a list.
6514* setcdr:: Changing the rest of a list.
6515* cons Exercise::
6516@end menu
6517
6518@node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6519@ifnottex
6520@unnumberedsec Strange Names
6521@end ifnottex
6522
6523The name of the @code{cons} function is not unreasonable: it is an
6524abbreviation of the word `construct'. The origins of the names for
6525@code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6526is an acronym from the phrase `Contents of the Address part of the
6527Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6528the phrase `Contents of the Decrement part of the Register'. These
6529phrases refer to specific pieces of hardware on the very early
6530computer on which the original Lisp was developed. Besides being
6531obsolete, the phrases have been completely irrelevant for more than 25
6532years to anyone thinking about Lisp. Nonetheless, although a few
6533brave scholars have begun to use more reasonable names for these
6534functions, the old terms are still in use. In particular, since the
6535terms are used in the Emacs Lisp source code, we will use them in this
6536introduction.
6537
6538@node car & cdr, cons, Strange Names, car cdr & cons
6539@comment node-name, next, previous, up
6540@section @code{car} and @code{cdr}
6541
6542The @sc{car} of a list is, quite simply, the first item in the list.
6543Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6544@code{rose}.
6545
6546@need 1200
6547If you are reading this in Info in GNU Emacs, you can see this by
6548evaluating the following:
6549
6550@smallexample
6551(car '(rose violet daisy buttercup))
6552@end smallexample
6553
6554@noindent
6555After evaluating the expression, @code{rose} will appear in the echo
6556area.
6557
6558Clearly, a more reasonable name for the @code{car} function would be
6559@code{first} and this is often suggested.
6560
6561@code{car} does not remove the first item from the list; it only reports
6562what it is. After @code{car} has been applied to a list, the list is
6563still the same as it was. In the jargon, @code{car} is
6564`non-destructive'. This feature turns out to be important.
6565
6566The @sc{cdr} of a list is the rest of the list, that is, the
6567@code{cdr} function returns the part of the list that follows the
6568first item. Thus, while the @sc{car} of the list @code{'(rose violet
6569daisy buttercup)} is @code{rose}, the rest of the list, the value
6570returned by the @code{cdr} function, is @code{(violet daisy
6571buttercup)}.
6572
6573@need 1250
6574You can see this by evaluating the following in the usual way:
6575
6576@smallexample
6577(cdr '(rose violet daisy buttercup))
6578@end smallexample
6579
6580@noindent
6581When you evaluate this, @code{(violet daisy buttercup)} will appear in
6582the echo area.
6583
6584Like @code{car}, @code{cdr} does not remove any elements from the
6585list---it just returns a report of what the second and subsequent
6586elements are.
6587
6588Incidentally, in the example, the list of flowers is quoted. If it were
6589not, the Lisp interpreter would try to evaluate the list by calling
6590@code{rose} as a function. In this example, we do not want to do that.
6591
6592Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6593
6594(There is a lesson here: when you name new functions, consider very
6595carefully what you are doing, since you may be stuck with the names
6596for far longer than you expect. The reason this document perpetuates
6597these names is that the Emacs Lisp source code uses them, and if I did
6598not use them, you would have a hard time reading the code; but do,
6599please, try to avoid using these terms yourself. The people who come
6600after you will be grateful to you.)
6601
6602When @code{car} and @code{cdr} are applied to a list made up of symbols,
6603such as the list @code{(pine fir oak maple)}, the element of the list
6604returned by the function @code{car} is the symbol @code{pine} without
6605any parentheses around it. @code{pine} is the first element in the
6606list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6607oak maple)}, as you can see by evaluating the following expressions in
6608the usual way:
6609
6610@smallexample
6611@group
6612(car '(pine fir oak maple))
6613
6614(cdr '(pine fir oak maple))
6615@end group
6616@end smallexample
6617
6618On the other hand, in a list of lists, the first element is itself a
6619list. @code{car} returns this first element as a list. For example,
6620the following list contains three sub-lists, a list of carnivores, a
6621list of herbivores and a list of sea mammals:
6622
6623@smallexample
6624@group
6625(car '((lion tiger cheetah)
6626 (gazelle antelope zebra)
6627 (whale dolphin seal)))
6628@end group
6629@end smallexample
6630
6631@noindent
6632In this example, the first element or @sc{car} of the list is the list of
6633carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6634@code{((gazelle antelope zebra) (whale dolphin seal))}.
6635
6636@smallexample
6637@group
6638(cdr '((lion tiger cheetah)
6639 (gazelle antelope zebra)
6640 (whale dolphin seal)))
6641@end group
6642@end smallexample
6643
6644It is worth saying again that @code{car} and @code{cdr} are
6645non-destructive---that is, they do not modify or change lists to which
6646they are applied. This is very important for how they are used.
6647
6648Also, in the first chapter, in the discussion about atoms, I said that
6649in Lisp, ``certain kinds of atom, such as an array, can be separated
6650into parts; but the mechanism for doing this is different from the
6651mechanism for splitting a list. As far as Lisp is concerned, the
6652atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
6653@code{car} and @code{cdr} functions are used for splitting lists and
6654are considered fundamental to Lisp. Since they cannot split or gain
6655access to the parts of an array, an array is considered an atom.
6656Conversely, the other fundamental function, @code{cons}, can put
6657together or construct a list, but not an array. (Arrays are handled
6658by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
6659Emacs Lisp Reference Manual}.)
6660
6661@node cons, nthcdr, car & cdr, car cdr & cons
6662@comment node-name, next, previous, up
6663@section @code{cons}
6664@findex cons, @r{introduced}
6665
6666The @code{cons} function constructs lists; it is the inverse of
6667@code{car} and @code{cdr}. For example, @code{cons} can be used to make
6668a four element list from the three element list, @code{(fir oak maple)}:
6669
6670@smallexample
6671(cons 'pine '(fir oak maple))
6672@end smallexample
6673
6674@need 800
6675@noindent
6676After evaluating this list, you will see
6677
6678@smallexample
6679(pine fir oak maple)
6680@end smallexample
6681
6682@noindent
b15dd613
RC
6683appear in the echo area. @code{cons} causes the creation of a new
6684list in which the element is followed by the elements of the original
6685list.
6686
6687We often say that `@code{cons} puts a new element at the beginning of
6688a list; it attaches or pushes elements onto the list', but this
6689phrasing can be misleading, since @code{cons} does not change an
6690existing list, but creates a new one.
6691
6692Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
8b096dce
EZ
6693
6694@menu
6695* Build a list::
6696* length:: How to find the length of a list.
6697@end menu
6698
6699@node Build a list, length, cons, cons
6700@ifnottex
6701@unnumberedsubsec Build a list
6702@end ifnottex
6703
6704@code{cons} must have a list to attach to.@footnote{Actually, you can
6705@code{cons} an element to an atom to produce a dotted pair. Dotted
6706pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6707Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
6708cannot start from absolutely nothing. If you are building a list, you
6709need to provide at least an empty list at the beginning. Here is a
6710series of @code{cons} expressions that build up a list of flowers. If
6711you are reading this in Info in GNU Emacs, you can evaluate each of
6712the expressions in the usual way; the value is printed in this text
6713after @samp{@result{}}, which you may read as `evaluates to'.
6714
6715@smallexample
6716@group
6717(cons 'buttercup ())
6718 @result{} (buttercup)
6719@end group
6720
6721@group
6722(cons 'daisy '(buttercup))
6723 @result{} (daisy buttercup)
6724@end group
6725
6726@group
6727(cons 'violet '(daisy buttercup))
6728 @result{} (violet daisy buttercup)
6729@end group
6730
6731@group
6732(cons 'rose '(violet daisy buttercup))
6733 @result{} (rose violet daisy buttercup)
6734@end group
6735@end smallexample
6736
6737@noindent
6738In the first example, the empty list is shown as @code{()} and a list
6739made up of @code{buttercup} followed by the empty list is constructed.
6740As you can see, the empty list is not shown in the list that was
6741constructed. All that you see is @code{(buttercup)}. The empty list is
6742not counted as an element of a list because there is nothing in an empty
6743list. Generally speaking, an empty list is invisible.
6744
6745The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6746two element list by putting @code{daisy} in front of @code{buttercup};
6747and the third example constructs a three element list by putting
6748@code{violet} in front of @code{daisy} and @code{buttercup}.
6749
6750@node length, , Build a list, cons
6751@comment node-name, next, previous, up
6752@subsection Find the Length of a List: @code{length}
6753@findex length
6754
6755You can find out how many elements there are in a list by using the Lisp
6756function @code{length}, as in the following examples:
6757
6758@smallexample
6759@group
6760(length '(buttercup))
6761 @result{} 1
6762@end group
6763
6764@group
6765(length '(daisy buttercup))
6766 @result{} 2
6767@end group
6768
6769@group
6770(length (cons 'violet '(daisy buttercup)))
6771 @result{} 3
6772@end group
6773@end smallexample
6774
6775@noindent
6776In the third example, the @code{cons} function is used to construct a
6777three element list which is then passed to the @code{length} function as
6778its argument.
6779
6780@need 1200
6781We can also use @code{length} to count the number of elements in an
6782empty list:
6783
6784@smallexample
6785@group
6786(length ())
6787 @result{} 0
6788@end group
6789@end smallexample
6790
6791@noindent
6792As you would expect, the number of elements in an empty list is zero.
6793
6794An interesting experiment is to find out what happens if you try to find
6795the length of no list at all; that is, if you try to call @code{length}
6796without giving it an argument, not even an empty list:
6797
6798@smallexample
6799(length )
6800@end smallexample
6801
6802@need 800
6803@noindent
6804What you see, if you evaluate this, is the error message
6805
6806@smallexample
6807Wrong number of arguments: #<subr length>, 0
6808@end smallexample
6809
6810@noindent
6811This means that the function receives the wrong number of
6812arguments, zero, when it expects some other number of arguments. In
6813this case, one argument is expected, the argument being a list whose
6814length the function is measuring. (Note that @emph{one} list is
6815@emph{one} argument, even if the list has many elements inside it.)
6816
6817The part of the error message that says @samp{#<subr length>} is the
6818name of the function. This is written with a special notation,
6819@samp{#<subr}, that indicates that the function @code{length} is one
6820of the primitive functions written in C rather than in Emacs Lisp.
6821(@samp{subr} is an abbreviation for `subroutine'.) @xref{What Is a
6822Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6823Manual}, for more about subroutines.
6824
6825@node nthcdr, nth, cons, car cdr & cons
6826@comment node-name, next, previous, up
6827@section @code{nthcdr}
6828@findex nthcdr
6829
6830The @code{nthcdr} function is associated with the @code{cdr} function.
6831What it does is take the @sc{cdr} of a list repeatedly.
6832
6833If you take the @sc{cdr} of the list @code{(pine fir
6834oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
6835repeat this on what was returned, you will be returned the list
6836@code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
6837list will just give you the original @sc{cdr} since the function does
6838not change the list. You need to evaluate the @sc{cdr} of the
6839@sc{cdr} and so on.) If you continue this, eventually you will be
6840returned an empty list, which in this case, instead of being shown as
6841@code{()} is shown as @code{nil}.
6842
6843@need 1200
6844For review, here is a series of repeated @sc{cdr}s, the text following
6845the @samp{@result{}} shows what is returned.
6846
6847@smallexample
6848@group
6849(cdr '(pine fir oak maple))
6850 @result{}(fir oak maple)
6851@end group
6852
6853@group
6854(cdr '(fir oak maple))
6855 @result{} (oak maple)
6856@end group
6857
6858@group
6859(cdr '(oak maple))
6860 @result{}(maple)
6861@end group
6862
6863@group
6864(cdr '(maple))
6865 @result{} nil
6866@end group
6867
6868@group
6869(cdr 'nil)
6870 @result{} nil
6871@end group
6872
6873@group
6874(cdr ())
6875 @result{} nil
6876@end group
6877@end smallexample
6878
6879@need 1200
6880You can also do several @sc{cdr}s without printing the values in
6881between, like this:
6882
6883@smallexample
6884@group
6885(cdr (cdr '(pine fir oak maple)))
6886 @result{} (oak maple)
6887@end group
6888@end smallexample
6889
6890@noindent
6891In this example, the Lisp interpreter evaluates the innermost list first.
6892The innermost list is quoted, so it just passes the list as it is to the
6893innermost @code{cdr}. This @code{cdr} passes a list made up of the
6894second and subsequent elements of the list to the outermost @code{cdr},
6895which produces a list composed of the third and subsequent elements of
6896the original list. In this example, the @code{cdr} function is repeated
6897and returns a list that consists of the original list without its
6898first two elements.
6899
6900The @code{nthcdr} function does the same as repeating the call to
6901@code{cdr}. In the following example, the argument 2 is passed to the
6902function @code{nthcdr}, along with the list, and the value returned is
6903the list without its first two items, which is exactly the same
6904as repeating @code{cdr} twice on the list:
6905
6906@smallexample
6907@group
6908(nthcdr 2 '(pine fir oak maple))
6909 @result{} (oak maple)
6910@end group
6911@end smallexample
6912
6913@need 1200
6914Using the original four element list, we can see what happens when
6915various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6916and 5:
6917
6918@smallexample
6919@group
6920;; @r{Leave the list as it was.}
6921(nthcdr 0 '(pine fir oak maple))
6922 @result{} (pine fir oak maple)
6923@end group
6924
6925@group
6926;; @r{Return a copy without the first element.}
6927(nthcdr 1 '(pine fir oak maple))
6928 @result{} (fir oak maple)
6929@end group
6930
6931@group
6932;; @r{Return a copy of the list without three elements.}
6933(nthcdr 3 '(pine fir oak maple))
6934 @result{} (maple)
6935@end group
6936
6937@group
6938;; @r{Return a copy lacking all four elements.}
6939(nthcdr 4 '(pine fir oak maple))
6940 @result{} nil
6941@end group
6942
6943@group
6944;; @r{Return a copy lacking all elements.}
6945(nthcdr 5 '(pine fir oak maple))
6946 @result{} nil
6947@end group
6948@end smallexample
6949
6950@node nth, setcar, nthcdr, car cdr & cons
6951@comment node-name, next, previous, up
6952@section @code{nth}
6953@findex nth
6954
6955The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6956The @code{nth} function takes the @sc{car} of the result returned by
6957@code{nthcdr}. It returns the Nth element of the list.
6958
6959@need 1500
6960Thus, if it were not defined in C for speed, the definition of
6961@code{nth} would be:
6962
6963@smallexample
6964@group
6965(defun nth (n list)
6966 "Returns the Nth element of LIST.
6967N counts from zero. If LIST is not that long, nil is returned."
6968 (car (nthcdr n list)))
6969@end group
6970@end smallexample
6971
6972@noindent
6973(Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6974but its definition was redone in C in the 1980s.)
6975
6976The @code{nth} function returns a single element of a list.
6977This can be very convenient.
6978
6979Note that the elements are numbered from zero, not one. That is to
6980say, the first element of a list, its @sc{car} is the zeroth element.
6981This is called `zero-based' counting and often bothers people who
6982are accustomed to the first element in a list being number one, which
6983is `one-based'.
6984
6985@need 1250
6986For example:
6987
6988@smallexample
6989@group
6990(nth 0 '("one" "two" "three"))
6991 @result{} "one"
6992
6993(nth 1 '("one" "two" "three"))
6994 @result{} "two"
6995@end group
6996@end smallexample
6997
6998It is worth mentioning that @code{nth}, like @code{nthcdr} and
6999@code{cdr}, does not change the original list---the function is
7000non-destructive. This is in sharp contrast to the @code{setcar} and
7001@code{setcdr} functions.
7002
7003@node setcar, setcdr, nth, car cdr & cons
7004@comment node-name, next, previous, up
7005@section @code{setcar}
7006@findex setcar
7007
7008As you might guess from their names, the @code{setcar} and @code{setcdr}
7009functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7010They actually change the original list, unlike @code{car} and @code{cdr}
7011which leave the original list as it was. One way to find out how this
7012works is to experiment. We will start with the @code{setcar} function.
7013
7014@need 1200
7015First, we can make a list and then set the value of a variable to the
7016list, using the @code{setq} function. Here is a list of animals:
7017
7018@smallexample
7019(setq animals '(antelope giraffe lion tiger))
7020@end smallexample
7021
7022@noindent
7023If you are reading this in Info inside of GNU Emacs, you can evaluate
7024this expression in the usual fashion, by positioning the cursor after
7025the expression and typing @kbd{C-x C-e}. (I'm doing this right here as
7026I write this. This is one of the advantages of having the interpreter
7027built into the computing environment.)
7028
7029@need 1200
7030When we evaluate the variable @code{animals}, we see that it is bound to
7031the list @code{(antelope giraffe lion tiger)}:
7032
7033@smallexample
7034@group
7035animals
7036 @result{} (antelope giraffe lion tiger)
7037@end group
7038@end smallexample
7039
7040@noindent
7041Put another way, the variable @code{animals} points to the list
7042@code{(antelope giraffe lion tiger)}.
7043
7044Next, evaluate the function @code{setcar} while passing it two
7045arguments, the variable @code{animals} and the quoted symbol
7046@code{hippopotamus}; this is done by writing the three element list
7047@code{(setcar animals 'hippopotamus)} and then evaluating it in the
7048usual fashion:
7049
7050@smallexample
7051(setcar animals 'hippopotamus)
7052@end smallexample
7053
7054@need 1200
7055@noindent
7056After evaluating this expression, evaluate the variable @code{animals}
7057again. You will see that the list of animals has changed:
7058
7059@smallexample
7060@group
7061animals
7062 @result{} (hippopotamus giraffe lion tiger)
7063@end group
7064@end smallexample
7065
7066@noindent
7067The first element on the list, @code{antelope} is replaced by
7068@code{hippopotamus}.
7069
7070So we can see that @code{setcar} did not add a new element to the list
7071as @code{cons} would have; it replaced @code{giraffe} with
7072@code{hippopotamus}; it @emph{changed} the list.
7073
7074@node setcdr, cons Exercise, setcar, car cdr & cons
7075@comment node-name, next, previous, up
7076@section @code{setcdr}
7077@findex setcdr
7078
7079The @code{setcdr} function is similar to the @code{setcar} function,
7080except that the function replaces the second and subsequent elements of
7081a list rather than the first element.
7082
7083@need 1200
7084To see how this works, set the value of the variable to a list of
7085domesticated animals by evaluating the following expression:
7086
7087@smallexample
7088(setq domesticated-animals '(horse cow sheep goat))
7089@end smallexample
7090
7091@need 1200
7092@noindent
7093If you now evaluate the list, you will be returned the list
7094@code{(horse cow sheep goat)}:
7095
7096@smallexample
7097@group
7098domesticated-animals
7099 @result{} (horse cow sheep goat)
7100@end group
7101@end smallexample
7102
7103@need 1200
7104Next, evaluate @code{setcdr} with two arguments, the name of the
7105variable which has a list as its value, and the list to which the
7106@sc{cdr} of the first list will be set;
7107
7108@smallexample
7109(setcdr domesticated-animals '(cat dog))
7110@end smallexample
7111
7112@noindent
7113If you evaluate this expression, the list @code{(cat dog)} will appear
7114in the echo area. This is the value returned by the function. The
7115result we are interested in is the ``side effect'', which we can see by
7116evaluating the variable @code{domesticated-animals}:
7117
7118@smallexample
7119@group
7120domesticated-animals
7121 @result{} (horse cat dog)
7122@end group
7123@end smallexample
7124
7125@noindent
7126Indeed, the list is changed from @code{(horse cow sheep goat)} to
7127@code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7128@code{(cow sheep goat)} to @code{(cat dog)}.
7129
7130@node cons Exercise, , setcdr, car cdr & cons
7131@section Exercise
7132
7133Construct a list of four birds by evaluating several expressions with
7134@code{cons}. Find out what happens when you @code{cons} a list onto
7135itself. Replace the first element of the list of four birds with a
7136fish. Replace the rest of that list with a list of other fish.
e601d8fd 7137
8b096dce
EZ
7138@node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7139@comment node-name, next, previous, up
7140@chapter Cutting and Storing Text
7141@cindex Cutting and storing text
7142@cindex Storing and cutting text
7143@cindex Killing text
7144@cindex Clipping text
7145@cindex Erasing text
7146@cindex Deleting text
7147
7148Whenever you cut or clip text out of a buffer with a `kill' command in
7149GNU Emacs, it is stored in a list and you can bring it back with a
7150`yank' command.
7151
7152(The use of the word `kill' in Emacs for processes which specifically
7153@emph{do not} destroy the values of the entities is an unfortunate
7154historical accident. A much more appropriate word would be `clip' since
7155that is what the kill commands do; they clip text out of a buffer and
7156put it into storage from which it can be brought back. I have often
7157been tempted to replace globally all occurrences of `kill' in the Emacs
7158sources with `clip' and all occurrences of `killed' with `clipped'.)
7159
7160@menu
7161* Storing Text:: Text is stored in a list.
7162* zap-to-char:: Cutting out text up to a character.
7163* kill-region:: Cutting text out of a region.
7164* Digression into C:: Minor note on C programming language macros.
7165* defvar:: How to give a variable an initial value.
7166* copy-region-as-kill:: A definition for copying text.
7167* cons & search-fwd Review::
7168* search Exercises::
7169@end menu
7170
7171@node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7172@ifnottex
7173@unnumberedsec Storing Text in a List
7174@end ifnottex
7175
7176When text is cut out of a buffer, it is stored on a list. Successive
7177pieces of text are stored on the list successively, so the list might
7178look like this:
7179
7180@smallexample
7181("a piece of text" "previous piece")
7182@end smallexample
7183
7184@need 1200
7185@noindent
b15dd613
RC
7186The function @code{cons} can be used to to create a new list from a
7187piece of text (an `atom', to use the jargon) and an existing list,
8b096dce
EZ
7188like this:
7189
7190@smallexample
7191@group
7192(cons "another piece"
7193 '("a piece of text" "previous piece"))
7194@end group
7195@end smallexample
7196
7197@need 1200
7198@noindent
7199If you evaluate this expression, a list of three elements will appear in
7200the echo area:
7201
7202@smallexample
7203("another piece" "a piece of text" "previous piece")
7204@end smallexample
7205
7206With the @code{car} and @code{nthcdr} functions, you can retrieve
7207whichever piece of text you want. For example, in the following code,
7208@code{nthcdr 1 @dots{}} returns the list with the first item removed;
7209and the @code{car} returns the first element of that remainder---the
7210second element of the original list:
7211
7212@smallexample
7213@group
7214(car (nthcdr 1 '("another piece"
7215 "a piece of text"
7216 "previous piece")))
7217 @result{} "a piece of text"
7218@end group
7219@end smallexample
7220
7221The actual functions in Emacs are more complex than this, of course.
7222The code for cutting and retrieving text has to be written so that
7223Emacs can figure out which element in the list you want---the first,
7224second, third, or whatever. In addition, when you get to the end of
7225the list, Emacs should give you the first element of the list, rather
7226than nothing at all.
7227
7228The list that holds the pieces of text is called the @dfn{kill ring}.
7229This chapter leads up to a description of the kill ring and how it is
7230used by first tracing how the @code{zap-to-char} function works. This
7231function uses (or `calls') a function that invokes a function that
7232manipulates the kill ring. Thus, before reaching the mountains, we
7233climb the foothills.
7234
7235A subsequent chapter describes how text that is cut from the buffer is
7236retrieved. @xref{Yanking, , Yanking Text Back}.
7237
7238@node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7239@comment node-name, next, previous, up
7240@section @code{zap-to-char}
7241@findex zap-to-char
7242
7243The @code{zap-to-char} function barely changed between GNU Emacs
7244version 19 and GNU Emacs version 21. However, @code{zap-to-char}
7245calls another function, @code{kill-region}, which enjoyed a major rewrite
7246on the way to version 21.
7247
7248The @code{kill-region} function in Emacs 19 is complex, but does not
7249use code that is important at this time. We will skip it.
7250
7251The @code{kill-region} function in Emacs 21 is easier to read than the
7252same function in Emacs 19 and introduces a very important concept,
7253that of error handling. We will walk through the function.
7254
7255But first, let us look at the interactive @code{zap-to-char} function.
7256
7257@menu
7258* Complete zap-to-char:: The complete implementation.
7259* zap-to-char interactive:: A three part interactive expression.
7260* zap-to-char body:: A short overview.
7261* search-forward:: How to search for a string.
7262* progn:: The @code{progn} special form.
7263* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7264@end menu
7265
7266@node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7267@ifnottex
7268@unnumberedsubsec The Complete @code{zap-to-char} Implementation
7269@end ifnottex
7270
7271The GNU Emacs version 19 and version 21 implementations of the
7272@code{zap-to-char} function are nearly identical in form, and they
7273work alike. The function removes the text in the region between the
7274location of the cursor (i.e., of point) up to and including the next
7275occurrence of a specified character. The text that @code{zap-to-char}
7276removes is put in the kill ring; and it can be retrieved from the kill
7277ring by typing @kbd{C-y} (@code{yank}). If the command is given an
7278argument, it removes text through that number of occurrences. Thus,
7279if the cursor were at the beginning of this sentence and the character
7280were @samp{s}, @samp{Thus} would be removed. If the argument were
7281two, @samp{Thus, if the curs} would be removed, up to and including
7282the @samp{s} in @samp{cursor}.
7283
7284If the specified character is not found, @code{zap-to-char} will say
7285``Search failed'', tell you the character you typed, and not remove
7286any text.
7287
7288In order to determine how much text to remove, @code{zap-to-char} uses
7289a search function. Searches are used extensively in code that
7290manipulates text, and we will focus attention on them as well as on the
7291deletion command.
7292
7293@need 800
7294Here is the complete text of the version 19 implementation of the function:
7295
7296@c v 19
7297@smallexample
7298@group
7299(defun zap-to-char (arg char) ; version 19 implementation
7300 "Kill up to and including ARG'th occurrence of CHAR.
7301Goes backward if ARG is negative; error if CHAR not found."
7302 (interactive "*p\ncZap to char: ")
7303 (kill-region (point)
7304 (progn
7305 (search-forward
7306 (char-to-string char) nil nil arg)
7307 (point))))
7308@end group
7309@end smallexample
7310
7311@node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7312@comment node-name, next, previous, up
7313@subsection The @code{interactive} Expression
7314
7315@need 800
7316The interactive expression in the @code{zap-to-char} command looks like
7317this:
7318
7319@smallexample
7320(interactive "*p\ncZap to char: ")
7321@end smallexample
7322
7323The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7324three different things. First, and most simply, the asterisk, @samp{*},
7325causes an error to be signalled if the buffer is read-only. This means that
7326if you try @code{zap-to-char} in a read-only buffer you will not be able to
7327remove text, and you will receive a message that says ``Buffer is
7328read-only''; your terminal may beep at you as well.
7329
7330The version 21 implementation does not have the asterisk, @samp{*}. The
7331function works the same as in version 19: in both cases, it cannot
7332remove text from a read-only buffer but the function does copy the
7333text that would have been removed to the kill ring. Also, in both
7334cases, you see an error message.
7335
7336However, the version 19 implementation copies text from a read-only
7337buffer only because of a mistake in the implementation of
7338@code{interactive}. According to the documentation for
7339@code{interactive}, the asterisk, @samp{*}, should prevent the
7340@code{zap-to-char} function from doing anything at all when the buffer
7341is read only. The function should not copy the text to the kill ring.
7342It is a bug that it does.
7343
7344In version 21, @code{interactive} is implemented correctly. So the
7345asterisk, @samp{*}, had to be removed from the interactive
7346specification. If you insert an @samp{*} and evaluate the function
7347definition, then the next time you run the @code{zap-to-char} function
7348on a read-only buffer, you will not copy any text.
7349
7350That change aside, and a change to the documentation, the two versions
7351of the @code{zap-to-char} function are identical.
7352
7353Let us continue with the interactive specification.
7354
7355The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7356This part is separated from the next part by a newline, @samp{\n}.
7357The @samp{p} means that the first argument to the function will be
7358passed the value of a `processed prefix'. The prefix argument is
7359passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7360the function is called interactively without a prefix, 1 is passed to
7361this argument.
7362
7363The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7364}. In this part, the lower case @samp{c} indicates that
7365@code{interactive} expects a prompt and that the argument will be a
7366character. The prompt follows the @samp{c} and is the string @samp{Zap
7367to char:@: } (with a space after the colon to make it look good).
7368
7369What all this does is prepare the arguments to @code{zap-to-char} so they
7370are of the right type, and give the user a prompt.
7371
7372@node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7373@comment node-name, next, previous, up
7374@subsection The Body of @code{zap-to-char}
7375
7376The body of the @code{zap-to-char} function contains the code that
7377kills (that is, removes) the text in the region from the current
7378position of the cursor up to and including the specified character.
7379The first part of the code looks like this:
7380
7381@smallexample
7382(kill-region (point) @dots{}
7383@end smallexample
7384
7385@noindent
7386@code{(point)} is the current position of the cursor.
7387
7388The next part of the code is an expression using @code{progn}. The body
7389of the @code{progn} consists of calls to @code{search-forward} and
7390@code{point}.
7391
7392It is easier to understand how @code{progn} works after learning about
7393@code{search-forward}, so we will look at @code{search-forward} and
7394then at @code{progn}.
7395
7396@node search-forward, progn, zap-to-char body, zap-to-char
7397@comment node-name, next, previous, up
7398@subsection The @code{search-forward} Function
7399@findex search-forward
7400
7401The @code{search-forward} function is used to locate the
7402zapped-for-character in @code{zap-to-char}. If the search is
7403successful, @code{search-forward} leaves point immediately after the
7404last character in the target string. (In @code{zap-to-char}, the
7405target string is just one character long.) If the search is
7406backwards, @code{search-forward} leaves point just before the first
7407character in the target. Also, @code{search-forward} returns @code{t}
7408for true. (Moving point is therefore a `side effect'.)
7409
7410@need 1250
7411In @code{zap-to-char}, the @code{search-forward} function looks like this:
7412
7413@smallexample
7414(search-forward (char-to-string char) nil nil arg)
7415@end smallexample
7416
7417The @code{search-forward} function takes four arguments:
7418
7419@enumerate
7420@item
7421The first argument is the target, what is searched for. This must be a
7422string, such as @samp{"z"}.
7423
7424As it happens, the argument passed to @code{zap-to-char} is a single
7425character. Because of the way computers are built, the Lisp
7426interpreter may treat a single character as being different from a
7427string of characters. Inside the computer, a single character has a
7428different electronic format than a string of one character. (A single
7429character can often be recorded in the computer using exactly one
7430byte; but a string may be longer, and the computer needs to be ready
7431for this.) Since the @code{search-forward} function searches for a
7432string, the character that the @code{zap-to-char} function receives as
7433its argument must be converted inside the computer from one format to
7434the other; otherwise the @code{search-forward} function will fail.
7435The @code{char-to-string} function is used to make this conversion.
7436
7437@item
7438The second argument bounds the search; it is specified as a position in
7439the buffer. In this case, the search can go to the end of the buffer,
7440so no bound is set and the second argument is @code{nil}.
7441
7442@item
7443The third argument tells the function what it should do if the search
7444fails---it can signal an error (and print a message) or it can return
7445@code{nil}. A @code{nil} as the third argument causes the function to
7446signal an error when the search fails.
7447
7448@item
7449The fourth argument to @code{search-forward} is the repeat count---how
7450many occurrences of the string to look for. This argument is optional
7451and if the function is called without a repeat count, this argument is
7452passed the value 1. If this argument is negative, the search goes
7453backwards.
7454@end enumerate
7455
7456@need 800
7457In template form, a @code{search-forward} expression looks like this:
7458
7459@smallexample
7460@group
7461(search-forward "@var{target-string}"
7462 @var{limit-of-search}
7463 @var{what-to-do-if-search-fails}
7464 @var{repeat-count})
7465@end group
7466@end smallexample
7467
7468We will look at @code{progn} next.
7469
7470@node progn, Summing up zap-to-char, search-forward, zap-to-char
7471@comment node-name, next, previous, up
7472@subsection The @code{progn} Special Form
7473@findex progn
7474
7475@code{progn} is a special form that causes each of its arguments to be
7476evaluated in sequence and then returns the value of the last one. The
7477preceding expressions are evaluated only for the side effects they
7478perform. The values produced by them are discarded.
7479
7480@need 800
7481The template for a @code{progn} expression is very simple:
7482
7483@smallexample
7484@group
7485(progn
7486 @var{body}@dots{})
7487@end group
7488@end smallexample
7489
7490In @code{zap-to-char}, the @code{progn} expression has to do two things:
7491put point in exactly the right position; and return the location of
7492point so that @code{kill-region} will know how far to kill to.
7493
7494The first argument to the @code{progn} is @code{search-forward}. When
7495@code{search-forward} finds the string, the function leaves point
7496immediately after the last character in the target string. (In this
7497case the target string is just one character long.) If the search is
7498backwards, @code{search-forward} leaves point just before the first
7499character in the target. The movement of point is a side effect.
7500
7501The second and last argument to @code{progn} is the expression
7502@code{(point)}. This expression returns the value of point, which in
7503this case will be the location to which it has been moved by
7504@code{search-forward}. This value is returned by the @code{progn}
7505expression and is passed to @code{kill-region} as @code{kill-region}'s
7506second argument.
7507
7508@node Summing up zap-to-char, , progn, zap-to-char
7509@comment node-name, next, previous, up
7510@subsection Summing up @code{zap-to-char}
7511
7512Now that we have seen how @code{search-forward} and @code{progn} work,
7513we can see how the @code{zap-to-char} function works as a whole.
7514
7515The first argument to @code{kill-region} is the position of the cursor
7516when the @code{zap-to-char} command is given---the value of point at
7517that time. Within the @code{progn}, the search function then moves
7518point to just after the zapped-to-character and @code{point} returns the
7519value of this location. The @code{kill-region} function puts together
7520these two values of point, the first one as the beginning of the region
7521and the second one as the end of the region, and removes the region.
7522
7523The @code{progn} special form is necessary because the @code{kill-region}
7524command takes two arguments; and it would fail if @code{search-forward}
7525and @code{point} expressions were written in sequence as two
7526additional arguments. The @code{progn} expression is a single argument
7527to @code{kill-region} and returns the one value that @code{kill-region}
7528needs for its second argument.
7529
7530@node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7531@comment node-name, next, previous, up
7532@section @code{kill-region}
7533@findex kill-region
7534
7535The @code{zap-to-char} function uses the @code{kill-region} function.
7536This function clips text from a region and copies that text to
7537the kill ring, from which it may be retrieved.
7538
7539The Emacs 21 version of that function uses @code{condition-case} and
7540@code{copy-region-as-kill}, both of which we will explain.
7541@code{condition-case} is an important special form.
7542
7543In essence, the @code{kill-region} function calls
7544@code{condition-case}, which takes three arguments. In this function,
7545the first argument does nothing. The second argument contains the
7546code that does the work when all goes well. The third argument
7547contains the code that is called in the event of an error.
7548
7549@menu
7550* Complete kill-region:: The function definition.
7551* condition-case:: Dealing with a problem.
7552* delete-and-extract-region:: Doing the work.
7553@end menu
7554
7555@node Complete kill-region, condition-case, kill-region, kill-region
7556@ifnottex
7557@unnumberedsubsec The Complete @code{kill-region} Definition
7558@end ifnottex
7559
7560@need 1200
7561We will go through the @code{condition-case} code in a moment. First,
7562let us look at the complete definition of @code{kill-region}, with
7563comments added:
7564
7565@c v 21
7566@smallexample
7567@group
7568(defun kill-region (beg end)
7569 "Kill between point and mark.
7570The text is deleted but saved in the kill ring."
7571 (interactive "r")
7572@end group
7573
7574@group
7575 ;; 1. `condition-case' takes three arguments.
7576 ;; If the first argument is nil, as it is here,
7577 ;; information about the error signal is not
7578 ;; stored for use by another function.
7579 (condition-case nil
7580@end group
7581
7582@group
7583 ;; 2. The second argument to `condition-case'
7584 ;; tells the Lisp interpreter what to do when all goes well.
7585@end group
7586
7587@group
7588 ;; The `delete-and-extract-region' function usually does the
7589 ;; work. If the beginning and ending of the region are both
7590 ;; the same, then the variable `string' will be empty, or nil
7591 (let ((string (delete-and-extract-region beg end)))
7592@end group
7593
7594@group
7595 ;; `when' is an `if' clause that cannot take an `else-part'.
7596 ;; Emacs normally sets the value of `last-command' to the
7597 ;; previous command.
7598@end group
7599@group
7600 ;; `kill-append' concatenates the new string and the old.
7601 ;; `kill-new' inserts text into a new item in the kill ring.
7602 (when string
7603 (if (eq last-command 'kill-region)
7604 ;; if true, prepend string
7605 (kill-append string (< end beg))
7606 (kill-new string)))
7607 (setq this-command 'kill-region))
7608@end group
7609
7610@group
7611 ;; 3. The third argument to `condition-case' tells the interpreter
7612 ;; what to do with an error.
7613@end group
7614@group
7615 ;; The third argument has a conditions part and a body part.
7616 ;; If the conditions are met (in this case,
7617 ;; if text or buffer is read-only)
7618 ;; then the body is executed.
7619@end group
7620@group
7621 ((buffer-read-only text-read-only) ;; this is the if-part
7622 ;; then...
7623 (copy-region-as-kill beg end)
7624@end group
7625@group
7626 (if kill-read-only-ok ;; usually this variable is nil
7627 (message "Read only text copied to kill ring")
7628 ;; or else, signal an error if the buffer is read-only;
7629 (barf-if-buffer-read-only)
7630 ;; and, in any case, signal that the text is read-only.
7631 (signal 'text-read-only (list (current-buffer)))))))
7632@end group
7633@end smallexample
7634
7635@node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7636@comment node-name, next, previous, up
7637@subsection @code{condition-case}
7638@findex condition-case
7639
7640As we have seen earlier (@pxref{Making Errors, , Generate an Error
7641Message}), when the Emacs Lisp interpreter has trouble evaluating an
7642expression, it provides you with help; in the jargon, this is called
7643``signaling an error''. Usually, the computer stops the program and
7644shows you a message.
7645
7646However, some programs undertake complicated actions. They should not
7647simply stop on an error. In the @code{kill-region} function, the most
7648likely error is that you will try to kill text that is read-only and
7649cannot be removed. So the @code{kill-region} function contains code
7650to handle this circumstance. This code, which makes up the body of
7651the @code{kill-region} function, is inside of a @code{condition-case}
7652special form.
7653
7654@need 800
7655The template for @code{condition-case} looks like this:
7656
7657@smallexample
7658@group
7659(condition-case
7660 @var{var}
7661 @var{bodyform}
7662 @var{error-handler}@dots{})
7663@end group
7664@end smallexample
7665
7666The second argument, @var{bodyform}, is straightforward. The
7667@code{condition-case} special form causes the Lisp interpreter to
7668evaluate the code in @var{bodyform}. If no error occurs, the special
7669form returns the code's value and produces the side-effects, if any.
7670
7671In short, the @var{bodyform} part of a @code{condition-case}
7672expression determines what should happen when everything works
7673correctly.
7674
7675However, if an error occurs, among its other actions, the function
7676generating the error signal will define one or more error condition
7677names.
7678
7679An error handler is the third argument to @code{condition case}.
7680An error handler has two parts, a @var{condition-name} and a
7681@var{body}. If the @var{condition-name} part of an error handler
7682matches a condition name generated by an error, then the @var{body}
7683part of the error handler is run.
7684
7685As you will expect, the @var{condition-name} part of an error handler
7686may be either a single condition name or a list of condition names.
7687
7688Also, a complete @code{condition-case} expression may contain more
7689than one error handler. When an error occurs, the first applicable
7690handler is run.
7691
7692Lastly, the first argument to the @code{condition-case} expression,
7693the @var{var} argument, is sometimes bound to a variable that
7694contains information about the error. However, if that argument is
7695nil, as is the case in @code{kill-region}, that information is
7696discarded.
7697
7698@need 1200
7699In brief, in the @code{kill-region} function, the code
7700@code{condition-case} works like this:
7701
7702@smallexample
7703@group
7704@var{If no errors}, @var{run only this code}
7705 @var{but}, @var{if errors}, @var{run this other code}.
7706@end group
7707@end smallexample
7708
7709@node delete-and-extract-region, , condition-case, kill-region
7710@comment node-name, next, previous, up
7711@subsection @code{delete-and-extract-region}
7712@findex delete-and-extract-region
7713
7714A @code{condition-case} expression has two parts, a part that is
7715evaluated in the expectation that all will go well, but which may
7716generate an error; and a part that is evaluated when there is an
7717error.
7718
7719First, let us look at the code in @code{kill-region} that is run in
7720the expectation that all goes well. This is the core of the function.
7721The code looks like this:
7722
7723@smallexample
7724@group
7725(let ((string (delete-and-extract-region beg end)))
7726 (when string
7727 (if (eq last-command 'kill-region)
7728 (kill-append string (< end beg))
7729 (kill-new string)))
7730 (setq this-command 'kill-region))
7731@end group
7732@end smallexample
7733
7734It looks complicated because we have the new functions
7735@code{delete-and-extract-region}, @code{kill-append}, and
7736@code{kill-new} as well as the new variables,
7737@code{last-command} and @code{this-command}.
7738
7739The @code{delete-and-extract-region} function is straightforward. It
7740is a built-in function that deletes the text in a region (a side
7741effect) and also returns that text. This is the function that
7742actually removes the text. (And if it cannot do that, it signals the
7743error.)
7744
7745In this @code{let} expression, the text that
7746@code{delete-and-extract-region} returns is placed in the local
7747variable called @samp{string}. This is the text that is removed from
7748the buffer. (To be more precise, the variable is set to point to the
7749address of the extracted text; to say it is `placed in' the variable
7750is simply a shorthand.)
7751
7752If the variable @samp{string} does point to text, that text is added
7753to the kill ring. The variable will have a @code{nil} value if no
7754text was removed.
7755
7756The code uses @code{when} to determine whether the variable
7757@samp{string} points to text. A @code{when} statement is simply a
7758programmers' convenience. A @code{when} statement is an @code{if}
7759statement without the possibility of an else clause. In your mind, you
7760can replace @code{when} with @code{if} and understand what goes on.
7761That is what the Lisp interpreter does.
7762
7763@cindex Macro, lisp
7764@cindex Lisp macro
7765Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
7766enables you to define new control constructs and other language
7767features. It tells the interpreter how to compute another Lisp
7768expression which will in turn compute the value. In this case, the
7769`other expression' is an @code{if} expression. For more about Lisp
7770macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7771Manual}. The C programming language also provides macros. These are
7772different, but also useful. We will briefly look at C macros in
b15dd613 7773@ref{Digression into C}.
8b096dce
EZ
7774
7775@need 1200
7776If the string has content, then another conditional expression is
7777executed. This is an @code{if} with both a then-part and an else-part.
7778
7779@smallexample
7780@group
7781(if (eq last-command 'kill-region)
7782 (kill-append string (< end beg))
7783 (kill-new string)))
7784@end group
7785@end smallexample
7786
7787The then-part is evaluated if the previous command was another call to
7788@code{kill-region}; if not, the else-part is evaluated.
7789
7790@code{last-command} is a variable that comes with Emacs that we have
7791not seen before. Normally, whenever a function is executed, Emacs
7792sets the value of @code{last-command} to the previous command.
7793
7794@need 1200
7795In this segment of the definition, the @code{if} expression checks
7796whether the previous command was @code{kill-region}. If it was,
7797
7798@smallexample
7799(kill-append string (< end beg))
7800@end smallexample
7801
7802@noindent
7803concatenates a copy of the newly clipped text to the just previously
7804clipped text in the kill ring. (If the @w{@code{(< end beg))}}
7805expression is true, @code{kill-append} prepends the string to the just
7806previously clipped text. For a detailed discussion, see
7807@ref{kill-append function, , The @code{kill-append} function}.)
7808
7809If you then yank back the text, i.e., `paste' it, you get both
7810pieces of text at once. That way, if you delete two words in a row,
7811and then yank them back, you get both words, in their proper order,
7812with one yank. (The @w{@code{(< end beg))}} expression makes sure the
7813order is correct.)
7814
7815On the other hand, if the previous command is not @code{kill-region},
7816then the @code{kill-new} function is called, which adds the text to
7817the kill ring as the latest item, and sets the
7818@code{kill-ring-yank-pointer} variable to point to it.
7819
7820@node Digression into C, defvar, kill-region, Cutting & Storing Text
7821@comment node-name, next, previous, up
b15dd613 7822@section Digression into C
8b096dce
EZ
7823@findex delete-and-extract-region
7824@cindex C, a digression into
7825@cindex Digression into C
7826
7827The @code{zap-to-char} command uses the
7828@code{delete-and-extract-region} function, which in turn uses two
7829other functions, @code{copy-region-as-kill} and
7830@code{del_range_1}. The @code{copy-region-as-kill} function will be
7831described in a following section; it puts a copy of the region in the
7832kill ring so it can be yanked back. (@xref{copy-region-as-kill, ,
7833@code{copy-region-as-kill}}.)
7834
7835The @code{delete-and-extract-region} function removes the contents of
7836a region and you cannot get them back.
7837
7838Unlike the other code discussed here, @code{delete-and-extract-region}
7839is not written in Emacs Lisp; it is written in C and is one of the
7840primitives of the GNU Emacs system. Since it is very simple, I will
7841digress briefly from Lisp and describe it here.
7842
7843@need 1500
7844Like many of the other Emacs primitives,
7845@code{delete-and-extract-region} is written as an instance of a C
7846macro, a macro being a template for code. The complete macro looks
7847like this:
7848
7849@c /usr/local/src/emacs/src/editfns.c
7850@smallexample
7851@group
7852DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7853 Sdelete_and_extract_region, 2, 2, 0,
7854 "Delete the text between START and END and return it.")
7855 (start, end)
7856 Lisp_Object start, end;
7857@{
7858 validate_region (&start, &end);
7859 return del_range_1 (XINT (start), XINT (end), 1, 1);
7860@}
7861@end group
7862@end smallexample
7863
7864Without going into the details of the macro writing process, let me
7865point out that this macro starts with the word @code{DEFUN}. The word
7866@code{DEFUN} was chosen since the code serves the same purpose as
7867@code{defun} does in Lisp. The word @code{DEFUN} is followed by seven
7868parts inside of parentheses:
7869
7870@itemize @bullet
7871@item
7872The first part is the name given to the function in Lisp,
7873@code{delete-and-extract-region}.
7874
7875@item
7876The second part is the name of the function in C,
7877@code{Fdelete_and_extract_region}. By convention, it starts with
7878@samp{F}. Since C does not use hyphens in names, underscores are used
7879instead.
7880
7881@item
7882The third part is the name for the C constant structure that records
7883information on this function for internal use. It is the name of the
7884function in C but begins with an @samp{S} instead of an @samp{F}.
7885
7886@item
7887The fourth and fifth parts specify the minimum and maximum number of
7888arguments the function can have. This function demands exactly 2
7889arguments.
7890
7891@item
7892The sixth part is nearly like the argument that follows the
7893@code{interactive} declaration in a function written in Lisp: a letter
7894followed, perhaps, by a prompt. The only difference from the Lisp is
7895when the macro is called with no arguments. Then you write a @code{0}
7896(which is a `null string'), as in this macro.
7897
7898If you were to specify arguments, you would place them between
7899quotation marks. The C macro for @code{goto-char} includes
7900@code{"NGoto char: "} in this position to indicate that the function
7901expects a raw prefix, in this case, a numerical location in a buffer,
7902and provides a prompt.
7903
7904@item
7905The seventh part is a documentation string, just like the one for a
7906function written in Emacs Lisp, except that every newline must be
7907written explicitly as @samp{\n} followed by a backslash and carriage
7908return.
7909
7910@need 1000
7911Thus, the first two lines of documentation for @code{goto-char} are
7912written like this:
7913
7914@smallexample
7915@group
7916 "Set point to POSITION, a number or marker.\n\
7917Beginning of buffer is position (point-min), end is (point-max).
7918@end group
7919@end smallexample
7920@end itemize
7921
7922@need 1200
7923In a C macro, the formal parameters come next, with a statement of
7924what kind of object they are, followed by what might be called the `body'
7925of the macro. For @code{delete-and-extract-region} the `body'
7926consists of the following two lines:
7927
7928@smallexample
7929@group
7930validate_region (&start, &end);
7931return del_range_1 (XINT (start), XINT (end), 1, 1);
7932@end group
7933@end smallexample
7934
7935The first function, @code{validate_region} checks whether the values
7936passed as the beginning and end of the region are the proper type and
7937are within range. The second function, @code{del_range_1}, actually
7938deletes the text.
7939
7940@code{del_range_1} is a complex function we will not look into. It
7941updates the buffer and does other things.
7942
7943However, it is worth looking at the two arguments passed to
7944@code{del_range}. These are @w{@code{XINT (start)}} and @w{@code{XINT
7945(end)}}.
7946
7947As far as the C language is concerned, @code{start} and @code{end} are
7948two integers that mark the beginning and end of the region to be
7949deleted@footnote{More precisely, and requiring more expert knowledge
7950to understand, the two integers are of type `Lisp_Object', which can
7951also be a C union instead of an integer type.}.
7952
7953In early versions of Emacs, these two numbers were thirty-two bits
7954long, but the code is slowly being generalized to handle other
7955lengths. Three of the available bits are used to specify the type of
7956information and a fourth bit is used for handling the computer's
7957memory; the remaining bits are used as `content'.
7958
7959@samp{XINT} is a C macro that extracts the relevant number from the
7960longer collection of bits; the four other bits are discarded.
7961
7962@need 800
7963The command in @code{delete-and-extract-region} looks like this:
7964
7965@smallexample
7966del_range_1 (XINT (start), XINT (end), 1, 1);
7967@end smallexample
7968
7969@noindent
7970It deletes the region between the beginning position, @code{start},
7971and the ending position, @code{end}.
7972
7973From the point of view of the person writing Lisp, Emacs is all very
7974simple; but hidden underneath is a great deal of complexity to make it
7975all work.
7976
7977@node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7978@comment node-name, next, previous, up
7979@section Initializing a Variable with @code{defvar}
7980@findex defvar
7981@cindex Initializing a variable
7982@cindex Variable initialization
7983
7984Unlike the @code{delete-and-extract-region} function, the
7985@code{copy-region-as-kill} function is written in Emacs Lisp. Two
7986functions within it, @code{kill-append} and @code{kill-new}, copy a
7987region in a buffer and save it in a variable called the
7988@code{kill-ring}. This section describes how the @code{kill-ring}
7989variable is created and initialized using the @code{defvar} special
7990form.
7991
7992(Again we note that the term @code{kill-ring} is a misnomer. The text
7993that is clipped out of the buffer can be brought back; it is not a ring
7994of corpses, but a ring of resurrectable text.)
7995
7996In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7997given an initial value by using the @code{defvar} special form. The
7998name comes from ``define variable''.
7999
8000The @code{defvar} special form is similar to @code{setq} in that it sets
8001the value of a variable. It is unlike @code{setq} in two ways: first,
8002it only sets the value of the variable if the variable does not already
8003have a value. If the variable already has a value, @code{defvar} does
8004not override the existing value. Second, @code{defvar} has a
8005documentation string.
8006
8007(Another special form, @code{defcustom}, is designed for variables
8008that people customize. It has more features than @code{defvar}.
8009(@xref{defcustom, , Setting Variables with @code{defcustom}}.)
8010
8011@menu
8012* See variable current value::
8013* defvar and asterisk:: An old-time convention.
8014@end menu
8015
8016@node See variable current value, defvar and asterisk, defvar, defvar
8017@ifnottex
8018@unnumberedsubsec Seeing the Current Value of a Variable
8019@end ifnottex
8020
8021You can see the current value of a variable, any variable, by using
8022the @code{describe-variable} function, which is usually invoked by
8023typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
8024(followed by @key{RET}) when prompted, you will see what is in your
8025current kill ring---this may be quite a lot! Conversely, if you have
8026been doing nothing this Emacs session except read this document, you
8027may have nothing in it. Also, you will see the documentation for
8028@code{kill-ring}:
8029
8030@smallexample
8031@group
8032Documentation:
8033List of killed text sequences.
8034Since the kill ring is supposed to interact nicely with cut-and-paste
8035facilities offered by window systems, use of this variable should
8036@end group
8037@group
8038interact nicely with `interprogram-cut-function' and
8039`interprogram-paste-function'. The functions `kill-new',
8040`kill-append', and `current-kill' are supposed to implement this
8041interaction; you may want to use them instead of manipulating the kill
8042ring directly.
8043@end group
8044@end smallexample
8045
8046@need 800
8047The kill ring is defined by a @code{defvar} in the following way:
8048
8049@smallexample
8050@group
8051(defvar kill-ring nil
8052 "List of killed text sequences.
8053@dots{}")
8054@end group
8055@end smallexample
8056
8057@noindent
8058In this variable definition, the variable is given an initial value of
8059@code{nil}, which makes sense, since if you have saved nothing, you want
8060nothing back if you give a @code{yank} command. The documentation
8061string is written just like the documentation string of a @code{defun}.
8062As with the documentation string of the @code{defun}, the first line of
8063the documentation should be a complete sentence, since some commands,
8064like @code{apropos}, print only the first line of documentation.
8065Succeeding lines should not be indented; otherwise they look odd when
8066you use @kbd{C-h v} (@code{describe-variable}).
8067
8068@node defvar and asterisk, , See variable current value, defvar
8069@subsection @code{defvar} and an asterisk
8070@findex defvar @r{for a user customizable variable}
8071@findex defvar @r{with an asterisk}
8072
8073In the past, Emacs used the @code{defvar} special form both for
8074internal variables that you would not expect a user to change and for
8075variables that you do expect a user to change. Although you can still
8076use @code{defvar} for user customizable variables, please use
8077@code{defcustom} instead, since that special form provides a path into
8078the Customization commands. (@xref{defcustom, , Setting Variables
8079with @code{defcustom}}.)
8080
8081When you specified a variable using the @code{defvar} special form,
8082you could distinguish a readily settable variable from others by
8083typing an asterisk, @samp{*}, in the first column of its documentation
8084string. For example:
8085
8086@smallexample
8087@group
8088(defvar shell-command-default-error-buffer nil
8089 "*Buffer name for `shell-command' @dots{} error output.
8090@dots{} ")
8091@end group
8092@end smallexample
8093
8094@noindent
8095This means that you could (and still can) use the @code{edit-options}
8096command to change the value of
8097@code{shell-command-default-error-buffer} temporarily.
8098
8099@findex edit-options
8100However, options set using @code{edit-options} are set only for the
8101duration of your editing session. The new values are not saved
8102between sessions. Each time Emacs starts, it reads the original
8103value, unless you change the value within your @file{.emacs} file,
8104either by setting it manually or by using @code{customize}.
8105@xref{Emacs Initialization, , Your @file{.emacs} File}.
8106
8107For me, the major use of the @code{edit-options} command is to suggest
8108variables that I might want to set in my @file{.emacs} file. I urge
8109you to look through the list. (@xref{Edit Options, , Editing Variable
8110Values, emacs, The GNU Emacs Manual}.)
8111
8112@node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8113@comment node-name, next, previous, up
8114@section @code{copy-region-as-kill}
8115@findex copy-region-as-kill
8116@findex nthcdr
8117
8118The @code{copy-region-as-kill} function copies a region of text from a
8119buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8120in the @code{kill-ring}.
8121
8122If you call @code{copy-region-as-kill} immediately after a
8123@code{kill-region} command, Emacs appends the newly copied text to the
8124previously copied text. This means that if you yank back the text, you
8125get it all, from both this and the previous operation. On the other
8126hand, if some other command precedes the @code{copy-region-as-kill},
8127the function copies the text into a separate entry in the kill ring.
8128
8129@menu
8130* Complete copy-region-as-kill:: The complete function definition.
8131* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8132@end menu
8133
8134@node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8135@ifnottex
8136@unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8137@end ifnottex
8138
8139@need 1200
8140Here is the complete text of the version 21 @code{copy-region-as-kill}
8141function:
8142
8143@smallexample
8144@group
8145(defun copy-region-as-kill (beg end)
8146 "Save the region as if killed, but don't kill it.
8147In Transient Mark mode, deactivate the mark.
8148If `interprogram-cut-function' is non-nil, also save
8149the text for a window system cut and paste."
8150 (interactive "r")
8151@end group
8152@group
8153 (if (eq last-command 'kill-region)
8154 (kill-append (buffer-substring beg end) (< end beg))
8155 (kill-new (buffer-substring beg end)))
8156@end group
8157@group
8158 (if transient-mark-mode
8159 (setq deactivate-mark t))
8160 nil)
8161@end group
8162@end smallexample
8163
8164@need 800
8165As usual, this function can be divided into its component parts:
8166
8167@smallexample
8168@group
8169(defun copy-region-as-kill (@var{argument-list})
8170 "@var{documentation}@dots{}"
8171 (interactive "r")
8172 @var{body}@dots{})
8173@end group
8174@end smallexample
8175
8176The arguments are @code{beg} and @code{end} and the function is
8177interactive with @code{"r"}, so the two arguments must refer to the
8178beginning and end of the region. If you have been reading though this
8179document from the beginning, understanding these parts of a function is
8180almost becoming routine.
8181
8182The documentation is somewhat confusing unless you remember that the
8183word `kill' has a meaning different from its usual meaning. The
8184`Transient Mark' and @code{interprogram-cut-function} comments explain
8185certain side-effects.
8186
8187After you once set a mark, a buffer always contains a region. If you
8188wish, you can use Transient Mark mode to highlight the region
8189temporarily. (No one wants to highlight the region all the time, so
8190Transient Mark mode highlights it only at appropriate times. Many
8191people turn off Transient Mark mode, so the region is never
8192highlighted.)
8193
8194Also, a windowing system allows you to copy, cut, and paste among
8195different programs. In the X windowing system, for example, the
8196@code{interprogram-cut-function} function is @code{x-select-text},
8197which works with the windowing system's equivalent of the Emacs kill
8198ring.
8199
8200The body of the @code{copy-region-as-kill} function starts with an
8201@code{if} clause. What this clause does is distinguish between two
8202different situations: whether or not this command is executed
8203immediately after a previous @code{kill-region} command. In the first
8204case, the new region is appended to the previously copied text.
8205Otherwise, it is inserted into the beginning of the kill ring as a
8206separate piece of text from the previous piece.
8207
8208The last two lines of the function prevent the region from lighting up
8209if Transient Mark mode is turned on.
8210
8211The body of @code{copy-region-as-kill} merits discussion in detail.
8212
8213@node copy-region-as-kill body, , Complete copy-region-as-kill, copy-region-as-kill
8214@comment node-name, next, previous, up
8215@subsection The Body of @code{copy-region-as-kill}
8216
8217The @code{copy-region-as-kill} function works in much the same way as
8218the @code{kill-region} function (@pxref{kill-region,
8219,@code{kill-region}}). Both are written so that two or more kills in
8220a row combine their text into a single entry. If you yank back the
8221text from the kill ring, you get it all in one piece. Moreover, kills
8222that kill forward from the current position of the cursor are added to
8223the end of the previously copied text and commands that copy text
8224backwards add it to the beginning of the previously copied text. This
8225way, the words in the text stay in the proper order.
8226
8227Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8228use of the @code{last-command} variable that keeps track of the
8229previous Emacs command.
8230
8231@menu
8232* last-command & this-command::
8233* kill-append function::
8234* kill-new function::
8235@end menu
8236
8237@node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8238@ifnottex
8239@unnumberedsubsubsec @code{last-command} and @code{this-command}
8240@end ifnottex
8241
8242Normally, whenever a function is executed, Emacs sets the value of
8243@code{this-command} to the function being executed (which in this case
8244would be @code{copy-region-as-kill}). At the same time, Emacs sets
8245the value of @code{last-command} to the previous value of
8246@code{this-command}.
8247
8248In the first part of the body of the @code{copy-region-as-kill}
8249function, an @code{if} expression determines whether the value of
8250@code{last-command} is @code{kill-region}. If so, the then-part of
8251the @code{if} expression is evaluated; it uses the @code{kill-append}
8252function to concatenate the text copied at this call to the function
8253with the text already in the first element (the @sc{car}) of the kill
8254ring. On the other hand, if the value of @code{last-command} is not
8255@code{kill-region}, then the @code{copy-region-as-kill} function
8256attaches a new element to the kill ring using the @code{kill-new}
8257function.
8258
8259@need 1250
8260The @code{if} expression reads as follows; it uses @code{eq}, which is
8261a function we have not yet seen:
8262
8263@smallexample
8264@group
8265 (if (eq last-command 'kill-region)
8266 ;; @r{then-part}
8267 (kill-append (buffer-substring beg end) (< end beg))
8268 ;; @r{else-part}
8269 (kill-new (buffer-substring beg end)))
8270@end group
8271@end smallexample
8272
8273@findex eq @r{(example of use)}
8274@noindent
8275The @code{eq} function tests whether its first argument is the same Lisp
8276object as its second argument. The @code{eq} function is similar to the
8277@code{equal} function in that it is used to test for equality, but
8278differs in that it determines whether two representations are actually
8279the same object inside the computer, but with different names.
8280@code{equal} determines whether the structure and contents of two
8281expressions are the same.
8282
8283If the previous command was @code{kill-region}, then the Emacs Lisp
8284interpreter calls the @code{kill-append} function
8285
8286@node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8287@unnumberedsubsubsec The @code{kill-append} function
8288@findex kill-append
8289
8290@need 800
8291The @code{kill-append} function looks like this:
8292
8293@smallexample
8294@group
8295(defun kill-append (string before-p)
8296 "Append STRING to the end of the latest kill in the kill ring.
8297If BEFORE-P is non-nil, prepend STRING to the kill.
8298If `interprogram-cut-function' is set, pass the resulting kill to
8299it."
8300 (kill-new (if before-p
8301 (concat string (car kill-ring))
8302 (concat (car kill-ring) string))
8303 t))
8304@end group
8305@end smallexample
8306
8307@noindent
8308The @code{kill-append} function is fairly straightforward. It uses
8309the @code{kill-new} function, which we will discuss in more detail in
8310a moment.
8311
8312First, let us look at the conditional that is one of the two arguments
8313to @code{kill-new}. It uses @code{concat} to concatenate the new text
8314to the @sc{car} of the kill ring. Whether it prepends or appends the
8315text depends on the results of an @code{if} expression:
8316
8317@smallexample
8318@group
8319(if before-p ; @r{if-part}
8320 (concat string (car kill-ring)) ; @r{then-part}
8321 (concat (car kill-ring) string)) ; @r{else-part}
8322@end group
8323@end smallexample
8324
8325@noindent
8326If the region being killed is before the region that was killed in the
8327last command, then it should be prepended before the material that was
8328saved in the previous kill; and conversely, if the killed text follows
8329what was just killed, it should be appended after the previous text.
8330The @code{if} expression depends on the predicate @code{before-p} to
8331decide whether the newly saved text should be put before or after the
8332previously saved text.
8333
8334The symbol @code{before-p} is the name of one of the arguments to
8335@code{kill-append}. When the @code{kill-append} function is
8336evaluated, it is bound to the value returned by evaluating the actual
8337argument. In this case, this is the expression @code{(< end beg)}.
8338This expression does not directly determine whether the killed text in
8339this command is located before or after the kill text of the last
8340command; what is does is determine whether the value of the variable
8341@code{end} is less than the value of the variable @code{beg}. If it
8342is, it means that the user is most likely heading towards the
8343beginning of the buffer. Also, the result of evaluating the predicate
8344expression, @code{(< end beg)}, will be true and the text will be
8345prepended before the previous text. On the other hand, if the value of
8346the variable @code{end} is greater than the value of the variable
8347@code{beg}, the text will be appended after the previous text.
8348
8349@need 800
8350When the newly saved text will be prepended, then the string with the new
8351text will be concatenated before the old text:
8352
8353@smallexample
8354(concat string (car kill-ring))
8355@end smallexample
8356
8357@need 1200
8358@noindent
8359But if the text will be appended, it will be concatenated
8360after the old text:
8361
8362@smallexample
8363(concat (car kill-ring) string))
8364@end smallexample
8365
8366To understand how this works, we first need to review the
8367@code{concat} function. The @code{concat} function links together or
8368unites two strings of text. The result is a string. For example:
8369
8370@smallexample
8371@group
8372(concat "abc" "def")
8373 @result{} "abcdef"
8374@end group
8375
8376@group
8377(concat "new "
8378 (car '("first element" "second element")))
8379 @result{} "new first element"
8380
8381(concat (car
8382 '("first element" "second element")) " modified")
8383 @result{} "first element modified"
8384@end group
8385@end smallexample
8386
8387We can now make sense of @code{kill-append}: it modifies the contents
8388of the kill ring. The kill ring is a list, each element of which is
8389saved text. The @code{kill-append} function uses the @code{kill-new}
8390function which in turn uses the @code{setcar} function.
8391
8392@node kill-new function, , kill-append function, copy-region-as-kill body
8393@unnumberedsubsubsec The @code{kill-new} function
8394@findex kill-new
8395
8396@need 1200
8397The @code{kill-new} function looks like this:
8398
8399@smallexample
8400@group
8401(defun kill-new (string &optional replace)
8402 "Make STRING the latest kill in the kill ring.
8403Set the kill-ring-yank pointer to point to it.
8404If `interprogram-cut-function' is non-nil, apply it to STRING.
8405Optional second argument REPLACE non-nil means that STRING will replace
8406the front of the kill ring, rather than being added to the list."
8407@end group
8408@group
8409 (and (fboundp 'menu-bar-update-yank-menu)
8410 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8411@end group
8412@group
8413 (if (and replace kill-ring)
8414 (setcar kill-ring string)
8415 (setq kill-ring (cons string kill-ring))
8416 (if (> (length kill-ring) kill-ring-max)
8417 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8418@end group
8419@group
8420 (setq kill-ring-yank-pointer kill-ring)
8421 (if interprogram-cut-function
8422 (funcall interprogram-cut-function string (not replace))))
8423@end group
8424@end smallexample
8425
8426As usual, we can look at this function in parts.
8427
8428@need 1200
8429The first line of the documentation makes sense:
8430
8431@smallexample
8432Make STRING the latest kill in the kill ring.
8433@end smallexample
8434
8435@noindent
8436Let's skip over the rest of the documentation for the moment.
8437
8438Also, let's skip over the first two lines of code, those involving
8439@code{menu-bar-update-yank-menu}. We will explain them below.
8440
8441@need 1200
8442The critical lines are these:
8443
8444@smallexample
8445@group
8446 (if (and replace kill-ring)
8447 ;; @r{then}
8448 (setcar kill-ring string)
8449@end group
8450@group
8451 ;; @r{else}
8452 (setq kill-ring (cons string kill-ring))
8453 (if (> (length kill-ring) kill-ring-max)
8454 ;; @r{avoid overly long kill ring}
8455 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8456@end group
8457@group
8458 (setq kill-ring-yank-pointer kill-ring)
8459 (if interprogram-cut-function
8460 (funcall interprogram-cut-function string (not replace))))
8461@end group
8462@end smallexample
8463
8464The conditional test is @w{@code{(and replace kill-ring)}}.
8465This will be true when two conditions are met: the kill ring has
8466something in it, and the @code{replace} variable is true.
8467
8468@need 1250
8469The @code{kill-append} function sets @code{replace} to be true; then,
8470when the kill ring has at least one item in it, the @code{setcar}
8471expression is executed:
8472
8473@smallexample
8474(setcar kill-ring string)
8475@end smallexample
8476
8477The @code{setcar} function actually changes the first element of the
8478@code{kill-ring} list to the value of @code{string}. It replaces the
8479first element.
8480
8481On the other hand, if the kill ring is empty, or replace is false, the
8482else-part of the condition is executed:
8483
8484@smallexample
8485@group
8486(setq kill-ring (cons string kill-ring))
8487(if (> (length kill-ring) kill-ring-max)
8488 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8489@end group
8490@end smallexample
8491
8492@noindent
8493This expression first constructs a new version of the kill ring by
8494prepending @code{string} to the existing kill ring as a new element.
8495Then it executes a second @code{if} clause. This second @code{if}
8496clause keeps the kill ring from growing too long.
8497
8498Let's look at these two expressions in order.
8499
8500The @code{setq} line of the else-part sets the new value of the kill
8501ring to what results from adding the string being killed to the old kill
8502ring.
8503
8504@need 800
8505We can see how this works with an example:
8506
8507@smallexample
8508(setq example-list '("here is a clause" "another clause"))
8509@end smallexample
8510
8511@need 1200
8512@noindent
8513After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8514@code{example-list} and see what it returns:
8515
8516@smallexample
8517@group
8518example-list
8519 @result{} ("here is a clause" "another clause")
8520@end group
8521@end smallexample
8522
8523@need 1200
8524@noindent
8525Now, we can add a new element on to this list by evaluating the
8526following expression:
8527@findex cons, @r{example}
8528
8529@smallexample
8530(setq example-list (cons "a third clause" example-list))
8531@end smallexample
8532
8533@need 800
8534@noindent
8535When we evaluate @code{example-list}, we find its value is:
8536
8537@smallexample
8538@group
8539example-list
8540 @result{} ("a third clause" "here is a clause" "another clause")
8541@end group
8542@end smallexample
8543
8544@noindent
8545Thus, the third clause was added to the list by @code{cons}.
8546
8547@need 1200
8548This is exactly similar to what the @code{setq} and @code{cons} do in
8549the function. Here is the line again:
8550
8551@smallexample
8552(setq kill-ring (cons string kill-ring))
8553@end smallexample
8554
8555@need 1200
8556Now for the second part of the @code{if} clause. This expression
8557keeps the kill ring from growing too long. It looks like this:
8558
8559@smallexample
8560@group
8561(if (> (length kill-ring) kill-ring-max)
8562 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8563@end group
8564@end smallexample
8565
8566The code checks whether the length of the kill ring is greater than
8567the maximum permitted length. This is the value of
8568@code{kill-ring-max} (which is 60, by default). If the length of the
8569kill ring is too long, then this code sets the last element of the
8570kill ring to @code{nil}. It does this by using two functions,
8571@code{nthcdr} and @code{setcdr}.
8572
8573We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8574It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8575@sc{car} of a list. In this case, however, @code{setcdr} will not be
8576setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8577function is used to cause it to set the @sc{cdr} of the next to last
8578element of the kill ring---this means that since the @sc{cdr} of the
8579next to last element is the last element of the kill ring, it will set
8580the last element of the kill ring.
8581
8582@findex nthcdr, @r{example}
8583The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8584list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8585@dots{} It does this @var{N} times and returns the results.
8586
8587@findex setcdr, @r{example}
8588Thus, if we had a four element list that was supposed to be three
8589elements long, we could set the @sc{cdr} of the next to last element
8590to @code{nil}, and thereby shorten the list.
8591
8592You can see this by evaluating the following three expressions in turn.
8593First set the value of @code{trees} to @code{(maple oak pine birch)},
8594then set the @sc{cdr} of its second @sc{cdr} to @code{nil} and then
8595find the value of @code{trees}:
8596
8597@smallexample
8598@group
8599(setq trees '(maple oak pine birch))
8600 @result{} (maple oak pine birch)
8601@end group
8602
8603@group
8604(setcdr (nthcdr 2 trees) nil)
8605 @result{} nil
8606
8607trees
8608 @result{} (maple oak pine)
8609@end group
8610@end smallexample
8611
8612@noindent
8613(The value returned by the @code{setcdr} expression is @code{nil} since
8614that is what the @sc{cdr} is set to.)
8615
8616To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8617@sc{cdr} a number of times that is one less than the maximum permitted
8618size of the kill ring and sets the @sc{cdr} of that element (which
8619will be the rest of the elements in the kill ring) to @code{nil}.
8620This prevents the kill ring from growing too long.
8621
8622@need 800
8623The next to last expression in the @code{kill-new} function is
8624
8625@smallexample
8626(setq kill-ring-yank-pointer kill-ring)
8627@end smallexample
8628
8629The @code{kill-ring-yank-pointer} is a global variable that is set to be
8630the @code{kill-ring}.
8631
8632Even though the @code{kill-ring-yank-pointer} is called a
8633@samp{pointer}, it is a variable just like the kill ring. However, the
8634name has been chosen to help humans understand how the variable is used.
8635The variable is used in functions such as @code{yank} and
8636@code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8637
8638@need 1200
8639Now, to return to the first two lines in the body of the function:
8640
8641@smallexample
8642@group
8643 (and (fboundp 'menu-bar-update-yank-menu)
8644 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8645@end group
8646@end smallexample
8647
8648@noindent
8649This is an expression whose first element is the function @code{and}.
8650
8651@findex and, @r{introduced}
8652The @code{and} special form evaluates each of its arguments until one of
8653the arguments returns a value of @code{nil}, in which case the
8654@code{and} expression returns @code{nil}; however, if none of the
8655arguments returns a value of @code{nil}, the value resulting from
8656evaluating the last argument is returned. (Since such a value is not
8657@code{nil}, it is considered true in Emacs Lisp.) In other words, an
8658@code{and} expression returns a true value only if all its arguments
8659are true.
8660@findex and
8661
8662In this case, the expression tests first to see whether
8663@code{menu-bar-update-yank-menu} exists as a function, and if so,
8664calls it. The @code{fboundp} function returns true if the symbol it
8665is testing has a function definition that `is not void'. If the
8666symbol's function definition were void, we would receive an error
8667message, as we did when we created errors intentionally (@pxref{Making
8668Errors, , Generate an Error Message}).
8669
8670@need 1200
8671Essentially, the @code{and} is an @code{if} expression that reads like
8672this:
8673
8674@smallexample
8675@group
8676if @var{the-menu-bar-function-exists}
8677 then @var{execute-it}
8678@end group
8679@end smallexample
8680
8681@code{menu-bar-update-yank-menu} is one of the functions that make it
8682possible to use the `Select and Paste' menu in the Edit item of a menu
8683bar; using a mouse, you can look at the various pieces of text you
8684have saved and select one piece to paste.
8685
8686Finally, the last expression in the @code{kill-new} function adds the
8687newly copied string to whatever facility exists for copying and
8688pasting among different programs running in a windowing system. In
8689the X Windowing system, for example, the @code{x-select-text} function
8690takes the string and stores it in memory operated by X. You can paste
8691the string in another program, such as an Xterm.
8692
8693@need 1200
8694The expression looks like this:
8695
8696@smallexample
8697@group
8698 (if interprogram-cut-function
8699 (funcall interprogram-cut-function string (not replace))))
8700@end group
8701@end smallexample
8702
8703If an @code{interprogram-cut-function} exists, then Emacs executes
8704@code{funcall}, which in turn calls its first argument as a function
8705and passes the remaining arguments to it. (Incidentally, as far as I
8706can see, this @code{if} expression could be replaced by an @code{and}
8707expression similar to the one in the first part of the function.)
8708
8709We are not going to discuss windowing systems and other programs
8710further, but merely note that this is a mechanism that enables GNU
8711Emacs to work easily and well with other programs.
8712
8713This code for placing text in the kill ring, either concatenated with
8714an existing element or as a new element, leads us to the code for
8715bringing back text that has been cut out of the buffer---the yank
8716commands. However, before discussing the yank commands, it is better
8717to learn how lists are implemented in a computer. This will make
8718clear such mysteries as the use of the term `pointer'.
8719
8720@node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8721@comment node-name, next, previous, up
8722@section Review
8723
8724Here is a brief summary of some recently introduced functions.
8725
8726@table @code
8727@item car
8728@itemx cdr
8729@code{car} returns the first element of a list; @code{cdr} returns the
8730second and subsequent elements of a list.
8731
8732@need 1250
8733For example:
8734
8735@smallexample
8736@group
8737(car '(1 2 3 4 5 6 7))
8738 @result{} 1
8739(cdr '(1 2 3 4 5 6 7))
8740 @result{} (2 3 4 5 6 7)
8741@end group
8742@end smallexample
8743
8744@item cons
8745@code{cons} constructs a list by prepending its first argument to its
8746second argument.
8747
8748@need 1250
8749For example:
8750
8751@smallexample
8752@group
8753(cons 1 '(2 3 4))
8754 @result{} (1 2 3 4)
8755@end group
8756@end smallexample
8757
8758@item nthcdr
8759Return the result of taking @sc{cdr} `n' times on a list.
8760@iftex
8761The
8762@tex
8763$n^{th}$
8764@end tex
8765@code{cdr}.
8766@end iftex
8767The `rest of the rest', as it were.
8768
8769@need 1250
8770For example:
8771
8772@smallexample
8773@group
8774(nthcdr 3 '(1 2 3 4 5 6 7))
8775 @result{} (4 5 6 7)
8776@end group
8777@end smallexample
8778
8779@item setcar
8780@itemx setcdr
8781@code{setcar} changes the first element of a list; @code{setcdr}
8782changes the second and subsequent elements of a list.
8783
8784@need 1250
8785For example:
8786
8787@smallexample
8788@group
8789(setq triple '(1 2 3))
8790
8791(setcar triple '37)
8792
8793triple
8794 @result{} (37 2 3)
8795
8796(setcdr triple '("foo" "bar"))
8797
8798triple
8799 @result{} (37 "foo" "bar")
8800@end group
8801@end smallexample
8802
8803@item progn
8804Evaluate each argument in sequence and then return the value of the
8805last.
8806
8807@need 1250
8808For example:
8809
8810@smallexample
8811@group
8812(progn 1 2 3 4)
8813 @result{} 4
8814@end group
8815@end smallexample
8816
8817@item save-restriction
8818Record whatever narrowing is in effect in the current buffer, if any,
8819and restore that narrowing after evaluating the arguments.
8820
8821@item search-forward
8822Search for a string, and if the string is found, move point.
8823
8824@need 1250
8825@noindent
8826Takes four arguments:
8827
8828@enumerate
8829@item
8830The string to search for.
8831
8832@item
8833Optionally, the limit of the search.
8834
8835@item
8836Optionally, what to do if the search fails, return @code{nil} or an
8837error message.
8838
8839@item
8840Optionally, how many times to repeat the search; if negative, the
8841search goes backwards.
8842@end enumerate
8843
8844@item kill-region
8845@itemx delete-region
8846@itemx copy-region-as-kill
8847
8848@code{kill-region} cuts the text between point and mark from the
8849buffer and stores that text in the kill ring, so you can get it back
8850by yanking.
8851
8852@code{delete-and-extract-region} removes the text between point and
8853mark from the buffer and throws it away. You cannot get it back.
8854
8855@code{copy-region-as-kill} copies the text between point and mark into
8856the kill ring, from which you can get it by yanking. The function
8857does not cut or remove the text from the buffer.
8858@end table
8859
8860@need 1500
8861@node search Exercises, , cons & search-fwd Review, Cutting & Storing Text
8862@section Searching Exercises
8863
8864@itemize @bullet
8865@item
8866Write an interactive function that searches for a string. If the
8867search finds the string, leave point after it and display a message
8868that says ``Found!''. (Do not use @code{search-forward} for the name
8869of this function; if you do, you will overwrite the existing version of
8870@code{search-forward} that comes with Emacs. Use a name such as
8871@code{test-search} instead.)
8872
8873@item
8874Write a function that prints the third element of the kill ring in the
8875echo area, if any; if the kill ring does not contain a third element,
8876print an appropriate message.
8877@end itemize
8878
8879@node List Implementation, Yanking, Cutting & Storing Text, Top
8880@comment node-name, next, previous, up
8881@chapter How Lists are Implemented
8882@cindex Lists in a computer
8883
8884In Lisp, atoms are recorded in a straightforward fashion; if the
8885implementation is not straightforward in practice, it is, nonetheless,
8886straightforward in theory. The atom @samp{rose}, for example, is
8887recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8888@samp{e}. A list, on the other hand, is kept differently. The mechanism
8889is equally simple, but it takes a moment to get used to the idea. A
8890list is kept using a series of pairs of pointers. In the series, the
8891first pointer in each pair points to an atom or to another list, and the
8892second pointer in each pair points to the next pair, or to the symbol
8893@code{nil}, which marks the end of the list.
8894
8895A pointer itself is quite simply the electronic address of what is
8896pointed to. Hence, a list is kept as a series of electronic addresses.
8897
8898@menu
8899* Lists diagrammed::
8900* Symbols as Chest:: Exploring a powerful metaphor.
8901* List Exercise::
8902@end menu
8903
8904@node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8905@ifnottex
8906@unnumberedsec Lists diagrammed
8907@end ifnottex
8908
8909For example, the list @code{(rose violet buttercup)} has three elements,
8910@samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
8911electronic address of @samp{rose} is recorded in a segment of computer
8912memory along with the address that gives the electronic address of where
8913the atom @samp{violet} is located; and that address (the one that tells
8914where @samp{violet} is located) is kept along with an address that tells
8915where the address for the atom @samp{buttercup} is located.
8916
8917@need 1200
8918This sounds more complicated than it is and is easier seen in a diagram:
8919
8920@c clear print-postscript-figures
8921@c !!! cons-cell-diagram #1
8922@ifnottex
8923@smallexample
8924@group
8925 ___ ___ ___ ___ ___ ___
8926 |___|___|--> |___|___|--> |___|___|--> nil
8927 | | |
8928 | | |
8929 --> rose --> violet --> buttercup
8930@end group
8931@end smallexample
8932@end ifnottex
8933@ifset print-postscript-figures
8934@sp 1
8935@tex
8936@image{cons-1}
8937%%%% old method of including an image
8938% \input /usr/local/lib/tex/inputs/psfig.tex
8939% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8940% \catcode`\@=0 %
8941@end tex
8942@sp 1
8943@end ifset
8944@ifclear print-postscript-figures
8945@iftex
8946@smallexample
8947@group
8948 ___ ___ ___ ___ ___ ___
8949 |___|___|--> |___|___|--> |___|___|--> nil
8950 | | |
8951 | | |
8952 --> rose --> violet --> buttercup
8953@end group
8954@end smallexample
8955@end iftex
8956@end ifclear
8957
8958@noindent
8959In the diagram, each box represents a word of computer memory that
8960holds a Lisp object, usually in the form of a memory address. The boxes,
8961i.e.@: the addresses, are in pairs. Each arrow points to what the address
8962is the address of, either an atom or another pair of addresses. The
8963first box is the electronic address of @samp{rose} and the arrow points
8964to @samp{rose}; the second box is the address of the next pair of boxes,
8965the first part of which is the address of @samp{violet} and the second
8966part of which is the address of the next pair. The very last box
8967points to the symbol @code{nil}, which marks the end of the list.
8968
8969@need 1200
8970When a variable is set to a list with a function such as @code{setq},
8971it stores the address of the first box in the variable. Thus,
8972evaluation of the expression
8973
8974@smallexample
8975(setq bouquet '(rose violet buttercup))
8976@end smallexample
8977
8978@need 1250
8979@noindent
8980creates a situation like this:
8981
8982@c cons-cell-diagram #2
8983@ifnottex
8984@smallexample
8985@group
8986bouquet
8987 |
8988 | ___ ___ ___ ___ ___ ___
8989 --> |___|___|--> |___|___|--> |___|___|--> nil
8990 | | |
8991 | | |
8992 --> rose --> violet --> buttercup
8993@end group
8994@end smallexample
8995@end ifnottex
8996@ifset print-postscript-figures
8997@sp 1
8998@tex
8999@image{cons-2}
9000%%%% old method of including an image
9001% \input /usr/local/lib/tex/inputs/psfig.tex
9002% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9003% \catcode`\@=0 %
9004@end tex
9005@sp 1
9006@end ifset
9007@ifclear print-postscript-figures
9008@iftex
9009@smallexample
9010@group
9011bouquet
9012 |
9013 | ___ ___ ___ ___ ___ ___
9014 --> |___|___|--> |___|___|--> |___|___|--> nil
9015 | | |
9016 | | |
9017 --> rose --> violet --> buttercup
9018@end group
9019@end smallexample
9020@end iftex
9021@end ifclear
9022
9023@noindent
9024In this example, the symbol @code{bouquet} holds the address of the first
9025pair of boxes.
9026
9027@need 1200
9028This same list can be illustrated in a different sort of box notation
9029like this:
9030
9031@c cons-cell-diagram #2a
9032@ifnottex
9033@smallexample
9034@group
9035bouquet
9036 |
9037 | -------------- --------------- ----------------
9038 | | car | cdr | | car | cdr | | car | cdr |
9039 -->| rose | o------->| violet | o------->| butter- | nil |
9040 | | | | | | | cup | |
9041 -------------- --------------- ----------------
9042@end group
9043@end smallexample
9044@end ifnottex
9045@ifset print-postscript-figures
9046@sp 1
9047@tex
9048@image{cons-2a}
9049%%%% old method of including an image
9050% \input /usr/local/lib/tex/inputs/psfig.tex
9051% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9052% \catcode`\@=0 %
9053@end tex
9054@sp 1
9055@end ifset
9056@ifclear print-postscript-figures
9057@iftex
9058@smallexample
9059@group
9060bouquet
9061 |
9062 | -------------- --------------- ----------------
9063 | | car | cdr | | car | cdr | | car | cdr |
9064 -->| rose | o------->| violet | o------->| butter- | nil |
9065 | | | | | | | cup | |
9066 -------------- --------------- ----------------
9067@end group
9068@end smallexample
9069@end iftex
9070@end ifclear
9071
9072(Symbols consist of more than pairs of addresses, but the structure of
9073a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9074consists of a group of address-boxes, one of which is the address of
9075the printed word @samp{bouquet}, a second of which is the address of a
9076function definition attached to the symbol, if any, a third of which
9077is the address of the first pair of address-boxes for the list
9078@code{(rose violet buttercup)}, and so on. Here we are showing that
9079the symbol's third address-box points to the first pair of
9080address-boxes for the list.)
9081
9082If a symbol is set to the @sc{cdr} of a list, the list itself is not
9083changed; the symbol simply has an address further down the list. (In
9084the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9085evaluation of the following expression
9086
9087@smallexample
9088(setq flowers (cdr bouquet))
9089@end smallexample
9090
9091@need 800
9092@noindent
9093produces this:
9094
9095@c cons-cell-diagram #3
9096@ifnottex
9097@sp 1
9098@smallexample
9099@group
9100bouquet flowers
9101 | |
9102 | ___ ___ | ___ ___ ___ ___
9103 --> | | | --> | | | | | |
9104 |___|___|----> |___|___|--> |___|___|--> nil
9105 | | |
9106 | | |
9107 --> rose --> violet --> buttercup
9108@end group
9109@end smallexample
9110@sp 1
9111@end ifnottex
9112@ifset print-postscript-figures
9113@sp 1
9114@tex
9115@image{cons-3}
9116%%%% old method of including an image
9117% \input /usr/local/lib/tex/inputs/psfig.tex
9118% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9119% \catcode`\@=0 %
9120@end tex
9121@sp 1
9122@end ifset
9123@ifclear print-postscript-figures
9124@iftex
9125@sp 1
9126@smallexample
9127@group
9128bouquet flowers
9129 | |
9130 | ___ ___ | ___ ___ ___ ___
9131 --> | | | --> | | | | | |
9132 |___|___|----> |___|___|--> |___|___|--> nil
9133 | | |
9134 | | |
9135 --> rose --> violet --> buttercup
9136@end group
9137@end smallexample
9138@sp 1
9139@end iftex
9140@end ifclear
9141
9142@noindent
9143The value of @code{flowers} is @code{(violet buttercup)}, which is
9144to say, the symbol @code{flowers} holds the address of the pair of
9145address-boxes, the first of which holds the address of @code{violet},
9146and the second of which holds the address of @code{buttercup}.
9147
9148A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9149pair}. @xref{List Type, , List Type , elisp, The GNU Emacs Lisp
9150Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9151Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9152information about cons cells and dotted pairs.
9153
9154@need 1200
9155The function @code{cons} adds a new pair of addresses to the front of
9156a series of addresses like that shown above. For example, evaluating
9157the expression
9158
9159@smallexample
9160(setq bouquet (cons 'lily bouquet))
9161@end smallexample
9162
9163@need 1500
9164@noindent
9165produces:
9166
9167@c cons-cell-diagram #4
9168@ifnottex
9169@sp 1
9170@smallexample
9171@group
9172bouquet flowers
9173 | |
9174 | ___ ___ ___ ___ | ___ ___ ___ ___
9175 --> | | | | | | --> | | | | | |
9176 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9177 | | | |
9178 | | | |
9179 --> lily --> rose --> violet --> buttercup
9180@end group
9181@end smallexample
9182@sp 1
9183@end ifnottex
9184@ifset print-postscript-figures
9185@sp 1
9186@tex
9187@image{cons-4}
9188%%%% old method of including an image
9189% \input /usr/local/lib/tex/inputs/psfig.tex
9190% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9191% \catcode`\@=0 %
9192@end tex
9193@sp 1
9194@end ifset
9195@ifclear print-postscript-figures
9196@iftex
9197@sp 1
9198@smallexample
9199@group
9200bouquet flowers
9201 | |
9202 | ___ ___ ___ ___ | ___ ___ ___ ___
9203 --> | | | | | | --> | | | | | |
9204 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9205 | | | |
9206 | | | |
9207 --> lily --> rose --> violet --> buttercup
9208@end group
9209@end smallexample
9210@sp 1
9211@end iftex
9212@end ifclear
9213
9214@need 1200
9215@noindent
9216However, this does not change the value of the symbol
9217@code{flowers}, as you can see by evaluating the following,
9218
9219@smallexample
9220(eq (cdr (cdr bouquet)) flowers)
9221@end smallexample
9222
9223@noindent
9224which returns @code{t} for true.
9225
9226Until it is reset, @code{flowers} still has the value
9227@code{(violet buttercup)}; that is, it has the address of the cons
9228cell whose first address is of @code{violet}. Also, this does not
9229alter any of the pre-existing cons cells; they are all still there.
9230
9231Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9232of the next cons cell in the series; to get the @sc{car} of a list,
9233you get the address of the first element of the list; to @code{cons} a
9234new element on a list, you add a new cons cell to the front of the list.
9235That is all there is to it! The underlying structure of Lisp is
9236brilliantly simple!
9237
9238And what does the last address in a series of cons cells refer to? It
9239is the address of the empty list, of @code{nil}.
9240
9241In summary, when a Lisp variable is set to a value, it is provided with
9242the address of the list to which the variable refers.
9243
9244@node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9245@section Symbols as a Chest of Drawers
9246@cindex Symbols as a Chest of Drawers
9247@cindex Chest of Drawers, metaphor for a symbol
9248@cindex Drawers, Chest of, metaphor for a symbol
9249
9250In an earlier section, I suggested that you might imagine a symbol as
9251being a chest of drawers. The function definition is put in one
9252drawer, the value in another, and so on. What is put in the drawer
9253holding the value can be changed without affecting the contents of the
9254drawer holding the function definition, and vice-versa.
9255
9256Actually, what is put in each drawer is the address of the value or
9257function definition. It is as if you found an old chest in the attic,
9258and in one of its drawers you found a map giving you directions to
9259where the buried treasure lies.
9260
9261(In addition to its name, symbol definition, and variable value, a
9262symbol has a `drawer' for a @dfn{property list} which can be used to
9263record other information. Property lists are not discussed here; see
9264@ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9265Reference Manual}.)
9266
9267@need 1500
9268Here is a fanciful representation:
9269
9270@c chest-of-drawers diagram
9271@ifnottex
9272@sp 1
9273@smallexample
9274@group
9275 Chest of Drawers Contents of Drawers
9276
9277 __ o0O0o __
9278 / \
9279 ---------------------
9280 | directions to | [map to]
9281 | symbol name | bouquet
9282 | |
9283 +---------------------+
9284 | directions to |
9285 | symbol definition | [none]
9286 | |
9287 +---------------------+
9288 | directions to | [map to]
9289 | variable value | (rose violet buttercup)
9290 | |
9291 +---------------------+
9292 | directions to |
9293 | property list | [not described here]
9294 | |
9295 +---------------------+
9296 |/ \|
9297@end group
9298@end smallexample
9299@sp 1
9300@end ifnottex
9301@ifset print-postscript-figures
9302@sp 1
9303@tex
9304@image{drawers}
9305%%%% old method of including an image
9306% \input /usr/local/lib/tex/inputs/psfig.tex
9307% \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9308% \catcode`\@=0 %
9309@end tex
9310@sp 1
9311@end ifset
9312@ifclear print-postscript-figures
9313@iftex
9314@sp 1
9315@smallexample
9316@group
9317 Chest of Drawers Contents of Drawers
9318
9319 __ o0O0o __
9320 / \
9321 ---------------------
9322 | directions to | [map to]
9323 | symbol name | bouquet
9324 | |
9325 +---------------------+
9326 | directions to |
9327 | symbol definition | [none]
9328 | |
9329 +---------------------+
9330 | directions to | [map to]
9331 | variable value | (rose violet buttercup)
9332 | |
9333 +---------------------+
9334 | directions to |
9335 | property list | [not described here]
9336 | |
9337 +---------------------+
9338 |/ \|
9339@end group
9340@end smallexample
9341@sp 1
9342@end iftex
9343@end ifclear
9344
9345@node List Exercise, , Symbols as Chest, List Implementation
9346@section Exercise
9347
9348Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
9349more flowers on to this list and set this new list to
9350@code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
9351What does the @code{more-flowers} list now contain?
9352
9353@node Yanking, Loops & Recursion, List Implementation, Top
9354@comment node-name, next, previous, up
9355@chapter Yanking Text Back
9356@findex yank
9357@findex rotate-yank-pointer
9358@cindex Text retrieval
9359@cindex Retrieving text
9360@cindex Pasting text
9361
9362Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9363you can bring it back with a `yank' command. The text that is cut out of
9364the buffer is put in the kill ring and the yank commands insert the
9365appropriate contents of the kill ring back into a buffer (not necessarily
9366the original buffer).
9367
9368A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9369the kill ring into the current buffer. If the @kbd{C-y} command is
9370followed immediately by @kbd{M-y}, the first element is replaced by
9371the second element. Successive @kbd{M-y} commands replace the second
9372element with the third, fourth, or fifth element, and so on. When the
9373last element in the kill ring is reached, it is replaced by the first
9374element and the cycle is repeated. (Thus the kill ring is called a
9375`ring' rather than just a `list'. However, the actual data structure
9376that holds the text is a list.
9377@xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9378list is handled as a ring.)
9379
9380@menu
9381* Kill Ring Overview:: The kill ring is a list.
9382* kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
9383* yank nthcdr Exercises::
9384@end menu
9385
9386@node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9387@comment node-name, next, previous, up
9388@section Kill Ring Overview
9389@cindex Kill ring overview
9390
9391The kill ring is a list of textual strings. This is what it looks like:
9392
9393@smallexample
9394("some text" "a different piece of text" "yet more text")
9395@end smallexample
9396
9397If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9398string of characters saying @samp{some text} would be inserted in this
9399buffer where my cursor is located.
9400
9401The @code{yank} command is also used for duplicating text by copying it.
9402The copied text is not cut from the buffer, but a copy of it is put on the
9403kill ring and is inserted by yanking it back.
9404
9405Three functions are used for bringing text back from the kill ring:
9406@code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9407which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9408which is used by the two other functions.
9409
9410These functions refer to the kill ring through a variable called the
9411@code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
9412@code{yank} and @code{yank-pop} functions is:
9413
9414@smallexample
9415(insert (car kill-ring-yank-pointer))
9416@end smallexample
9417
9418To begin to understand how @code{yank} and @code{yank-pop} work, it is
9419first necessary to look at the @code{kill-ring-yank-pointer} variable
9420and the @code{rotate-yank-pointer} function.
9421
9422@node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9423@comment node-name, next, previous, up
9424@section The @code{kill-ring-yank-pointer} Variable
9425
9426@code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9427a variable. It points to something by being bound to the value of what
9428it points to, like any other Lisp variable.
9429
9430@need 1000
9431Thus, if the value of the kill ring is:
9432
9433@smallexample
9434("some text" "a different piece of text" "yet more text")
9435@end smallexample
9436
9437@need 1250
9438@noindent
9439and the @code{kill-ring-yank-pointer} points to the second clause, the
9440value of @code{kill-ring-yank-pointer} is:
9441
9442@smallexample
9443("a different piece of text" "yet more text")
9444@end smallexample
9445
9446As explained in the previous chapter (@pxref{List Implementation}), the
9447computer does not keep two different copies of the text being pointed to
9448by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
9449words ``a different piece of text'' and ``yet more text'' are not
9450duplicated. Instead, the two Lisp variables point to the same pieces of
9451text. Here is a diagram:
9452
9453@c cons-cell-diagram #5
9454@ifnottex
9455@smallexample
9456@group
9457kill-ring kill-ring-yank-pointer
9458 | |
9459 | ___ ___ | ___ ___ ___ ___
9460 ---> | | | --> | | | | | |
9461 |___|___|----> |___|___|--> |___|___|--> nil
9462 | | |
9463 | | |
9464 | | --> "yet more text"
9465 | |
9466 | --> "a different piece of text
9467 |
9468 --> "some text"
9469@end group
9470@end smallexample
9471@sp 1
9472@end ifnottex
9473@ifset print-postscript-figures
9474@sp 1
9475@tex
9476@image{cons-5}
9477%%%% old method of including an image
9478% \input /usr/local/lib/tex/inputs/psfig.tex
9479% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9480% \catcode`\@=0 %
9481@end tex
9482@sp 1
9483@end ifset
9484@ifclear print-postscript-figures
9485@iftex
9486@smallexample
9487@group
9488kill-ring kill-ring-yank-pointer
9489 | |
9490 | ___ ___ | ___ ___ ___ ___
9491 ---> | | | --> | | | | | |
9492 |___|___|----> |___|___|--> |___|___|--> nil
9493 | | |
9494 | | |
9495 | | --> "yet more text"
9496 | |
9497 | --> "a different piece of text
9498 |
9499 --> "some text"
9500@end group
9501@end smallexample
9502@sp 1
9503@end iftex
9504@end ifclear
9505
9506Both the variable @code{kill-ring} and the variable
9507@code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
9508usually described as if it were actually what it is composed of. The
9509@code{kill-ring} is spoken of as if it were the list rather than that it
9510points to the list. Conversely, the @code{kill-ring-yank-pointer} is
9511spoken of as pointing to a list.
9512
9513These two ways of talking about the same thing sound confusing at first but
9514make sense on reflection. The kill ring is generally thought of as the
9515complete structure of data that holds the information of what has recently
9516been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
9517on the other hand, serves to indicate---that is, to `point to'---that part
9518of the kill ring of which the first element (the @sc{car}) will be
9519inserted.
9520
9521The @code{rotate-yank-pointer} function changes the element in the
9522kill ring to which the @code{kill-ring-yank-pointer} points; when the
9523pointer is set to point to the next element beyond the end of the kill
9524ring, it automatically sets it to point to the first element of the
9525kill ring. This is how the list is transformed into a ring. The
9526@code{rotate-yank-pointer} function itself is not difficult, but
9527contains many details. It and the much simpler @code{yank} and
9528@code{yank-pop} functions are described in an appendix.
9529@xref{Kill Ring, , Handling the Kill Ring}.
9530
9531@need 1500
9532@node yank nthcdr Exercises, , kill-ring-yank-pointer, Yanking
9533@section Exercises with @code{yank} and @code{nthcdr}
9534
9535@itemize @bullet
9536@item
9537Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9538your kill ring. Add several items to your kill ring; look at its
9539value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
9540around the kill ring. How many items were in your kill ring? Find
9541the value of @code{kill-ring-max}. Was your kill ring full, or could
9542you have kept more blocks of text within it?
9543
9544@item
9545Using @code{nthcdr} and @code{car}, construct a series of expressions
9546to return the first, second, third, and fourth elements of a list.
9547@end itemize
9548
9549@node Loops & Recursion, Regexp Search, Yanking, Top
9550@comment node-name, next, previous, up
9551@chapter Loops and Recursion
9552@cindex Loops and recursion
9553@cindex Recursion and loops
9554@cindex Repetition (loops)
9555
9556Emacs Lisp has two primary ways to cause an expression, or a series of
9557expressions, to be evaluated repeatedly: one uses a @code{while}
9558loop, and the other uses @dfn{recursion}.
9559
9560Repetition can be very valuable. For example, to move forward four
9561sentences, you need only write a program that will move forward one
9562sentence and then repeat the process four times. Since a computer does
9563not get bored or tired, such repetitive action does not have the
9564deleterious effects that excessive or the wrong kinds of repetition can
9565have on humans.
9566
9567People mostly write Emacs Lisp functions using @code{while} loops and
9568their kin; but you can use recursion, which provides a very powerful
9569way to think about and then to solve problems@footnote{You can write
9570recursive functions to be frugal or wasteful of mental or computer
9571resources; as it happens, methods that people find easy---that are
9572frugal of `mental resources'---sometimes use considerable computer
9573resources. Emacs was designed to run on machines that we now consider
9574limited and its default settings are conservative. You may want to
9575increase the values of @code{max-specpdl-size} and
9576@code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
957715 and 30 times their default value.}.
9578
9579@menu
9580* while:: Causing a stretch of code to repeat.
9581* dolist dotimes::
9582* Recursion:: Causing a function to call itself.
9583* Looping exercise::
9584@end menu
9585
9586@node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9587@comment node-name, next, previous, up
9588@section @code{while}
9589@cindex Loops
9590@findex while
9591
9592The @code{while} special form tests whether the value returned by
9593evaluating its first argument is true or false. This is similar to what
9594the Lisp interpreter does with an @code{if}; what the interpreter does
9595next, however, is different.
9596
9597In a @code{while} expression, if the value returned by evaluating the
9598first argument is false, the Lisp interpreter skips the rest of the
9599expression (the @dfn{body} of the expression) and does not evaluate it.
9600However, if the value is true, the Lisp interpreter evaluates the body
9601of the expression and then again tests whether the first argument to
9602@code{while} is true or false. If the value returned by evaluating the
9603first argument is again true, the Lisp interpreter again evaluates the
9604body of the expression.
9605
9606@need 1200
9607The template for a @code{while} expression looks like this:
9608
9609@smallexample
9610@group
9611(while @var{true-or-false-test}
9612 @var{body}@dots{})
9613@end group
9614@end smallexample
9615
9616@menu
9617* Looping with while:: Repeat so long as test returns true.
9618* Loop Example:: A @code{while} loop that uses a list.
9619* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
9620* Incrementing Loop:: A loop with an incrementing counter.
9621* Decrementing Loop:: A loop with a decrementing counter.
9622@end menu
9623
9624@node Looping with while, Loop Example, while, while
9625@ifnottex
9626@unnumberedsubsec Looping with @code{while}
9627@end ifnottex
9628
9629So long as the true-or-false-test of the @code{while} expression
9630returns a true value when it is evaluated, the body is repeatedly
9631evaluated. This process is called a loop since the Lisp interpreter
9632repeats the same thing again and again, like an airplane doing a loop.
9633When the result of evaluating the true-or-false-test is false, the
9634Lisp interpreter does not evaluate the rest of the @code{while}
9635expression and `exits the loop'.
9636
9637Clearly, if the value returned by evaluating the first argument to
9638@code{while} is always true, the body following will be evaluated
9639again and again @dots{} and again @dots{} forever. Conversely, if the
9640value returned is never true, the expressions in the body will never
9641be evaluated. The craft of writing a @code{while} loop consists of
9642choosing a mechanism such that the true-or-false-test returns true
9643just the number of times that you want the subsequent expressions to
9644be evaluated, and then have the test return false.
9645
9646The value returned by evaluating a @code{while} is the value of the
9647true-or-false-test. An interesting consequence of this is that a
9648@code{while} loop that evaluates without error will return @code{nil}
9649or false regardless of whether it has looped 1 or 100 times or none at
9650all. A @code{while} expression that evaluates successfully never
9651returns a true value! What this means is that @code{while} is always
9652evaluated for its side effects, which is to say, the consequences of
9653evaluating the expressions within the body of the @code{while} loop.
9654This makes sense. It is not the mere act of looping that is desired,
9655but the consequences of what happens when the expressions in the loop
9656are repeatedly evaluated.
9657
9658@node Loop Example, print-elements-of-list, Looping with while, while
9659@comment node-name, next, previous, up
9660@subsection A @code{while} Loop and a List
9661
9662A common way to control a @code{while} loop is to test whether a list
9663has any elements. If it does, the loop is repeated; but if it does not,
9664the repetition is ended. Since this is an important technique, we will
9665create a short example to illustrate it.
9666
9667A simple way to test whether a list has elements is to evaluate the
9668list: if it has no elements, it is an empty list and will return the
9669empty list, @code{()}, which is a synonym for @code{nil} or false. On
9670the other hand, a list with elements will return those elements when it
9671is evaluated. Since Emacs Lisp considers as true any value that is not
9672@code{nil}, a list that returns elements will test true in a
9673@code{while} loop.
9674
9675@need 1200
9676For example, you can set the variable @code{empty-list} to @code{nil} by
9677evaluating the following @code{setq} expression:
9678
9679@smallexample
9680(setq empty-list ())
9681@end smallexample
9682
9683@noindent
9684After evaluating the @code{setq} expression, you can evaluate the
9685variable @code{empty-list} in the usual way, by placing the cursor after
9686the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9687echo area:
9688
9689@smallexample
9690empty-list
9691@end smallexample
9692
9693On the other hand, if you set a variable to be a list with elements, the
9694list will appear when you evaluate the variable, as you can see by
9695evaluating the following two expressions:
9696
9697@smallexample
9698@group
9699(setq animals '(gazelle giraffe lion tiger))
9700
9701animals
9702@end group
9703@end smallexample
9704
9705Thus, to create a @code{while} loop that tests whether there are any
9706items in the list @code{animals}, the first part of the loop will be
9707written like this:
9708
9709@smallexample
9710@group
9711(while animals
9712 @dots{}
9713@end group
9714@end smallexample
9715
9716@noindent
9717When the @code{while} tests its first argument, the variable
9718@code{animals} is evaluated. It returns a list. So long as the list
9719has elements, the @code{while} considers the results of the test to be
9720true; but when the list is empty, it considers the results of the test
9721to be false.
9722
9723To prevent the @code{while} loop from running forever, some mechanism
9724needs to be provided to empty the list eventually. An oft-used
9725technique is to have one of the subsequent forms in the @code{while}
9726expression set the value of the list to be the @sc{cdr} of the list.
9727Each time the @code{cdr} function is evaluated, the list will be made
9728shorter, until eventually only the empty list will be left. At this
9729point, the test of the @code{while} loop will return false, and the
9730arguments to the @code{while} will no longer be evaluated.
9731
9732For example, the list of animals bound to the variable @code{animals}
9733can be set to be the @sc{cdr} of the original list with the
9734following expression:
9735
9736@smallexample
9737(setq animals (cdr animals))
9738@end smallexample
9739
9740@noindent
9741If you have evaluated the previous expressions and then evaluate this
9742expression, you will see @code{(giraffe lion tiger)} appear in the echo
9743area. If you evaluate the expression again, @code{(lion tiger)} will
9744appear in the echo area. If you evaluate it again and yet again,
9745@code{(tiger)} appears and then the empty list, shown by @code{nil}.
9746
9747A template for a @code{while} loop that uses the @code{cdr} function
9748repeatedly to cause the true-or-false-test eventually to test false
9749looks like this:
9750
9751@smallexample
9752@group
9753(while @var{test-whether-list-is-empty}
9754 @var{body}@dots{}
9755 @var{set-list-to-cdr-of-list})
9756@end group
9757@end smallexample
9758
9759This test and use of @code{cdr} can be put together in a function that
9760goes through a list and prints each element of the list on a line of its
9761own.
9762
9763@node print-elements-of-list, Incrementing Loop, Loop Example, while
9764@subsection An Example: @code{print-elements-of-list}
9765@findex print-elements-of-list
9766
9767The @code{print-elements-of-list} function illustrates a @code{while}
9768loop with a list.
9769
9770@cindex @file{*scratch*} buffer
9771The function requires several lines for its output. If you are
9772reading this in Emacs 21 or a later version, you can evaluate the
9773following expression inside of Info, as usual.
9774
9775If you are using an earlier version of Emacs, you need to copy the
9776necessary expressions to your @file{*scratch*} buffer and evaluate
9777them there. This is because the echo area had only one line in the
9778earlier versions.
9779
9780You can copy the expressions by marking the beginning of the region
9781with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9782the end of the region and then copying the region using @kbd{M-w}
9783(@code{copy-region-as-kill}). In the @file{*scratch*} buffer, you can
9784yank the expressions back by typing @kbd{C-y} (@code{yank}).
9785
9786After you have copied the expressions to the @file{*scratch*} buffer,
9787evaluate each expression in turn. Be sure to evaluate the last
9788expression, @code{(print-elements-of-list animals)}, by typing
9789@kbd{C-u C-x C-e}, that is, by giving an argument to
9790@code{eval-last-sexp}. This will cause the result of the evaluation
9791to be printed in the @file{*scratch*} buffer instead of being printed
9792in the echo area. (Otherwise you will see something like this in your
b15dd613 9793echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
8b096dce
EZ
9794each @samp{^J} stands for a `newline'.)
9795
9796@need 1500
9797If you are using Emacs 21 or later, you can evaluate these expressions
9798directly in the Info buffer, and the echo area will grow to show the
9799results.
9800
9801@smallexample
9802@group
9803(setq animals '(gazelle giraffe lion tiger))
9804
9805(defun print-elements-of-list (list)
9806 "Print each element of LIST on a line of its own."
9807 (while list
9808 (print (car list))
9809 (setq list (cdr list))))
9810
9811(print-elements-of-list animals)
9812@end group
9813@end smallexample
9814
9815@need 1200
9816@noindent
9817When you evaluate the three expressions in sequence, you will see
9818this:
9819
9820@smallexample
9821@group
8b096dce
EZ
9822gazelle
9823
b15dd613
RC
9824giraffe
9825
8b096dce
EZ
9826lion
9827
9828tiger
9829nil
9830@end group
9831@end smallexample
9832
9833Each element of the list is printed on a line of its own (that is what
9834the function @code{print} does) and then the value returned by the
9835function is printed. Since the last expression in the function is the
9836@code{while} loop, and since @code{while} loops always return
9837@code{nil}, a @code{nil} is printed after the last element of the list.
9838
9839@node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9840@comment node-name, next, previous, up
9841@subsection A Loop with an Incrementing Counter
9842
9843A loop is not useful unless it stops when it ought. Besides
9844controlling a loop with a list, a common way of stopping a loop is to
9845write the first argument as a test that returns false when the correct
9846number of repetitions are complete. This means that the loop must
9847have a counter---an expression that counts how many times the loop
9848repeats itself.
9849
9850The test can be an expression such as @code{(< count desired-number)}
9851which returns @code{t} for true if the value of @code{count} is less
9852than the @code{desired-number} of repetitions and @code{nil} for false if
9853the value of @code{count} is equal to or is greater than the
9854@code{desired-number}. The expression that increments the count can be
9855a simple @code{setq} such as @code{(setq count (1+ count))}, where
9856@code{1+} is a built-in function in Emacs Lisp that adds 1 to its
18432d81 9857argument. (The expression @w{@code{(1+ count)}} has the same result as
28be162e 9858@w{@code{(+ count 1)}}, but is easier for a human to read.)
8b096dce
EZ
9859
9860@need 1250
9861The template for a @code{while} loop controlled by an incrementing
9862counter looks like this:
9863
9864@smallexample
9865@group
9866@var{set-count-to-initial-value}
9867(while (< count desired-number) ; @r{true-or-false-test}
9868 @var{body}@dots{}
9869 (setq count (1+ count))) ; @r{incrementer}
9870@end group
9871@end smallexample
9872
9873@noindent
9874Note that you need to set the initial value of @code{count}; usually it
9875is set to 1.
9876
9877@menu
9878* Incrementing Example:: Counting pebbles in a triangle.
9879* Inc Example parts:: The parts of the function definition.
9880* Inc Example altogether:: Putting the function definition together.
9881@end menu
9882
9883@node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9884@unnumberedsubsubsec Example with incrementing counter
9885
9886Suppose you are playing on the beach and decide to make a triangle of
9887pebbles, putting one pebble in the first row, two in the second row,
9888three in the third row and so on, like this:
9889
9890@sp 1
9891@c pebble diagram
9892@ifnottex
9893@smallexample
9894@group
9895 *
9896 * *
9897 * * *
9898 * * * *
9899@end group
9900@end smallexample
9901@end ifnottex
9902@iftex
9903@smallexample
9904@group
9905 @bullet{}
9906 @bullet{} @bullet{}
9907 @bullet{} @bullet{} @bullet{}
9908 @bullet{} @bullet{} @bullet{} @bullet{}
9909@end group
9910@end smallexample
9911@end iftex
9912@sp 1
9913
9914@noindent
9915(About 2500 years ago, Pythagoras and others developed the beginnings of
9916number theory by considering questions such as this.)
9917
9918Suppose you want to know how many pebbles you will need to make a
9919triangle with 7 rows?
9920
9921Clearly, what you need to do is add up the numbers from 1 to 7. There
9922are two ways to do this; start with the smallest number, one, and add up
9923the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9924number and add the list going down: 7, 6, 5, 4 and so on. Because both
9925mechanisms illustrate common ways of writing @code{while} loops, we will
9926create two examples, one counting up and the other counting down. In
9927this first example, we will start with 1 and add 2, 3, 4 and so on.
9928
9929If you are just adding up a short list of numbers, the easiest way to do
9930it is to add up all the numbers at once. However, if you do not know
9931ahead of time how many numbers your list will have, or if you want to be
9932prepared for a very long list, then you need to design your addition so
9933that what you do is repeat a simple process many times instead of doing
9934a more complex process once.
9935
9936For example, instead of adding up all the pebbles all at once, what you
9937can do is add the number of pebbles in the first row, 1, to the number
9938in the second row, 2, and then add the total of those two rows to the
9939third row, 3. Then you can add the number in the fourth row, 4, to the
9940total of the first three rows; and so on.
9941
9942The critical characteristic of the process is that each repetitive
9943action is simple. In this case, at each step we add only two numbers,
9944the number of pebbles in the row and the total already found. This
9945process of adding two numbers is repeated again and again until the last
9946row has been added to the total of all the preceding rows. In a more
9947complex loop the repetitive action might not be so simple, but it will
9948be simpler than doing everything all at once.
9949
9950@node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9951@unnumberedsubsubsec The parts of the function definition
9952
9953The preceding analysis gives us the bones of our function definition:
9954first, we will need a variable that we can call @code{total} that will
9955be the total number of pebbles. This will be the value returned by
9956the function.
9957
9958Second, we know that the function will require an argument: this
9959argument will be the total number of rows in the triangle. It can be
9960called @code{number-of-rows}.
9961
9962Finally, we need a variable to use as a counter. We could call this
9963variable @code{counter}, but a better name is @code{row-number}.
9964That is because what the counter does is count rows, and a program
9965should be written to be as understandable as possible.
9966
9967When the Lisp interpreter first starts evaluating the expressions in the
9968function, the value of @code{total} should be set to zero, since we have
9969not added anything to it. Then the function should add the number of
9970pebbles in the first row to the total, and then add the number of
9971pebbles in the second to the total, and then add the number of
9972pebbles in the third row to the total, and so on, until there are no
9973more rows left to add.
9974
9975Both @code{total} and @code{row-number} are used only inside the
9976function, so they can be declared as local variables with @code{let}
9977and given initial values. Clearly, the initial value for @code{total}
9978should be 0. The initial value of @code{row-number} should be 1,
9979since we start with the first row. This means that the @code{let}
9980statement will look like this:
9981
9982@smallexample
9983@group
9984 (let ((total 0)
9985 (row-number 1))
9986 @var{body}@dots{})
9987@end group
9988@end smallexample
9989
9990After the internal variables are declared and bound to their initial
9991values, we can begin the @code{while} loop. The expression that serves
9992as the test should return a value of @code{t} for true so long as the
9993@code{row-number} is less than or equal to the @code{number-of-rows}.
9994(If the expression tests true only so long as the row number is less
9995than the number of rows in the triangle, the last row will never be
9996added to the total; hence the row number has to be either less than or
9997equal to the number of rows.)
9998
9999@need 1500
10000@findex <= @r{(less than or equal)}
10001Lisp provides the @code{<=} function that returns true if the value of
10002its first argument is less than or equal to the value of its second
10003argument and false otherwise. So the expression that the @code{while}
10004will evaluate as its test should look like this:
10005
10006@smallexample
10007(<= row-number number-of-rows)
10008@end smallexample
10009
10010The total number of pebbles can be found by repeatedly adding the number
10011of pebbles in a row to the total already found. Since the number of
10012pebbles in the row is equal to the row number, the total can be found by
10013adding the row number to the total. (Clearly, in a more complex
10014situation, the number of pebbles in the row might be related to the row
10015number in a more complicated way; if this were the case, the row number
10016would be replaced by the appropriate expression.)
10017
10018@smallexample
10019(setq total (+ total row-number))
10020@end smallexample
10021
10022@noindent
10023What this does is set the new value of @code{total} to be equal to the
10024sum of adding the number of pebbles in the row to the previous total.
10025
10026After setting the value of @code{total}, the conditions need to be
10027established for the next repetition of the loop, if there is one. This
10028is done by incrementing the value of the @code{row-number} variable,
10029which serves as a counter. After the @code{row-number} variable has
10030been incremented, the true-or-false-test at the beginning of the
10031@code{while} loop tests whether its value is still less than or equal to
10032the value of the @code{number-of-rows} and if it is, adds the new value
10033of the @code{row-number} variable to the @code{total} of the previous
10034repetition of the loop.
10035
10036@need 1200
10037The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10038@code{row-number} variable can be incremented with this expression:
10039
10040@smallexample
10041(setq row-number (1+ row-number))
10042@end smallexample
10043
10044@node Inc Example altogether, , Inc Example parts, Incrementing Loop
10045@unnumberedsubsubsec Putting the function definition together
10046
10047We have created the parts for the function definition; now we need to
10048put them together.
10049
10050@need 800
10051First, the contents of the @code{while} expression:
10052
10053@smallexample
10054@group
10055(while (<= row-number number-of-rows) ; @r{true-or-false-test}
10056 (setq total (+ total row-number))
10057 (setq row-number (1+ row-number))) ; @r{incrementer}
10058@end group
10059@end smallexample
10060
10061Along with the @code{let} expression varlist, this very nearly
10062completes the body of the function definition. However, it requires
10063one final element, the need for which is somewhat subtle.
10064
10065The final touch is to place the variable @code{total} on a line by
10066itself after the @code{while} expression. Otherwise, the value returned
10067by the whole function is the value of the last expression that is
10068evaluated in the body of the @code{let}, and this is the value
10069returned by the @code{while}, which is always @code{nil}.
10070
10071This may not be evident at first sight. It almost looks as if the
10072incrementing expression is the last expression of the whole function.
10073But that expression is part of the body of the @code{while}; it is the
10074last element of the list that starts with the symbol @code{while}.
10075Moreover, the whole of the @code{while} loop is a list within the body
10076of the @code{let}.
10077
10078@need 1250
10079In outline, the function will look like this:
10080
10081@smallexample
10082@group
10083(defun @var{name-of-function} (@var{argument-list})
10084 "@var{documentation}@dots{}"
10085 (let (@var{varlist})
10086 (while (@var{true-or-false-test})
10087 @var{body-of-while}@dots{} )
10088 @dots{} ) ; @r{Need final expression here.}
10089@end group
10090@end smallexample
10091
10092The result of evaluating the @code{let} is what is going to be returned
10093by the @code{defun} since the @code{let} is not embedded within any
10094containing list, except for the @code{defun} as a whole. However, if
10095the @code{while} is the last element of the @code{let} expression, the
10096function will always return @code{nil}. This is not what we want!
10097Instead, what we want is the value of the variable @code{total}. This
10098is returned by simply placing the symbol as the last element of the list
10099starting with @code{let}. It gets evaluated after the preceding
10100elements of the list are evaluated, which means it gets evaluated after
10101it has been assigned the correct value for the total.
10102
10103It may be easier to see this by printing the list starting with
10104@code{let} all on one line. This format makes it evident that the
10105@var{varlist} and @code{while} expressions are the second and third
10106elements of the list starting with @code{let}, and the @code{total} is
10107the last element:
10108
10109@smallexample
10110@group
10111(let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10112@end group
10113@end smallexample
10114
10115@need 1200
10116Putting everything together, the @code{triangle} function definition
10117looks like this:
10118
10119@smallexample
10120@group
10121(defun triangle (number-of-rows) ; @r{Version with}
10122 ; @r{ incrementing counter.}
10123 "Add up the number of pebbles in a triangle.
10124The first row has one pebble, the second row two pebbles,
10125the third row three pebbles, and so on.
10126The argument is NUMBER-OF-ROWS."
10127@end group
10128@group
10129 (let ((total 0)
10130 (row-number 1))
10131 (while (<= row-number number-of-rows)
10132 (setq total (+ total row-number))
10133 (setq row-number (1+ row-number)))
10134 total))
10135@end group
10136@end smallexample
10137
10138@need 1200
10139After you have installed @code{triangle} by evaluating the function, you
10140can try it out. Here are two examples:
10141
10142@smallexample
10143@group
10144(triangle 4)
10145
10146(triangle 7)
10147@end group
10148@end smallexample
10149
10150@noindent
10151The sum of the first four numbers is 10 and the sum of the first seven
10152numbers is 28.
10153
10154@node Decrementing Loop, , Incrementing Loop, while
10155@comment node-name, next, previous, up
10156@subsection Loop with a Decrementing Counter
10157
10158Another common way to write a @code{while} loop is to write the test
10159so that it determines whether a counter is greater than zero. So long
10160as the counter is greater than zero, the loop is repeated. But when
10161the counter is equal to or less than zero, the loop is stopped. For
10162this to work, the counter has to start out greater than zero and then
10163be made smaller and smaller by a form that is evaluated
10164repeatedly.
10165
10166The test will be an expression such as @code{(> counter 0)} which
10167returns @code{t} for true if the value of @code{counter} is greater
10168than zero, and @code{nil} for false if the value of @code{counter} is
10169equal to or less than zero. The expression that makes the number
10170smaller and smaller can be a simple @code{setq} such as @code{(setq
10171counter (1- counter))}, where @code{1-} is a built-in function in
10172Emacs Lisp that subtracts 1 from its argument.
10173
10174@need 1250
10175The template for a decrementing @code{while} loop looks like this:
10176
10177@smallexample
10178@group
10179(while (> counter 0) ; @r{true-or-false-test}
10180 @var{body}@dots{}
10181 (setq counter (1- counter))) ; @r{decrementer}
10182@end group
10183@end smallexample
10184
10185@menu
10186* Decrementing Example:: More pebbles on the beach.
10187* Dec Example parts:: The parts of the function definition.
10188* Dec Example altogether:: Putting the function definition together.
10189@end menu
10190
10191@node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10192@unnumberedsubsubsec Example with decrementing counter
10193
10194To illustrate a loop with a decrementing counter, we will rewrite the
10195@code{triangle} function so the counter decreases to zero.
10196
10197This is the reverse of the earlier version of the function. In this
10198case, to find out how many pebbles are needed to make a triangle with
101993 rows, add the number of pebbles in the third row, 3, to the number
10200in the preceding row, 2, and then add the total of those two rows to
10201the row that precedes them, which is 1.
10202
10203Likewise, to find the number of pebbles in a triangle with 7 rows, add
10204the number of pebbles in the seventh row, 7, to the number in the
10205preceding row, which is 6, and then add the total of those two rows to
10206the row that precedes them, which is 5, and so on. As in the previous
10207example, each addition only involves adding two numbers, the total of
10208the rows already added up and the number of pebbles in the row that is
10209being added to the total. This process of adding two numbers is
10210repeated again and again until there are no more pebbles to add.
10211
10212We know how many pebbles to start with: the number of pebbles in the
10213last row is equal to the number of rows. If the triangle has seven
10214rows, the number of pebbles in the last row is 7. Likewise, we know how
10215many pebbles are in the preceding row: it is one less than the number in
10216the row.
10217
10218@node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10219@unnumberedsubsubsec The parts of the function definition
10220
10221We start with three variables: the total number of rows in the
10222triangle; the number of pebbles in a row; and the total number of
10223pebbles, which is what we want to calculate. These variables can be
10224named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10225@code{total}, respectively.
10226
10227Both @code{total} and @code{number-of-pebbles-in-row} are used only
10228inside the function and are declared with @code{let}. The initial
10229value of @code{total} should, of course, be zero. However, the
10230initial value of @code{number-of-pebbles-in-row} should be equal to
10231the number of rows in the triangle, since the addition will start with
10232the longest row.
10233
10234@need 1250
10235This means that the beginning of the @code{let} expression will look
10236like this:
10237
10238@smallexample
10239@group
10240(let ((total 0)
10241 (number-of-pebbles-in-row number-of-rows))
10242 @var{body}@dots{})
10243@end group
10244@end smallexample
10245
10246The total number of pebbles can be found by repeatedly adding the number
10247of pebbles in a row to the total already found, that is, by repeatedly
10248evaluating the following expression:
10249
10250@smallexample
10251(setq total (+ total number-of-pebbles-in-row))
10252@end smallexample
10253
10254@noindent
10255After the @code{number-of-pebbles-in-row} is added to the @code{total},
10256the @code{number-of-pebbles-in-row} should be decremented by one, since
10257the next time the loop repeats, the preceding row will be
10258added to the total.
10259
10260The number of pebbles in a preceding row is one less than the number of
10261pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10262used to compute the number of pebbles in the preceding row. This can be
10263done with the following expression:
10264
10265@smallexample
10266@group
10267(setq number-of-pebbles-in-row
10268 (1- number-of-pebbles-in-row))
10269@end group
10270@end smallexample
10271
10272Finally, we know that the @code{while} loop should stop making repeated
10273additions when there are no pebbles in a row. So the test for
10274the @code{while} loop is simply:
10275
10276@smallexample
10277(while (> number-of-pebbles-in-row 0)
10278@end smallexample
10279
10280@node Dec Example altogether, , Dec Example parts, Decrementing Loop
10281@unnumberedsubsubsec Putting the function definition together
10282
10283We can put these expressions together to create a function definition
10284that works. However, on examination, we find that one of the local
10285variables is unneeded!
10286
10287@need 1250
10288The function definition looks like this:
10289
10290@smallexample
10291@group
10292;;; @r{First subtractive version.}
10293(defun triangle (number-of-rows)
10294 "Add up the number of pebbles in a triangle."
10295 (let ((total 0)
10296 (number-of-pebbles-in-row number-of-rows))
10297 (while (> number-of-pebbles-in-row 0)
10298 (setq total (+ total number-of-pebbles-in-row))
10299 (setq number-of-pebbles-in-row
10300 (1- number-of-pebbles-in-row)))
10301 total))
10302@end group
10303@end smallexample
10304
10305As written, this function works.
10306
10307However, we do not need @code{number-of-pebbles-in-row}.
10308
10309@cindex Argument as local variable
10310When the @code{triangle} function is evaluated, the symbol
10311@code{number-of-rows} will be bound to a number, giving it an initial
10312value. That number can be changed in the body of the function as if
10313it were a local variable, without any fear that such a change will
10314effect the value of the variable outside of the function. This is a
10315very useful characteristic of Lisp; it means that the variable
10316@code{number-of-rows} can be used anywhere in the function where
10317@code{number-of-pebbles-in-row} is used.
10318
10319@need 800
10320Here is a second version of the function written a bit more cleanly:
10321
10322@smallexample
10323@group
10324(defun triangle (number) ; @r{Second version.}
10325 "Return sum of numbers 1 through NUMBER inclusive."
10326 (let ((total 0))
10327 (while (> number 0)
10328 (setq total (+ total number))
10329 (setq number (1- number)))
10330 total))
10331@end group
10332@end smallexample
10333
10334In brief, a properly written @code{while} loop will consist of three parts:
10335
10336@enumerate
10337@item
10338A test that will return false after the loop has repeated itself the
10339correct number of times.
10340
10341@item
10342An expression the evaluation of which will return the value desired
10343after being repeatedly evaluated.
10344
10345@item
10346An expression to change the value passed to the true-or-false-test so
10347that the test returns false after the loop has repeated itself the right
10348number of times.
10349@end enumerate
10350
10351@node dolist dotimes, Recursion, while, Loops & Recursion
10352@comment node-name, next, previous, up
10353@section Save your time: @code{dolist} and @code{dotimes}
10354
10355In addition to @code{while}, both @code{dolist} and @code{dotimes}
10356provide for looping. Sometimes these are quicker to write than the
10357equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
10358Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10359
10360@code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10361list': @code{dolist} automatically shortens the list each time it
10362loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10363each shorter version of the list to the first of its arguments.
10364
e601d8fd 10365@code{dotimes} loops a specific number of times: you specify the number.
8b096dce
EZ
10366
10367@menu
10368* dolist::
10369* dotimes::
10370@end menu
10371
10372@node dolist, dotimes, dolist dotimes, dolist dotimes
10373@unnumberedsubsubsec The @code{dolist} Macro
10374@findex dolist
10375
10376Suppose, for example, you want to reverse a list, so that
10377``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10378
10379@need 1250
10380In practice, you would use the @code{reverse} function, like this:
10381
10382@smallexample
10383@group
10384(setq animals '(gazelle giraffe lion tiger))
10385
10386(reverse animals)
10387@end group
10388@end smallexample
10389
10390@need 800
10391@noindent
10392Here is how you could reverse the list using a @code{while} loop:
10393
10394@smallexample
10395@group
10396(setq animals '(gazelle giraffe lion tiger))
10397
10398(defun reverse-list-with-while (list)
10399 "Using while, reverse the order of LIST."
10400 (let (value) ; make sure list starts empty
10401 (while list
10402 (setq value (cons (car list) value))
10403 (setq list (cdr list)))
10404 value))
10405
10406(reverse-list-with-while animals)
10407@end group
10408@end smallexample
10409
10410@need 800
10411@noindent
10412And here is how you could use the @code{dolist} macro:
10413
10414@smallexample
10415@group
10416(setq animals '(gazelle giraffe lion tiger))
10417
10418(defun reverse-list-with-dolist (list)
10419 "Using dolist, reverse the order of LIST."
10420 (let (value) ; make sure list starts empty
10421 (dolist (element list value)
10422 (setq value (cons element value)))))
10423
10424(reverse-list-with-dolist animals)
10425@end group
10426@end smallexample
10427
10428@need 1250
10429@noindent
10430In Info, you can place your cursor after the closing parenthesis of
10431each expression and type @kbd{C-x C-e}; in each case, you should see
10432
10433@smallexample
10434(tiger lion giraffe gazelle)
10435@end smallexample
10436
10437@noindent
10438in the echo area.
10439
10440For this example, the existing @code{reverse} function is obviously best.
10441The @code{while} loop is just like our first example (@pxref{Loop
10442Example, , A @code{while} Loop and a List}). The @code{while} first
10443checks whether the list has elements; if so, it constructs a new list
10444by adding the first element of the list to the existing list (which in
10445the first iteration of the loop is @code{nil}). Since the second
10446element is prepended in front of the first element, and the third
10447element is prepended in front of the second element, the list is reversed.
10448
10449In the expression using a @code{while} loop,
10450the @w{@code{(setq list (cdr list))}}
10451expression shortens the list, so the @code{while} loop eventually
10452stops. In addition, it provides the @code{cons} expression with a new
10453first element by creating a new and shorter list at each repetition of
10454the loop.
10455
10456The @code{dolist} expression does very much the same as the
10457@code{while} expression, except that the @code{dolist} macro does some
10458of the work you have to do when writing a @code{while} expression.
10459
10460Like a @code{while} loop, a @code{dolist} loops. What is different is
10461that it automatically shortens the list each time it loops --- it
10462`@sc{cdr}s down the list' on its own --- and it automatically binds
10463the @sc{car} of each shorter version of the list to the first of its
10464arguments.
10465
10466In the example, the @sc{car} of each shorter version of the list is
10467referred to using the symbol @samp{element}, the list itself is called
10468@samp{list}, and the value returned is called @samp{value}. The
10469remainder of the @code{dolist} expression is the body.
10470
10471The @code{dolist} expression binds the @sc{car} of each shorter
10472version of the list to @code{element} and then evaluates the body of
10473the expression; and repeats the loop. The result is returned in
10474@code{value}.
10475
10476@node dotimes, , dolist, dolist dotimes
10477@unnumberedsubsubsec The @code{dotimes} Macro
10478@findex dotimes
10479
10480The @code{dotimes} macro is similar to @code{dolist}, except that it
10481loops a specific number of times.
10482
10483The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10484and so forth each time around the loop, and the value of the third
10485argument is returned. You need to provide the value of the second
10486argument, which is how many times the macro loops.
10487
10488@need 1250
10489For example, the following binds the numbers from 0 up to, but not
10490including, the number 3 to the first argument, @var{number}, and then
10491constructs a list of the three numbers. (The first number is 0, the
10492second number is 1, and the third number is 2; this makes a total of
10493three numbers in all, starting with zero as the first number.)
10494
10495@smallexample
10496@group
10497(let (value) ; otherwise a value is a void variable
10498 (dotimes (number 3 value)
10499 (setq value (cons number value))))
10500
10501@result{} (2 1 0)
10502@end group
10503@end smallexample
10504
10505@noindent
10506@code{dotimes} returns @code{value}, so the way to use
10507@code{dotimes} is to operate on some expression @var{number} number of
10508times and then return the result, either as a list or an atom.
10509
10510@need 1250
10511Here is an example of a @code{defun} that uses @code{dotimes} to add
10512up the number of pebbles in a triangle.
10513
10514@smallexample
10515@group
10516(defun triangle-using-dotimes (number-of-rows)
10517 "Using dotimes, add up the number of pebbles in a triangle."
10518(let ((total 0)) ; otherwise a total is a void variable
10519 (dotimes (number number-of-rows total)
10520 (setq total (+ total (1+ number))))))
10521
10522(triangle-using-dotimes 4)
10523@end group
10524@end smallexample
10525
10526@node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10527@comment node-name, next, previous, up
10528@section Recursion
10529@cindex Recursion
10530
10531A recursive function contains code that tells the Lisp interpreter to
10532call a program that runs exactly like itself, but with slightly
10533different arguments. The code runs exactly the same because it has
b15dd613
RC
10534the same name. However, even though the program has the same name, it
10535is not the same entity. It is different. In the jargon, it is a
10536different `instance'.
8b096dce
EZ
10537
10538Eventually, if the program is written correctly, the `slightly
10539different arguments' will become sufficiently different from the first
10540arguments that the final instance will stop.
10541
10542@menu
10543* Building Robots:: Same model, different serial number ...
10544* Recursive Definition Parts:: Walk until you stop ...
10545* Recursion with list:: Using a list as the test whether to recurse.
10546* Recursive triangle function::
10547* Recursion with cond::
10548* Recursive Patterns:: Often used templates.
10549* No Deferment:: Don't store up work ...
10550* No deferment solution::
10551@end menu
10552
10553@node Building Robots, Recursive Definition Parts, Recursion, Recursion
10554@comment node-name, next, previous, up
10555@subsection Building Robots: Extending the Metaphor
10556@cindex Building robots
10557@cindex Robots, building
10558
10559It is sometimes helpful to think of a running program as a robot that
10560does a job. In doing its job, a recursive function calls on a second
10561robot to help it. The second robot is identical to the first in every
10562way, except that the second robot helps the first and has been
10563passed different arguments than the first.
10564
10565In a recursive function, the second robot may call a third; and the
10566third may call a fourth, and so on. Each of these is a different
10567entity; but all are clones.
10568
10569Since each robot has slightly different instructions---the arguments
10570will differ from one robot to the next---the last robot should know
10571when to stop.
10572
10573Let's expand on the metaphor in which a computer program is a robot.
10574
10575A function definition provides the blueprints for a robot. When you
10576install a function definition, that is, when you evaluate a
10577@code{defun} special form, you install the necessary equipment to
10578build robots. It is as if you were in a factory, setting up an
10579assembly line. Robots with the same name are built according to the
10580same blueprints. So they have, as it were, the same `model number',
10581but a different `serial number'.
10582
10583We often say that a recursive function `calls itself'. What we mean
10584is that the instructions in a recursive function cause the Lisp
10585interpreter to run a different function that has the same name and
10586does the same job as the first, but with different arguments.
10587
10588It is important that the arguments differ from one instance to the
10589next; otherwise, the process will never stop.
10590
10591@node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10592@comment node-name, next, previous, up
10593@subsection The Parts of a Recursive Definition
10594@cindex Parts of a Recursive Definition
10595@cindex Recursive Definition Parts
10596
10597A recursive function typically contains a conditional expression which
10598has three parts:
10599
10600@enumerate
10601@item
10602A true-or-false-test that determines whether the function is called
10603again, here called the @dfn{do-again-test}.
10604
10605@item
10606The name of the function. When this name is called, a new instance of
10607the function---a new robot, as it were---is created and told what to do.
10608
10609@item
10610An expression that returns a different value each time the function is
10611called, here called the @dfn{next-step-expression}. Consequently, the
10612argument (or arguments) passed to the new instance of the function
10613will be different from that passed to the previous instance. This
10614causes the conditional expression, the @dfn{do-again-test}, to test
10615false after the correct number of repetitions.
10616@end enumerate
10617
10618Recursive functions can be much simpler than any other kind of
10619function. Indeed, when people first start to use them, they often look
10620so mysteriously simple as to be incomprehensible. Like riding a
10621bicycle, reading a recursive function definition takes a certain knack
10622which is hard at first but then seems simple.
10623
10624@need 1200
10625There are several different common recursive patterns. A very simple
10626pattern looks like this:
10627
10628@smallexample
10629@group
10630(defun @var{name-of-recursive-function} (@var{argument-list})
10631 "@var{documentation}@dots{}"
10632 (if @var{do-again-test}
10633 @var{body}@dots{}
10634 (@var{name-of-recursive-function}
10635 @var{next-step-expression})))
10636@end group
10637@end smallexample
10638
10639Each time a recursive function is evaluated, a new instance of it is
10640created and told what to do. The arguments tell the instance what to do.
10641
10642An argument is bound to the value of the next-step-expression. Each
10643instance runs with a different value of the next-step-expression.
10644
10645The value in the next-step-expression is used in the do-again-test.
10646
10647The value returned by the next-step-expression is passed to the new
10648instance of the function, which evaluates it (or some
10649transmogrification of it) to determine whether to continue or stop.
10650The next-step-expression is designed so that the do-again-test returns
10651false when the function should no longer be repeated.
10652
10653The do-again-test is sometimes called the @dfn{stop condition},
10654since it stops the repetitions when it tests false.
10655
10656@node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10657@comment node-name, next, previous, up
10658@subsection Recursion with a List
10659
10660The example of a @code{while} loop that printed the elements of a list
10661of numbers can be written recursively. Here is the code, including
10662an expression to set the value of the variable @code{animals} to a list.
10663
10664If you are using Emacs 20 or before, this example must be copied to
10665the @file{*scratch*} buffer and each expression must be evaluated
10666there. Use @kbd{C-u C-x C-e} to evaluate the
10667@code{(print-elements-recursively animals)} expression so that the
10668results are printed in the buffer; otherwise the Lisp interpreter will
10669try to squeeze the results into the one line of the echo area.
10670
10671Also, place your cursor immediately after the last closing parenthesis
10672of the @code{print-elements-recursively} function, before the comment.
10673Otherwise, the Lisp interpreter will try to evaluate the comment.
10674
10675If you are using Emacs 21 or later, you can evaluate this expression
10676directly in Info.
10677
10678@findex print-elements-recursively
10679@smallexample
10680@group
10681(setq animals '(gazelle giraffe lion tiger))
10682
10683(defun print-elements-recursively (list)
10684 "Print each element of LIST on a line of its own.
10685Uses recursion."
10686 (if list ; @r{do-again-test}
10687 (progn
10688 (print (car list)) ; @r{body}
10689 (print-elements-recursively ; @r{recursive call}
10690 (cdr list))))) ; @r{next-step-expression}
10691
10692(print-elements-recursively animals)
10693@end group
10694@end smallexample
10695
10696The @code{print-elements-recursively} function first tests whether
10697there is any content in the list; if there is, the function prints the
10698first element of the list, the @sc{car} of the list. Then the
10699function `invokes itself', but gives itself as its argument, not the
10700whole list, but the second and subsequent elements of the list, the
10701@sc{cdr} of the list.
10702
10703Put another way, if the list is not empty, the function invokes
10704another instance of code that is similar to the initial code, but is a
10705different thread of execution, with different arguments than the first
10706instance.
10707
10708Put in yet another way, if the list is not empty, the first robot
10709assemblies a second robot and tells it what to do; the second robot is
10710a different individual from the first, but is the same model.
10711
10712When the second evaluation occurs, the @code{if} expression is
10713evaluated and if true, prints the first element of the list it
10714receives as its argument (which is the second element of the original
10715list). Then the function `calls itself' with the @sc{cdr} of the list
10716it is invoked with, which (the second time around) is the @sc{cdr} of
10717the @sc{cdr} of the original list.
10718
10719Note that although we say that the function `calls itself', what we
10720mean is that the Lisp interpreter assembles and instructs a new
10721instance of the program. The new instance is a clone of the first,
10722but is a separate individual.
10723
10724Each time the function `invokes itself', it invokes itself on a
10725shorter version of the original list. It creates a new instance that
10726works on a shorter list.
10727
10728Eventually, the function invokes itself on an empty list. It creates
10729a new instance whose argument is @code{nil}. The conditional expression
10730tests the value of @code{list}. Since the value of @code{list} is
10731@code{nil}, the @code{if} expression tests false so the then-part is
10732not evaluated. The function as a whole then returns @code{nil}.
10733
10734@need 1200
10735When you evaluate @code{(print-elements-recursively animals)} in the
10736@file{*scratch*} buffer, you see this result:
10737
10738@smallexample
10739@group
8b096dce
EZ
10740gazelle
10741
b15dd613
RC
10742giraffe
10743
8b096dce
EZ
10744lion
10745
10746tiger
10747nil
10748@end group
10749@end smallexample
10750
10751@node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10752@comment node-name, next, previous, up
10753@subsection Recursion in Place of a Counter
10754@findex triangle-recursively
10755
10756@need 1200
10757The @code{triangle} function described in a previous section can also
10758be written recursively. It looks like this:
10759
10760@smallexample
10761@group
10762(defun triangle-recursively (number)
10763 "Return the sum of the numbers 1 through NUMBER inclusive.
10764Uses recursion."
10765 (if (= number 1) ; @r{do-again-test}
10766 1 ; @r{then-part}
10767 (+ number ; @r{else-part}
10768 (triangle-recursively ; @r{recursive call}
10769 (1- number))))) ; @r{next-step-expression}
10770
10771(triangle-recursively 7)
10772@end group
10773@end smallexample
10774
10775@noindent
10776You can install this function by evaluating it and then try it by
10777evaluating @code{(triangle-recursively 7)}. (Remember to put your
10778cursor immediately after the last parenthesis of the function
10779definition, before the comment.) The function evaluates to 28.
10780
10781To understand how this function works, let's consider what happens in the
10782various cases when the function is passed 1, 2, 3, or 4 as the value of
10783its argument.
10784
10785@menu
10786* Recursive Example arg of 1 or 2::
10787* Recursive Example arg of 3 or 4::
10788@end menu
10789
10790@node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10791@ifnottex
10792@unnumberedsubsubsec An argument of 1 or 2
10793@end ifnottex
10794
10795First, what happens if the value of the argument is 1?
10796
10797The function has an @code{if} expression after the documentation
10798string. It tests whether the value of @code{number} is equal to 1; if
10799so, Emacs evaluates the then-part of the @code{if} expression, which
10800returns the number 1 as the value of the function. (A triangle with
10801one row has one pebble in it.)
10802
10803Suppose, however, that the value of the argument is 2. In this case,
10804Emacs evaluates the else-part of the @code{if} expression.
10805
10806@need 1200
10807The else-part consists of an addition, the recursive call to
10808@code{triangle-recursively} and a decrementing action; and it looks like
10809this:
10810
10811@smallexample
10812(+ number (triangle-recursively (1- number)))
10813@end smallexample
10814
10815When Emacs evaluates this expression, the innermost expression is
10816evaluated first; then the other parts in sequence. Here are the steps
10817in detail:
10818
10819@table @i
10820@item Step 1 @w{ } Evaluate the innermost expression.
10821
10822The innermost expression is @code{(1- number)} so Emacs decrements the
10823value of @code{number} from 2 to 1.
10824
10825@item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
10826
10827The Lisp interpreter creates an individual instance of
10828@code{triangle-recursively}. It does not matter that this function is
10829contained within itself. Emacs passes the result Step 1 as the
10830argument used by this instance of the @code{triangle-recursively}
10831function
10832
10833In this case, Emacs evaluates @code{triangle-recursively} with an
10834argument of 1. This means that this evaluation of
10835@code{triangle-recursively} returns 1.
10836
10837@item Step 3 @w{ } Evaluate the value of @code{number}.
10838
10839The variable @code{number} is the second element of the list that
10840starts with @code{+}; its value is 2.
10841
10842@item Step 4 @w{ } Evaluate the @code{+} expression.
10843
10844The @code{+} expression receives two arguments, the first
10845from the evaluation of @code{number} (Step 3) and the second from the
10846evaluation of @code{triangle-recursively} (Step 2).
10847
10848The result of the addition is the sum of 2 plus 1, and the number 3 is
10849returned, which is correct. A triangle with two rows has three
10850pebbles in it.
10851@end table
10852
10853@node Recursive Example arg of 3 or 4, , Recursive Example arg of 1 or 2, Recursive triangle function
10854@unnumberedsubsubsec An argument of 3 or 4
10855
10856Suppose that @code{triangle-recursively} is called with an argument of
108573.
10858
10859@table @i
10860@item Step 1 @w{ } Evaluate the do-again-test.
10861
10862The @code{if} expression is evaluated first. This is the do-again
10863test and returns false, so the else-part of the @code{if} expression
10864is evaluated. (Note that in this example, the do-again-test causes
10865the function to call itself when it tests false, not when it tests
10866true.)
10867
10868@item Step 2 @w{ } Evaluate the innermost expression of the else-part.
10869
10870The innermost expression of the else-part is evaluated, which decrements
108713 to 2. This is the next-step-expression.
10872
10873@item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
10874
10875The number 2 is passed to the @code{triangle-recursively} function.
10876
10877We know what happens when Emacs evaluates @code{triangle-recursively} with
10878an argument of 2. After going through the sequence of actions described
10879earlier, it returns a value of 3. So that is what will happen here.
10880
10881@item Step 4 @w{ } Evaluate the addition.
10882
108833 will be passed as an argument to the addition and will be added to the
10884number with which the function was called, which is 3.
10885@end table
10886
10887@noindent
10888The value returned by the function as a whole will be 6.
10889
10890Now that we know what will happen when @code{triangle-recursively} is
10891called with an argument of 3, it is evident what will happen if it is
10892called with an argument of 4:
10893
10894@quotation
10895@need 800
10896In the recursive call, the evaluation of
10897
10898@smallexample
10899(triangle-recursively (1- 4))
10900@end smallexample
10901
10902@need 800
10903@noindent
10904will return the value of evaluating
10905
10906@smallexample
10907(triangle-recursively 3)
10908@end smallexample
10909
10910@noindent
10911which is 6 and this value will be added to 4 by the addition in the
10912third line.
10913@end quotation
10914
10915@noindent
10916The value returned by the function as a whole will be 10.
10917
10918Each time @code{triangle-recursively} is evaluated, it evaluates a
10919version of itself---a different instance of itself---with a smaller
10920argument, until the argument is small enough so that it does not
10921evaluate itself.
10922
10923Note that this particular design for a recursive function
10924requires that operations be deferred.
10925
10926Before @code{(triangle-recursively 7)} can calculate its answer, it
10927must call @code{(triangle-recursively 6)}; and before
10928@code{(triangle-recursively 6)} can calculate its answer, it must call
10929@code{(triangle-recursively 5)}; and so on. That is to say, the
10930calculation that @code{(triangle-recursively 7)} makes must be
10931deferred until @code{(triangle-recursively 6)} makes its calculation;
10932and @code{(triangle-recursively 6)} must defer until
10933@code{(triangle-recursively 5)} completes; and so on.
10934
10935If each of these instances of @code{triangle-recursively} are thought
10936of as different robots, the first robot must wait for the second to
10937complete its job, which must wait until the third completes, and so
10938on.
10939
10940There is a way around this kind of waiting, which we will discuss in
10941@ref{No Deferment, , Recursion without Deferments}.
10942
10943@node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10944@comment node-name, next, previous, up
10945@subsection Recursion Example Using @code{cond}
10946@findex cond
10947
10948The version of @code{triangle-recursively} described earlier is written
10949with the @code{if} special form. It can also be written using another
10950special form called @code{cond}. The name of the special form
10951@code{cond} is an abbreviation of the word @samp{conditional}.
10952
10953Although the @code{cond} special form is not used as often in the
10954Emacs Lisp sources as @code{if}, it is used often enough to justify
10955explaining it.
10956
10957@need 800
10958The template for a @code{cond} expression looks like this:
10959
10960@smallexample
10961@group
10962(cond
10963 @var{body}@dots{})
10964@end group
10965@end smallexample
10966
10967@noindent
10968where the @var{body} is a series of lists.
10969
10970@need 800
10971Written out more fully, the template looks like this:
10972
10973@smallexample
10974@group
10975(cond
10976 (@var{first-true-or-false-test} @var{first-consequent})
10977 (@var{second-true-or-false-test} @var{second-consequent})
10978 (@var{third-true-or-false-test} @var{third-consequent})
10979 @dots{})
10980@end group
10981@end smallexample
10982
10983When the Lisp interpreter evaluates the @code{cond} expression, it
10984evaluates the first element (the @sc{car} or true-or-false-test) of
10985the first expression in a series of expressions within the body of the
10986@code{cond}.
10987
10988If the true-or-false-test returns @code{nil} the rest of that
10989expression, the consequent, is skipped and the true-or-false-test of the
10990next expression is evaluated. When an expression is found whose
10991true-or-false-test returns a value that is not @code{nil}, the
10992consequent of that expression is evaluated. The consequent can be one
10993or more expressions. If the consequent consists of more than one
10994expression, the expressions are evaluated in sequence and the value of
10995the last one is returned. If the expression does not have a consequent,
10996the value of the true-or-false-test is returned.
10997
10998If none of the true-or-false-tests test true, the @code{cond} expression
10999returns @code{nil}.
11000
11001@need 1250
11002Written using @code{cond}, the @code{triangle} function looks like this:
11003
11004@smallexample
11005@group
11006(defun triangle-using-cond (number)
11007 (cond ((<= number 0) 0)
11008 ((= number 1) 1)
11009 ((> number 1)
11010 (+ number (triangle-using-cond (1- number))))))
11011@end group
11012@end smallexample
11013
11014@noindent
11015In this example, the @code{cond} returns 0 if the number is less than or
11016equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11017number (triangle-using-cond (1- number)))} if the number is greater than
110181.
11019
11020@node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11021@comment node-name, next, previous, up
11022@subsection Recursive Patterns
11023@cindex Recursive Patterns
11024
11025Here are three common recursive patterns. Each involves a list.
11026Recursion does not need to involve lists, but Lisp is designed for lists
11027and this provides a sense of its primal capabilities.
11028
11029@menu
11030* Every::
11031* Accumulate::
11032* Keep::
11033@end menu
11034
11035@node Every, Accumulate, Recursive Patterns, Recursive Patterns
11036@comment node-name, next, previous, up
11037@unnumberedsubsubsec Recursive Pattern: @emph{every}
11038@cindex Every, type of recursive pattern
11039@cindex Recursive pattern: every
11040
11041In the @code{every} recursive pattern, an action is performed on every
11042element of a list.
11043
11044@need 1500
11045The basic pattern is:
11046
11047@itemize @bullet
11048@item
11049If a list be empty, return @code{nil}.
11050@item
11051Else, act on the beginning of the list (the @sc{car} of the list)
11052 @itemize @minus
11053 @item
11054 through a recursive call by the function on the rest (the
11055 @sc{cdr}) of the list,
11056 @item
11057 and, optionally, combine the acted-on element, using @code{cons},
11058 with the results of acting on the rest.
11059 @end itemize
11060@end itemize
11061
11062@need 1500
11063Here is example:
11064
11065@smallexample
11066@group
11067(defun square-each (numbers-list)
11068 "Square each of a NUMBERS LIST, recursively."
11069 (if (not numbers-list) ; do-again-test
11070 nil
11071 (cons
11072 (* (car numbers-list) (car numbers-list))
11073 (square-each (cdr numbers-list))))) ; next-step-expression
11074@end group
11075
11076@group
11077(square-each '(1 2 3))
11078 @result{} (1 4 9)
11079@end group
11080@end smallexample
11081
11082@need 1200
11083@noindent
11084If @code{numbers-list} is empty, do nothing. But if it has content,
11085construct a list combining the square of the first number in the list
11086with the result of the recursive call.
11087
11088(The example follows the pattern exactly: @code{nil} is returned if
11089the numbers' list is empty. In practice, you would write the
11090conditional so it carries out the action when the numbers' list is not
11091empty.)
11092
11093The @code{print-elements-recursively} function (@pxref{Recursion with
11094list, , Recursion with a List}) is another example of an @code{every}
11095pattern, except in this case, rather than bring the results together
11096using @code{cons}, we print each element of output.
11097
11098@need 1250
11099The @code{print-elements-recursively} function looks like this:
11100
11101@smallexample
11102@group
11103(setq animals '(gazelle giraffe lion tiger))
11104@end group
11105
11106@group
11107(defun print-elements-recursively (list)
11108 "Print each element of LIST on a line of its own.
11109Uses recursion."
11110 (if list ; @r{do-again-test}
11111 (progn
11112 (print (car list)) ; @r{body}
11113 (print-elements-recursively ; @r{recursive call}
11114 (cdr list))))) ; @r{next-step-expression}
11115
11116(print-elements-recursively animals)
11117@end group
11118@end smallexample
11119
11120@need 1500
11121The pattern for @code{print-elements-recursively} is:
11122
11123@itemize @bullet
11124@item
11125If the list be empty, do nothing.
11126@item
11127But if the list has at least one element,
11128 @itemize @minus
11129 @item
11130 act on the beginning of the list (the @sc{car} of the list),
11131 @item
11132 and make a recursive call on the rest (the @sc{cdr}) of the list.
11133 @end itemize
11134@end itemize
11135
11136@node Accumulate, Keep, Every, Recursive Patterns
11137@comment node-name, next, previous, up
11138@unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11139@cindex Accumulate, type of recursive pattern
11140@cindex Recursive pattern: accumulate
11141
11142Another recursive pattern is called the @code{accumulate} pattern. In
11143the @code{accumulate} recursive pattern, an action is performed on
11144every element of a list and the result of that action is accumulated
11145with the results of performing the action on the other elements.
11146
11147This is very like the `every' pattern using @code{cons}, except that
11148@code{cons} is not used, but some other combiner.
11149
11150@need 1500
11151The pattern is:
11152
11153@itemize @bullet
11154@item
11155If a list be empty, return zero or some other constant.
11156@item
11157Else, act on the beginning of the list (the @sc{car} of the list),
11158 @itemize @minus
11159 @item
11160 and combine that acted-on element, using @code{+} or
11161 some other combining function, with
11162 @item
11163 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11164 @end itemize
11165@end itemize
11166
11167@need 1500
11168Here is an example:
11169
11170@smallexample
11171@group
11172(defun add-elements (numbers-list)
11173 "Add the elements of NUMBERS-LIST together."
11174 (if (not numbers-list)
11175 0
11176 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11177@end group
11178
11179@group
11180(add-elements '(1 2 3 4))
11181 @result{} 10
11182@end group
11183@end smallexample
11184
11185@xref{Files List, , Making a List of Files}, for an example of the
11186accumulate pattern.
11187
11188@node Keep, , Accumulate, Recursive Patterns
11189@comment node-name, next, previous, up
11190@unnumberedsubsubsec Recursive Pattern: @emph{keep}
11191@cindex Keep, type of recursive pattern
11192@cindex Recursive pattern: keep
11193
11194A third recursive pattern is called the @code{keep} pattern.
11195In the @code{keep} recursive pattern, each element of a list is tested;
11196the element is acted on and the results are kept only if the element
11197meets a criterion.
11198
11199Again, this is very like the `every' pattern, except the element is
11200skipped unless it meets a criterion.
11201
11202@need 1500
11203The pattern has three parts:
11204
11205@itemize @bullet
11206@item
11207If a list be empty, return @code{nil}.
11208@item
11209Else, if the beginning of the list (the @sc{car} of the list) passes
11210 a test
11211 @itemize @minus
11212 @item
11213 act on that element and combine it, using @code{cons} with
11214 @item
11215 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11216 @end itemize
11217@item
11218Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11219the test
11220 @itemize @minus
11221 @item
11222 skip on that element,
11223 @item
11224 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11225 @end itemize
11226@end itemize
11227
11228@need 1500
11229Here is an example that uses @code{cond}:
11230
11231@smallexample
11232@group
11233(defun keep-three-letter-words (word-list)
11234 "Keep three letter words in WORD-LIST."
11235 (cond
11236 ;; First do-again-test: stop-condition
11237 ((not word-list) nil)
11238
11239 ;; Second do-again-test: when to act
11240 ((eq 3 (length (symbol-name (car word-list))))
11241 ;; combine acted-on element with recursive call on shorter list
11242 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11243
11244 ;; Third do-again-test: when to skip element;
11245 ;; recursively call shorter list with next-step expression
11246 (t (keep-three-letter-words (cdr word-list)))))
11247@end group
11248
11249@group
11250(keep-three-letter-words '(one two three four five six))
11251 @result{} (one two six)
11252@end group
11253@end smallexample
11254
11255It goes without saying that you need not use @code{nil} as the test for
11256when to stop; and you can, of course, combine these patterns.
11257
11258@node No Deferment, No deferment solution, Recursive Patterns, Recursion
11259@subsection Recursion without Deferments
11260@cindex Deferment in recursion
11261@cindex Recursion without Deferments
11262
11263Let's consider again what happens with the @code{triangle-recursively}
11264function. We will find that the intermediate calculations are
11265deferred until all can be done.
11266
11267@need 800
11268Here is the function definition:
11269
11270@smallexample
11271@group
11272(defun triangle-recursively (number)
11273 "Return the sum of the numbers 1 through NUMBER inclusive.
11274Uses recursion."
11275 (if (= number 1) ; @r{do-again-test}
11276 1 ; @r{then-part}
11277 (+ number ; @r{else-part}
11278 (triangle-recursively ; @r{recursive call}
11279 (1- number))))) ; @r{next-step-expression}
11280@end group
11281@end smallexample
11282
11283What happens when we call this function with a argument of 7?
11284
11285The first instance of the @code{triangle-recursively} function adds
11286the number 7 to the value returned by a second instance of
11287@code{triangle-recursively}, an instance that has been passed an
11288argument of 6. That is to say, the first calculation is:
11289
11290@smallexample
b15dd613 11291(+ 7 (triangle-recursively 6))
8b096dce
EZ
11292@end smallexample
11293
11294@noindent
11295The first instance of @code{triangle-recursively}---you may want to
11296think of it as a little robot---cannot complete its job. It must hand
11297off the calculation for @code{(triangle-recursively 6)} to a second
11298instance of the program, to a second robot. This second individual is
11299completely different from the first one; it is, in the jargon, a
11300`different instantiation'. Or, put another way, it is a different
11301robot. It is the same model as the first; it calculates triangle
11302numbers recursively; but it has a different serial number.
11303
11304And what does @code{(triangle-recursively 6)} return? It returns the
11305number 6 added to the value returned by evaluating
11306@code{triangle-recursively} with an argument of 5. Using the robot
11307metaphor, it asks yet another robot to help it.
11308
11309@need 800
11310Now the total is:
11311
11312@smallexample
b15dd613 11313(+ 7 6 (triangle-recursively 5))
8b096dce
EZ
11314@end smallexample
11315
11316@need 800
11317And what happens next?
11318
11319@smallexample
b15dd613 11320(+ 7 6 5 (triangle-recursively 4))
8b096dce
EZ
11321@end smallexample
11322
11323Each time @code{triangle-recursively} is called, except for the last
11324time, it creates another instance of the program---another robot---and
11325asks it to make a calculation.
11326
11327@need 800
11328Eventually, the full addition is set up and performed:
11329
11330@smallexample
11331(+ 7 6 5 4 3 2 1)
11332@end smallexample
11333
11334This design for the function defers the calculation of the first step
11335until the second can be done, and defers that until the third can be
11336done, and so on. Each deferment means the computer must remember what
11337is being waited on. This is not a problem when there are only a few
11338steps, as in this example. But it can be a problem when there are
11339more steps.
11340
11341@node No deferment solution, , No Deferment, Recursion
11342@subsection No Deferment Solution
11343@cindex No deferment solution
11344@cindex Defermentless solution
11345@cindex Solution without deferment
11346
11347The solution to the problem of deferred operations is to write in a
11348manner that does not defer operations@footnote{The phrase @dfn{tail
11349recursive} is used to describe such a process, one that uses
11350`constant space'.}. This requires
11351writing to a different pattern, often one that involves writing two
11352function definitions, an `initialization' function and a `helper'
11353function.
11354
11355The `initialization' function sets up the job; the `helper' function
11356does the work.
11357
11358@need 1200
11359Here are the two function definitions for adding up numbers. They are
11360so simple, I find them hard to understand.
11361
11362@smallexample
11363@group
11364(defun triangle-initialization (number)
11365 "Return the sum of the numbers 1 through NUMBER inclusive.
11366This is the `initialization' component of a two function
11367duo that uses recursion."
11368 (triangle-recursive-helper 0 0 number))
11369@end group
11370@end smallexample
11371
11372@smallexample
11373@group
11374(defun triangle-recursive-helper (sum counter number)
11375 "Return SUM, using COUNTER, through NUMBER inclusive.
11376This is the `helper' component of a two function duo
11377that uses recursion."
11378 (if (> counter number)
11379 sum
11380 (triangle-recursive-helper (+ sum counter) ; @r{sum}
11381 (1+ counter) ; @r{counter}
11382 number))) ; @r{number}
11383@end group
11384@end smallexample
11385
11386@need 1250
11387Install both function definitions by evaluating them, then call
11388@code{triangle-initialization} with 2 rows:
11389
11390@smallexample
11391@group
11392(triangle-initialization 2)
11393 @result{} 3
11394@end group
11395@end smallexample
11396
11397The `initialization' function calls the first instance of the `helper'
11398function with three arguments: zero, zero, and a number which is the
11399number of rows in the triangle.
11400
11401The first two arguments passed to the `helper' function are
11402initialization values. These values are changed when
11403@code{triangle-recursive-helper} invokes new instances.@footnote{The
11404jargon is mildly confusing: @code{triangle-recursive-helper} uses a
11405process that is iterative in a procedure that is recursive. The
11406process is called iterative because the computer need only record the
11407three values, @code{sum}, @code{counter}, and @code{number}; the
11408procedure is recursive because the function `calls itself'. On the
11409other hand, both the process and the procedure used by
11410@code{triangle-recursively} are called recursive. The word
11411`recursive' has different meanings in the two contexts.}
11412
11413Let's see what happens when we have a triangle that has one row. (This
11414triangle will have one pebble in it!)
11415
11416@need 1200
11417@code{triangle-initialization} will call its helper with
11418the arguments @w{@code{0 0 1}}. That function will run the conditional
11419test whether @code{(> counter number)}:
11420
11421@smallexample
11422(> 0 1)
11423@end smallexample
11424
11425@need 1200
11426@noindent
11427and find that the result is false, so it will invoke
11428the then-part of the @code{if} clause:
11429
11430@smallexample
11431@group
11432 (triangle-recursive-helper
11433 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11434 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11435 number) ; @r{number stays the same}
11436@end group
11437@end smallexample
11438
11439@need 800
11440@noindent
11441which will first compute:
11442
11443@smallexample
11444@group
11445(triangle-recursive-helper (+ 0 0) ; @r{sum}
11446 (1+ 0) ; @r{counter}
11447 1) ; @r{number}
11448@exdent which is:
11449
11450(triangle-recursive-helper 0 1 1)
11451@end group
11452@end smallexample
11453
11454Again, @code{(> counter number)} will be false, so again, the Lisp
11455interpreter will evaluate @code{triangle-recursive-helper}, creating a
11456new instance with new arguments.
11457
11458@need 800
11459This new instance will be;
11460
11461@smallexample
11462@group
11463 (triangle-recursive-helper
11464 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11465 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11466 number) ; @r{number stays the same}
11467
11468@exdent which is:
11469
11470(triangle-recursive-helper 1 2 1)
11471@end group
11472@end smallexample
11473
11474In this case, the @code{(> counter number)} test will be true! So the
11475instance will return the value of the sum, which will be 1, as
11476expected.
11477
11478Now, let's pass @code{triangle-initialization} an argument
11479of 2, to find out how many pebbles there are in a triangle with two rows.
11480
11481That function calls @code{(triangle-recursive-helper 0 0 2)}.
11482
11483@need 800
11484In stages, the instances called will be:
11485
11486@smallexample
11487@group
11488 @r{sum counter number}
11489(triangle-recursive-helper 0 1 2)
11490
11491(triangle-recursive-helper 1 2 2)
11492
11493(triangle-recursive-helper 3 3 2)
11494@end group
11495@end smallexample
11496
11497When the last instance is called, the @code{(> counter number)} test
11498will be true, so the instance will return the value of @code{sum},
11499which will be 3.
11500
11501This kind of pattern helps when you are writing functions that can use
11502many resources in a computer.
11503
11504@need 1500
11505@node Looping exercise, , Recursion, Loops & Recursion
11506@section Looping Exercise
11507
11508@itemize @bullet
11509@item
11510Write a function similar to @code{triangle} in which each row has a
11511value which is the square of the row number. Use a @code{while} loop.
11512
11513@item
11514Write a function similar to @code{triangle} that multiplies instead of
11515adds the values.
11516
11517@item
11518Rewrite these two functions recursively. Rewrite these functions
11519using @code{cond}.
11520
11521@c comma in printed title causes problem in Info cross reference
11522@item
11523Write a function for Texinfo mode that creates an index entry at the
11524beginning of a paragraph for every @samp{@@dfn} within the paragraph.
11525(In a Texinfo file, @samp{@@dfn} marks a definition. For more
11526information, see
11527@ifinfo
11528@ref{Indicating, , Indicating Definitions, texinfo}.)
11529@end ifinfo
11530@ifhtml
11531@ref{Indicating, , Indicating, texinfo, Texinfo Manual}.)
11532@end ifhtml
11533@iftex
11534``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
11535Documentation Format}.)
11536@end iftex
11537@end itemize
11538
11539@node Regexp Search, Counting Words, Loops & Recursion, Top
11540@comment node-name, next, previous, up
11541@chapter Regular Expression Searches
11542@cindex Searches, illustrating
11543@cindex Regular expression searches
11544@cindex Patterns, searching for
11545@cindex Motion by sentence and paragraph
11546@cindex Sentences, movement by
11547@cindex Paragraphs, movement by
11548
11549Regular expression searches are used extensively in GNU Emacs. The
11550two functions, @code{forward-sentence} and @code{forward-paragraph},
11551illustrate these searches well. They use regular expressions to find
11552where to move point. The phrase `regular expression' is often written
11553as `regexp'.
11554
11555Regular expression searches are described in @ref{Regexp Search, ,
11556Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11557@ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11558Manual}. In writing this chapter, I am presuming that you have at
11559least a mild acquaintance with them. The major point to remember is
11560that regular expressions permit you to search for patterns as well as
11561for literal strings of characters. For example, the code in
11562@code{forward-sentence} searches for the pattern of possible
11563characters that could mark the end of a sentence, and moves point to
11564that spot.
11565
11566Before looking at the code for the @code{forward-sentence} function, it
11567is worth considering what the pattern that marks the end of a sentence
11568must be. The pattern is discussed in the next section; following that
11569is a description of the regular expression search function,
11570@code{re-search-forward}. The @code{forward-sentence} function
11571is described in the section following. Finally, the
11572@code{forward-paragraph} function is described in the last section of
11573this chapter. @code{forward-paragraph} is a complex function that
11574introduces several new features.
11575
11576@menu
11577* sentence-end:: The regular expression for @code{sentence-end}.
11578* re-search-forward:: Very similar to @code{search-forward}.
11579* forward-sentence:: A straightforward example of regexp search.
11580* forward-paragraph:: A somewhat complex example.
11581* etags:: How to create your own @file{TAGS} table.
11582* Regexp Review::
11583* re-search Exercises::
11584@end menu
11585
11586@node sentence-end, re-search-forward, Regexp Search, Regexp Search
11587@comment node-name, next, previous, up
11588@section The Regular Expression for @code{sentence-end}
11589@findex sentence-end
11590
11591The symbol @code{sentence-end} is bound to the pattern that marks the
11592end of a sentence. What should this regular expression be?
11593
11594Clearly, a sentence may be ended by a period, a question mark, or an
11595exclamation mark. Indeed, only clauses that end with one of those three
11596characters should be considered the end of a sentence. This means that
11597the pattern should include the character set:
11598
11599@smallexample
11600[.?!]
11601@end smallexample
11602
11603However, we do not want @code{forward-sentence} merely to jump to a
11604period, a question mark, or an exclamation mark, because such a character
11605might be used in the middle of a sentence. A period, for example, is
11606used after abbreviations. So other information is needed.
11607
11608According to convention, you type two spaces after every sentence, but
11609only one space after a period, a question mark, or an exclamation mark in
11610the body of a sentence. So a period, a question mark, or an exclamation
11611mark followed by two spaces is a good indicator of an end of sentence.
11612However, in a file, the two spaces may instead be a tab or the end of a
11613line. This means that the regular expression should include these three
11614items as alternatives.
11615
11616@need 800
11617This group of alternatives will look like this:
11618
11619@smallexample
11620@group
11621\\($\\| \\| \\)
11622 ^ ^^
11623 TAB SPC
11624@end group
11625@end smallexample
11626
11627@noindent
11628Here, @samp{$} indicates the end of the line, and I have pointed out
11629where the tab and two spaces are inserted in the expression. Both are
11630inserted by putting the actual characters into the expression.
11631
11632Two backslashes, @samp{\\}, are required before the parentheses and
11633vertical bars: the first backslash quotes the following backslash in
11634Emacs; and the second indicates that the following character, the
11635parenthesis or the vertical bar, is special.
11636
11637@need 1000
11638Also, a sentence may be followed by one or more carriage returns, like
11639this:
11640
11641@smallexample
11642@group
11643[
11644]*
11645@end group
11646@end smallexample
11647
11648@noindent
11649Like tabs and spaces, a carriage return is inserted into a regular
11650expression by inserting it literally. The asterisk indicates that the
11651@key{RET} is repeated zero or more times.
11652
11653But a sentence end does not consist only of a period, a question mark or
11654an exclamation mark followed by appropriate space: a closing quotation
11655mark or a closing brace of some kind may precede the space. Indeed more
11656than one such mark or brace may precede the space. These require a
11657expression that looks like this:
11658
11659@smallexample
11660[]\"')@}]*
11661@end smallexample
11662
11663In this expression, the first @samp{]} is the first character in the
11664expression; the second character is @samp{"}, which is preceded by a
11665@samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
11666three characters are @samp{'}, @samp{)}, and @samp{@}}.
11667
11668All this suggests what the regular expression pattern for matching the
11669end of a sentence should be; and, indeed, if we evaluate
11670@code{sentence-end} we find that it returns the following value:
11671
11672@smallexample
11673@group
11674sentence-end
11675 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
11676]*"
11677@end group
11678@end smallexample
11679
11680@ignore
11681
11682@noindent
11683(Note that here the @key{TAB}, two spaces, and @key{RET} are shown
11684literally in the pattern.)
11685
11686This regular expression can be decyphered as follows:
11687
11688@table @code
11689@item [.?!]
11690The first part of the pattern is the three characters, a period, a question
11691mark and an exclamation mark, within square brackets. The pattern must
11692begin with one or other of these characters.
11693
11694@item []\"')@}]*
11695The second part of the pattern is the group of closing braces and
11696quotation marks, which can appear zero or more times. These may follow
11697the period, question mark or exclamation mark. In a regular expression,
11698the backslash, @samp{\}, followed by the double quotation mark,
11699@samp{"}, indicates the class of string-quote characters. Usually, the
11700double quotation mark is the only character in this class. The
11701asterisk, @samp{*}, indicates that the items in the previous group (the
11702group surrounded by square brackets, @samp{[]}) may be repeated zero or
11703more times.
11704
11705@item \\($\\| \\| \\)
11706The third part of the pattern is one or other of: either the end of a
11707line, or two blank spaces, or a tab. The double back-slashes are used
11708to prevent Emacs from reading the parentheses and vertical bars as part
11709of the search pattern; the parentheses are used to mark the group and
11710the vertical bars are used to indicated that the patterns to either side
11711of them are alternatives. The dollar sign is used to indicate the end
11712of a line and both the two spaces and the tab are each inserted as is to
11713indicate what they are.
11714
11715@item [@key{RET}]*
11716Finally, the last part of the pattern indicates that the end of the line
11717or the whitespace following the period, question mark or exclamation
11718mark may, but need not, be followed by one or more carriage returns. In
11719the pattern, the carriage return is inserted as an actual carriage
11720return between square brackets but here it is shown as @key{RET}.
11721@end table
11722
11723@end ignore
11724
11725@node re-search-forward, forward-sentence, sentence-end, Regexp Search
11726@comment node-name, next, previous, up
11727@section The @code{re-search-forward} Function
11728@findex re-search-forward
11729
11730The @code{re-search-forward} function is very like the
11731@code{search-forward} function. (@xref{search-forward, , The
11732@code{search-forward} Function}.)
11733
11734@code{re-search-forward} searches for a regular expression. If the
11735search is successful, it leaves point immediately after the last
11736character in the target. If the search is backwards, it leaves point
11737just before the first character in the target. You may tell
11738@code{re-search-forward} to return @code{t} for true. (Moving point
11739is therefore a `side effect'.)
11740
11741Like @code{search-forward}, the @code{re-search-forward} function takes
11742four arguments:
11743
11744@enumerate
11745@item
11746The first argument is the regular expression that the function searches
11747for. The regular expression will be a string between quotations marks.
11748
11749@item
11750The optional second argument limits how far the function will search; it is a
11751bound, which is specified as a position in the buffer.
11752
11753@item
11754The optional third argument specifies how the function responds to
11755failure: @code{nil} as the third argument causes the function to
11756signal an error (and print a message) when the search fails; any other
11757value causes it to return @code{nil} if the search fails and @code{t}
11758if the search succeeds.
11759
11760@item
11761The optional fourth argument is the repeat count. A negative repeat
11762count causes @code{re-search-forward} to search backwards.
11763@end enumerate
11764
11765@need 800
11766The template for @code{re-search-forward} looks like this:
11767
11768@smallexample
11769@group
11770(re-search-forward "@var{regular-expression}"
11771 @var{limit-of-search}
11772 @var{what-to-do-if-search-fails}
11773 @var{repeat-count})
11774@end group
11775@end smallexample
11776
11777The second, third, and fourth arguments are optional. However, if you
11778want to pass a value to either or both of the last two arguments, you
11779must also pass a value to all the preceding arguments. Otherwise, the
11780Lisp interpreter will mistake which argument you are passing the value
11781to.
11782
11783@need 1200
11784In the @code{forward-sentence} function, the regular expression will be
11785the value of the variable @code{sentence-end}, namely:
11786
11787@smallexample
11788@group
11789"[.?!][]\"')@}]*\\($\\| \\| \\)[
11790]*"
11791@end group
11792@end smallexample
11793
11794@noindent
11795The limit of the search will be the end of the paragraph (since a
11796sentence cannot go beyond a paragraph). If the search fails, the
11797function will return @code{nil}; and the repeat count will be provided
11798by the argument to the @code{forward-sentence} function.
11799
11800@node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11801@comment node-name, next, previous, up
11802@section @code{forward-sentence}
11803@findex forward-sentence
11804
11805The command to move the cursor forward a sentence is a straightforward
11806illustration of how to use regular expression searches in Emacs Lisp.
11807Indeed, the function looks longer and more complicated than it is; this
11808is because the function is designed to go backwards as well as forwards;
11809and, optionally, over more than one sentence. The function is usually
11810bound to the key command @kbd{M-e}.
11811
11812@menu
11813* Complete forward-sentence::
11814* fwd-sentence while loops:: Two @code{while} loops.
11815* fwd-sentence re-search:: A regular expression search.
11816@end menu
11817
11818@node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11819@ifnottex
11820@unnumberedsubsec Complete @code{forward-sentence} function definition
11821@end ifnottex
11822
11823@need 1250
11824Here is the code for @code{forward-sentence}:
11825
11826@smallexample
11827@group
11828(defun forward-sentence (&optional arg)
11829 "Move forward to next sentence-end. With argument, repeat.
11830With negative argument, move backward repeatedly to sentence-beginning.
11831Sentence ends are identified by the value of sentence-end
11832treated as a regular expression. Also, every paragraph boundary
11833terminates sentences as well."
11834@end group
11835@group
11836 (interactive "p")
11837 (or arg (setq arg 1))
11838 (while (< arg 0)
11839 (let ((par-beg
11840 (save-excursion (start-of-paragraph-text) (point))))
11841 (if (re-search-backward
11842 (concat sentence-end "[^ \t\n]") par-beg t)
11843 (goto-char (1- (match-end 0)))
11844 (goto-char par-beg)))
11845 (setq arg (1+ arg)))
11846 (while (> arg 0)
11847 (let ((par-end
11848 (save-excursion (end-of-paragraph-text) (point))))
11849 (if (re-search-forward sentence-end par-end t)
11850 (skip-chars-backward " \t\n")
11851 (goto-char par-end)))
11852 (setq arg (1- arg))))
11853@end group
11854@end smallexample
11855
11856The function looks long at first sight and it is best to look at its
11857skeleton first, and then its muscle. The way to see the skeleton is to
11858look at the expressions that start in the left-most columns:
11859
11860@smallexample
11861@group
11862(defun forward-sentence (&optional arg)
11863 "@var{documentation}@dots{}"
11864 (interactive "p")
11865 (or arg (setq arg 1))
11866 (while (< arg 0)
11867 @var{body-of-while-loop}
11868 (while (> arg 0)
11869 @var{body-of-while-loop}
11870@end group
11871@end smallexample
11872
11873This looks much simpler! The function definition consists of
11874documentation, an @code{interactive} expression, an @code{or}
11875expression, and @code{while} loops.
11876
11877Let's look at each of these parts in turn.
11878
11879We note that the documentation is thorough and understandable.
11880
11881The function has an @code{interactive "p"} declaration. This means
11882that the processed prefix argument, if any, is passed to the
11883function as its argument. (This will be a number.) If the function
11884is not passed an argument (it is optional) then the argument
11885@code{arg} will be bound to 1. When @code{forward-sentence} is called
11886non-interactively without an argument, @code{arg} is bound to
11887@code{nil}.
11888
11889The @code{or} expression handles the prefix argument. What it does is
11890either leave the value of @code{arg} as it is, but only if @code{arg}
11891is bound to a value; or it sets the value of @code{arg} to 1, in the
11892case when @code{arg} is bound to @code{nil}.
11893
11894@node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11895@unnumberedsubsec The @code{while} loops
11896
11897Two @code{while} loops follow the @code{or} expression. The first
11898@code{while} has a true-or-false-test that tests true if the prefix
11899argument for @code{forward-sentence} is a negative number. This is for
11900going backwards. The body of this loop is similar to the body of the
11901second @code{while} clause, but it is not exactly the same. We will
11902skip this @code{while} loop and concentrate on the second @code{while}
11903loop.
11904
11905@need 1500
11906The second @code{while} loop is for moving point forward. Its skeleton
11907looks like this:
11908
11909@smallexample
11910@group
11911(while (> arg 0) ; @r{true-or-false-test}
11912 (let @var{varlist}
11913 (if (@var{true-or-false-test})
11914 @var{then-part}
11915 @var{else-part}
11916 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
11917@end group
11918@end smallexample
11919
11920The @code{while} loop is of the decrementing kind.
11921(@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
11922has a true-or-false-test that tests true so long as the counter (in
11923this case, the variable @code{arg}) is greater than zero; and it has a
11924decrementer that subtracts 1 from the value of the counter every time
11925the loop repeats.
11926
11927If no prefix argument is given to @code{forward-sentence}, which is
11928the most common way the command is used, this @code{while} loop will
11929run once, since the value of @code{arg} will be 1.
11930
11931The body of the @code{while} loop consists of a @code{let} expression,
11932which creates and binds a local variable, and has, as its body, an
11933@code{if} expression.
11934
11935@need 1250
11936The body of the @code{while} loop looks like this:
11937
11938@smallexample
11939@group
11940(let ((par-end
11941 (save-excursion (end-of-paragraph-text) (point))))
11942 (if (re-search-forward sentence-end par-end t)
11943 (skip-chars-backward " \t\n")
11944 (goto-char par-end)))
11945@end group
11946@end smallexample
11947
11948The @code{let} expression creates and binds the local variable
11949@code{par-end}. As we shall see, this local variable is designed to
11950provide a bound or limit to the regular expression search. If the
11951search fails to find a proper sentence ending in the paragraph, it will
11952stop on reaching the end of the paragraph.
11953
11954But first, let us examine how @code{par-end} is bound to the value of
11955the end of the paragraph. What happens is that the @code{let} sets the
11956value of @code{par-end} to the value returned when the Lisp interpreter
11957evaluates the expression
11958
11959@smallexample
11960@group
11961(save-excursion (end-of-paragraph-text) (point))
11962@end group
11963@end smallexample
11964
11965@noindent
11966In this expression, @code{(end-of-paragraph-text)} moves point to the
11967end of the paragraph, @code{(point)} returns the value of point, and then
11968@code{save-excursion} restores point to its original position. Thus,
11969the @code{let} binds @code{par-end} to the value returned by the
11970@code{save-excursion} expression, which is the position of the end of
11971the paragraph. (The @code{(end-of-paragraph-text)} function uses
11972@code{forward-paragraph}, which we will discuss shortly.)
11973
11974@need 1200
11975Emacs next evaluates the body of the @code{let}, which is an @code{if}
11976expression that looks like this:
11977
11978@smallexample
11979@group
11980(if (re-search-forward sentence-end par-end t) ; @r{if-part}
11981 (skip-chars-backward " \t\n") ; @r{then-part}
11982 (goto-char par-end))) ; @r{else-part}
11983@end group
11984@end smallexample
11985
11986The @code{if} tests whether its first argument is true and if so,
11987evaluates its then-part; otherwise, the Emacs Lisp interpreter
11988evaluates the else-part. The true-or-false-test of the @code{if}
11989expression is the regular expression search.
11990
11991It may seem odd to have what looks like the `real work' of
11992the @code{forward-sentence} function buried here, but this is a common
11993way this kind of operation is carried out in Lisp.
11994
11995@node fwd-sentence re-search, , fwd-sentence while loops, forward-sentence
11996@unnumberedsubsec The regular expression search
11997
11998The @code{re-search-forward} function searches for the end of the
11999sentence, that is, for the pattern defined by the @code{sentence-end}
12000regular expression. If the pattern is found---if the end of the sentence is
12001found---then the @code{re-search-forward} function does two things:
12002
12003@enumerate
12004@item
12005The @code{re-search-forward} function carries out a side effect, which
12006is to move point to the end of the occurrence found.
12007
12008@item
12009The @code{re-search-forward} function returns a value of true. This is
12010the value received by the @code{if}, and means that the search was
12011successful.
12012@end enumerate
12013
12014@noindent
12015The side effect, the movement of point, is completed before the
12016@code{if} function is handed the value returned by the successful
12017conclusion of the search.
12018
12019When the @code{if} function receives the value of true from a successful
12020call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12021which is the expression @code{(skip-chars-backward " \t\n")}. This
12022expression moves backwards over any blank spaces, tabs or carriage
12023returns until a printed character is found and then leaves point after
12024the character. Since point has already been moved to the end of the
12025pattern that marks the end of the sentence, this action leaves point
12026right after the closing printed character of the sentence, which is
12027usually a period.
12028
12029On the other hand, if the @code{re-search-forward} function fails to
12030find a pattern marking the end of the sentence, the function returns
12031false. The false then causes the @code{if} to evaluate its third
12032argument, which is @code{(goto-char par-end)}: it moves point to the
12033end of the paragraph.
12034
12035Regular expression searches are exceptionally useful and the pattern
12036illustrated by @code{re-search-forward}, in which the search is the
12037test of an @code{if} expression, is handy. You will see or write code
12038incorporating this pattern often.
12039
12040@node forward-paragraph, etags, forward-sentence, Regexp Search
12041@comment node-name, next, previous, up
12042@section @code{forward-paragraph}: a Goldmine of Functions
12043@findex forward-paragraph
12044
12045The @code{forward-paragraph} function moves point forward to the end
12046of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12047number of functions that are important in themselves, including
12048@code{let*}, @code{match-beginning}, and @code{looking-at}.
12049
12050The function definition for @code{forward-paragraph} is considerably
12051longer than the function definition for @code{forward-sentence}
12052because it works with a paragraph, each line of which may begin with a
12053fill prefix.
12054
12055A fill prefix consists of a string of characters that are repeated at
12056the beginning of each line. For example, in Lisp code, it is a
12057convention to start each line of a paragraph-long comment with
12058@samp{;;; }. In Text mode, four blank spaces make up another common
12059fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
12060emacs, The GNU Emacs Manual}, for more information about fill
12061prefixes.)
12062
12063The existence of a fill prefix means that in addition to being able to
12064find the end of a paragraph whose lines begin on the left-most
12065column, the @code{forward-paragraph} function must be able to find the
12066end of a paragraph when all or many of the lines in the buffer begin
12067with the fill prefix.
12068
12069Moreover, it is sometimes practical to ignore a fill prefix that
12070exists, especially when blank lines separate paragraphs.
12071This is an added complication.
12072
12073@menu
12074* forward-paragraph in brief:: Key parts of the function definition.
12075* fwd-para let:: The @code{let*} expression.
12076* fwd-para while:: The forward motion @code{while} loop.
12077* fwd-para between paragraphs:: Movement between paragraphs.
12078* fwd-para within paragraph:: Movement within paragraphs.
12079* fwd-para no fill prefix:: When there is no fill prefix.
12080* fwd-para with fill prefix:: When there is a fill prefix.
12081* fwd-para summary:: Summary of @code{forward-paragraph} code.
12082@end menu
12083
12084@node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12085@ifnottex
12086@unnumberedsubsec Shortened @code{forward-paragraph} function definition
12087@end ifnottex
12088
12089Rather than print all of the @code{forward-paragraph} function, we
12090will only print parts of it. Read without preparation, the function
12091can be daunting!
12092
12093@need 800
12094In outline, the function looks like this:
12095
12096@smallexample
12097@group
12098(defun forward-paragraph (&optional arg)
12099 "@var{documentation}@dots{}"
12100 (interactive "p")
12101 (or arg (setq arg 1))
12102 (let*
12103 @var{varlist}
12104 (while (< arg 0) ; @r{backward-moving-code}
12105 @dots{}
12106 (setq arg (1+ arg)))
12107 (while (> arg 0) ; @r{forward-moving-code}
12108 @dots{}
12109 (setq arg (1- arg)))))
12110@end group
12111@end smallexample
12112
12113The first parts of the function are routine: the function's argument
12114list consists of one optional argument. Documentation follows.
12115
12116The lower case @samp{p} in the @code{interactive} declaration means
12117that the processed prefix argument, if any, is passed to the function.
12118This will be a number, and is the repeat count of how many paragraphs
12119point will move. The @code{or} expression in the next line handles
12120the common case when no argument is passed to the function, which occurs
12121if the function is called from other code rather than interactively.
12122This case was described earlier. (@xref{forward-sentence, The
12123@code{forward-sentence} function}.) Now we reach the end of the
12124familiar part of this function.
12125
12126@node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12127@unnumberedsubsec The @code{let*} expression
12128
12129The next line of the @code{forward-paragraph} function begins a
12130@code{let*} expression. This is a different kind of expression than
12131we have seen so far. The symbol is @code{let*} not @code{let}.
12132
12133The @code{let*} special form is like @code{let} except that Emacs sets
12134each variable in sequence, one after another, and variables in the
12135latter part of the varlist can make use of the values to which Emacs
12136set variables in the earlier part of the varlist.
12137
12138In the @code{let*} expression in this function, Emacs binds two
12139variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12140The value to which @code{paragraph-separate} is bound depends on the
12141value of @code{fill-prefix-regexp}.
12142
12143@need 1200
12144Let's look at each in turn. The symbol @code{fill-prefix-regexp} is
12145set to the value returned by evaluating the following list:
12146
12147@smallexample
12148@group
12149(and fill-prefix
12150 (not (equal fill-prefix ""))
12151 (not paragraph-ignore-fill-prefix)
12152 (regexp-quote fill-prefix))
12153@end group
12154@end smallexample
12155
12156@noindent
12157This is an expression whose first element is the @code{and} special form.
12158
12159As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12160function}), the @code{and} special form evaluates each of its
12161arguments until one of the arguments returns a value of @code{nil}, in
12162which case the @code{and} expression returns @code{nil}; however, if
12163none of the arguments returns a value of @code{nil}, the value
12164resulting from evaluating the last argument is returned. (Since such
12165a value is not @code{nil}, it is considered true in Lisp.) In other
12166words, an @code{and} expression returns a true value only if all its
12167arguments are true.
12168@findex and
12169
12170In this case, the variable @code{fill-prefix-regexp} is bound to a
12171non-@code{nil} value only if the following four expressions produce a
12172true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12173@code{fill-prefix-regexp} is bound to @code{nil}.
12174
12175@table @code
12176@item fill-prefix
12177When this variable is evaluated, the value of the fill prefix, if any,
12178is returned. If there is no fill prefix, this variable returns
12179@code{nil}.
12180
12181@item (not (equal fill-prefix "")
12182This expression checks whether an existing fill prefix is an empty
12183string, that is, a string with no characters in it. An empty string is
12184not a useful fill prefix.
12185
12186@item (not paragraph-ignore-fill-prefix)
12187This expression returns @code{nil} if the variable
12188@code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12189true value such as @code{t}.
12190
12191@item (regexp-quote fill-prefix)
12192This is the last argument to the @code{and} special form. If all the
12193arguments to the @code{and} are true, the value resulting from
12194evaluating this expression will be returned by the @code{and} expression
12195and bound to the variable @code{fill-prefix-regexp},
12196@end table
12197
12198@findex regexp-quote
12199@noindent
12200The result of evaluating this @code{and} expression successfully is that
12201@code{fill-prefix-regexp} will be bound to the value of
12202@code{fill-prefix} as modified by the @code{regexp-quote} function.
12203What @code{regexp-quote} does is read a string and return a regular
12204expression that will exactly match the string and match nothing else.
12205This means that @code{fill-prefix-regexp} will be set to a value that
12206will exactly match the fill prefix if the fill prefix exists.
12207Otherwise, the variable will be set to @code{nil}.
12208
12209The second local variable in the @code{let*} expression is
12210@code{paragraph-separate}. It is bound to the value returned by
12211evaluating the expression:
12212
12213@smallexample
12214@group
12215(if fill-prefix-regexp
12216 (concat paragraph-separate
12217 "\\|^" fill-prefix-regexp "[ \t]*$")
12218 paragraph-separate)))
12219@end group
12220@end smallexample
12221
12222This expression shows why @code{let*} rather than @code{let} was used.
12223The true-or-false-test for the @code{if} depends on whether the variable
12224@code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12225
12226If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12227the else-part of the @code{if} expression and binds
12228@code{paragraph-separate} to its local value.
12229(@code{paragraph-separate} is a regular expression that matches what
12230separates paragraphs.)
12231
12232But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12233the then-part of the @code{if} expression and binds
12234@code{paragraph-separate} to a regular expression that includes the
12235@code{fill-prefix-regexp} as part of the pattern.
12236
12237Specifically, @code{paragraph-separate} is set to the original value
12238of the paragraph separate regular expression concatenated with an
12239alternative expression that consists of the @code{fill-prefix-regexp}
12240followed by a blank line. The @samp{^} indicates that the
12241@code{fill-prefix-regexp} must begin a line, and the optional
12242whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12243The @samp{\\|} defines this portion of the regexp as an alternative to
12244@code{paragraph-separate}.
12245
12246Now we get into the body of the @code{let*}. The first part of the body
12247of the @code{let*} deals with the case when the function is given a
12248negative argument and is therefore moving backwards. We will skip this
12249section.
12250
12251@node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12252@unnumberedsubsec The forward motion @code{while} loop
12253
12254The second part of the body of the @code{let*} deals with forward
12255motion. It is a @code{while} loop that repeats itself so long as the
12256value of @code{arg} is greater than zero. In the most common use of
12257the function, the value of the argument is 1, so the body of the
12258@code{while} loop is evaluated exactly once, and the cursor moves
12259forward one paragraph.
12260
12261This part handles three situations: when point is between paragraphs,
12262when point is within a paragraph and there is a fill prefix, and
12263when point is within a paragraph and there is no fill prefix.
12264
12265@need 800
12266The @code{while} loop looks like this:
12267
12268@smallexample
12269@group
12270(while (> arg 0)
12271 (beginning-of-line)
12272
12273 ;; @r{between paragraphs}
12274 (while (prog1 (and (not (eobp))
12275 (looking-at paragraph-separate))
12276 (forward-line 1)))
12277@end group
12278
12279@group
12280 ;; @r{within paragraphs, with a fill prefix}
12281 (if fill-prefix-regexp
12282 ;; @r{There is a fill prefix; it overrides paragraph-start.}
12283 (while (and (not (eobp))
12284 (not (looking-at paragraph-separate))
12285 (looking-at fill-prefix-regexp))
12286 (forward-line 1))
12287@end group
12288
12289@group
12290 ;; @r{within paragraphs, no fill prefix}
12291 (if (re-search-forward paragraph-start nil t)
12292 (goto-char (match-beginning 0))
12293 (goto-char (point-max))))
12294
12295 (setq arg (1- arg)))
12296@end group
12297@end smallexample
12298
12299We can see immediately that this is a decrementing counter @code{while}
12300loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12301
12302@need 800
12303The body of the loop consists of three expressions:
12304
12305@smallexample
12306@group
12307;; @r{between paragraphs}
12308(beginning-of-line)
12309(while
12310 @var{body-of-while})
12311@end group
12312
12313@group
12314;; @r{within paragraphs, with fill prefix}
12315(if @var{true-or-false-test}
12316 @var{then-part}
12317@end group
12318
12319@group
12320;; @r{within paragraphs, no fill prefix}
12321 @var{else-part}
12322@end group
12323@end smallexample
12324
12325@noindent
12326When the Emacs Lisp interpreter evaluates the body of the
12327@code{while} loop, the first thing it does is evaluate the
12328@code{(beginning-of-line)} expression and move point to the beginning
12329of the line. Then there is an inner @code{while} loop. This
12330@code{while} loop is designed to move the cursor out of the blank
12331space between paragraphs, if it should happen to be there. Finally,
12332there is an @code{if} expression that actually moves point to the end
12333of the paragraph.
12334
12335@node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12336@unnumberedsubsec Between paragraphs
12337
12338First, let us look at the inner @code{while} loop. This loop handles
12339the case when point is between paragraphs; it uses three functions
12340that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12341@findex prog1
12342@findex eobp
12343@findex looking-at
12344
12345@itemize @bullet
12346@item
12347@code{prog1} is similar to the @code{progn} special form,
12348except that @code{prog1} evaluates its arguments in sequence and then
12349returns the value of its first argument as the value of the whole
12350expression. (@code{progn} returns the value of its last argument as the
12351value of the expression.) The second and subsequent arguments to
12352@code{prog1} are evaluated only for their side effects.
12353
12354@item
12355@code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12356function that returns true if point is at the end of the buffer.
12357
12358@item
12359@code{looking-at} is a function that returns true if the text following
12360point matches the regular expression passed @code{looking-at} as its
12361argument.
12362@end itemize
12363
12364@need 800
12365The @code{while} loop we are studying looks like this:
12366
12367@smallexample
12368@group
12369(while (prog1 (and (not (eobp))
12370 (looking-at paragraph-separate))
12371 (forward-line 1)))
12372@end group
12373@end smallexample
12374
12375@need 1200
12376@noindent
12377This is a @code{while} loop with no body! The true-or-false-test of the
12378loop is the expression:
12379
12380@smallexample
12381@group
12382(prog1 (and (not (eobp))
12383 (looking-at paragraph-separate))
12384 (forward-line 1))
12385@end group
12386@end smallexample
12387
12388@noindent
12389The first argument to the @code{prog1} is the @code{and} expression. It
12390has within in it a test of whether point is at the end of the buffer and
12391also a test of whether the pattern following point matches the regular
12392expression for separating paragraphs.
12393
12394If the cursor is not at the end of the buffer and if the characters
12395following the cursor mark the separation between two paragraphs, then
12396the @code{and} expression is true. After evaluating the @code{and}
12397expression, the Lisp interpreter evaluates the second argument to
12398@code{prog1}, which is @code{forward-line}. This moves point forward
12399one line. The value returned by the @code{prog1} however, is the
12400value of its first argument, so the @code{while} loop continues so
12401long as point is not at the end of the buffer and is between
12402paragraphs. When, finally, point is moved to a paragraph, the
12403@code{and} expression tests false. Note however, that the
12404@code{forward-line} command is carried out anyhow. This means that
12405when point is moved from between paragraphs to a paragraph, it is left
12406at the beginning of the second line of the paragraph.
12407
12408@node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12409@unnumberedsubsec Within paragraphs
12410
12411The next expression in the outer @code{while} loop is an @code{if}
12412expression. The Lisp interpreter evaluates the then-part of the
12413@code{if} when the @code{fill-prefix-regexp} variable has a value other
12414than @code{nil}, and it evaluates the else-part when the value of
12415@code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12416fill prefix.
12417
12418@node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12419@unnumberedsubsec No fill prefix
12420
12421It is simplest to look at the code for the case when there is no fill
12422prefix first. This code consists of yet another inner @code{if}
12423expression, and reads as follows:
12424
12425@smallexample
12426@group
12427(if (re-search-forward paragraph-start nil t)
12428 (goto-char (match-beginning 0))
12429 (goto-char (point-max)))
12430@end group
12431@end smallexample
12432
12433@noindent
12434This expression actually does the work that most people think of as
12435the primary purpose of the @code{forward-paragraph} command: it causes
12436a regular expression search to occur that searches forward to the
12437start of the next paragraph and if it is found, moves point there; but
12438if the start of another paragraph if not found, it moves point to the
12439end of the accessible region of the buffer.
12440
12441The only unfamiliar part of this is the use of @code{match-beginning}.
12442This is another function that is new to us. The
12443@code{match-beginning} function returns a number specifying the
12444location of the start of the text that was matched by the last regular
12445expression search.
12446
12447The @code{match-beginning} function is used here because of a
12448characteristic of a forward search: a successful forward search,
12449regardless of whether it is a plain search or a regular expression
12450search, will move point to the end of the text that is found. In this
12451case, a successful search will move point to the end of the pattern for
12452@code{paragraph-start}, which will be the beginning of the next
12453paragraph rather than the end of the current one.
12454
12455However, we want to put point at the end of the current paragraph, not at
12456the beginning of the next one. The two positions may be different,
12457because there may be several blank lines between paragraphs.
12458
12459@findex match-beginning
12460When given an argument of 0, @code{match-beginning} returns the position
12461that is the start of the text that the most recent regular
12462expression search matched. In this case, the most recent regular
12463expression search is the one looking for @code{paragraph-start}, so
12464@code{match-beginning} returns the beginning position of the pattern,
12465rather than the end of the pattern. The beginning position is the end
12466of the paragraph.
12467
12468(Incidentally, when passed a positive number as an argument, the
12469@code{match-beginning} function will place point at that parenthesized
12470expression in the last regular expression. It is a useful function.)
12471
12472@node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12473@unnumberedsubsec With a fill prefix
12474
12475The inner @code{if} expression just discussed is the else-part of an enclosing
12476@code{if} expression which tests whether there is a fill prefix. If
12477there is a fill prefix, the then-part of this @code{if} is evaluated.
12478It looks like this:
12479
12480@smallexample
12481@group
12482(while (and (not (eobp))
12483 (not (looking-at paragraph-separate))
12484 (looking-at fill-prefix-regexp))
12485 (forward-line 1))
12486@end group
12487@end smallexample
12488
12489@noindent
12490What this expression does is move point forward line by line so long
12491as three conditions are true:
12492
12493@enumerate
12494@item
12495Point is not at the end of the buffer.
12496
12497@item
12498The text following point does not separate paragraphs.
12499
12500@item
12501The pattern following point is the fill prefix regular expression.
12502@end enumerate
12503
12504The last condition may be puzzling, until you remember that point was
12505moved to the beginning of the line early in the @code{forward-paragraph}
12506function. This means that if the text has a fill prefix, the
12507@code{looking-at} function will see it.
12508
12509@node fwd-para summary, , fwd-para with fill prefix, forward-paragraph
12510@unnumberedsubsec Summary
12511
12512In summary, when moving forward, the @code{forward-paragraph} function
12513does the following:
12514
12515@itemize @bullet
12516@item
12517Move point to the beginning of the line.
12518
12519@item
12520Skip over lines between paragraphs.
12521
12522@item
12523Check whether there is a fill prefix, and if there is:
12524
12525@itemize ---
12526
12527@item
12528Go forward line by line so long as the line is not a paragraph
12529separating line.
12530@end itemize
12531
12532@item
12533But if there is no fill prefix,
12534
12535@itemize ---
12536
12537@item
12538Search for the next paragraph start pattern.
12539
12540@item
12541Go to the beginning of the paragraph start pattern, which will be the
12542end of the previous paragraph.
12543
12544@item
12545Or else go to the end of the accessible portion of the buffer.
12546@end itemize
12547@end itemize
12548
12549@need 1200
12550For review, here is the code we have just been discussing, formatted
12551for clarity:
12552
12553@smallexample
12554@group
12555(interactive "p")
12556(or arg (setq arg 1))
12557(let* (
12558 (fill-prefix-regexp
12559 (and fill-prefix (not (equal fill-prefix ""))
12560 (not paragraph-ignore-fill-prefix)
12561 (regexp-quote fill-prefix)))
12562@end group
12563
12564@group
12565 (paragraph-separate
12566 (if fill-prefix-regexp
12567 (concat paragraph-separate
12568 "\\|^"
12569 fill-prefix-regexp
12570 "[ \t]*$")
12571 paragraph-separate)))
12572
12573 @var{omitted-backward-moving-code} @dots{}
12574@end group
12575
12576@group
12577 (while (> arg 0) ; @r{forward-moving-code}
12578 (beginning-of-line)
12579
12580 (while (prog1 (and (not (eobp))
12581 (looking-at paragraph-separate))
12582 (forward-line 1)))
12583@end group
12584
12585@group
12586 (if fill-prefix-regexp
12587 (while (and (not (eobp)) ; @r{then-part}
12588 (not (looking-at paragraph-separate))
12589 (looking-at fill-prefix-regexp))
12590 (forward-line 1))
12591@end group
12592@group
12593 ; @r{else-part: the inner-if}
12594 (if (re-search-forward paragraph-start nil t)
12595 (goto-char (match-beginning 0))
12596 (goto-char (point-max))))
12597
12598 (setq arg (1- arg))))) ; @r{decrementer}
12599@end group
12600@end smallexample
12601
12602The full definition for the @code{forward-paragraph} function not only
12603includes this code for going forwards, but also code for going backwards.
12604
12605If you are reading this inside of GNU Emacs and you want to see the
12606whole function, you can type @kbd{C-h f} (@code{describe-function})
12607and the name of the function. This gives you the function
12608documentation and the name of the library containing the function's
12609source. Place point over the name of the library and press the RET
12610key; you will be taken directly to the source. (Be sure to install
12611your sources! Without them, you are like a person who tries to drive
12612a car with his eyes shut!)
12613
12614@c !!! again, 21.0.100 tags table location in this paragraph
12615Or -- a good habit to get into -- you can type @kbd{M-.}
12616(@code{find-tag}) and the name of the function when prompted for it.
12617This will take you directly to the source. If the @code{find-tag}
12618function first asks you for the name of a @file{TAGS} table, give it
12619the name of the @file{TAGS} file such as
12620@file{/usr/local/share/emacs/21.0.100/lisp/TAGS}. (The exact path to your
12621@file{TAGS} file depends on how your copy of Emacs was installed.)
12622
12623You can also create your own @file{TAGS} file for directories that
12624lack one.
12625@ifnottex
12626@xref{etags, , Create Your Own @file{TAGS} File}.
12627@end ifnottex
12628
12629@node etags, Regexp Review, forward-paragraph, Regexp Search
12630@section Create Your Own @file{TAGS} File
12631@findex etags
12632@cindex @file{TAGS} file, create own
12633
12634The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12635source for a function, variable, node, or other source. The function
12636depends on tags tables to tell it where to go.
12637
12638You often need to build and install tags tables yourself. They are
12639not built automatically. A tags table is called a @file{TAGS} file;
12640the name is in upper case letters.
12641
12642You can create a @file{TAGS} file by calling the @code{etags} program
12643that comes as a part of the Emacs distribution. Usually, @code{etags}
12644is compiled and installed when Emacs is built. (@code{etags} is not
12645an Emacs Lisp function or a part of Emacs; it is a C program.)
12646
12647@need 1250
12648To create a @file{TAGS} file, first switch to the directory in which
12649you want to create the file. In Emacs you can do this with the
12650@kbd{M-x cd} command, or by visiting a file in the directory, or by
12651listing the directory with @kbd{C-x d} (@code{dired}). Then run the
12652compile command, with @w{@code{etags *.el}} as the command to execute
12653
12654@smallexample
12655M-x compile RET etags *.el RET
12656@end smallexample
12657
12658@noindent
12659to create a @file{TAGS} file.
12660
12661For example, if you have a large number of files in your
12662@file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12663of which I load 12---you can create a @file{TAGS} file for the Emacs
12664Lisp files in that directory.
12665
12666@need 1250
12667The @code{etags} program takes all the
12668usual shell `wildcards'. For example, if you have two directories for
12669which you want a single @file{TAGS file}, type
12670@w{@code{etags *.el ../elisp/*.el}},
12671where @file{../elisp/} is the second directory:
12672
12673@smallexample
12674M-x compile RET etags *.el ../elisp/*.el RET
12675@end smallexample
12676
12677@need 1250
12678Type
12679
12680@smallexample
12681M-x compile RET etags --help RET
12682@end smallexample
12683
12684@noindent
12685to see a list of the options accepted by @code{etags} as well as a
12686list of supported languages.
12687
12688The @code{etags} program handles more than 20 languages, including
12689Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12690Pascal, Perl, Python, Texinfo, makefiles, and most assemblers. The
12691program has no switches for specifying the language; it recognizes the
12692language in an input file according to its file name and contents.
12693
12694@file{etags} is very helpful when you are writing code yourself and
12695want to refer back to functions you have already written. Just run
12696@code{etags} again at intervals as you write new functions, so they
12697become part of the @file{TAGS} file.
12698
12699If you think an appropriate @file{TAGS} file already exists for what
12700you want, but do not know where it is, you can use the @code{locate}
12701program to attempt to find it.
12702
12703Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12704full path names of all your @file{TAGS} files. On my system, this
12705command lists 34 @file{TAGS} files. On the other hand, a `plain
12706vanilla' system I recently installed did not contain any @file{TAGS}
12707files.
12708
12709If the tags table you want has been created, you can use the @code{M-x
12710visit-tags-table} command to specify it. Otherwise, you will need to
12711create the tag table yourself and then use @code{M-x
12712visit-tags-table}.
12713
12714@subsubheading Building Tags in the Emacs sources
12715@cindex Building Tags in the Emacs sources
12716@cindex Tags in the Emacs sources
12717@findex make tags
12718
12719The GNU Emacs sources come with a @file{Makefile} that contains a
12720sophisticated @code{etags} command that creates, collects, and merges
12721tags tables from all over the Emacs sources and puts the information
12722into one @file{TAGS} file in the @file{src/} directory below the top
12723level of your Emacs source directory.
12724
12725@need 1250
12726To build this @file{TAGS} file, go to the top level of your Emacs
12727source directory and run the compile command @code{make tags}:
12728
12729@smallexample
12730M-x compile RET make tags RET
12731@end smallexample
12732
12733@noindent
12734(The @code{make tags} command works well with the GNU Emacs sources,
12735as well as with some other source packages.)
12736
12737For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12738Manual}.
12739
12740@node Regexp Review, re-search Exercises, etags, Regexp Search
12741@comment node-name, next, previous, up
12742@section Review
12743
12744Here is a brief summary of some recently introduced functions.
12745
12746@table @code
12747@item while
12748Repeatedly evaluate the body of the expression so long as the first
12749element of the body tests true. Then return @code{nil}. (The
12750expression is evaluated only for its side effects.)
12751
12752@need 1250
12753For example:
12754
12755@smallexample
12756@group
12757(let ((foo 2))
12758 (while (> foo 0)
12759 (insert (format "foo is %d.\n" foo))
12760 (setq foo (1- foo))))
12761
12762 @result{} foo is 2.
12763 foo is 1.
12764 nil
12765@end group
12766@end smallexample
12767@noindent
12768(The @code{insert} function inserts its arguments at point; the
12769@code{format} function returns a string formatted from its arguments
12770the way @code{message} formats its arguments; @code{\n} produces a new
12771line.)
12772
12773@item re-search-forward
12774Search for a pattern, and if the pattern is found, move point to rest
12775just after it.
12776
12777@noindent
12778Takes four arguments, like @code{search-forward}:
12779
12780@enumerate
12781@item
12782A regular expression that specifies the pattern to search for.
12783
12784@item
12785Optionally, the limit of the search.
12786
12787@item
12788Optionally, what to do if the search fails, return @code{nil} or an
12789error message.
12790
12791@item
12792Optionally, how many times to repeat the search; if negative, the
12793search goes backwards.
12794@end enumerate
12795
12796@item let*
12797Bind some variables locally to particular values,
12798and then evaluate the remaining arguments, returning the value of the
12799last one. While binding the local variables, use the local values of
12800variables bound earlier, if any.
12801
12802@need 1250
12803For example:
12804
12805@smallexample
12806@group
12807(let* ((foo 7)
12808 (bar (* 3 foo)))
12809 (message "`bar' is %d." bar))
12810 @result{} `bar' is 21.
12811@end group
12812@end smallexample
12813
12814@item match-beginning
12815Return the position of the start of the text found by the last regular
12816expression search.
12817
12818@item looking-at
12819Return @code{t} for true if the text after point matches the argument,
12820which should be a regular expression.
12821
12822@item eobp
12823Return @code{t} for true if point is at the end of the accessible part
12824of a buffer. The end of the accessible part is the end of the buffer
12825if the buffer is not narrowed; it is the end of the narrowed part if
12826the buffer is narrowed.
12827
12828@item prog1
12829Evaluate each argument in sequence and then return the value of the
12830@emph{first}.
12831
12832@need 1250
12833For example:
12834
12835@smallexample
12836@group
12837(prog1 1 2 3 4)
12838 @result{} 1
12839@end group
12840@end smallexample
12841@end table
12842
12843@need 1500
12844@node re-search Exercises, , Regexp Review, Regexp Search
12845@section Exercises with @code{re-search-forward}
12846
12847@itemize @bullet
12848@item
12849Write a function to search for a regular expression that matches two
12850or more blank lines in sequence.
12851
12852@item
12853Write a function to search for duplicated words, such as `the the'.
12854@xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12855Manual}, for information on how to write a regexp (a regular
12856expression) to match a string that is composed of two identical
12857halves. You can devise several regexps; some are better than others.
12858The function I use is described in an appendix, along with several
12859regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
12860@end itemize
12861
12862@node Counting Words, Words in a defun, Regexp Search, Top
12863@chapter Counting: Repetition and Regexps
12864@cindex Repetition for word counting
12865@cindex Regular expressions for word counting
12866
12867Repetition and regular expression searches are powerful tools that you
12868often use when you write code in Emacs Lisp. This chapter illustrates
12869the use of regular expression searches through the construction of
12870word count commands using @code{while} loops and recursion.
12871
12872@menu
12873* Why Count Words::
12874* count-words-region:: Use a regexp, but find a problem.
12875* recursive-count-words:: Start with case of no words in region.
12876* Counting Exercise::
12877@end menu
12878
12879@node Why Count Words, count-words-region, Counting Words, Counting Words
12880@ifnottex
12881@unnumberedsec Counting words
12882@end ifnottex
12883
12884The standard Emacs distribution contains a function for counting the
12885number of lines within a region. However, there is no corresponding
12886function for counting words.
12887
12888Certain types of writing ask you to count words. Thus, if you write
12889an essay, you may be limited to 800 words; if you write a novel, you
12890may discipline yourself to write 1000 words a day. It seems odd to me
12891that Emacs lacks a word count command. Perhaps people use Emacs
12892mostly for code or types of documentation that do not require word
12893counts; or perhaps they restrict themselves to the operating system
12894word count command, @code{wc}. Alternatively, people may follow
12895the publishers' convention and compute a word count by dividing the
12896number of characters in a document by five. In any event, here are
12897commands to count words.
12898
12899@node count-words-region, recursive-count-words, Why Count Words, Counting Words
12900@comment node-name, next, previous, up
12901@section The @code{count-words-region} Function
12902@findex count-words-region
12903
12904A word count command could count words in a line, paragraph, region,
12905or buffer. What should the command cover? You could design the
12906command to count the number of words in a complete buffer. However,
12907the Emacs tradition encourages flexibility---you may want to count
12908words in just a section, rather than all of a buffer. So it makes
12909more sense to design the command to count the number of words in a
12910region. Once you have a @code{count-words-region} command, you can,
12911if you wish, count words in a whole buffer by marking it with @kbd{C-x
12912h} (@code{mark-whole-buffer}).
12913
12914Clearly, counting words is a repetitive act: starting from the
12915beginning of the region, you count the first word, then the second
12916word, then the third word, and so on, until you reach the end of the
12917region. This means that word counting is ideally suited to recursion
12918or to a @code{while} loop.
12919
12920@menu
12921* Design count-words-region:: The definition using a @code{while} loop.
12922* Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
12923@end menu
12924
12925@node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12926@ifnottex
12927@unnumberedsubsec Designing @code{count-words-region}
12928@end ifnottex
12929
12930First, we will implement the word count command with a @code{while}
12931loop, then with recursion. The command will, of course, be
12932interactive.
12933
12934@need 800
12935The template for an interactive function definition is, as always:
12936
12937@smallexample
12938@group
12939(defun @var{name-of-function} (@var{argument-list})
12940 "@var{documentation}@dots{}"
12941 (@var{interactive-expression}@dots{})
12942 @var{body}@dots{})
12943@end group
12944@end smallexample
12945
12946What we need to do is fill in the slots.
12947
12948The name of the function should be self-explanatory and similar to the
12949existing @code{count-lines-region} name. This makes the name easier
12950to remember. @code{count-words-region} is a good choice.
12951
12952The function counts words within a region. This means that the
12953argument list must contain symbols that are bound to the two
12954positions, the beginning and end of the region. These two positions
12955can be called @samp{beginning} and @samp{end} respectively. The first
12956line of the documentation should be a single sentence, since that is
12957all that is printed as documentation by a command such as
12958@code{apropos}. The interactive expression will be of the form
12959@samp{(interactive "r")}, since that will cause Emacs to pass the
12960beginning and end of the region to the function's argument list. All
12961this is routine.
12962
12963The body of the function needs to be written to do three tasks:
12964first, to set up conditions under which the @code{while} loop can
12965count words, second, to run the @code{while} loop, and third, to send
12966a message to the user.
12967
12968When a user calls @code{count-words-region}, point may be at the
12969beginning or the end of the region. However, the counting process
12970must start at the beginning of the region. This means we will want
12971to put point there if it is not already there. Executing
12972@code{(goto-char beginning)} ensures this. Of course, we will want to
12973return point to its expected position when the function finishes its
12974work. For this reason, the body must be enclosed in a
12975@code{save-excursion} expression.
12976
12977The central part of the body of the function consists of a
12978@code{while} loop in which one expression jumps point forward word by
12979word, and another expression counts those jumps. The true-or-false-test
12980of the @code{while} loop should test true so long as point should jump
12981forward, and false when point is at the end of the region.
12982
12983We could use @code{(forward-word 1)} as the expression for moving point
12984forward word by word, but it is easier to see what Emacs identifies as a
12985`word' if we use a regular expression search.
12986
12987A regular expression search that finds the pattern for which it is
12988searching leaves point after the last character matched. This means
12989that a succession of successful word searches will move point forward
12990word by word.
12991
12992As a practical matter, we want the regular expression search to jump
12993over whitespace and punctuation between words as well as over the
12994words themselves. A regexp that refuses to jump over interword
12995whitespace would never jump more than one word! This means that
12996the regexp should include the whitespace and punctuation that follows
12997a word, if any, as well as the word itself. (A word may end a buffer
12998and not have any following whitespace or punctuation, so that part of
12999the regexp must be optional.)
13000
13001Thus, what we want for the regexp is a pattern defining one or more
13002word constituent characters followed, optionally, by one or more
13003characters that are not word constituents. The regular expression for
13004this is:
13005
13006@smallexample
13007\w+\W*
13008@end smallexample
13009
13010@noindent
13011The buffer's syntax table determines which characters are and are not
13012word constituents. (@xref{Syntax, , What Constitutes a Word or
13013Symbol?}, for more about syntax. Also, see @ref{Syntax, Syntax, The
13014Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
13015Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13016
13017@need 800
13018The search expression looks like this:
13019
13020@smallexample
13021(re-search-forward "\\w+\\W*")
13022@end smallexample
13023
13024@noindent
13025(Note that paired backslashes precede the @samp{w} and @samp{W}. A
13026single backslash has special meaning to the Emacs Lisp interpreter. It
13027indicates that the following character is interpreted differently than
13028usual. For example, the two characters, @samp{\n}, stand for
13029@samp{newline}, rather than for a backslash followed by @samp{n}. Two
13030backslashes in a row stand for an ordinary, `unspecial' backslash.)
13031
13032We need a counter to count how many words there are; this variable
13033must first be set to 0 and then incremented each time Emacs goes
13034around the @code{while} loop. The incrementing expression is simply:
13035
13036@smallexample
13037(setq count (1+ count))
13038@end smallexample
13039
13040Finally, we want to tell the user how many words there are in the
13041region. The @code{message} function is intended for presenting this
13042kind of information to the user. The message has to be phrased so
13043that it reads properly regardless of how many words there are in the
13044region: we don't want to say that ``there are 1 words in the region''.
13045The conflict between singular and plural is ungrammatical. We can
13046solve this problem by using a conditional expression that evaluates
13047different messages depending on the number of words in the region.
13048There are three possibilities: no words in the region, one word in the
13049region, and more than one word. This means that the @code{cond}
13050special form is appropriate.
13051
13052@need 1500
13053All this leads to the following function definition:
13054
13055@smallexample
13056@group
13057;;; @r{First version; has bugs!}
13058(defun count-words-region (beginning end)
13059 "Print number of words in the region.
13060Words are defined as at least one word-constituent
13061character followed by at least one character that
13062is not a word-constituent. The buffer's syntax
13063table determines which characters these are."
13064 (interactive "r")
13065 (message "Counting words in region ... ")
13066@end group
13067
13068@group
13069;;; @r{1. Set up appropriate conditions.}
13070 (save-excursion
13071 (goto-char beginning)
13072 (let ((count 0))
13073@end group
13074
13075@group
13076;;; @r{2. Run the} while @r{loop.}
13077 (while (< (point) end)
13078 (re-search-forward "\\w+\\W*")
13079 (setq count (1+ count)))
13080@end group
13081
13082@group
13083;;; @r{3. Send a message to the user.}
13084 (cond ((zerop count)
13085 (message
13086 "The region does NOT have any words."))
13087 ((= 1 count)
13088 (message
13089 "The region has 1 word."))
13090 (t
13091 (message
13092 "The region has %d words." count))))))
13093@end group
13094@end smallexample
13095
13096@noindent
13097As written, the function works, but not in all circumstances.
13098
13099@node Whitespace Bug, , Design count-words-region, count-words-region
13100@comment node-name, next, previous, up
13101@subsection The Whitespace Bug in @code{count-words-region}
13102
13103The @code{count-words-region} command described in the preceding
13104section has two bugs, or rather, one bug with two manifestations.
13105First, if you mark a region containing only whitespace in the middle
13106of some text, the @code{count-words-region} command tells you that the
13107region contains one word! Second, if you mark a region containing
13108only whitespace at the end of the buffer or the accessible portion of
13109a narrowed buffer, the command displays an error message that looks
13110like this:
13111
13112@smallexample
13113Search failed: "\\w+\\W*"
13114@end smallexample
13115
13116If you are reading this in Info in GNU Emacs, you can test for these
13117bugs yourself.
13118
13119First, evaluate the function in the usual manner to install it.
13120@ifinfo
13121Here is a copy of the definition. Place your cursor after the closing
13122parenthesis and type @kbd{C-x C-e} to install it.
13123
13124@smallexample
13125@group
13126;; @r{First version; has bugs!}
13127(defun count-words-region (beginning end)
13128 "Print number of words in the region.
13129Words are defined as at least one word-constituent character followed
13130by at least one character that is not a word-constituent. The buffer's
13131syntax table determines which characters these are."
13132@end group
13133@group
13134 (interactive "r")
13135 (message "Counting words in region ... ")
13136@end group
13137
13138@group
13139;;; @r{1. Set up appropriate conditions.}
13140 (save-excursion
13141 (goto-char beginning)
13142 (let ((count 0))
13143@end group
13144
13145@group
13146;;; @r{2. Run the} while @r{loop.}
13147 (while (< (point) end)
13148 (re-search-forward "\\w+\\W*")
13149 (setq count (1+ count)))
13150@end group
13151
13152@group
13153;;; @r{3. Send a message to the user.}
13154 (cond ((zerop count)
13155 (message "The region does NOT have any words."))
13156 ((= 1 count) (message "The region has 1 word."))
13157 (t (message "The region has %d words." count))))))
13158@end group
13159@end smallexample
13160@end ifinfo
13161
13162@need 1000
13163If you wish, you can also install this keybinding by evaluating it:
13164
13165@smallexample
13166(global-set-key "\C-c=" 'count-words-region)
13167@end smallexample
13168
13169To conduct the first test, set mark and point to the beginning and end
13170of the following line and then type @kbd{C-c =} (or @kbd{M-x
13171count-words-region} if you have not bound @kbd{C-c =}):
13172
13173@smallexample
13174 one two three
13175@end smallexample
13176
13177@noindent
13178Emacs will tell you, correctly, that the region has three words.
13179
13180Repeat the test, but place mark at the beginning of the line and place
13181point just @emph{before} the word @samp{one}. Again type the command
13182@kbd{C-c =} (or @kbd{M-x count-words-region}). Emacs should tell you
13183that the region has no words, since it is composed only of the
13184whitespace at the beginning of the line. But instead Emacs tells you
13185that the region has one word!
13186
13187For the third test, copy the sample line to the end of the
13188@file{*scratch*} buffer and then type several spaces at the end of the
13189line. Place mark right after the word @samp{three} and point at the
13190end of line. (The end of the line will be the end of the buffer.)
13191Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13192Again, Emacs should tell you that the region has no words, since it is
13193composed only of the whitespace at the end of the line. Instead,
13194Emacs displays an error message saying @samp{Search failed}.
13195
13196The two bugs stem from the same problem.
13197
13198Consider the first manifestation of the bug, in which the command
13199tells you that the whitespace at the beginning of the line contains
13200one word. What happens is this: The @code{M-x count-words-region}
13201command moves point to the beginning of the region. The @code{while}
13202tests whether the value of point is smaller than the value of
13203@code{end}, which it is. Consequently, the regular expression search
13204looks for and finds the first word. It leaves point after the word.
13205@code{count} is set to one. The @code{while} loop repeats; but this
13206time the value of point is larger than the value of @code{end}, the
13207loop is exited; and the function displays a message saying the number
13208of words in the region is one. In brief, the regular expression
13209search looks for and finds the word even though it is outside
13210the marked region.
13211
13212In the second manifestation of the bug, the region is whitespace at
13213the end of the buffer. Emacs says @samp{Search failed}. What happens
13214is that the true-or-false-test in the @code{while} loop tests true, so
13215the search expression is executed. But since there are no more words
13216in the buffer, the search fails.
13217
13218In both manifestations of the bug, the search extends or attempts to
13219extend outside of the region.
13220
13221The solution is to limit the search to the region---this is a fairly
13222simple action, but as you may have come to expect, it is not quite as
13223simple as you might think.
13224
13225As we have seen, the @code{re-search-forward} function takes a search
13226pattern as its first argument. But in addition to this first,
13227mandatory argument, it accepts three optional arguments. The optional
13228second argument bounds the search. The optional third argument, if
13229@code{t}, causes the function to return @code{nil} rather than signal
13230an error if the search fails. The optional fourth argument is a
13231repeat count. (In Emacs, you can see a function's documentation by
13232typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13233
13234In the @code{count-words-region} definition, the value of the end of
13235the region is held by the variable @code{end} which is passed as an
13236argument to the function. Thus, we can add @code{end} as an argument
13237to the regular expression search expression:
13238
13239@smallexample
13240(re-search-forward "\\w+\\W*" end)
13241@end smallexample
13242
13243However, if you make only this change to the @code{count-words-region}
13244definition and then test the new version of the definition on a
13245stretch of whitespace, you will receive an error message saying
13246@samp{Search failed}.
13247
13248What happens is this: the search is limited to the region, and fails
13249as you expect because there are no word-constituent characters in the
13250region. Since it fails, we receive an error message. But we do not
13251want to receive an error message in this case; we want to receive the
13252message that "The region does NOT have any words."
13253
13254The solution to this problem is to provide @code{re-search-forward}
13255with a third argument of @code{t}, which causes the function to return
13256@code{nil} rather than signal an error if the search fails.
13257
13258However, if you make this change and try it, you will see the message
13259``Counting words in region ... '' and @dots{} you will keep on seeing
13260that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13261
13262Here is what happens: the search is limited to the region, as before,
13263and it fails because there are no word-constituent characters in the
13264region, as expected. Consequently, the @code{re-search-forward}
13265expression returns @code{nil}. It does nothing else. In particular,
13266it does not move point, which it does as a side effect if it finds the
13267search target. After the @code{re-search-forward} expression returns
13268@code{nil}, the next expression in the @code{while} loop is evaluated.
13269This expression increments the count. Then the loop repeats. The
13270true-or-false-test tests true because the value of point is still less
13271than the value of end, since the @code{re-search-forward} expression
13272did not move point. @dots{} and the cycle repeats @dots{}
13273
13274The @code{count-words-region} definition requires yet another
13275modification, to cause the true-or-false-test of the @code{while} loop
13276to test false if the search fails. Put another way, there are two
13277conditions that must be satisfied in the true-or-false-test before the
13278word count variable is incremented: point must still be within the
13279region and the search expression must have found a word to count.
13280
13281Since both the first condition and the second condition must be true
13282together, the two expressions, the region test and the search
13283expression, can be joined with an @code{and} special form and embedded in
13284the @code{while} loop as the true-or-false-test, like this:
13285
13286@smallexample
13287(and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13288@end smallexample
13289
13290@c colon in printed section title causes problem in Info cross reference
13291@c also trouble with an overfull hbox
13292@iftex
13293@noindent
13294(For information about @code{and}, see
13295@ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13296Functions}.)
13297@end iftex
13298@ifinfo
13299@noindent
13300(@xref{forward-paragraph}, for information about @code{and}.)
13301@end ifinfo
13302
13303The @code{re-search-forward} expression returns @code{t} if the search
13304succeeds and as a side effect moves point. Consequently, as words are
13305found, point is moved through the region. When the search
13306expression fails to find another word, or when point reaches the end
13307of the region, the true-or-false-test tests false, the @code{while}
13308loop exists, and the @code{count-words-region} function displays one
13309or other of its messages.
13310
13311After incorporating these final changes, the @code{count-words-region}
13312works without bugs (or at least, without bugs that I have found!).
13313Here is what it looks like:
13314
13315@smallexample
13316@group
13317;;; @r{Final version:} @code{while}
13318(defun count-words-region (beginning end)
13319 "Print number of words in the region."
13320 (interactive "r")
13321 (message "Counting words in region ... ")
13322@end group
13323
13324@group
13325;;; @r{1. Set up appropriate conditions.}
13326 (save-excursion
13327 (let ((count 0))
13328 (goto-char beginning)
13329@end group
13330
13331@group
13332;;; @r{2. Run the} while @r{loop.}
13333 (while (and (< (point) end)
13334 (re-search-forward "\\w+\\W*" end t))
13335 (setq count (1+ count)))
13336@end group
13337
13338@group
13339;;; @r{3. Send a message to the user.}
13340 (cond ((zerop count)
13341 (message
13342 "The region does NOT have any words."))
13343 ((= 1 count)
13344 (message
13345 "The region has 1 word."))
13346 (t
13347 (message
13348 "The region has %d words." count))))))
13349@end group
13350@end smallexample
13351
13352@node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13353@comment node-name, next, previous, up
13354@section Count Words Recursively
13355@cindex Count words recursively
13356@cindex Recursively counting words
13357@cindex Words, counted recursively
13358
13359You can write the function for counting words recursively as well as
13360with a @code{while} loop. Let's see how this is done.
13361
13362First, we need to recognize that the @code{count-words-region}
13363function has three jobs: it sets up the appropriate conditions for
13364counting to occur; it counts the words in the region; and it sends a
13365message to the user telling how many words there are.
13366
13367If we write a single recursive function to do everything, we will
13368receive a message for every recursive call. If the region contains 13
13369words, we will receive thirteen messages, one right after the other.
13370We don't want this! Instead, we must write two functions to do the
13371job, one of which (the recursive function) will be used inside of the
13372other. One function will set up the conditions and display the
13373message; the other will return the word count.
13374
13375Let us start with the function that causes the message to be displayed.
13376We can continue to call this @code{count-words-region}.
13377
13378This is the function that the user will call. It will be interactive.
13379Indeed, it will be similar to our previous versions of this
13380function, except that it will call @code{recursive-count-words} to
13381determine how many words are in the region.
13382
13383@need 1250
13384We can readily construct a template for this function, based on our
13385previous versions:
13386
13387@smallexample
13388@group
13389;; @r{Recursive version; uses regular expression search}
13390(defun count-words-region (beginning end)
13391 "@var{documentation}@dots{}"
13392 (@var{interactive-expression}@dots{})
13393@end group
13394@group
13395
13396;;; @r{1. Set up appropriate conditions.}
13397 (@var{explanatory message})
13398 (@var{set-up functions}@dots{}
13399@end group
13400@group
13401
13402;;; @r{2. Count the words.}
13403 @var{recursive call}
13404@end group
13405@group
13406
13407;;; @r{3. Send a message to the user.}
13408 @var{message providing word count}))
13409@end group
13410@end smallexample
13411
13412The definition looks straightforward, except that somehow the count
13413returned by the recursive call must be passed to the message
13414displaying the word count. A little thought suggests that this can be
13415done by making use of a @code{let} expression: we can bind a variable
13416in the varlist of a @code{let} expression to the number of words in
13417the region, as returned by the recursive call; and then the
13418@code{cond} expression, using binding, can display the value to the
13419user.
13420
13421Often, one thinks of the binding within a @code{let} expression as
13422somehow secondary to the `primary' work of a function. But in this
13423case, what you might consider the `primary' job of the function,
13424counting words, is done within the @code{let} expression.
13425
13426@need 1250
13427Using @code{let}, the function definition looks like this:
13428
13429@smallexample
13430@group
13431(defun count-words-region (beginning end)
13432 "Print number of words in the region."
13433 (interactive "r")
13434@end group
13435
13436@group
13437;;; @r{1. Set up appropriate conditions.}
13438 (message "Counting words in region ... ")
13439 (save-excursion
13440 (goto-char beginning)
13441@end group
13442
13443@group
13444;;; @r{2. Count the words.}
13445 (let ((count (recursive-count-words end)))
13446@end group
13447
13448@group
13449;;; @r{3. Send a message to the user.}
13450 (cond ((zerop count)
13451 (message
13452 "The region does NOT have any words."))
13453 ((= 1 count)
13454 (message
13455 "The region has 1 word."))
13456 (t
13457 (message
13458 "The region has %d words." count))))))
13459@end group
13460@end smallexample
13461
13462Next, we need to write the recursive counting function.
13463
13464A recursive function has at least three parts: the `do-again-test', the
13465`next-step-expression', and the recursive call.
13466
13467The do-again-test determines whether the function will or will not be
13468called again. Since we are counting words in a region and can use a
13469function that moves point forward for every word, the do-again-test
13470can check whether point is still within the region. The do-again-test
13471should find the value of point and determine whether point is before,
13472at, or after the value of the end of the region. We can use the
13473@code{point} function to locate point. Clearly, we must pass the
13474value of the end of the region to the recursive counting function as an
13475argument.
13476
13477In addition, the do-again-test should also test whether the search finds a
13478word. If it does not, the function should not call itself again.
13479
13480The next-step-expression changes a value so that when the recursive
13481function is supposed to stop calling itself, it stops. More
13482precisely, the next-step-expression changes a value so that at the
13483right time, the do-again-test stops the recursive function from
13484calling itself again. In this case, the next-step-expression can be
13485the expression that moves point forward, word by word.
13486
13487The third part of a recursive function is the recursive call.
13488
13489Somewhere, also, we also need a part that does the `work' of the
13490function, a part that does the counting. A vital part!
13491
13492@need 1250
13493But already, we have an outline of the recursive counting function:
13494
13495@smallexample
13496@group
13497(defun recursive-count-words (region-end)
13498 "@var{documentation}@dots{}"
13499 @var{do-again-test}
13500 @var{next-step-expression}
13501 @var{recursive call})
13502@end group
13503@end smallexample
13504
13505Now we need to fill in the slots. Let's start with the simplest cases
13506first: if point is at or beyond the end of the region, there cannot
13507be any words in the region, so the function should return zero.
13508Likewise, if the search fails, there are no words to count, so the
13509function should return zero.
13510
13511On the other hand, if point is within the region and the search
13512succeeds, the function should call itself again.
13513
13514@need 800
13515Thus, the do-again-test should look like this:
13516
13517@smallexample
13518@group
13519(and (< (point) region-end)
13520 (re-search-forward "\\w+\\W*" region-end t))
13521@end group
13522@end smallexample
13523
13524Note that the search expression is part of the do-again-test---the
13525function returns @code{t} if its search succeeds and @code{nil} if it
13526fails. (@xref{Whitespace Bug, , The Whitespace Bug in
13527@code{count-words-region}}, for an explanation of how
13528@code{re-search-forward} works.)
13529
13530The do-again-test is the true-or-false test of an @code{if} clause.
13531Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13532clause should call the function again; but if it fails, the else-part
13533should return zero since either point is outside the region or the
13534search failed because there were no words to find.
13535
13536But before considering the recursive call, we need to consider the
13537next-step-expression. What is it? Interestingly, it is the search
13538part of the do-again-test.
13539
13540In addition to returning @code{t} or @code{nil} for the
13541do-again-test, @code{re-search-forward} moves point forward as a side
13542effect of a successful search. This is the action that changes the
13543value of point so that the recursive function stops calling itself
13544when point completes its movement through the region. Consequently,
13545the @code{re-search-forward} expression is the next-step-expression.
13546
13547@need 1200
13548In outline, then, the body of the @code{recursive-count-words}
13549function looks like this:
13550
13551@smallexample
13552@group
13553(if @var{do-again-test-and-next-step-combined}
13554 ;; @r{then}
13555 @var{recursive-call-returning-count}
13556 ;; @r{else}
13557 @var{return-zero})
13558@end group
13559@end smallexample
13560
13561How to incorporate the mechanism that counts?
13562
13563If you are not used to writing recursive functions, a question like
13564this can be troublesome. But it can and should be approached
13565systematically.
13566
13567We know that the counting mechanism should be associated in some way
13568with the recursive call. Indeed, since the next-step-expression moves
13569point forward by one word, and since a recursive call is made for
13570each word, the counting mechanism must be an expression that adds one
13571to the value returned by a call to @code{recursive-count-words}.
13572
13573Consider several cases:
13574
13575@itemize @bullet
13576@item
13577If there are two words in the region, the function should return
13578a value resulting from adding one to the value returned when it counts
13579the first word, plus the number returned when it counts the remaining
13580words in the region, which in this case is one.
13581
13582@item
13583If there is one word in the region, the function should return
13584a value resulting from adding one to the value returned when it counts
13585that word, plus the number returned when it counts the remaining
13586words in the region, which in this case is zero.
13587
13588@item
13589If there are no words in the region, the function should return zero.
13590@end itemize
13591
13592From the sketch we can see that the else-part of the @code{if} returns
13593zero for the case of no words. This means that the then-part of the
13594@code{if} must return a value resulting from adding one to the value
13595returned from a count of the remaining words.
13596
13597@need 1200
13598The expression will look like this, where @code{1+} is a function that
13599adds one to its argument.
13600
13601@smallexample
13602(1+ (recursive-count-words region-end))
13603@end smallexample
13604
13605@need 1200
13606The whole @code{recursive-count-words} function will then look like
13607this:
13608
13609@smallexample
13610@group
13611(defun recursive-count-words (region-end)
13612 "@var{documentation}@dots{}"
13613
13614;;; @r{1. do-again-test}
13615 (if (and (< (point) region-end)
13616 (re-search-forward "\\w+\\W*" region-end t))
13617@end group
13618
13619@group
13620;;; @r{2. then-part: the recursive call}
13621 (1+ (recursive-count-words region-end))
13622
13623;;; @r{3. else-part}
13624 0))
13625@end group
13626@end smallexample
13627
13628@need 1250
13629Let's examine how this works:
13630
13631If there are no words in the region, the else part of the @code{if}
13632expression is evaluated and consequently the function returns zero.
13633
13634If there is one word in the region, the value of point is less than
13635the value of @code{region-end} and the search succeeds. In this case,
13636the true-or-false-test of the @code{if} expression tests true, and the
13637then-part of the @code{if} expression is evaluated. The counting
13638expression is evaluated. This expression returns a value (which will
13639be the value returned by the whole function) that is the sum of one
13640added to the value returned by a recursive call.
13641
13642Meanwhile, the next-step-expression has caused point to jump over the
13643first (and in this case only) word in the region. This means that
13644when @code{(recursive-count-words region-end)} is evaluated a second
13645time, as a result of the recursive call, the value of point will be
13646equal to or greater than the value of region end. So this time,
13647@code{recursive-count-words} will return zero. The zero will be added
13648to one, and the original evaluation of @code{recursive-count-words}
13649will return one plus zero, which is one, which is the correct amount.
13650
13651Clearly, if there are two words in the region, the first call to
13652@code{recursive-count-words} returns one added to the value returned
13653by calling @code{recursive-count-words} on a region containing the
13654remaining word---that is, it adds one to one, producing two, which is
13655the correct amount.
13656
13657Similarly, if there are three words in the region, the first call to
13658@code{recursive-count-words} returns one added to the value returned
13659by calling @code{recursive-count-words} on a region containing the
13660remaining two words---and so on and so on.
13661
13662@need 1250
13663@noindent
13664With full documentation the two functions look like this:
13665
13666@need 1250
13667@noindent
13668The recursive function:
13669
13670@findex recursive-count-words
13671@smallexample
13672@group
13673(defun recursive-count-words (region-end)
13674 "Number of words between point and REGION-END."
13675@end group
13676
13677@group
13678;;; @r{1. do-again-test}
13679 (if (and (< (point) region-end)
13680 (re-search-forward "\\w+\\W*" region-end t))
13681@end group
13682
13683@group
13684;;; @r{2. then-part: the recursive call}
13685 (1+ (recursive-count-words region-end))
13686
13687;;; @r{3. else-part}
13688 0))
13689@end group
13690@end smallexample
13691
13692@need 800
13693@noindent
13694The wrapper:
13695
13696@smallexample
13697@group
13698;;; @r{Recursive version}
13699(defun count-words-region (beginning end)
13700 "Print number of words in the region.
13701@end group
13702
13703@group
13704Words are defined as at least one word-constituent
13705character followed by at least one character that is
13706not a word-constituent. The buffer's syntax table
13707determines which characters these are."
13708@end group
13709@group
13710 (interactive "r")
13711 (message "Counting words in region ... ")
13712 (save-excursion
13713 (goto-char beginning)
13714 (let ((count (recursive-count-words end)))
13715@end group
13716@group
13717 (cond ((zerop count)
13718 (message
13719 "The region does NOT have any words."))
13720@end group
13721@group
13722 ((= 1 count)
13723 (message "The region has 1 word."))
13724 (t
13725 (message
13726 "The region has %d words." count))))))
13727@end group
13728@end smallexample
13729
13730@node Counting Exercise, , recursive-count-words, Counting Words
13731@section Exercise: Counting Punctuation
13732
13733Using a @code{while} loop, write a function to count the number of
13734punctuation marks in a region---period, comma, semicolon, colon,
13735exclamation mark, and question mark. Do the same using recursion.
13736
13737@node Words in a defun, Readying a Graph, Counting Words, Top
13738@chapter Counting Words in a @code{defun}
13739@cindex Counting words in a @code{defun}
13740@cindex Word counting in a @code{defun}
13741
13742Our next project is to count the number of words in a function
13743definition. Clearly, this can be done using some variant of
13744@code{count-word-region}. @xref{Counting Words, , Counting Words:
13745Repetition and Regexps}. If we are just going to count the words in
13746one definition, it is easy enough to mark the definition with the
13747@kbd{C-M-h} (@code{mark-defun}) command, and then call
13748@code{count-word-region}.
13749
13750However, I am more ambitious: I want to count the words and symbols in
13751every definition in the Emacs sources and then print a graph that
13752shows how many functions there are of each length: how many contain 40
13753to 49 words or symbols, how many contain 50 to 59 words or symbols,
13754and so on. I have often been curious how long a typical function is,
13755and this will tell.
13756
13757@menu
13758* Divide and Conquer::
13759* Words and Symbols:: What to count?
13760* Syntax:: What constitutes a word or symbol?
13761* count-words-in-defun:: Very like @code{count-words}.
13762* Several defuns:: Counting several defuns in a file.
13763* Find a File:: Do you want to look at a file?
13764* lengths-list-file:: A list of the lengths of many definitions.
13765* Several files:: Counting in definitions in different files.
13766* Several files recursively:: Recursively counting in different files.
13767* Prepare the data:: Prepare the data for display in a graph.
13768@end menu
13769
13770@node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13771@ifnottex
13772@unnumberedsec Divide and Conquer
13773@end ifnottex
13774
13775Described in one phrase, the histogram project is daunting; but
13776divided into numerous small steps, each of which we can take one at a
13777time, the project becomes less fearsome. Let us consider what the
13778steps must be:
13779
13780@itemize @bullet
13781@item
13782First, write a function to count the words in one definition. This
13783includes the problem of handling symbols as well as words.
13784
13785@item
13786Second, write a function to list the numbers of words in each function
13787in a file. This function can use the @code{count-words-in-defun}
13788function.
13789
13790@item
13791Third, write a function to list the numbers of words in each function
13792in each of several files. This entails automatically finding the
13793various files, switching to them, and counting the words in the
13794definitions within them.
13795
13796@item
13797Fourth, write a function to convert the list of numbers that we
13798created in step three to a form that will be suitable for printing as
13799a graph.
13800
13801@item
13802Fifth, write a function to print the results as a graph.
13803@end itemize
13804
13805This is quite a project! But if we take each step slowly, it will not
13806be difficult.
13807
13808@node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13809@section What to Count?
13810@cindex Words and symbols in defun
13811
13812When we first start thinking about how to count the words in a
13813function definition, the first question is (or ought to be) what are
13814we going to count? When we speak of `words' with respect to a Lisp
13815function definition, we are actually speaking, in large part, of
13816`symbols'. For example, the following @code{multiply-by-seven}
13817function contains the five symbols @code{defun},
13818@code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
13819addition, in the documentation string, it contains the four words
13820@samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
13821symbol @samp{number} is repeated, so the definition contains a total
13822of ten words and symbols.
13823
13824@smallexample
13825@group
13826(defun multiply-by-seven (number)
13827 "Multiply NUMBER by seven."
13828 (* 7 number))
13829@end group
13830@end smallexample
13831
13832@noindent
13833However, if we mark the @code{multiply-by-seven} definition with
13834@kbd{C-M-h} (@code{mark-defun}), and then call
13835@code{count-words-region} on it, we will find that
13836@code{count-words-region} claims the definition has eleven words, not
13837ten! Something is wrong!
13838
13839The problem is twofold: @code{count-words-region} does not count the
13840@samp{*} as a word, and it counts the single symbol,
13841@code{multiply-by-seven}, as containing three words. The hyphens are
13842treated as if they were interword spaces rather than intraword
13843connectors: @samp{multiply-by-seven} is counted as if it were written
13844@samp{multiply by seven}.
13845
13846The cause of this confusion is the regular expression search within
13847the @code{count-words-region} definition that moves point forward word
13848by word. In the canonical version of @code{count-words-region}, the
13849regexp is:
13850
13851@smallexample
13852"\\w+\\W*"
13853@end smallexample
13854
13855@noindent
13856This regular expression is a pattern defining one or more word
13857constituent characters possibly followed by one or more characters
13858that are not word constituents. What is meant by `word constituent
13859characters' brings us to the issue of syntax, which is worth a section
13860of its own.
13861
13862@node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13863@section What Constitutes a Word or Symbol?
13864@cindex Syntax categories and tables
13865
13866Emacs treats different characters as belonging to different
13867@dfn{syntax categories}. For example, the regular expression,
13868@samp{\\w+}, is a pattern specifying one or more @emph{word
13869constituent} characters. Word constituent characters are members of
13870one syntax category. Other syntax categories include the class of
13871punctuation characters, such as the period and the comma, and the
13872class of whitespace characters, such as the blank space and the tab
13873character. (For more information, see @ref{Syntax, Syntax, The Syntax
13874Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13875Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13876
13877Syntax tables specify which characters belong to which categories.
13878Usually, a hyphen is not specified as a `word constituent character'.
13879Instead, it is specified as being in the `class of characters that are
13880part of symbol names but not words.' This means that the
13881@code{count-words-region} function treats it in the same way it treats
13882an interword white space, which is why @code{count-words-region}
13883counts @samp{multiply-by-seven} as three words.
13884
13885There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13886one symbol: modify the syntax table or modify the regular expression.
13887
13888We could redefine a hyphen as a word constituent character by
13889modifying the syntax table that Emacs keeps for each mode. This
13890action would serve our purpose, except that a hyphen is merely the
13891most common character within symbols that is not typically a word
13892constituent character; there are others, too.
13893
13894Alternatively, we can redefine the regular expression used in the
13895@code{count-words} definition so as to include symbols. This
13896procedure has the merit of clarity, but the task is a little tricky.
13897
13898@need 1200
13899The first part is simple enough: the pattern must match ``at least one
13900character that is a word or symbol constituent''. Thus:
13901
13902@smallexample
13903"\\(\\w\\|\\s_\\)+"
13904@end smallexample
13905
13906@noindent
13907The @samp{\\(} is the first part of the grouping construct that
13908includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13909by the @samp{\\|}. The @samp{\\w} matches any word-constituent
13910character and the @samp{\\s_} matches any character that is part of a
13911symbol name but not a word-constituent character. The @samp{+}
13912following the group indicates that the word or symbol constituent
13913characters must be matched at least once.
13914
13915However, the second part of the regexp is more difficult to design.
13916What we want is to follow the first part with ``optionally one or more
13917characters that are not constituents of a word or symbol''. At first,
13918I thought I could define this with the following:
13919
13920@smallexample
13921"\\(\\W\\|\\S_\\)*"
13922@end smallexample
13923
13924@noindent
13925The upper case @samp{W} and @samp{S} match characters that are
13926@emph{not} word or symbol constituents. Unfortunately, this
13927expression matches any character that is either not a word constituent
13928or not a symbol constituent. This matches any character!
13929
13930I then noticed that every word or symbol in my test region was
13931followed by white space (blank space, tab, or newline). So I tried
13932placing a pattern to match one or more blank spaces after the pattern
13933for one or more word or symbol constituents. This failed, too. Words
13934and symbols are often separated by whitespace, but in actual code
13935parentheses may follow symbols and punctuation may follow words. So
13936finally, I designed a pattern in which the word or symbol constituents
13937are followed optionally by characters that are not white space and
13938then followed optionally by white space.
13939
13940@need 800
13941Here is the full regular expression:
13942
13943@smallexample
13944"\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13945@end smallexample
13946
13947@node count-words-in-defun, Several defuns, Syntax, Words in a defun
13948@section The @code{count-words-in-defun} Function
13949@cindex Counting words in a @code{defun}
13950
13951We have seen that there are several ways to write a
13952@code{count-word-region} function. To write a
13953@code{count-words-in-defun}, we need merely adapt one of these
13954versions.
13955
13956The version that uses a @code{while} loop is easy to understand, so I
13957am going to adapt that. Because @code{count-words-in-defun} will be
13958part of a more complex program, it need not be interactive and it need
13959not display a message but just return the count. These considerations
13960simplify the definition a little.
13961
13962On the other hand, @code{count-words-in-defun} will be used within a
13963buffer that contains function definitions. Consequently, it is
13964reasonable to ask that the function determine whether it is called
13965when point is within a function definition, and if it is, to return
13966the count for that definition. This adds complexity to the
13967definition, but saves us from needing to pass arguments to the
13968function.
13969
13970@need 1250
13971These considerations lead us to prepare the following template:
13972
13973@smallexample
13974@group
13975(defun count-words-in-defun ()
13976 "@var{documentation}@dots{}"
13977 (@var{set up}@dots{}
13978 (@var{while loop}@dots{})
13979 @var{return count})
13980@end group
13981@end smallexample
13982
13983@noindent
13984As usual, our job is to fill in the slots.
13985
13986First, the set up.
13987
13988We are presuming that this function will be called within a buffer
13989containing function definitions. Point will either be within a
13990function definition or not. For @code{count-words-in-defun} to work,
13991point must move to the beginning of the definition, a counter must
13992start at zero, and the counting loop must stop when point reaches the
13993end of the definition.
13994
13995The @code{beginning-of-defun} function searches backwards for an
13996opening delimiter such as a @samp{(} at the beginning of a line, and
13997moves point to that position, or else to the limit of the search. In
13998practice, this means that @code{beginning-of-defun} moves point to the
13999beginning of an enclosing or preceding function definition, or else to
14000the beginning of the buffer. We can use @code{beginning-of-defun} to
14001place point where we wish to start.
14002
14003The @code{while} loop requires a counter to keep track of the words or
14004symbols being counted. A @code{let} expression can be used to create
14005a local variable for this purpose, and bind it to an initial value of zero.
14006
14007The @code{end-of-defun} function works like @code{beginning-of-defun}
14008except that it moves point to the end of the definition.
14009@code{end-of-defun} can be used as part of an expression that
14010determines the position of the end of the definition.
14011
14012The set up for @code{count-words-in-defun} takes shape rapidly: first
14013we move point to the beginning of the definition, then we create a
14014local variable to hold the count, and finally, we record the position
14015of the end of the definition so the @code{while} loop will know when to stop
14016looping.
14017
14018@need 1250
14019The code looks like this:
14020
14021@smallexample
14022@group
14023(beginning-of-defun)
14024(let ((count 0)
14025 (end (save-excursion (end-of-defun) (point))))
14026@end group
14027@end smallexample
14028
14029@noindent
14030The code is simple. The only slight complication is likely to concern
14031@code{end}: it is bound to the position of the end of the definition
14032by a @code{save-excursion} expression that returns the value of point
14033after @code{end-of-defun} temporarily moves it to the end of the
14034definition.
14035
14036The second part of the @code{count-words-in-defun}, after the set up,
14037is the @code{while} loop.
14038
14039The loop must contain an expression that jumps point forward word by
14040word and symbol by symbol, and another expression that counts the
14041jumps. The true-or-false-test for the @code{while} loop should test
14042true so long as point should jump forward, and false when point is at
14043the end of the definition. We have already redefined the regular
14044expression for this (@pxref{Syntax}), so the loop is straightforward:
14045
14046@smallexample
14047@group
14048(while (and (< (point) end)
14049 (re-search-forward
14050 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14051 (setq count (1+ count)))
14052@end group
14053@end smallexample
14054
14055The third part of the function definition returns the count of words
14056and symbols. This part is the last expression within the body of the
14057@code{let} expression, and can be, very simply, the local variable
14058@code{count}, which when evaluated returns the count.
14059
14060@need 1250
14061Put together, the @code{count-words-in-defun} definition looks like this:
14062
14063@findex count-words-in-defun
14064@smallexample
14065@group
14066(defun count-words-in-defun ()
14067 "Return the number of words and symbols in a defun."
14068 (beginning-of-defun)
14069 (let ((count 0)
14070 (end (save-excursion (end-of-defun) (point))))
14071@end group
14072@group
14073 (while
14074 (and (< (point) end)
14075 (re-search-forward
14076 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14077 end t))
14078 (setq count (1+ count)))
14079 count))
14080@end group
14081@end smallexample
14082
14083How to test this? The function is not interactive, but it is easy to
14084put a wrapper around the function to make it interactive; we can use
14085almost the same code as for the recursive version of
14086@code{count-words-region}:
14087
14088@smallexample
14089@group
14090;;; @r{Interactive version.}
14091(defun count-words-defun ()
14092 "Number of words and symbols in a function definition."
14093 (interactive)
14094 (message
14095 "Counting words and symbols in function definition ... ")
14096@end group
14097@group
14098 (let ((count (count-words-in-defun)))
14099 (cond
14100 ((zerop count)
14101 (message
14102 "The definition does NOT have any words or symbols."))
14103@end group
14104@group
14105 ((= 1 count)
14106 (message
14107 "The definition has 1 word or symbol."))
14108 (t
14109 (message
14110 "The definition has %d words or symbols." count)))))
14111@end group
14112@end smallexample
14113
14114@need 800
14115@noindent
14116Let's re-use @kbd{C-c =} as a convenient keybinding:
14117
14118@smallexample
14119(global-set-key "\C-c=" 'count-words-defun)
14120@end smallexample
14121
14122Now we can try out @code{count-words-defun}: install both
14123@code{count-words-in-defun} and @code{count-words-defun}, and set the
14124keybinding, and then place the cursor within the following definition:
14125
14126@smallexample
14127@group
14128(defun multiply-by-seven (number)
14129 "Multiply NUMBER by seven."
14130 (* 7 number))
14131 @result{} 10
14132@end group
14133@end smallexample
14134
14135@noindent
14136Success! The definition has 10 words and symbols.
14137
14138The next problem is to count the numbers of words and symbols in
14139several definitions within a single file.
14140
14141@node Several defuns, Find a File, count-words-in-defun, Words in a defun
14142@section Count Several @code{defuns} Within a File
14143
14144A file such as @file{simple.el} may have 80 or more function
14145definitions within it. Our long term goal is to collect statistics on
14146many files, but as a first step, our immediate goal is to collect
14147statistics on one file.
14148
14149The information will be a series of numbers, each number being the
14150length of a function definition. We can store the numbers in a list.
14151
14152We know that we will want to incorporate the information regarding one
14153file with information about many other files; this means that the
14154function for counting definition lengths within one file need only
14155return the list of lengths. It need not and should not display any
14156messages.
14157
14158The word count commands contain one expression to jump point forward
14159word by word and another expression to count the jumps. The function
14160to return the lengths of definitions can be designed to work the same
14161way, with one expression to jump point forward definition by
14162definition and another expression to construct the lengths' list.
14163
14164This statement of the problem makes it elementary to write the
14165function definition. Clearly, we will start the count at the
14166beginning of the file, so the first command will be @code{(goto-char
14167(point-min))}. Next, we start the @code{while} loop; and the
14168true-or-false test of the loop can be a regular expression search for
14169the next function definition---so long as the search succeeds, point
14170is moved forward and then the body of the loop is evaluated. The body
14171needs an expression that constructs the lengths' list. @code{cons},
14172the list construction command, can be used to create the list. That
14173is almost all there is to it.
14174
14175@need 800
14176Here is what this fragment of code looks like:
14177
14178@smallexample
14179@group
14180(goto-char (point-min))
14181(while (re-search-forward "^(defun" nil t)
14182 (setq lengths-list
14183 (cons (count-words-in-defun) lengths-list)))
14184@end group
14185@end smallexample
14186
14187What we have left out is the mechanism for finding the file that
14188contains the function definitions.
14189
14190In previous examples, we either used this, the Info file, or we
14191switched back and forth to some other buffer, such as the
14192@file{*scratch*} buffer.
14193
14194Finding a file is a new process that we have not yet discussed.
14195
14196@node Find a File, lengths-list-file, Several defuns, Words in a defun
14197@comment node-name, next, previous, up
14198@section Find a File
14199@cindex Find a File
14200
14201To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14202command. This command is almost, but not quite right for the lengths
14203problem.
14204
14205@need 1200
14206Let's look at the source for @code{find-file} (you can use the
14207@code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14208find the source of a function):
14209
14210@smallexample
14211@group
14212(defun find-file (filename)
14213 "Edit file FILENAME.
14214Switch to a buffer visiting file FILENAME,
14215creating one if none already exists."
14216 (interactive "FFind file: ")
14217 (switch-to-buffer (find-file-noselect filename)))
14218@end group
14219@end smallexample
14220
14221The definition possesses short but complete documentation and an
14222interactive specification that prompts you for a file name when you
14223use the command interactively. The body of the definition contains
14224two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14225
14226According to its documentation as shown by @kbd{C-h f} (the
14227@code{describe-function} command), the @code{find-file-noselect}
14228function reads the named file into a buffer and returns the buffer.
14229However, the buffer is not selected. Emacs does not switch its
14230attention (or yours if you are using @code{find-file-noselect}) to the
14231named buffer. That is what @code{switch-to-buffer} does: it switches
14232the buffer to which Emacs attention is directed; and it switches the
14233buffer displayed in the window to the new buffer. We have discussed
14234buffer switching elsewhere. (@xref{Switching Buffers}.)
14235
14236In this histogram project, we do not need to display each file on the
14237screen as the program determines the length of each definition within
14238it. Instead of employing @code{switch-to-buffer}, we can work with
14239@code{set-buffer}, which redirects the attention of the computer
14240program to a different buffer but does not redisplay it on the screen.
14241So instead of calling on @code{find-file} to do the job, we must write
14242our own expression.
14243
14244The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
14245
14246@node lengths-list-file, Several files, Find a File, Words in a defun
14247@section @code{lengths-list-file} in Detail
14248
14249The core of the @code{lengths-list-file} function is a @code{while}
14250loop containing a function to move point forward `defun by defun' and
14251a function to count the number of words and symbols in each defun.
14252This core must be surrounded by functions that do various other tasks,
14253including finding the file, and ensuring that point starts out at the
14254beginning of the file. The function definition looks like this:
14255@findex lengths-list-file
14256
14257@smallexample
14258@group
14259(defun lengths-list-file (filename)
14260 "Return list of definitions' lengths within FILE.
14261The returned list is a list of numbers.
14262Each number is the number of words or
14263symbols in one function definition."
14264@end group
14265@group
14266 (message "Working on `%s' ... " filename)
14267 (save-excursion
14268 (let ((buffer (find-file-noselect filename))
14269 (lengths-list))
14270 (set-buffer buffer)
14271 (setq buffer-read-only t)
14272 (widen)
14273 (goto-char (point-min))
14274 (while (re-search-forward "^(defun" nil t)
14275 (setq lengths-list
14276 (cons (count-words-in-defun) lengths-list)))
14277 (kill-buffer buffer)
14278 lengths-list)))
14279@end group
14280@end smallexample
14281
14282@noindent
14283The function is passed one argument, the name of the file on which it
14284will work. It has four lines of documentation, but no interactive
14285specification. Since people worry that a computer is broken if they
14286don't see anything going on, the first line of the body is a
14287message.
14288
14289The next line contains a @code{save-excursion} that returns Emacs'
14290attention to the current buffer when the function completes. This is
14291useful in case you embed this function in another function that
14292presumes point is restored to the original buffer.
14293
14294In the varlist of the @code{let} expression, Emacs finds the file and
14295binds the local variable @code{buffer} to the buffer containing the
14296file. At the same time, Emacs creates @code{lengths-list} as a local
14297variable.
14298
14299Next, Emacs switches its attention to the buffer.
14300
14301In the following line, Emacs makes the buffer read-only. Ideally,
14302this line is not necessary. None of the functions for counting words
14303and symbols in a function definition should change the buffer.
14304Besides, the buffer is not going to be saved, even if it were changed.
14305This line is entirely the consequence of great, perhaps excessive,
14306caution. The reason for the caution is that this function and those
14307it calls work on the sources for Emacs and it is very inconvenient if
14308they are inadvertently modified. It goes without saying that I did
14309not realize a need for this line until an experiment went awry and
14310started to modify my Emacs source files @dots{}
14311
14312Next comes a call to widen the buffer if it is narrowed. This
14313function is usually not needed---Emacs creates a fresh buffer if none
14314already exists; but if a buffer visiting the file already exists Emacs
14315returns that one. In this case, the buffer may be narrowed and must
14316be widened. If we wanted to be fully `user-friendly', we would
14317arrange to save the restriction and the location of point, but we
14318won't.
14319
14320The @code{(goto-char (point-min))} expression moves point to the
14321beginning of the buffer.
14322
14323Then comes a @code{while} loop in which the `work' of the function is
14324carried out. In the loop, Emacs determines the length of each
14325definition and constructs a lengths' list containing the information.
14326
14327Emacs kills the buffer after working through it. This is to save
14328space inside of Emacs. My version of Emacs 19 contained over 300
14329source files of interest; Emacs 21 contains over 800 source files.
14330Another function will apply @code{lengths-list-file} to each of the
14331files.
14332
14333Finally, the last expression within the @code{let} expression is the
14334@code{lengths-list} variable; its value is returned as the value of
14335the whole function.
14336
14337You can try this function by installing it in the usual fashion. Then
14338place your cursor after the following expression and type @kbd{C-x
14339C-e} (@code{eval-last-sexp}).
14340
14341@c !!! 21.0.100 lisp sources location here
14342@smallexample
14343(lengths-list-file
14344 "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14345@end smallexample
14346
14347@c was: (lengths-list-file "../lisp/debug.el")
14348@c !!! as of 21, Info file is in
14349@c /usr/share/info/emacs-lisp-intro.info.gz
14350@c but debug.el is in /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14351
14352@noindent
14353(You may need to change the pathname of the file; the one here worked
14354with GNU Emacs version 21.0.100. To change the expression, copy it to
14355the @file{*scratch*} buffer and edit it.
14356
14357@need 1200
14358@noindent
14359(Also, to see the full length of the list, rather than a truncated
14360version, you may have to evaluate the following:
14361
14362@smallexample
14363(custom-set-variables '(eval-expression-print-length nil))
14364@end smallexample
14365
14366@noindent
14367(@xref{defcustom, , Setting Variables with @code{defcustom}}.
14368Then evaluate the @code{lengths-list-file} expression.)
14369
14370@need 1200
14371The lengths' list for @file{debug.el} takes less than a second to
14372produce and looks like this:
14373
14374@smallexample
14375(77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14376@end smallexample
14377
14378@need 1500
14379(Using my old machine, the version 19 lengths' list for @file{debug.el}
14380took seven seconds to produce and looked like this:
14381
14382@smallexample
14383(75 41 80 62 20 45 44 68 45 12 34 235)
14384@end smallexample
14385
14386(The newer version of @file{debug.el} contains more defuns than the
14387earlier one; and my new machine is much faster than the old one.)
14388
14389Note that the length of the last definition in the file is first in
14390the list.
14391
14392@node Several files, Several files recursively, lengths-list-file, Words in a defun
14393@section Count Words in @code{defuns} in Different Files
14394
14395In the previous section, we created a function that returns a list of
14396the lengths of each definition in a file. Now, we want to define a
14397function to return a master list of the lengths of the definitions in
14398a list of files.
14399
14400Working on each of a list of files is a repetitious act, so we can use
14401either a @code{while} loop or recursion.
14402
14403@menu
14404* lengths-list-many-files:: Return a list of the lengths of defuns.
14405* append:: Attach one list to another.
14406@end menu
14407
14408@node lengths-list-many-files, append, Several files, Several files
14409@ifnottex
14410@unnumberedsubsec Determine the lengths of @code{defuns}
14411@end ifnottex
14412
14413The design using a @code{while} loop is routine. The argument passed
14414the function is a list of files. As we saw earlier (@pxref{Loop
14415Example}), you can write a @code{while} loop so that the body of the
14416loop is evaluated if such a list contains elements, but to exit the
14417loop if the list is empty. For this design to work, the body of the
14418loop must contain an expression that shortens the list each time the
14419body is evaluated, so that eventually the list is empty. The usual
14420technique is to set the value of the list to the value of the @sc{cdr}
14421of the list each time the body is evaluated.
14422
14423@need 800
14424The template looks like this:
14425
14426@smallexample
14427@group
14428(while @var{test-whether-list-is-empty}
14429 @var{body}@dots{}
14430 @var{set-list-to-cdr-of-list})
14431@end group
14432@end smallexample
14433
14434Also, we remember that a @code{while} loop returns @code{nil} (the
14435result of evaluating the true-or-false-test), not the result of any
14436evaluation within its body. (The evaluations within the body of the
14437loop are done for their side effects.) However, the expression that
14438sets the lengths' list is part of the body---and that is the value
14439that we want returned by the function as a whole. To do this, we
14440enclose the @code{while} loop within a @code{let} expression, and
14441arrange that the last element of the @code{let} expression contains
14442the value of the lengths' list. (@xref{Incrementing Example, , Loop
14443Example with an Incrementing Counter}.)
14444
14445@findex lengths-list-many-files
14446@need 1250
14447These considerations lead us directly to the function itself:
14448
14449@smallexample
14450@group
14451;;; @r{Use @code{while} loop.}
14452(defun lengths-list-many-files (list-of-files)
14453 "Return list of lengths of defuns in LIST-OF-FILES."
14454@end group
14455@group
14456 (let (lengths-list)
14457
14458;;; @r{true-or-false-test}
14459 (while list-of-files
14460 (setq lengths-list
14461 (append
14462 lengths-list
14463
14464;;; @r{Generate a lengths' list.}
14465 (lengths-list-file
14466 (expand-file-name (car list-of-files)))))
14467@end group
14468
14469@group
14470;;; @r{Make files' list shorter.}
14471 (setq list-of-files (cdr list-of-files)))
14472
14473;;; @r{Return final value of lengths' list.}
14474 lengths-list))
14475@end group
14476@end smallexample
14477
14478@code{expand-file-name} is a built-in function that converts a file
14479name to the absolute, long, path name form of the directory in which
14480the function is called.
14481
14482@c !!! 21.0.100 lisp sources location here
14483@need 1500
14484Thus, if @code{expand-file-name} is called on @code{debug.el} when
14485Emacs is visiting the
14486@file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14487
14488@smallexample
14489debug.el
14490@end smallexample
14491
14492@need 800
14493@noindent
14494becomes
14495
14496@c !!! 21.0.100 lisp sources location here
14497@smallexample
14498/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14499@end smallexample
14500
14501The only other new element of this function definition is the as yet
14502unstudied function @code{append}, which merits a short section for
14503itself.
14504
14505@node append, , lengths-list-many-files, Several files
14506@subsection The @code{append} Function
14507
14508@need 800
14509The @code{append} function attaches one list to another. Thus,
14510
14511@smallexample
14512(append '(1 2 3 4) '(5 6 7 8))
14513@end smallexample
14514
14515@need 800
14516@noindent
14517produces the list
14518
14519@smallexample
14520(1 2 3 4 5 6 7 8)
14521@end smallexample
14522
14523This is exactly how we want to attach two lengths' lists produced by
14524@code{lengths-list-file} to each other. The results contrast with
14525@code{cons},
14526
14527@smallexample
14528(cons '(1 2 3 4) '(5 6 7 8))
14529@end smallexample
14530
14531@need 1250
14532@noindent
14533which constructs a new list in which the first argument to @code{cons}
14534becomes the first element of the new list:
14535
14536@smallexample
14537((1 2 3 4) 5 6 7 8)
14538@end smallexample
14539
14540@node Several files recursively, Prepare the data, Several files, Words in a defun
14541@section Recursively Count Words in Different Files
14542
14543Besides a @code{while} loop, you can work on each of a list of files
14544with recursion. A recursive version of @code{lengths-list-many-files}
14545is short and simple.
14546
14547The recursive function has the usual parts: the `do-again-test', the
14548`next-step-expression', and the recursive call. The `do-again-test'
14549determines whether the function should call itself again, which it
14550will do if the @code{list-of-files} contains any remaining elements;
14551the `next-step-expression' resets the @code{list-of-files} to the
14552@sc{cdr} of itself, so eventually the list will be empty; and the
14553recursive call calls itself on the shorter list. The complete
14554function is shorter than this description!
14555@findex recursive-lengths-list-many-files
14556
14557@smallexample
14558@group
14559(defun recursive-lengths-list-many-files (list-of-files)
14560 "Return list of lengths of each defun in LIST-OF-FILES."
14561 (if list-of-files ; @r{do-again-test}
14562 (append
14563 (lengths-list-file
14564 (expand-file-name (car list-of-files)))
14565 (recursive-lengths-list-many-files
14566 (cdr list-of-files)))))
14567@end group
14568@end smallexample
14569
14570@noindent
14571In a sentence, the function returns the lengths' list for the first of
14572the @code{list-of-files} appended to the result of calling itself on
14573the rest of the @code{list-of-files}.
14574
14575Here is a test of @code{recursive-lengths-list-many-files}, along with
14576the results of running @code{lengths-list-file} on each of the files
14577individually.
14578
14579Install @code{recursive-lengths-list-many-files} and
14580@code{lengths-list-file}, if necessary, and then evaluate the
14581following expressions. You may need to change the files' pathnames;
14582those here work when this Info file and the Emacs sources are located
14583in their customary places. To change the expressions, copy them to
14584the @file{*scratch*} buffer, edit them, and then evaluate them.
14585
14586The results are shown after the @samp{@result{}}. (These results are
14587for files from Emacs Version 21.0.100; files from other versions of
14588Emacs may produce different results.)
14589
14590@c !!! 21.0.100 lisp sources location here
14591@smallexample
14592@group
14593(cd "/usr/local/share/emacs/21.0.100/")
14594
14595(lengths-list-file "./lisp/macros.el")
14596 @result{} (273 263 456 90)
14597@end group
14598
14599@group
14600(lengths-list-file "./lisp/mail/mailalias.el")
14601 @result{} (38 32 26 77 174 180 321 198 324)
14602@end group
14603
14604@group
14605(lengths-list-file "./lisp/makesum.el")
14606 @result{} (85 181)
14607@end group
14608
14609@group
14610(recursive-lengths-list-many-files
14611 '("./lisp/macros.el"
14612 "./lisp/mail/mailalias.el"
14613 "./lisp/makesum.el"))
14614 @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14615@end group
14616@end smallexample
14617
14618The @code{recursive-lengths-list-many-files} function produces the
14619output we want.
14620
14621The next step is to prepare the data in the list for display in a graph.
14622
14623@node Prepare the data, , Several files recursively, Words in a defun
14624@section Prepare the Data for Display in a Graph
14625
14626The @code{recursive-lengths-list-many-files} function returns a list
14627of numbers. Each number records the length of a function definition.
14628What we need to do now is transform this data into a list of numbers
14629suitable for generating a graph. The new list will tell how many
14630functions definitions contain less than 10 words and
14631symbols, how many contain between 10 and 19 words and symbols, how
14632many contain between 20 and 29 words and symbols, and so on.
14633
14634In brief, we need to go through the lengths' list produced by the
14635@code{recursive-lengths-list-many-files} function and count the number
14636of defuns within each range of lengths, and produce a list of those
14637numbers.
14638
14639Based on what we have done before, we can readily foresee that it
14640should not be too hard to write a function that `@sc{cdr}s' down the
14641lengths' list, looks at each element, determines which length range it
14642is in, and increments a counter for that range.
14643
14644However, before beginning to write such a function, we should consider
14645the advantages of sorting the lengths' list first, so the numbers are
14646ordered from smallest to largest. First, sorting will make it easier
14647to count the numbers in each range, since two adjacent numbers will
14648either be in the same length range or in adjacent ranges. Second, by
14649inspecting a sorted list, we can discover the highest and lowest
14650number, and thereby determine the largest and smallest length range
14651that we will need.
14652
14653@menu
14654* Sorting:: Sorting lists.
14655* Files List:: Making a list of files.
14656* Counting function definitions::
14657@end menu
14658
14659@node Sorting, Files List, Prepare the data, Prepare the data
14660@subsection Sorting Lists
14661@findex sort
14662
14663Emacs contains a function to sort lists, called (as you might guess)
14664@code{sort}. The @code{sort} function takes two arguments, the list
14665to be sorted, and a predicate that determines whether the first of
14666two list elements is ``less'' than the second.
14667
14668As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14669Type Object as an Argument}), a predicate is a function that
14670determines whether some property is true or false. The @code{sort}
14671function will reorder a list according to whatever property the
14672predicate uses; this means that @code{sort} can be used to sort
14673non-numeric lists by non-numeric criteria---it can, for example,
14674alphabetize a list.
14675
14676@need 1250
14677The @code{<} function is used when sorting a numeric list. For example,
14678
14679@smallexample
14680(sort '(4 8 21 17 33 7 21 7) '<)
14681@end smallexample
14682
14683@need 800
14684@noindent
14685produces this:
14686
14687@smallexample
14688(4 7 7 8 17 21 21 33)
14689@end smallexample
14690
14691@noindent
14692(Note that in this example, both the arguments are quoted so that the
14693symbols are not evaluated before being passed to @code{sort} as
14694arguments.)
14695
14696Sorting the list returned by the
14697@code{recursive-lengths-list-many-files} function is straightforward;
14698it uses the @code{<} function:
14699
14700@smallexample
14701@group
14702(sort
14703 (recursive-lengths-list-many-files
14704 '("../lisp/macros.el"
14705 "../lisp/mailalias.el"
14706 "../lisp/makesum.el"))
14707 '<
14708@end group
14709@end smallexample
14710
14711@need 800
14712@noindent
14713which produces:
14714
14715@smallexample
14716(85 86 116 122 154 176 179 265)
14717@end smallexample
14718
14719@noindent
14720(Note that in this example, the first argument to @code{sort} is not
14721quoted, since the expression must be evaluated so as to produce the
14722list that is passed to @code{sort}.)
14723
14724@node Files List, Counting function definitions, Sorting, Prepare the data
14725@subsection Making a List of Files
14726
14727The @code{recursive-lengths-list-many-files} function requires a list
14728of files as its argument. For our test examples, we constructed such
14729a list by hand; but the Emacs Lisp source directory is too large for
14730us to do for that. Instead, we will write a function to do the job
14731for us. In this function, we will use both a @code{while} loop and a
14732recursive call.
14733
14734@findex directory-files
14735We did not have to write a function like this for older versions of
14736GNU Emacs, since they placed all the @samp{.el} files in one
14737directory. Instead, we were able to use the @code{directory-files}
14738function, which lists the names of files that match a specified
14739pattern within a single directory.
14740
14741However, recent versions of Emacs place Emacs Lisp files in
14742sub-directories of the top level @file{lisp} directory. This
14743re-arrangement eases navigation. For example, all the mail related
14744files are in a @file{lisp} sub-directory called @file{mail}. But at
14745the same time, this arrangement forces us to create a file listing
14746function that descends into the sub-directories.
14747
14748@findex files-in-below-directory
14749We can create this function, called @code{files-in-below-directory},
14750using familiar functions such as @code{car}, @code{nthcdr}, and
14751@code{substring} in conjunction with an existing function called
14752@code{directory-files-and-attributes}. This latter function not only
14753lists all the filenames in a directory, including the names
14754of sub-directories, but also their attributes.
14755
14756To restate our goal: to create a function that will enable us
14757to feed filenames to @code{recursive-lengths-list-many-files}
14758as a list that looks like this (but with more elements):
14759
14760@smallexample
14761@group
14762("../lisp/macros.el"
14763 "../lisp/mail/rmail.el"
14764 "../lisp/makesum.el")
14765@end group
14766@end smallexample
14767
14768The @code{directory-files-and-attributes} function returns a list of
14769lists. Each of the lists within the main list consists of 13
14770elements. The first element is a string that contains the name of the
14771file -- which, in GNU/Linux, may be a `directory file', that is to
14772say, a file with the special attributes of a directory. The second
14773element of the list is @code{t} for a directory, a string
14774for symbolic link (the string is the name linked to), or @code{nil}.
14775
14776For example, the first @samp{.el} file in the @file{lisp/} directory
14777is @file{abbrev.el}. Its name is
14778@file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14779directory or a symbolic link.
14780
14781@need 1000
14782This is how @code{directory-files-and-attributes} lists that file and
14783its attributes:
14784
14785@smallexample
14786@group
14787("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14788nil
147891
147901000
14791100
14792@end group
14793@group
14794(15019 32380)
14795(14883 48041)
14796(15214 49336)
1479711583
14798"-rw-rw-r--"
14799@end group
14800@group
14801t
14802341385
14803776)
14804@end group
14805@end smallexample
14806
14807@need 1200
14808On the other hand, @file{mail/} is a directory within the @file{lisp/}
14809directory. The beginning of its listing looks like this:
14810
14811@smallexample
14812@group
14813("/usr/local/share/emacs/21.0.100/lisp/mail"
14814t
14815@dots{}
14816)
14817@end group
14818@end smallexample
14819
14820(Look at the documentation of @code{file-attributes} to learn about
14821the different attributes. Bear in mind that the
14822@code{file-attributes} function does not list the filename, so its
14823first element is @code{directory-files-and-attributes}'s second
14824element.)
14825
14826We will want our new function, @code{files-in-below-directory}, to
14827list the @samp{.el} files in the directory it is told to check, and in
14828any directories below that directory.
14829
14830This gives us a hint on how to construct
14831@code{files-in-below-directory}: within a directory, the function
14832should add @samp{.el} filenames to a list; and if, within a directory,
14833the function comes upon a sub-directory, it should go into that
14834sub-directory and repeat its actions.
14835
14836However, we should note that every directory contains a name that
14837refers to itself, called @file{.}, (``dot'') and a name that refers to
14838its parent directory, called @file{..} (``double dot''). (In
14839@file{/}, the root directory, @file{..} refers to itself, since
14840@file{/} has no parent.) Clearly, we do not want our
14841@code{files-in-below-directory} function to enter those directories,
14842since they always lead us, directly or indirectly, to the current
14843directory.
14844
14845Consequently, our @code{files-in-below-directory} function must do
14846several tasks:
14847
14848@itemize @bullet
14849@item
14850Check to see whether it is looking at a filename that ends in
14851@samp{.el}; and if so, add its name to a list.
14852
14853@item
14854Check to see whether it is looking at a filename that is the name of a
14855directory; and if so,
14856
14857@itemize @minus
14858@item
14859Check to see whether it is looking at @file{.} or @file{..}; and if
14860so skip it.
14861
14862@item
14863Or else, go into that directory and repeat the process.
14864@end itemize
14865@end itemize
14866
14867Let's write a function definition to do these tasks. We will use a
14868@code{while} loop to move from one filename to another within a
14869directory, checking what needs to be done; and we will use a recursive
14870call to repeat the actions on each sub-directory. The recursive
14871pattern is `accumulate'
14872(@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14873using @code{append} as the combiner.
14874
14875@ignore
14876(directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14877(shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14878@end ignore
14879
14880@c /usr/local/share/emacs/21.0.100/lisp/
14881
14882@need 800
14883Here is the function:
14884
14885@smallexample
14886@group
14887(defun files-in-below-directory (directory)
14888 "List the .el files in DIRECTORY and in its sub-directories."
14889 ;; Although the function will be used non-interactively,
14890 ;; it will be easier to test if we make it interactive.
14891 ;; The directory will have a name such as
14892 ;; "/usr/local/share/emacs/21.0.100/lisp/"
14893 (interactive "DDirectory name: ")
14894@end group
14895@group
14896 (let (el-files-list
14897 (current-directory-list
14898 (directory-files-and-attributes directory t)))
14899 ;; while we are in the current directory
14900 (while current-directory-list
14901@end group
14902@group
14903 (cond
14904 ;; check to see whether filename ends in `.el'
14905 ;; and if so, append its name to a list.
14906 ((equal ".el" (substring (car (car current-directory-list)) -3))
14907 (setq el-files-list
14908 (cons (car (car current-directory-list)) el-files-list)))
14909@end group
14910@group
14911 ;; check whether filename is that of a directory
14912 ((eq t (car (cdr (car current-directory-list))))
14913 ;; decide whether to skip or recurse
14914 (if
14915 (equal (or "." "..")
14916 (substring (car (car current-directory-list)) -1))
14917 ;; then do nothing if filename is that of
14918 ;; current directory or parent
14919 ()
14920@end group
14921@group
14922 ;; else descend into the directory and repeat the process
14923 (setq el-files-list
14924 (append
14925 (files-in-below-directory
14926 (car (car current-directory-list)))
14927 el-files-list)))))
14928 ;; move to the next filename in the list; this also
14929 ;; shortens the list so the while loop eventually comes to an end
14930 (setq current-directory-list (cdr current-directory-list)))
14931 ;; return the filenames
14932 el-files-list))
14933@end group
14934@end smallexample
14935
14936@c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14937
14938The @code{files-in-below-directory} @code{directory-files} function
14939takes one argument, the name of a directory.
14940
14941@need 1250
14942Thus, on my system,
14943
14944@c !!! 21.0.100 lisp sources location here
14945@smallexample
14946@group
14947(length
14948 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14949@end group
14950@end smallexample
14951
14952@noindent
14953tells me that my version 21.0.100 Lisp sources directory contains 754
14954@samp{.el} files.
14955
14956@code{files-in-below-directory} returns a list in reverse alphabetical
14957order. An expression to sort the list in alphabetical order looks
14958like this:
14959
14960@smallexample
14961@group
14962(sort
14963 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14964 'string-lessp)
14965@end group
14966@end smallexample
14967
14968@ignore
14969(defun test ()
14970 "Test how long it takes to find lengths of all elisp defuns."
14971 (insert "\n" (current-time-string) "\n")
14972 (sit-for 0)
14973 (sort
14974 (recursive-lengths-list-many-files
14975 '("../lisp/macros.el"
14976 "../lisp/mailalias.el"
14977 "../lisp/makesum.el"))
14978 '<)
14979 (insert (format "%s" (current-time-string))))
14980
14981@end ignore
14982
14983@node Counting function definitions, , Files List, Prepare the data
14984@subsection Counting function definitions
14985
14986Our immediate goal is to generate a list that tells us how many
14987function definitions contain fewer than 10 words and symbols, how many
14988contain between 10 and 19 words and symbols, how many contain between
1498920 and 29 words and symbols, and so on.
14990
14991With a sorted list of numbers, this is easy: count how many elements
14992of the list are smaller than 10, then, after moving past the numbers
14993just counted, count how many are smaller than 20, then, after moving
14994past the numbers just counted, count how many are smaller than 30, and
14995so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
14996larger than the top of that range. We can call the list of such
14997numbers the @code{top-of-ranges} list.
14998
14999@need 1200
15000If we wished, we could generate this list automatically, but it is
15001simpler to write a list manually. Here it is:
15002@vindex top-of-ranges
15003
15004@smallexample
15005@group
15006(defvar top-of-ranges
15007 '(10 20 30 40 50
15008 60 70 80 90 100
15009 110 120 130 140 150
15010 160 170 180 190 200
15011 210 220 230 240 250
15012 260 270 280 290 300)
15013 "List specifying ranges for `defuns-per-range'.")
15014@end group
15015@end smallexample
15016
15017To change the ranges, we edit this list.
15018
15019Next, we need to write the function that creates the list of the
15020number of definitions within each range. Clearly, this function must
15021take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15022as arguments.
15023
15024The @code{defuns-per-range} function must do two things again and
15025again: it must count the number of definitions within a range
15026specified by the current top-of-range value; and it must shift to the
15027next higher value in the @code{top-of-ranges} list after counting the
15028number of definitions in the current range. Since each of these
15029actions is repetitive, we can use @code{while} loops for the job.
15030One loop counts the number of definitions in the range defined by the
15031current top-of-range value, and the other loop selects each of the
15032top-of-range values in turn.
15033
15034Several entries of the @code{sorted-lengths} list are counted for each
15035range; this means that the loop for the @code{sorted-lengths} list
15036will be inside the loop for the @code{top-of-ranges} list, like a
15037small gear inside a big gear.
15038
15039The inner loop counts the number of definitions within the range. It
15040is a simple counting loop of the type we have seen before.
15041(@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15042The true-or-false test of the loop tests whether the value from the
15043@code{sorted-lengths} list is smaller than the current value of the
15044top of the range. If it is, the function increments the counter and
15045tests the next value from the @code{sorted-lengths} list.
15046
15047@need 1250
15048The inner loop looks like this:
15049
15050@smallexample
15051@group
15052(while @var{length-element-smaller-than-top-of-range}
15053 (setq number-within-range (1+ number-within-range))
15054 (setq sorted-lengths (cdr sorted-lengths)))
15055@end group
15056@end smallexample
15057
15058The outer loop must start with the lowest value of the
15059@code{top-of-ranges} list, and then be set to each of the succeeding
15060higher values in turn. This can be done with a loop like this:
15061
15062@smallexample
15063@group
15064(while top-of-ranges
15065 @var{body-of-loop}@dots{}
15066 (setq top-of-ranges (cdr top-of-ranges)))
15067@end group
15068@end smallexample
15069
15070@need 1200
15071Put together, the two loops look like this:
15072
15073@smallexample
15074@group
15075(while top-of-ranges
15076
15077 ;; @r{Count the number of elements within the current range.}
15078 (while @var{length-element-smaller-than-top-of-range}
15079 (setq number-within-range (1+ number-within-range))
15080 (setq sorted-lengths (cdr sorted-lengths)))
15081
15082 ;; @r{Move to next range.}
15083 (setq top-of-ranges (cdr top-of-ranges)))
15084@end group
15085@end smallexample
15086
15087In addition, in each circuit of the outer loop, Emacs should record
15088the number of definitions within that range (the value of
15089@code{number-within-range}) in a list. We can use @code{cons} for
15090this purpose. (@xref{cons, , @code{cons}}.)
15091
15092The @code{cons} function works fine, except that the list it
15093constructs will contain the number of definitions for the highest
15094range at its beginning and the number of definitions for the lowest
15095range at its end. This is because @code{cons} attaches new elements
15096of the list to the beginning of the list, and since the two loops are
15097working their way through the lengths' list from the lower end first,
15098the @code{defuns-per-range-list} will end up largest number first.
15099But we will want to print our graph with smallest values first and the
15100larger later. The solution is to reverse the order of the
15101@code{defuns-per-range-list}. We can do this using the
15102@code{nreverse} function, which reverses the order of a list.
15103@findex nreverse
15104
15105@need 800
15106For example,
15107
15108@smallexample
15109(nreverse '(1 2 3 4))
15110@end smallexample
15111
15112@need 800
15113@noindent
15114produces:
15115
15116@smallexample
15117(4 3 2 1)
15118@end smallexample
15119
15120Note that the @code{nreverse} function is ``destructive''---that is,
15121it changes the list to which it is applied; this contrasts with the
15122@code{car} and @code{cdr} functions, which are non-destructive. In
15123this case, we do not want the original @code{defuns-per-range-list},
15124so it does not matter that it is destroyed. (The @code{reverse}
15125function provides a reversed copy of a list, leaving the original list
15126as is.)
15127@findex reverse
15128
15129@need 1250
15130Put all together, the @code{defuns-per-range} looks like this:
15131
15132@smallexample
15133@group
15134(defun defuns-per-range (sorted-lengths top-of-ranges)
15135 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15136 (let ((top-of-range (car top-of-ranges))
15137 (number-within-range 0)
15138 defuns-per-range-list)
15139@end group
15140
15141@group
15142 ;; @r{Outer loop.}
15143 (while top-of-ranges
15144@end group
15145
15146@group
15147 ;; @r{Inner loop.}
15148 (while (and
15149 ;; @r{Need number for numeric test.}
15150 (car sorted-lengths)
15151 (< (car sorted-lengths) top-of-range))
15152@end group
15153
15154@group
15155 ;; @r{Count number of definitions within current range.}
15156 (setq number-within-range (1+ number-within-range))
15157 (setq sorted-lengths (cdr sorted-lengths)))
15158
15159 ;; @r{Exit inner loop but remain within outer loop.}
15160@end group
15161
15162@group
15163 (setq defuns-per-range-list
15164 (cons number-within-range defuns-per-range-list))
15165 (setq number-within-range 0) ; @r{Reset count to zero.}
15166@end group
15167
15168@group
15169 ;; @r{Move to next range.}
15170 (setq top-of-ranges (cdr top-of-ranges))
15171 ;; @r{Specify next top of range value.}
15172 (setq top-of-range (car top-of-ranges)))
15173@end group
15174
15175@group
15176 ;; @r{Exit outer loop and count the number of defuns larger than}
15177 ;; @r{ the largest top-of-range value.}
15178 (setq defuns-per-range-list
15179 (cons
15180 (length sorted-lengths)
15181 defuns-per-range-list))
15182@end group
15183
15184@group
15185 ;; @r{Return a list of the number of definitions within each range,}
15186 ;; @r{ smallest to largest.}
15187 (nreverse defuns-per-range-list)))
15188@end group
15189@end smallexample
15190
15191@need 1200
15192@noindent
15193The function is straightforward except for one subtle feature. The
15194true-or-false test of the inner loop looks like this:
15195
15196@smallexample
15197@group
15198(and (car sorted-lengths)
15199 (< (car sorted-lengths) top-of-range))
15200@end group
15201@end smallexample
15202
15203@need 800
15204@noindent
15205instead of like this:
15206
15207@smallexample
15208(< (car sorted-lengths) top-of-range)
15209@end smallexample
15210
15211The purpose of the test is to determine whether the first item in the
15212@code{sorted-lengths} list is less than the value of the top of the
15213range.
15214
15215The simple version of the test works fine unless the
15216@code{sorted-lengths} list has a @code{nil} value. In that case, the
15217@code{(car sorted-lengths)} expression function returns
15218@code{nil}. The @code{<} function cannot compare a number to
15219@code{nil}, which is an empty list, so Emacs signals an error and
15220stops the function from attempting to continue to execute.
15221
15222The @code{sorted-lengths} list always becomes @code{nil} when the
15223counter reaches the end of the list. This means that any attempt to
15224use the @code{defuns-per-range} function with the simple version of
15225the test will fail.
15226
15227We solve the problem by using the @code{(car sorted-lengths)}
15228expression in conjunction with the @code{and} expression. The
15229@code{(car sorted-lengths)} expression returns a non-@code{nil}
15230value so long as the list has at least one number within it, but
15231returns @code{nil} if the list is empty. The @code{and} expression
15232first evaluates the @code{(car sorted-lengths)} expression, and
15233if it is @code{nil}, returns false @emph{without} evaluating the
15234@code{<} expression. But if the @code{(car sorted-lengths)}
15235expression returns a non-@code{nil} value, the @code{and} expression
15236evaluates the @code{<} expression, and returns that value as the value
15237of the @code{and} expression.
15238
15239@c colon in printed section title causes problem in Info cross reference
15240This way, we avoid an error.
15241@iftex
15242@xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15243Functions}, for more information about @code{and}.
15244@end iftex
15245@ifinfo
15246@xref{forward-paragraph}, for more information about @code{and}.
15247@end ifinfo
15248
15249Here is a short test of the @code{defuns-per-range} function. First,
15250evaluate the expression that binds (a shortened)
15251@code{top-of-ranges} list to the list of values, then evaluate the
15252expression for binding the @code{sorted-lengths} list, and then
15253evaluate the @code{defuns-per-range} function.
15254
15255@smallexample
15256@group
15257;; @r{(Shorter list than we will use later.)}
15258(setq top-of-ranges
15259 '(110 120 130 140 150
15260 160 170 180 190 200))
15261
15262(setq sorted-lengths
15263 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15264
15265(defuns-per-range sorted-lengths top-of-ranges)
15266@end group
15267@end smallexample
15268
15269@need 800
15270@noindent
15271The list returned looks like this:
15272
15273@smallexample
15274(2 2 2 0 0 1 0 2 0 0 4)
15275@end smallexample
15276
15277@noindent
15278Indeed, there are two elements of the @code{sorted-lengths} list
15279smaller than 110, two elements between 110 and 119, two elements
15280between 120 and 129, and so on. There are four elements with a value
15281of 200 or larger.
15282
15283@c The next step is to turn this numbers' list into a graph.
15284
15285@node Readying a Graph, Emacs Initialization, Words in a defun, Top
15286@chapter Readying a Graph
15287@cindex Readying a graph
15288@cindex Graph prototype
15289@cindex Prototype graph
15290@cindex Body of graph
15291
15292Our goal is to construct a graph showing the numbers of function
15293definitions of various lengths in the Emacs lisp sources.
15294
15295As a practical matter, if you were creating a graph, you would
15296probably use a program such as @code{gnuplot} to do the job.
15297(@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
15298however, we create one from scratch, and in the process we will
15299re-acquaint ourselves with some of what we learned before and learn
15300more.
15301
15302In this chapter, we will first write a simple graph printing function.
15303This first definition will be a @dfn{prototype}, a rapidly written
15304function that enables us to reconnoiter this unknown graph-making
15305territory. We will discover dragons, or find that they are myth.
15306After scouting the terrain, we will feel more confident and enhance
15307the function to label the axes automatically.
15308
15309@menu
15310* Columns of a graph::
15311* graph-body-print:: How to print the body of a graph.
15312* recursive-graph-body-print::
15313* Printed Axes::
15314* Line Graph Exercise::
15315@end menu
15316
15317@node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15318@ifnottex
15319@unnumberedsec Printing the Columns of a Graph
15320@end ifnottex
15321
15322Since Emacs is designed to be flexible and work with all kinds of
15323terminals, including character-only terminals, the graph will need to
15324be made from one of the `typewriter' symbols. An asterisk will do; as
15325we enhance the graph-printing function, we can make the choice of
15326symbol a user option.
15327
15328We can call this function @code{graph-body-print}; it will take a
15329@code{numbers-list} as its only argument. At this stage, we will not
15330label the graph, but only print its body.
15331
15332The @code{graph-body-print} function inserts a vertical column of
15333asterisks for each element in the @code{numbers-list}. The height of
15334each line is determined by the value of that element of the
15335@code{numbers-list}.
15336
15337Inserting columns is a repetitive act; that means that this function can
15338be written either with a @code{while} loop or recursively.
15339
15340Our first challenge is to discover how to print a column of asterisks.
15341Usually, in Emacs, we print characters onto a screen horizontally,
15342line by line, by typing. We have two routes we can follow: write our
15343own column-insertion function or discover whether one exists in Emacs.
15344
15345To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15346command. This command is like the @kbd{C-h a} (command-apropos)
15347command, except that the latter finds only those functions that are
15348commands. The @kbd{M-x apropos} command lists all symbols that match
15349a regular expression, including functions that are not interactive.
15350@findex apropos
15351
15352What we want to look for is some command that prints or inserts
15353columns. Very likely, the name of the function will contain either
15354the word `print' or the word `insert' or the word `column'.
15355Therefore, we can simply type @kbd{M-x apropos RET
15356print\|insert\|column RET} and look at the result. On my system, this
15357command takes quite some time, and then produces a list of 79
15358functions and variables. Scanning down the list, the only function
15359that looks as if it might do the job is @code{insert-rectangle}.
15360
15361@need 1200
15362Indeed, this is the function we want; its documentation says:
15363
15364@smallexample
15365@group
15366insert-rectangle:
15367Insert text of RECTANGLE with upper left corner at point.
15368RECTANGLE's first line is inserted at point,
15369its second line is inserted at a point vertically under point, etc.
15370RECTANGLE should be a list of strings.
15371@end group
15372@end smallexample
15373
15374We can run a quick test, to make sure it does what we expect of it.
15375
15376Here is the result of placing the cursor after the
15377@code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15378(@code{eval-last-sexp}). The function inserts the strings
15379@samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15380point. Also the function returns @code{nil}.
15381
15382@smallexample
15383@group
15384(insert-rectangle '("first" "second" "third"))first
15385 second
15386 third
15387nil
15388@end group
15389@end smallexample
15390
15391@noindent
15392Of course, we won't be inserting the text of the
15393@code{insert-rectangle} expression itself into the buffer in which we
15394are making the graph, but will call the function from our program. We
15395shall, however, have to make sure that point is in the buffer at the
15396place where the @code{insert-rectangle} function will insert its
15397column of strings.
15398
15399If you are reading this in Info, you can see how this works by
15400switching to another buffer, such as the @file{*scratch*} buffer,
15401placing point somewhere in the buffer, typing @kbd{M-:},
15402typing the @code{insert-rectangle} expression into the minibuffer at
15403the prompt, and then typing @key{RET}. This causes Emacs to evaluate
15404the expression in the minibuffer, but to use as the value of point the
15405position of point in the @file{*scratch*} buffer. (@kbd{M-:}
15406is the keybinding for @code{eval-expression}.)
15407
15408We find when we do this that point ends up at the end of the last
15409inserted line---that is to say, this function moves point as a
15410side-effect. If we were to repeat the command, with point at this
15411position, the next insertion would be below and to the right of the
15412previous insertion. We don't want this! If we are going to make a
15413bar graph, the columns need to be beside each other.
15414
15415So we discover that each cycle of the column-inserting @code{while}
15416loop must reposition point to the place we want it, and that place
15417will be at the top, not the bottom, of the column. Moreover, we
15418remember that when we print a graph, we do not expect all the columns
15419to be the same height. This means that the top of each column may be
15420at a different height from the previous one. We cannot simply
15421reposition point to the same line each time, but moved over to the
15422right---or perhaps we can@dots{}
15423
15424We are planning to make the columns of the bar graph out of asterisks.
15425The number of asterisks in the column is the number specified by the
15426current element of the @code{numbers-list}. We need to construct a
15427list of asterisks of the right length for each call to
15428@code{insert-rectangle}. If this list consists solely of the requisite
15429number of asterisks, then we will have position point the right number
15430of lines above the base for the graph to print correctly. This could
15431be difficult.
15432
15433Alternatively, if we can figure out some way to pass
15434@code{insert-rectangle} a list of the same length each time, then we
15435can place point on the same line each time, but move it over one
15436column to the right for each new column. If we do this, however, some
15437of the entries in the list passed to @code{insert-rectangle} must be
15438blanks rather than asterisks. For example, if the maximum height of
15439the graph is 5, but the height of the column is 3, then
15440@code{insert-rectangle} requires an argument that looks like this:
15441
15442@smallexample
15443(" " " " "*" "*" "*")
15444@end smallexample
15445
15446This last proposal is not so difficult, so long as we can determine
15447the column height. There are two ways for us to specify the column
15448height: we can arbitrarily state what it will be, which would work
15449fine for graphs of that height; or we can search through the list of
15450numbers and use the maximum height of the list as the maximum height
15451of the graph. If the latter operation were difficult, then the former
15452procedure would be easiest, but there is a function built into Emacs
15453that determines the maximum of its arguments. We can use that
15454function. The function is called @code{max} and it returns the
15455largest of all its arguments, which must be numbers. Thus, for
15456example,
15457
15458@smallexample
15459(max 3 4 6 5 7 3)
15460@end smallexample
15461
15462@noindent
15463returns 7. (A corresponding function called @code{min} returns the
15464smallest of all its arguments.)
15465@findex max
15466@findex min
15467
15468However, we cannot simply call @code{max} on the @code{numbers-list};
15469the @code{max} function expects numbers as its argument, not a list of
15470numbers. Thus, the following expression,
15471
15472@smallexample
15473(max '(3 4 6 5 7 3))
15474@end smallexample
15475
15476@need 800
15477@noindent
15478produces the following error message;
15479
15480@smallexample
15481Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
15482@end smallexample
15483
15484@findex apply
15485We need a function that passes a list of arguments to a function.
15486This function is @code{apply}. This function `applies' its first
15487argument (a function) to its remaining arguments, the last of which
15488may be a list.
15489
15490@need 1250
15491For example,
15492
15493@smallexample
15494(apply 'max 3 4 7 3 '(4 8 5))
15495@end smallexample
15496
15497@noindent
15498returns 8.
15499
15500(Incidentally, I don't know how you would learn of this function
15501without a book such as this. It is possible to discover other
15502functions, like @code{search-forward} or @code{insert-rectangle}, by
15503guessing at a part of their names and then using @code{apropos}. Even
15504though its base in metaphor is clear---`apply' its first argument to
15505the rest---I doubt a novice would come up with that particular word
15506when using @code{apropos} or other aid. Of course, I could be wrong;
15507after all, the function was first named by someone who had to invent
15508it.)
15509
15510The second and subsequent arguments to @code{apply} are optional, so
15511we can use @code{apply} to call a function and pass the elements of a
15512list to it, like this, which also returns 8:
15513
15514@smallexample
15515(apply 'max '(4 8 5))
15516@end smallexample
15517
15518This latter way is how we will use @code{apply}. The
15519@code{recursive-lengths-list-many-files} function returns a numbers'
15520list to which we can apply @code{max} (we could also apply @code{max} to
15521the sorted numbers' list; it does not matter whether the list is
15522sorted or not.)
15523
15524@need 800
15525Hence, the operation for finding the maximum height of the graph is this:
15526
15527@smallexample
15528(setq max-graph-height (apply 'max numbers-list))
15529@end smallexample
15530
15531Now we can return to the question of how to create a list of strings
15532for a column of the graph. Told the maximum height of the graph
15533and the number of asterisks that should appear in the column, the
15534function should return a list of strings for the
15535@code{insert-rectangle} command to insert.
15536
15537Each column is made up of asterisks or blanks. Since the function is
15538passed the value of the height of the column and the number of
15539asterisks in the column, the number of blanks can be found by
15540subtracting the number of asterisks from the height of the column.
15541Given the number of blanks and the number of asterisks, two
15542@code{while} loops can be used to construct the list:
15543
15544@smallexample
15545@group
15546;;; @r{First version.}
15547(defun column-of-graph (max-graph-height actual-height)
15548 "Return list of strings that is one column of a graph."
15549 (let ((insert-list nil)
15550 (number-of-top-blanks
15551 (- max-graph-height actual-height)))
15552@end group
15553
15554@group
15555 ;; @r{Fill in asterisks.}
15556 (while (> actual-height 0)
15557 (setq insert-list (cons "*" insert-list))
15558 (setq actual-height (1- actual-height)))
15559@end group
15560
15561@group
15562 ;; @r{Fill in blanks.}
15563 (while (> number-of-top-blanks 0)
15564 (setq insert-list (cons " " insert-list))
15565 (setq number-of-top-blanks
15566 (1- number-of-top-blanks)))
15567@end group
15568
15569@group
15570 ;; @r{Return whole list.}
15571 insert-list))
15572@end group
15573@end smallexample
15574
15575If you install this function and then evaluate the following
15576expression you will see that it returns the list as desired:
15577
15578@smallexample
15579(column-of-graph 5 3)
15580@end smallexample
15581
15582@need 800
15583@noindent
15584returns
15585
15586@smallexample
15587(" " " " "*" "*" "*")
15588@end smallexample
15589
15590As written, @code{column-of-graph} contains a major flaw: the symbols
15591used for the blank and for the marked entries in the column are
15592`hard-coded' as a space and asterisk. This is fine for a prototype,
15593but you, or another user, may wish to use other symbols. For example,
15594in testing the graph function, you many want to use a period in place
15595of the space, to make sure the point is being repositioned properly
15596each time the @code{insert-rectangle} function is called; or you might
15597want to substitute a @samp{+} sign or other symbol for the asterisk.
15598You might even want to make a graph-column that is more than one
15599display column wide. The program should be more flexible. The way to
15600do that is to replace the blank and the asterisk with two variables
15601that we can call @code{graph-blank} and @code{graph-symbol} and define
15602those variables separately.
15603
15604Also, the documentation is not well written. These considerations
15605lead us to the second version of the function:
15606
15607@smallexample
15608@group
15609(defvar graph-symbol "*"
15610 "String used as symbol in graph, usually an asterisk.")
15611@end group
15612
15613@group
15614(defvar graph-blank " "
15615 "String used as blank in graph, usually a blank space.
15616graph-blank must be the same number of columns wide
15617as graph-symbol.")
15618@end group
15619@end smallexample
15620
15621@noindent
15622(For an explanation of @code{defvar}, see
15623@ref{defvar, , Initializing a Variable with @code{defvar}}.)
15624
15625@smallexample
15626@group
15627;;; @r{Second version.}
15628(defun column-of-graph (max-graph-height actual-height)
15629 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15630
15631@end group
15632@group
15633The graph-symbols are contiguous entries at the end
15634of the list.
15635The list will be inserted as one column of a graph.
15636The strings are either graph-blank or graph-symbol."
15637@end group
15638
15639@group
15640 (let ((insert-list nil)
15641 (number-of-top-blanks
15642 (- max-graph-height actual-height)))
15643@end group
15644
15645@group
15646 ;; @r{Fill in @code{graph-symbols}.}
15647 (while (> actual-height 0)
15648 (setq insert-list (cons graph-symbol insert-list))
15649 (setq actual-height (1- actual-height)))
15650@end group
15651
15652@group
15653 ;; @r{Fill in @code{graph-blanks}.}
15654 (while (> number-of-top-blanks 0)
15655 (setq insert-list (cons graph-blank insert-list))
15656 (setq number-of-top-blanks
15657 (1- number-of-top-blanks)))
15658
15659 ;; @r{Return whole list.}
15660 insert-list))
15661@end group
15662@end smallexample
15663
15664If we wished, we could rewrite @code{column-of-graph} a third time to
15665provide optionally for a line graph as well as for a bar graph. This
15666would not be hard to do. One way to think of a line graph is that it
15667is no more than a bar graph in which the part of each bar that is
15668below the top is blank. To construct a column for a line graph, the
15669function first constructs a list of blanks that is one shorter than
15670the value, then it uses @code{cons} to attach a graph symbol to the
15671list; then it uses @code{cons} again to attach the `top blanks' to
15672the list.
15673
15674It is easy to see how to write such a function, but since we don't
15675need it, we will not do it. But the job could be done, and if it were
15676done, it would be done with @code{column-of-graph}. Even more
15677important, it is worth noting that few changes would have to be made
15678anywhere else. The enhancement, if we ever wish to make it, is
15679simple.
15680
15681Now, finally, we come to our first actual graph printing function.
15682This prints the body of a graph, not the labels for the vertical and
15683horizontal axes, so we can call this @code{graph-body-print}.
15684
15685@node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15686@section The @code{graph-body-print} Function
15687@findex graph-body-print
15688
15689After our preparation in the preceding section, the
15690@code{graph-body-print} function is straightforward. The function
15691will print column after column of asterisks and blanks, using the
15692elements of a numbers' list to specify the number of asterisks in each
15693column. This is a repetitive act, which means we can use a
15694decrementing @code{while} loop or recursive function for the job. In
15695this section, we will write the definition using a @code{while} loop.
15696
15697The @code{column-of-graph} function requires the height of the graph
15698as an argument, so we should determine and record that as a local variable.
15699
15700This leads us to the following template for the @code{while} loop
15701version of this function:
15702
15703@smallexample
15704@group
15705(defun graph-body-print (numbers-list)
15706 "@var{documentation}@dots{}"
15707 (let ((height @dots{}
15708 @dots{}))
15709@end group
15710
15711@group
15712 (while numbers-list
15713 @var{insert-columns-and-reposition-point}
15714 (setq numbers-list (cdr numbers-list)))))
15715@end group
15716@end smallexample
15717
15718@noindent
15719We need to fill in the slots of the template.
15720
15721Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15722determine the height of the graph.
15723
15724The @code{while} loop will cycle through the @code{numbers-list} one
15725element at a time. As it is shortened by the @code{(setq numbers-list
15726(cdr numbers-list))} expression, the @sc{car} of each instance of the
15727list is the value of the argument for @code{column-of-graph}.
15728
15729At each cycle of the @code{while} loop, the @code{insert-rectangle}
15730function inserts the list returned by @code{column-of-graph}. Since
15731the @code{insert-rectangle} function moves point to the lower right of
15732the inserted rectangle, we need to save the location of point at the
15733time the rectangle is inserted, move back to that position after the
15734rectangle is inserted, and then move horizontally to the next place
15735from which @code{insert-rectangle} is called.
15736
15737If the inserted columns are one character wide, as they will be if
15738single blanks and asterisks are used, the repositioning command is
15739simply @code{(forward-char 1)}; however, the width of a column may be
15740greater than one. This means that the repositioning command should be
15741written @code{(forward-char symbol-width)}. The @code{symbol-width}
15742itself is the length of a @code{graph-blank} and can be found using
15743the expression @code{(length graph-blank)}. The best place to bind
15744the @code{symbol-width} variable to the value of the width of graph
15745column is in the varlist of the @code{let} expression.
15746
15747@need 1250
15748These considerations lead to the following function definition:
15749
15750@smallexample
15751@group
15752(defun graph-body-print (numbers-list)
15753 "Print a bar graph of the NUMBERS-LIST.
15754The numbers-list consists of the Y-axis values."
15755
15756 (let ((height (apply 'max numbers-list))
15757 (symbol-width (length graph-blank))
15758 from-position)
15759@end group
15760
15761@group
15762 (while numbers-list
15763 (setq from-position (point))
15764 (insert-rectangle
15765 (column-of-graph height (car numbers-list)))
15766 (goto-char from-position)
15767 (forward-char symbol-width)
15768@end group
15769@group
15770 ;; @r{Draw graph column by column.}
15771 (sit-for 0)
15772 (setq numbers-list (cdr numbers-list)))
15773@end group
15774@group
15775 ;; @r{Place point for X axis labels.}
15776 (forward-line height)
15777 (insert "\n")
15778))
15779@end group
15780@end smallexample
15781
15782@noindent
15783The one unexpected expression in this function is the
15784@w{@code{(sit-for 0)}} expression in the @code{while} loop. This
15785expression makes the graph printing operation more interesting to
15786watch than it would be otherwise. The expression causes Emacs to
15787`sit' or do nothing for a zero length of time and then redraw the
15788screen. Placed here, it causes Emacs to redraw the screen column by
15789column. Without it, Emacs would not redraw the screen until the
15790function exits.
15791
15792We can test @code{graph-body-print} with a short list of numbers.
15793
15794@enumerate
15795@item
15796Install @code{graph-symbol}, @code{graph-blank},
15797@code{column-of-graph}, which are in
475dc40a
EZ
15798@iftex
15799@ref{Readying a Graph, , Readying a Graph},
15800@end iftex
15801@ifinfo
15802@ref{Columns of a graph},
15803@end ifinfo
8b096dce
EZ
15804and @code{graph-body-print}.
15805
15806@need 800
15807@item
15808Copy the following expression:
15809
15810@smallexample
15811(graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15812@end smallexample
15813
15814@item
15815Switch to the @file{*scratch*} buffer and place the cursor where you
15816want the graph to start.
15817
15818@item
15819Type @kbd{M-:} (@code{eval-expression}).
15820
15821@item
15822Yank the @code{graph-body-print} expression into the minibuffer
15823with @kbd{C-y} (@code{yank)}.
15824
15825@item
15826Press @key{RET} to evaluate the @code{graph-body-print} expression.
15827@end enumerate
15828
15829@need 800
15830Emacs will print a graph like this:
15831
15832@smallexample
15833@group
15834 *
15835 * **
15836 * ****
15837 *** ****
15838 ********* *
15839 ************
15840 *************
15841@end group
15842@end smallexample
15843
15844@node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15845@section The @code{recursive-graph-body-print} Function
15846@findex recursive-graph-body-print
15847
15848The @code{graph-body-print} function may also be written recursively.
15849The recursive solution is divided into two parts: an outside `wrapper'
15850that uses a @code{let} expression to determine the values of several
15851variables that need only be found once, such as the maximum height of
15852the graph, and an inside function that is called recursively to print
15853the graph.
15854
15855@need 1250
15856The `wrapper' is uncomplicated:
15857
15858@smallexample
15859@group
15860(defun recursive-graph-body-print (numbers-list)
15861 "Print a bar graph of the NUMBERS-LIST.
15862The numbers-list consists of the Y-axis values."
15863 (let ((height (apply 'max numbers-list))
15864 (symbol-width (length graph-blank))
15865 from-position)
15866 (recursive-graph-body-print-internal
15867 numbers-list
15868 height
15869 symbol-width)))
15870@end group
15871@end smallexample
15872
15873The recursive function is a little more difficult. It has four parts:
15874the `do-again-test', the printing code, the recursive call, and the
15875`next-step-expression'. The `do-again-test' is an @code{if}
15876expression that determines whether the @code{numbers-list} contains
15877any remaining elements; if it does, the function prints one column of
15878the graph using the printing code and calls itself again. The
15879function calls itself again according to the value produced by the
15880`next-step-expression' which causes the call to act on a shorter
15881version of the @code{numbers-list}.
15882
15883@smallexample
15884@group
15885(defun recursive-graph-body-print-internal
15886 (numbers-list height symbol-width)
15887 "Print a bar graph.
15888Used within recursive-graph-body-print function."
15889@end group
15890
15891@group
15892 (if numbers-list
15893 (progn
15894 (setq from-position (point))
15895 (insert-rectangle
15896 (column-of-graph height (car numbers-list)))
15897@end group
15898@group
15899 (goto-char from-position)
15900 (forward-char symbol-width)
15901 (sit-for 0) ; @r{Draw graph column by column.}
15902 (recursive-graph-body-print-internal
15903 (cdr numbers-list) height symbol-width))))
15904@end group
15905@end smallexample
15906
15907@need 1250
15908After installation, this expression can be tested; here is a sample:
15909
15910@smallexample
15911(recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15912@end smallexample
15913
15914@need 800
15915Here is what @code{recursive-graph-body-print} produces:
15916
15917@smallexample
15918@group
15919 *
15920 ** *
15921 **** *
15922 **** ***
15923 * *********
15924 ************
15925 *************
15926@end group
15927@end smallexample
15928
15929Either of these two functions, @code{graph-body-print} or
15930@code{recursive-graph-body-print}, create the body of a graph.
15931
15932@node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15933@section Need for Printed Axes
15934
15935A graph needs printed axes, so you can orient yourself. For a do-once
15936project, it may be reasonable to draw the axes by hand using Emacs'
15937Picture mode; but a graph drawing function may be used more than once.
15938
15939For this reason, I have written enhancements to the basic
15940@code{print-graph-body} function that automatically print labels for
15941the horizontal and vertical axes. Since the label printing functions
15942do not contain much new material, I have placed their description in
15943an appendix. @xref{Full Graph, , A Graph with Labelled Axes}.
15944
15945@node Line Graph Exercise, , Printed Axes, Readying a Graph
15946@section Exercise
15947
15948Write a line graph version of the graph printing functions.
15949
15950@node Emacs Initialization, Debugging, Readying a Graph, Top
15951@chapter Your @file{.emacs} File
15952@cindex @file{.emacs} file
15953@cindex Customizing your @file{.emacs} file
15954@cindex Initialization file
15955
15956``You don't have to like Emacs to like it'' -- this seemingly
15957paradoxical statement is the secret of GNU Emacs. The plain, `out of
15958the box' Emacs is a generic tool. Most people who use it, customize
15959it to suit themselves.
15960
15961GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15962expressions in Emacs Lisp you can change or extend Emacs.
15963
15964@menu
15965* Default Configuration::
15966* Site-wide Init:: You can write site-wide init files.
15967* defcustom:: Emacs will write code for you.
15968* Beginning a .emacs File:: How to write a @code{.emacs file}.
15969* Text and Auto-fill:: Automatically wrap lines.
15970* Mail Aliases:: Use abbreviations for email addresses.
15971* Indent Tabs Mode:: Don't use tabs with @TeX{}
15972* Keybindings:: Create some personal keybindings.
15973* Keymaps:: More about key binding.
15974* Loading Files:: Load (i.e., evaluate) files automatically.
15975* Autoload:: Make functions available.
15976* Simple Extension:: Define a function; bind it to a key.
15977* X11 Colors:: Colors in version 19 in X.
15978* Miscellaneous::
15979* Mode Line:: How to customize your mode line.
15980@end menu
15981
15982@node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15983@ifnottex
15984@unnumberedsec Emacs' Default Configuration
15985@end ifnottex
15986
15987There are those who appreciate Emacs' default configuration. After
15988all, Emacs starts you in C mode when you edit a C file, starts you in
15989Fortran mode when you edit a Fortran file, and starts you in
15990Fundamental mode when you edit an unadorned file. This all makes
15991sense, if you do not know who is going to use Emacs. Who knows what a
15992person hopes to do with an unadorned file? Fundamental mode is the
15993right default for such a file, just as C mode is the right default for
15994editing C code. But when you do know who is going to use Emacs---you,
15995yourself---then it makes sense to customize Emacs.
15996
15997For example, I seldom want Fundamental mode when I edit an
15998otherwise undistinguished file; I want Text mode. This is why I
15999customize Emacs: so it suits me.
16000
16001You can customize and extend Emacs by writing or adapting a
16002@file{~/.emacs} file. This is your personal initialization file; its
16003contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16004may also add @file{.el} to @file{~/.emacs} and call it a
16005@file{~/.emacs.el} file. In the past, you were forbidden to type the
16006extra keystrokes that the name @file{~/.emacs.el} requires, but now
16007you may. The new format is consistent with the Emacs Lisp file
16008naming conventions; the old format saves typing.}
16009
16010A @file{~/.emacs} file contains Emacs Lisp code. You can write this
16011code yourself; or you can use Emacs' @code{customize} feature to write
16012the code for you. You can combine your own expressions and
16013auto-written Customize expressions in your @file{.emacs} file.
16014
16015(I myself prefer to write my own expressions, except for those,
16016particularly fonts, that I find easier to manipulate using the
16017@code{customize} command. I combine the two methods.)
16018
16019Most of this chapter is about writing expressions yourself. It
16020describes a simple @file{.emacs} file; for more information, see
16021@ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16022@ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16023Manual}.
16024
16025@node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16026@section Site-wide Initialization Files
16027
16028@cindex @file{default.el} init file
16029@cindex @file{site-init.el} init file
16030@cindex @file{site-load.el} init file
16031In addition to your personal initialization file, Emacs automatically
16032loads various site-wide initialization files, if they exist. These
16033have the same form as your @file{.emacs} file, but are loaded by
16034everyone.
16035
16036Two site-wide initialization files, @file{site-load.el} and
16037@file{site-init.el}, are loaded into Emacs and then `dumped' if a
16038`dumped' version of Emacs is created, as is most common. (Dumped
16039copies of Emacs load more quickly. However, once a file is loaded and
16040dumped, a change to it does not lead to a change in Emacs unless you
16041load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16042Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16043@file{INSTALL} file.)
16044
16045Three other site-wide initialization files are loaded automatically
16046each time you start Emacs, if they exist. These are
16047@file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16048file, and @file{default.el}, and the terminal type file, which are both
16049loaded @emph{after} your @file{.emacs} file.
16050
16051Settings and definitions in your @file{.emacs} file will overwrite
16052conflicting settings and definitions in a @file{site-start.el} file,
16053if it exists; but the settings and definitions in a @file{default.el}
16054or terminal type file will overwrite those in your @file{.emacs} file.
16055(You can prevent interference from a terminal type file by setting
16056@code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16057Simple Extension}.)
16058
16059@c Rewritten to avoid overfull hbox.
16060The @file{INSTALL} file that comes in the distribution contains
16061descriptions of the @file{site-init.el} and @file{site-load.el} files.
16062
16063The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16064control loading. These files are in the @file{lisp} directory of the
16065Emacs distribution and are worth perusing.
16066
16067The @file{loaddefs.el} file contains a good many suggestions as to
16068what to put into your own @file{.emacs} file, or into a site-wide
16069initialization file.
16070
16071@node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16072@section Specifying Variables using @code{defcustom}
16073@findex defcustom
16074
16075You can specify variables using @code{defcustom} so that you and
e601d8fd 16076others can then use Emacs' @code{customize} feature to set their
8b096dce
EZ
16077values. (You cannot use @code{customize} to write function
16078definitions; but you can write @code{defuns} in your @file{.emacs}
16079file. Indeed, you can write any Lisp expression in your @file{.emacs}
16080file.)
16081
16082The @code{customize} feature depends on the @code{defcustom} special
16083form. Although you can use @code{defvar} or @code{setq} for variables
16084that users set, the @code{defcustom} special form is designed for the
16085job.
16086
16087You can use your knowledge of @code{defvar} for writing the
16088first three arguments for @code{defcustom}. The first argument to
16089@code{defcustom} is the name of the variable. The second argument is
16090the variable's initial value, if any; and this value is set only if
16091the value has not already been set. The third argument is the
16092documentation.
16093
16094The fourth and subsequent arguments to @code{defcustom} specify types
16095and options; these are not featured in @code{defvar}. (These
16096arguments are optional.)
16097
16098Each of these arguments consists of a keyword followed by a value.
16099Each keyword starts with the character @code{:}.
16100
16101@need 1250
16102For example, the customizable user option variable
16103@code{text-mode-hook} looks like this:
16104
16105@smallexample
16106@group
16107(defcustom text-mode-hook nil
16108 "Normal hook run when entering Text mode and many related modes."
16109 :type 'hook
16110 :options '(turn-on-auto-fill flyspell-mode)
16111 :group 'data)
16112@end group
16113@end smallexample
16114
16115@noindent
16116The name of the variable is @code{text-mode-hook}; it has no default
16117value; and its documentation string tells you what it does.
16118
16119The @code{:type} keyword tells Emacs what kind of data
16120@code{text-mode-hook} should be set to and how to display the value in
16121a Customization buffer.
16122
16123The @code{:options} keyword specifies a suggested list of values for
16124the variable. Currently, you can use @code{:options} only for a hook.
16125The list is only a suggestion; it is not exclusive; a person who sets
16126the variable may set it to other values; the list shown following the
16127@code{:options} keyword is intended to offer convenient choices to a
16128user.
16129
16130Finally, the @code{:group} keyword tells the Emacs Customization
16131command in which group the variable is located. This tells where to
16132find it.
16133
16134For more information, see @ref{Customization, , Writing Customization
16135Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16136
16137Consider @code{text-mode-hook} as an example.
16138
16139There are two ways to customize this variable. You can use the
16140customization command or write the appropriate expressions yourself.
16141
16142@need 800
16143Using the customization command, you can type:
16144
16145@smallexample
16146M-x customize
16147@end smallexample
16148
16149@noindent
16150and find that the group for editing files of data is called `data'.
16151Enter that group. Text Mode Hook is the first member. You can click
16152on its various options to set the values. After you click on the
16153button to
16154
16155@smallexample
16156Save for Future Sessions
16157@end smallexample
16158
16159@noindent
16160Emacs will write an expression into your @file{.emacs} file.
16161It will look like this:
16162
16163@smallexample
16164@group
16165(custom-set-variables
16166 ;; custom-set-variables was added by Custom --
16167 ;; don't edit or cut/paste it!
16168 ;; Your init file should contain only one such instance.
16169 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16170@end group
16171@end smallexample
16172
16173@noindent
16174(The @code{text-mode-hook-identify} function tells
16175@code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16176
16177In spite of the warning, you certainly may edit, cut, and paste the
16178expression! I do all time. The purpose of the warning is to scare
16179those who do not know what they are doing, so they do not
16180inadvertently generate an error.
16181
16182The @code{custom-set-variables} works somewhat differently than a
16183@code{setq}. While I have never learned the differences, I do modify
16184the @code{custom-set-variables} expressions in my @file{.emacs} file
16185by hand: I make the changes in what appears to me to be a reasonable
16186manner and have not had any problems. Others prefer to use the
16187Customization command and let Emacs do the work for them.
16188
16189Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16190This function sets the various font faces. Over time, I have set a
16191considerable number of faces. Some of the time, I re-set them using
16192@code{customize}; other times, I simply edit the
16193@code{custom-set-faces} expression in my @file{.emacs} file itself.
16194
16195The second way to customize your @code{text-mode-hook} is to set it
16196yourself in your @file{.emacs} file using code that has nothing to do
16197with the @code{custom-set-@dots{}} functions.
16198
16199@need 800
16200When you do this, and later use @code{customize}, you will see a
16201message that says
16202
16203@smallexample
16204this option has been changed outside the customize buffer.
16205@end smallexample
16206
16207@need 800
16208This message is only a warning. If you click on the button to
16209
16210@smallexample
16211Save for Future Sessions
16212@end smallexample
16213
16214@noindent
16215Emacs will write a @code{custom-set-@dots{}} expression near the end
16216of your @file{.emacs} file that will be evaluated after your
16217hand-written expression. It will, therefore, overrule your
16218hand-written expression. No harm will be done. When you do this,
16219however, be careful to remember which expression is active; if you
16220forget, you may confuse yourself.
16221
16222So long as you remember where the values are set, you will have no
16223trouble. In any event, the values are always set in your
16224initialization file, which is usually called @file{.emacs}.
16225
16226I myself use @code{customize} for hardly anything. Mostly, I write
16227expressions myself.
16228
16229@node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16230@section Beginning a @file{.emacs} File
16231@cindex @file{.emacs} file, beginning of
16232
16233When you start Emacs, it loads your @file{.emacs} file unless you tell
16234it not to by specifying @samp{-q} on the command line. (The
16235@code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16236
16237A @file{.emacs} file contains Lisp expressions. Often, these are no
16238more than expressions to set values; sometimes they are function
16239definitions.
16240
16241@xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16242Manual}, for a short description of initialization files.
16243
16244This chapter goes over some of the same ground, but is a walk among
16245extracts from a complete, long-used @file{.emacs} file---my own.
16246
16247The first part of the file consists of comments: reminders to myself.
16248By now, of course, I remember these things, but when I started, I did
16249not.
16250
16251@smallexample
16252@group
16253;;;; Bob's .emacs file
16254; Robert J. Chassell
16255; 26 September 1985
16256@end group
16257@end smallexample
16258
16259@noindent
16260Look at that date! I started this file a long time ago. I have been
16261adding to it ever since.
16262
16263@smallexample
16264@group
16265; Each section in this file is introduced by a
16266; line beginning with four semicolons; and each
16267; entry is introduced by a line beginning with
16268; three semicolons.
16269@end group
16270@end smallexample
16271
16272@noindent
16273This describes the usual conventions for comments in Emacs Lisp.
16274Everything on a line that follows a semicolon is a comment. Two,
16275three, and four semicolons are used as section and subsection
16276markers. (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16277Manual}, for more about comments.)
16278
16279@smallexample
16280@group
16281;;;; The Help Key
16282; Control-h is the help key;
16283; after typing control-h, type a letter to
16284; indicate the subject about which you want help.
16285; For an explanation of the help facility,
16286; type control-h two times in a row.
16287@end group
16288@end smallexample
16289
16290@noindent
16291Just remember: type @kbd{C-h} two times for help.
16292
16293@smallexample
16294@group
16295; To find out about any mode, type control-h m
16296; while in that mode. For example, to find out
16297; about mail mode, enter mail mode and then type
16298; control-h m.
16299@end group
16300@end smallexample
16301
16302@noindent
16303`Mode help', as I call this, is very helpful. Usually, it tells you
16304all you need to know.
16305
16306Of course, you don't need to include comments like these in your
16307@file{.emacs} file. I included them in mine because I kept forgetting
16308about Mode help or the conventions for comments---but I was able to
16309remember to look here to remind myself.
16310
16311@node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16312@section Text and Auto Fill Mode
16313
16314Now we come to the part that `turns on' Text mode and
16315Auto Fill mode.
16316
16317@smallexample
16318@group
16319;;; Text mode and Auto Fill mode
16320; The next three lines put Emacs into Text mode
16321; and Auto Fill mode, and are for writers who
16322; want to start writing prose rather than code.
16323
16324(setq default-major-mode 'text-mode)
16325(add-hook 'text-mode-hook 'text-mode-hook-identify)
16326(add-hook 'text-mode-hook 'turn-on-auto-fill)
16327@end group
16328@end smallexample
16329
16330Here is the first part of this @file{.emacs} file that does something
16331besides remind a forgetful human!
16332
16333The first of the two lines in parentheses tells Emacs to turn on Text
16334mode when you find a file, @emph{unless} that file should go into some
16335other mode, such as C mode.
16336
16337@cindex Per-buffer, local variables list
16338@cindex Local variables list, per-buffer,
16339@cindex Automatic mode selection
16340@cindex Mode selection, automatic
16341When Emacs reads a file, it looks at the extension to the file name,
16342if any. (The extension is the part that comes after a @samp{.}.) If
16343the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16344on C mode. Also, Emacs looks at first nonblank line of the file; if
16345the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
16346possesses a list of extensions and specifications that it uses
16347automatically. In addition, Emacs looks near the last page for a
16348per-buffer, ``local variables list'', if any.
16349
16350@ifinfo
16351@xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16352Emacs Manual}.
16353
16354@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16355Manual}.
16356@end ifinfo
16357@iftex
16358See sections ``How Major Modes are Chosen'' and ``Local Variables in
16359Files'' in @cite{The GNU Emacs Manual}.
16360@end iftex
16361
16362Now, back to the @file{.emacs} file.
16363
16364@need 800
16365Here is the line again; how does it work?
16366
16367@cindex Text Mode turned on
16368@smallexample
16369(setq default-major-mode 'text-mode)
16370@end smallexample
16371
16372@noindent
16373This line is a short, but complete Emacs Lisp expression.
16374
16375We are already familiar with @code{setq}. It sets the following variable,
16376@code{default-major-mode}, to the subsequent value, which is
16377@code{text-mode}. The single quote mark before @code{text-mode} tells
16378Emacs to deal directly with the @code{text-mode} variable, not with
16379whatever it might stand for. @xref{set & setq, , Setting the Value of
16380a Variable}, for a reminder of how @code{setq} works. The main point
16381is that there is no difference between the procedure you use to set
16382a value in your @file{.emacs} file and the procedure you use anywhere
16383else in Emacs.
16384
16385@need 800
16386Here are the next two lines:
16387
16388@cindex Auto Fill mode turned on
16389@findex add-hook
16390@smallexample
16391(add-hook 'text-mode-hook 'text-mode-hook-identify)
16392(add-hook 'text-mode-hook 'turn-on-auto-fill)
16393@end smallexample
16394
16395@noindent
16396In these two lines, the @code{add-hook} command first adds
16397@code{text-mode-hook-identify} to the variable called
16398@code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16399variable.
16400
16401@code{turn-on-auto-fill} is the name of a program, that, you guessed
16402it!, turns on Auto Fill mode. @code{text-mode-hook-identify} is a
16403function that tells @code{toggle-text-mode-auto-fill} which buffers
16404are in Text mode.
16405
16406Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16407onto Text mode. So every time Emacs turns on Text mode, Emacs also
16408turns on Auto Fill mode.
16409
16410In brief, the first line causes Emacs to enter Text mode when you edit
16411a file, unless the file name extension, first non-blank line, or local
16412variables tell Emacs otherwise.
16413
16414Text mode among other actions, sets the syntax table to work
16415conveniently for writers. In Text mode, Emacs considers an apostrophe
16416as part of a word like a letter; but Emacs does not consider a period
16417or a space as part of a word. Thus, @kbd{M-f} moves you over
16418@samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
16419the @samp{t} of @samp{it's}.
16420
16421The second and third lines causes Emacs to turn on Auto Fill mode when
16422it turns on Text mode. In Auto Fill mode, Emacs automatically breaks
16423a line that is too wide and brings the excessively wide part of the
16424line down to the next line. Emacs breaks lines between words, not
16425within them.
16426
16427When Auto Fill mode is turned off, lines continue to the right as you
16428type them. Depending on how you set the value of
16429@code{truncate-lines}, the words you type either disappear off the
16430right side of the screen, or else are shown, in a rather ugly and
16431unreadable manner, as a continuation line on the screen.
16432
16433@need 1250
16434In addition, in this part of my @file{.emacs} file, I tell the Emacs
16435fill commands to insert two spaces after a colon:
16436
16437@smallexample
16438(setq colon-double-space t)
16439@end smallexample
16440
16441@node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16442@section Mail Aliases
16443
16444Here is a @code{setq} that `turns on' mail aliases, along with more
16445reminders.
16446
16447@smallexample
16448@group
16449;;; Mail mode
16450; To enter mail mode, type `C-x m'
16451; To enter RMAIL (for reading mail),
16452; type `M-x rmail'
16453
16454(setq mail-aliases t)
16455@end group
16456@end smallexample
16457
16458@cindex Mail aliases
16459@noindent
16460This @code{setq} command sets the value of the variable
16461@code{mail-aliases} to @code{t}. Since @code{t} means true, the line
16462says, in effect, ``Yes, use mail aliases.''
16463
16464Mail aliases are convenient short names for long email addresses or
16465for lists of email addresses. The file where you keep your `aliases'
16466is @file{~/.mailrc}. You write an alias like this:
16467
16468@smallexample
16469alias geo george@@foobar.wiz.edu
16470@end smallexample
16471
16472@noindent
16473When you write a message to George, address it to @samp{geo}; the
16474mailer will automatically expand @samp{geo} to the full address.
16475
16476@node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16477@section Indent Tabs Mode
16478@cindex Tabs, preventing
16479@findex indent-tabs-mode
16480
16481By default, Emacs inserts tabs in place of multiple spaces when it
16482formats a region. (For example, you might indent many lines of text
16483all at once with the @code{indent-region} command.) Tabs look fine on
16484a terminal or with ordinary printing, but they produce badly indented
16485output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16486
16487@need 1250
16488The following turns off Indent Tabs mode:
16489
16490@smallexample
16491@group
16492;;; Prevent Extraneous Tabs
16493(setq-default indent-tabs-mode nil)
16494@end group
16495@end smallexample
16496
16497Note that this line uses @code{setq-default} rather than the
16498@code{setq} command that we have seen before. The @code{setq-default}
16499command sets values only in buffers that do not have their own local
16500values for the variable.
16501
16502@ifinfo
16503@xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16504
16505@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16506Manual}.
16507@end ifinfo
16508@iftex
16509See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16510Files'' in @cite{The GNU Emacs Manual}.
16511@end iftex
16512
16513@node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16514@section Some Keybindings
16515
16516Now for some personal keybindings:
16517
16518@smallexample
16519@group
16520;;; Compare windows
16521(global-set-key "\C-cw" 'compare-windows)
16522@end group
16523@end smallexample
16524
16525@findex compare-windows
16526@code{compare-windows} is a nifty command that compares the text in
16527your current window with text in the next window. It makes the
16528comparison by starting at point in each window, moving over text in
16529each window as far as they match. I use this command all the time.
16530
16531This also shows how to set a key globally, for all modes.
16532
16533@cindex Setting a key globally
16534@cindex Global set key
16535@cindex Key setting globally
16536@findex global-set-key
16537The command is @code{global-set-key}. It is followed by the
16538keybinding. In a @file{.emacs} file, the keybinding is written as
16539shown: @code{\C-c} stands for `control-c', which means `press the
16540control key and the @kbd{c} key at the same time'. The @code{w} means
16541`press the @kbd{w} key'. The keybinding is surrounded by double
16542quotation marks. In documentation, you would write this as @kbd{C-c
16543w}. (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16544than a @key{CTL} key, you would write @code{\M-c}. @xref{Init
16545Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16546Manual}, for details.)
16547
16548The command invoked by the keys is @code{compare-windows}. Note that
16549@code{compare-windows} is preceded by a single quote; otherwise, Emacs
16550would first try to evaluate the symbol to determine its value.
16551
16552These three things, the double quotation marks, the backslash before
16553the @samp{C}, and the single quote mark are necessary parts of
16554keybinding that I tend to forget. Fortunately, I have come to
16555remember that I should look at my existing @file{.emacs} file, and
16556adapt what is there.
16557
16558As for the keybinding itself: @kbd{C-c w}. This combines the prefix
16559key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
16560set of keys, @kbd{C-c} followed by a single character, is strictly
16561reserved for individuals' own use. (I call these `own' keys, since
16562these are for my own use.) You should always be able to create such a
16563keybinding for your own use without stomping on someone else's
16564keybinding. If you ever write an extension to Emacs, please avoid
16565taking any of these keys for public use. Create a key like @kbd{C-c
16566C-w} instead. Otherwise, we will run out of `own' keys.
16567
16568@need 1250
16569Here is another keybinding, with a comment:
16570
16571@smallexample
16572@group
16573;;; Keybinding for `occur'
16574; I use occur a lot, so let's bind it to a key:
16575(global-set-key "\C-co" 'occur)
16576@end group
16577@end smallexample
16578
16579@findex occur
16580The @code{occur} command shows all the lines in the current buffer
16581that contain a match for a regular expression. Matching lines are
16582shown in a buffer called @file{*Occur*}. That buffer serves as a menu
16583to jump to occurrences.
16584
16585@findex global-unset-key
16586@cindex Unbinding key
16587@cindex Key unbinding
16588@need 1250
16589Here is how to unbind a key, so it does not
16590work:
16591
16592@smallexample
16593@group
16594;;; Unbind `C-x f'
16595(global-unset-key "\C-xf")
16596@end group
16597@end smallexample
16598
16599There is a reason for this unbinding: I found I inadvertently typed
16600@w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
16601file, as I intended, I accidentally set the width for filled text,
16602almost always to a width I did not want. Since I hardly ever reset my
16603default width, I simply unbound the key.
16604
16605@findex list-buffers, @r{rebound}
16606@findex buffer-menu, @r{bound to key}
16607@need 1250
16608The following rebinds an existing key:
16609
16610@smallexample
16611@group
16612;;; Rebind `C-x C-b' for `buffer-menu'
16613(global-set-key "\C-x\C-b" 'buffer-menu)
16614@end group
16615@end smallexample
16616
16617By default, @kbd{C-x C-b} runs the
16618@code{list-buffers} command. This command lists
16619your buffers in @emph{another} window. Since I
16620almost always want to do something in that
16621window, I prefer the @code{buffer-menu}
16622command, which not only lists the buffers,
16623but moves point into that window.
16624
16625@node Keymaps, Loading Files, Keybindings, Emacs Initialization
16626@section Keymaps
16627@cindex Keymaps
16628@cindex Rebinding keys
16629
16630Emacs uses @dfn{keymaps} to record which keys call which commands.
16631When you use @code{global-set-key} to set the keybinding for a single
16632command in all parts of Emacs, you are specifying the keybinding in
16633@code{current-global-map}.
16634
16635Specific modes, such as C mode or Text mode, have their own keymaps;
16636the mode-specific keymaps override the global map that is shared by
16637all buffers.
16638
16639The @code{global-set-key} function binds, or rebinds, the global
16640keymap. For example, the following binds the key @kbd{C-x C-b} to the
16641function @code{buffer-menu}:
16642
16643@smallexample
16644(global-set-key "\C-x\C-b" 'buffer-menu)
16645@end smallexample
16646
16647Mode-specific keymaps are bound using the @code{define-key} function,
16648which takes a specific keymap as an argument, as well as the key and
16649the command. For example, my @file{.emacs} file contains the
16650following expression to bind the @code{texinfo-insert-@@group} command
16651to @kbd{C-c C-c g}:
16652
16653@smallexample
16654@group
16655(define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16656@end group
16657@end smallexample
16658
16659@noindent
16660The @code{texinfo-insert-@@group} function itself is a little extension
16661to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
16662use this command all the time and prefer to type the three strokes
16663@kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16664(@samp{@@group} and its matching @samp{@@end group} are commands that
16665keep all enclosed text together on one page; many multi-line examples
16666in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16667
16668@need 1250
16669Here is the @code{texinfo-insert-@@group} function definition:
16670
16671@smallexample
16672@group
16673(defun texinfo-insert-@@group ()
16674 "Insert the string @@group in a Texinfo buffer."
16675 (interactive)
16676 (beginning-of-line)
16677 (insert "@@group\n"))
16678@end group
16679@end smallexample
16680
16681(Of course, I could have used Abbrev mode to save typing, rather than
16682write a function to insert a word; but I prefer key strokes consistent
16683with other Texinfo mode key bindings.)
16684
16685You will see numerous @code{define-key} expressions in
16686@file{loaddefs.el} as well as in the various mode libraries, such as
16687@file{cc-mode.el} and @file{lisp-mode.el}.
16688
16689@xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16690Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16691Reference Manual}, for more information about keymaps.
16692
16693@node Loading Files, Autoload, Keymaps, Emacs Initialization
16694@section Loading Files
16695@cindex Loading files
16696@c findex load
16697
16698Many people in the GNU Emacs community have written extensions to
16699Emacs. As time goes by, these extensions are often included in new
16700releases. For example, the Calendar and Diary packages are now part
16701of the standard GNU Emacs.
16702
16703(Calc, which I consider a vital part of Emacs, would be part of the
16704standard distribution except that it was so large it was packaged
16705separately and no one has changed that.)
16706
16707You can use a @code{load} command to evaluate a complete file and
16708thereby install all the functions and variables in the file into Emacs.
16709For example:
16710
16711@c (auto-compression-mode t)
16712
16713@smallexample
16714(load "~/emacs/slowsplit")
16715@end smallexample
16716
16717This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16718exists, the faster, byte compiled @file{slowsplit.elc} file from the
16719@file{emacs} sub-directory of your home directory. The file contains
16720the function @code{split-window-quietly}, which John Robinson wrote in
167211989.
16722
16723The @code{split-window-quietly} function splits a window with the
16724minimum of redisplay. I installed it in 1989 because it worked well
16725with the slow 1200 baud terminals I was then using. Nowadays, I only
16726occasionally come across such a slow connection, but I continue to use
16727the function because I like the way it leaves the bottom half of a
16728buffer in the lower of the new windows and the top half in the upper
16729window.
16730
16731@need 1250
16732To replace the key binding for the default
16733@code{split-window-vertically}, you must also unset that key and bind
16734the keys to @code{split-window-quietly}, like this:
16735
16736@smallexample
16737@group
16738(global-unset-key "\C-x2")
16739(global-set-key "\C-x2" 'split-window-quietly)
16740@end group
16741@end smallexample
16742
16743@vindex load-path
16744If you load many extensions, as I do, then instead of specifying the
16745exact location of the extension file, as shown above, you can specify
16746that directory as part of Emacs' @code{load-path}. Then, when Emacs
16747loads a file, it will search that directory as well as its default
16748list of directories. (The default list is specified in @file{paths.h}
16749when Emacs is built.)
16750
16751@need 1250
16752The following command adds your @file{~/emacs} directory to the
16753existing load path:
16754
16755@smallexample
16756@group
16757;;; Emacs Load Path
16758(setq load-path (cons "~/emacs" load-path))
16759@end group
16760@end smallexample
16761
16762Incidentally, @code{load-library} is an interactive interface to the
16763@code{load} function. The complete function looks like this:
16764
16765@findex load-library
16766@smallexample
16767@group
16768(defun load-library (library)
16769 "Load the library named LIBRARY.
16770This is an interface to the function `load'."
16771 (interactive "sLoad library: ")
16772 (load library))
16773@end group
16774@end smallexample
16775
16776The name of the function, @code{load-library}, comes from the use of
16777`library' as a conventional synonym for `file'. The source for the
16778@code{load-library} command is in the @file{files.el} library.
16779
16780Another interactive command that does a slightly different job is
16781@code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
16782Emacs, emacs, The GNU Emacs Manual}, for information on the
16783distinction between @code{load-library} and this command.
16784
16785@node Autoload, Simple Extension, Loading Files, Emacs Initialization
16786@section Autoloading
16787@findex autoload
16788
16789Instead of installing a function by loading the file that contains it,
16790or by evaluating the function definition, you can make the function
16791available but not actually install it until it is first called. This
16792is called @dfn{autoloading}.
16793
16794When you execute an autoloaded function, Emacs automatically evaluates
16795the file that contains the definition, and then calls the function.
16796
16797Emacs starts quicker with autoloaded functions, since their libraries
16798are not loaded right away; but you need to wait a moment when you
16799first use such a function, while its containing file is evaluated.
16800
16801Rarely used functions are frequently autoloaded. The
16802@file{loaddefs.el} library contains hundreds of autoloaded functions,
16803from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
16804come to use a `rare' function frequently. When you do, you should
16805load that function's file with a @code{load} expression in your
16806@file{.emacs} file.
16807
16808In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16809that contain functions that would otherwise be autoloaded. (Actually,
16810it would have been better to include these files in my `dumped' Emacs
16811when I built it, but I forgot. @xref{Building Emacs, , Building
16812Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16813file for more about dumping.)
16814
16815You may also want to include autoloaded expressions in your @file{.emacs}
16816file. @code{autoload} is a built-in function that takes up to five
16817arguments, the final three of which are optional. The first argument
16818is the name of the function to be autoloaded; the second is the name
16819of the file to be loaded. The third argument is documentation for the
16820function, and the fourth tells whether the function can be called
16821interactively. The fifth argument tells what type of
16822object---@code{autoload} can handle a keymap or macro as well as a
16823function (the default is a function).
16824
16825@need 800
16826Here is a typical example:
16827
16828@smallexample
16829@group
16830(autoload 'html-helper-mode
16831 "html-helper-mode" "Edit HTML documents" t)
16832@end group
16833@end smallexample
16834
16835@noindent
16836(@code{html-helper-mode} is an alternative to @code{html-mode}, which
16837is a standard part of the distribution).
16838
16839@noindent
16840This expression autoloads the @code{html-helper-mode} function. It
16841takes it from the @file{html-helper-mode.el} file (or from the byte
16842compiled file @file{html-helper-mode.elc}, if it exists.) The file
16843must be located in a directory specified by @code{load-path}. The
16844documentation says that this is a mode to help you edit documents
16845written in the HyperText Markup Language. You can call this mode
16846interactively by typing @kbd{M-x html-helper-mode}. (You need to
16847duplicate the function's regular documentation in the autoload
16848expression because the regular function is not yet loaded, so its
16849documentation is not available.)
16850
16851@xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16852Manual}, for more information.
16853
16854@node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16855@section A Simple Extension: @code{line-to-top-of-window}
16856@findex line-to-top-of-window
16857@cindex Simple extension in @file{.emacs} file
16858
16859Here is a simple extension to Emacs that moves the line point is on to
16860the top of the window. I use this all the time, to make text easier
16861to read.
16862
16863You can put the following code into a separate file and then load it
16864from your @file{.emacs} file, or you can include it within your
16865@file{.emacs} file.
16866
16867@need 1250
16868Here is the definition:
16869
16870@smallexample
16871@group
16872;;; Line to top of window;
16873;;; replace three keystroke sequence C-u 0 C-l
16874(defun line-to-top-of-window ()
16875 "Move the line point is on to top of window."
16876 (interactive)
16877 (recenter 0))
16878@end group
16879@end smallexample
16880
16881@need 1250
16882Now for the keybinding.
16883
16884Nowadays, function keys as well as mouse button events and
16885non-@sc{ascii} characters are written within square brackets, without
16886quotation marks. (In Emacs version 18 and before, you had to write
16887different function key bindings for each different make of terminal.)
16888
16889I bind @code{line-to-top-of-window} to my @key{F6} function key like
16890this:
16891
16892@smallexample
16893(global-set-key [f6] 'line-to-top-of-window)
16894@end smallexample
16895
16896For more information, see @ref{Init Rebinding, , Rebinding Keys in
16897Your Init File, emacs, The GNU Emacs Manual}.
16898
16899@cindex Conditional 'twixt two versions of Emacs
16900@cindex Version of Emacs, choosing
16901@cindex Emacs version, choosing
16902If you run two versions of GNU Emacs, such as versions 20 and 21, and
16903use one @file{.emacs} file, you can select which code to evaluate with
16904the following conditional:
16905
16906@smallexample
16907@group
16908(cond
16909 ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16910 ;; evaluate version 20 code
16911 ( @dots{} ))
16912 ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16913 ;; evaluate version 21 code
16914 ( @dots{} )))
16915@end group
16916@end smallexample
16917
16918For example, in contrast to version 20, version 21 blinks its cursor
16919by default. I hate such blinking, as well as some other features in
16920version 21, so I placed the following in my @file{.emacs}
16921file@footnote{When I start instances of Emacs that do not load my
16922@file{.emacs} file or any site file, I also turn off blinking:
16923
16924@smallexample
16925emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16926@end smallexample
16927}:
16928
16929@smallexample
16930@group
16931(if (string-equal "21" (substring (emacs-version) 10 12))
16932 (progn
16933 (blink-cursor-mode 0)
16934 ;; Insert newline when you press `C-n' (next-line)
16935 ;; at the end of the buffer
16936 (setq next-line-add-newlines t)
16937@end group
16938@group
16939 ;; Turn on image viewing
16940 (auto-image-file-mode t)
16941@end group
16942@group
16943 ;; Turn on menu bar (this bar has text)
16944 ;; (Use numeric argument to turn on)
16945 (menu-bar-mode 1)
16946@end group
16947@group
16948 ;; Turn off tool bar (this bar has icons)
16949 ;; (Use numeric argument to turn on)
16950 (tool-bar-mode nil)
16951@end group
16952@group
16953 ;; Turn off tooltip mode for tool bar
16954 ;; (This mode causes icon explanations to pop up)
16955 ;; (Use numeric argument to turn on)
16956 (tooltip-mode nil)
16957 ;; If tooltips turned on, make tips appear promptly
16958 (setq tooltip-delay 0.1) ; default is one second
16959 ))
16960@end group
16961@end smallexample
16962
16963@noindent
16964(You will note that instead of typing @code{(number-to-string 21)}, I
16965decided to save typing and wrote `21' as a string, @code{"21"}, rather
16966than convert it from an integer to a string. In this instance, this
16967expression is better than the longer, but more general
16968@code{(number-to-string 21)}. However, if you do not know ahead of
16969time what type of information will be returned, then the
16970@code{number-to-string} function will be needed.)
16971
16972@node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16973@section X11 Colors
16974
16975You can specify colors when you use Emacs with the MIT X Windowing
16976system.
16977
16978I dislike the default colors and specify my own.
16979
16980@need 1250
16981Here are the expressions in my @file{.emacs}
16982file that set values:
16983
16984@smallexample
16985@group
16986;; Set cursor color
16987(set-cursor-color "white")
16988
16989;; Set mouse color
16990(set-mouse-color "white")
16991
16992;; Set foreground and background
16993(set-foreground-color "white")
16994(set-background-color "darkblue")
16995@end group
16996
16997@group
16998;;; Set highlighting colors for isearch and drag
16999(set-face-foreground 'highlight "white")
17000(set-face-background 'highlight "blue")
17001@end group
17002
17003@group
17004(set-face-foreground 'region "cyan")
17005(set-face-background 'region "blue")
17006@end group
17007
17008@group
17009(set-face-foreground 'secondary-selection "skyblue")
17010(set-face-background 'secondary-selection "darkblue")
17011@end group
17012
17013@group
17014;; Set calendar highlighting colors
17015(setq calendar-load-hook
17016 '(lambda ()
17017 (set-face-foreground 'diary-face "skyblue")
17018 (set-face-background 'holiday-face "slate blue")
17019 (set-face-foreground 'holiday-face "white")))
17020@end group
17021@end smallexample
17022
17023The various shades of blue soothe my eye and prevent me from seeing
17024the screen flicker.
17025
17026Alternatively, I could have set my specifications in various X
17027initialization files. For example, I could set the foreground,
17028background, cursor, and pointer (i.e., mouse) colors in my
17029@file{~/.Xresources} file like this:
17030
17031@smallexample
17032@group
17033Emacs*foreground: white
17034Emacs*background: darkblue
17035Emacs*cursorColor: white
17036Emacs*pointerColor: white
17037@end group
17038@end smallexample
17039
17040In any event, since it is not part of Emacs, I set the root color of
17041my X window in my @file{~/.xinitrc} file, like this@footnote{I
17042occasionally run more modern window managers, such as Sawfish with
17043GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17044image rather than a plain color.}:
17045
17046@smallexample
17047@group
17048# I use TWM for window manager.
17049xsetroot -solid Navy -fg white &
17050@end group
17051@end smallexample
17052
17053@node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17054@section Miscellaneous Settings for a @file{.emacs} File
17055
17056Here are a few miscellaneous settings:
17057@sp 1
17058
17059@itemize @minus
17060@item
17061Set the shape and color of the mouse cursor:
17062@smallexample
17063@group
17064; Cursor shapes are defined in
17065; `/usr/include/X11/cursorfont.h';
17066; for example, the `target' cursor is number 128;
17067; the `top_left_arrow' cursor is number 132.
17068@end group
17069
17070@group
17071(let ((mpointer (x-get-resource "*mpointer"
17072 "*emacs*mpointer")))
17073 ;; If you have not set your mouse pointer
17074 ;; then set it, otherwise leave as is:
17075 (if (eq mpointer nil)
17076 (setq mpointer "132")) ; top_left_arrow
17077@end group
17078@group
17079 (setq x-pointer-shape (string-to-int mpointer))
17080 (set-mouse-color "white"))
17081@end group
17082@end smallexample
17083@end itemize
17084
17085@node Mode Line, , Miscellaneous, Emacs Initialization
17086@section A Modified Mode Line
17087@vindex default-mode-line-format
17088@cindex Mode line format
17089
17090Finally, a feature I really like: a modified mode line.
17091
17092When I work over a network, I forget which machine I am using. Also,
17093I tend to I lose track of where I am, and which line point is on.
17094
17095So I reset my mode line to look like this:
17096
17097@smallexample
17098-:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
17099@end smallexample
17100
17101I am visiting a file called @file{foo.texi}, on my machine
17102@file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
17103Texinfo mode, and am at the top of the buffer.
17104
17105@need 1200
17106My @file{.emacs} file has a section that looks like this:
17107
17108@smallexample
17109@group
17110;; Set a Mode Line that tells me which machine, which directory,
17111;; and which line I am on, plus the other customary information.
17112(setq default-mode-line-format
17113 (quote
17114 (#("-" 0 1
17115 (help-echo
17116 "mouse-1: select window, mouse-2: delete others ..."))
17117 mode-line-mule-info
17118 mode-line-modified
17119 mode-line-frame-identification
17120 " "
17121@end group
17122@group
17123 mode-line-buffer-identification
17124 " "
17125 (:eval (substring
17126 (system-name) 0 (string-match "\\..+" (system-name))))
17127 ":"
17128 default-directory
17129 #(" " 0 1
17130 (help-echo
17131 "mouse-1: select window, mouse-2: delete others ..."))
17132 (line-number-mode " Line %l ")
17133 global-mode-string
17134@end group
17135@group
17136 #(" %[(" 0 6
17137 (help-echo
17138 "mouse-1: select window, mouse-2: delete others ..."))
17139 (:eval (mode-line-mode-name))
17140 mode-line-process
17141 minor-mode-alist
17142 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17143 ")%] "
17144 (-3 . "%P")
17145 ;; "-%-"
17146 )))
17147@end group
17148@end smallexample
17149
17150@noindent
17151Here, I redefine the default mode line. Most of the parts are from
17152the original; but I make a few changes. I set the @emph{default} mode
17153line format so as to permit various modes, such as Info, to override
17154it.
17155
17156Many elements in the list are self-explanatory:
17157@code{mode-line-modified} is a variable that tells whether the buffer
17158has been modified, @code{mode-name} tells the name of the mode, and so
17159on. However, the format looks complicated because of two features we
17160have not discussed.
17161
17162The first string in the mode line is a dash or hyphen, @samp{-}. In
17163the old days, it would have been specified simply as @code{"-"}. But
17164nowadays, Emacs can add properties to a string, such as highlighting
17165or, as in this case, a help feature. If you place your mouse cursor
17166over the hyphen, some help information appears (By default, you must
17167wait one second before the information appears. You can change that
17168timing by changing the value of @code{tooltip-delay}.)
17169
17170@need 1000
17171The new string format has a special syntax:
17172
17173@smallexample
17174#("-" 0 1 (help-echo "mouse-1: select window, ..."))
17175@end smallexample
17176
17177@noindent
17178The @code{#(} begins a list. The first element of the list is the
17179string itself, just one @samp{-}. The second and third
17180elements specify the range over which the fourth element applies. A
17181range starts @emph{after} a character, so a zero means the range
17182starts just before the first character; a 1 means that the range ends
17183just after the first character. The third element is the property for
17184the range. It consists of a property list, a
17185property name, in this case, @samp{help-echo}, followed by a value, in this
17186case, a string. The second, third, and fourth elements of this new
17187string format can be repeated.
17188
17189@xref{Text Props and Strings, , Text Properties in String, elisp, The
17190GNU Emacs Lisp Reference Manual}, and see @ref{Mode Line Format, , Mode
17191Line Format, elisp, The GNU Emacs Lisp Reference Manual}, for more
17192information.
17193
17194@code{mode-line-buffer-identification}
17195displays the current buffer name. It is a list
17196beginning @code{(#("%12b" 0 4 @dots{}}.
17197The @code{#(} begins the list.
17198
17199The @samp{"%12b"} displays the current buffer name, using the
17200@code{buffer-name} function with which we are familiar; the `12'
17201specifies the maximum number of characters that will be displayed.
17202When a name has fewer characters, whitespace is added to fill out to
17203this number. (Buffer names can and often should be longer than 12
17204characters; this length works well in a typical 80 column wide
17205window.)
17206
17207@code{:eval} is a new feature in GNU Emacs version 21. It says to
17208evaluate the following form and use the result as a string to display.
17209In this case, the expression displays the first component of the full
17210system name. The end of the first component is a @samp{.} (`period'),
17211so I use the @code{string-match} function to tell me the length of the
17212first component. The substring from the zeroth character to that
17213length is the name of the machine.
17214
17215@need 1250
17216This is the expression:
17217
17218@smallexample
17219@group
17220(:eval (substring
17221 (system-name) 0 (string-match "\\..+" (system-name))))
17222@end group
17223@end smallexample
17224
17225@samp{%[} and @samp{%]} cause a pair of square brackets
17226to appear for each recursive editing level. @samp{%n} says `Narrow'
17227when narrowing is in effect. @samp{%P} tells you the percentage of
17228the buffer that is above the bottom of the window, or `Top', `Bottom',
17229or `All'. (A lower case @samp{p} tell you the percentage above the
17230@emph{top} of the window.) @samp{%-} inserts enough dashes to fill
17231out the line.
17232
17233Remember, ``You don't have to like Emacs to like it'' --- your own
17234Emacs can have different colors, different commands, and different
17235keys than a default Emacs.
17236
17237On the other hand, if you want to bring up a plain `out of the box'
17238Emacs, with no customization, type:
17239
17240@smallexample
17241emacs -q
17242@end smallexample
17243
17244@noindent
17245This will start an Emacs that does @emph{not} load your
17246@file{~/.emacs} initialization file. A plain, default Emacs. Nothing
17247more.
17248
17249@node Debugging, Conclusion, Emacs Initialization, Top
17250@chapter Debugging
17251@cindex debugging
17252
17253GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
17254first is built into the internals of Emacs and is always with you;
17255the second requires that you instrument a function before you can use it.
17256
17257Both debuggers are described extensively in @ref{Debugging, ,
17258Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17259In this chapter, I will walk through a short example of each.
17260
17261@menu
17262* debug:: How to use the built-in debugger.
17263* debug-on-entry:: Start debugging when you call a function.
17264* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
17265* edebug:: How to use Edebug, a source level debugger.
17266* Debugging Exercises::
17267@end menu
17268
17269@node debug, debug-on-entry, Debugging, Debugging
17270@section @code{debug}
17271@findex debug
17272
17273Suppose you have written a function definition that is intended to
17274return the sum of the numbers 1 through a given number. (This is the
17275@code{triangle} function discussed earlier. @xref{Decrementing
17276Example, , Example with Decrementing Counter}, for a discussion.)
17277@c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17278
17279However, your function definition has a bug. You have mistyped
17280@samp{1=} for @samp{1-}. Here is the broken definition:
17281
17282@findex triangle-bugged
17283@smallexample
17284@group
17285(defun triangle-bugged (number)
17286 "Return sum of numbers 1 through NUMBER inclusive."
17287 (let ((total 0))
17288 (while (> number 0)
17289 (setq total (+ total number))
17290 (setq number (1= number))) ; @r{Error here.}
17291 total))
17292@end group
17293@end smallexample
17294
17295If you are reading this in Info, you can evaluate this definition in
17296the normal fashion. You will see @code{triangle-bugged} appear in the
17297echo area.
17298
17299@need 1250
17300Now evaluate the @code{triangle-bugged} function with an
17301argument of 4:
17302
17303@smallexample
17304(triangle-bugged 4)
17305@end smallexample
17306
17307@noindent
17308In GNU Emacs version 21, you will create and enter a
17309@file{*Backtrace*} buffer that says:
17310
17311@noindent
17312@smallexample
17313@group
17314---------- Buffer: *Backtrace* ----------
17315Debugger entered--Lisp error: (void-function 1=)
17316 (1= number)
17317 (setq number (1= number))
17318 (while (> number 0) (setq total (+ total number))
17319 (setq number (1= number)))
17320 (let ((total 0)) (while (> number 0) (setq total ...)
17321 (setq number ...)) total)
17322 triangle-bugged(4)
17323@end group
17324@group
17325 eval((triangle-bugged 4))
17326 eval-last-sexp-1(nil)
17327 eval-last-sexp(nil)
17328 call-interactively(eval-last-sexp)
17329---------- Buffer: *Backtrace* ----------
17330@end group
17331@end smallexample
17332
17333@noindent
17334(I have reformatted this example slightly; the debugger does not fold
17335long lines. As usual, you can quit the debugger by typing @kbd{q} in
17336the @file{*Backtrace*} buffer.)
17337
17338In practice, for a bug as simple as this, the `Lisp error' line will
17339tell you what you need to know to correct the definition. The
17340function @code{1=} is `void'.
17341
17342@need 800
17343In GNU Emacs 20 and before, you will see:
17344
17345@smallexample
17346Symbol's function definition is void:@: 1=
17347@end smallexample
17348
17349@noindent
17350which has the same meaning as the @file{*Backtrace*} buffer line in
17351version 21.
17352
17353However, suppose you are not quite certain what is going on?
17354You can read the complete backtrace.
17355
17356In this case, you need to run GNU Emacs 21, which automatically starts
17357the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17358you need to start the debugger manually as described below.
17359
17360Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17361what Emacs did that led to the error. Emacs made an interactive call
17362to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17363of the @code{triangle-bugged} expression. Each line above tells you
17364what the Lisp interpreter evaluated next.
17365
17366@need 1250
17367The third line from the top of the buffer is
17368
17369@smallexample
17370(setq number (1= number))
17371@end smallexample
17372
17373@noindent
17374Emacs tried to evaluate this expression; in order to do so, it tried
17375to evaluate the inner expression shown on the second line from the
17376top:
17377
17378@smallexample
17379(1= number)
17380@end smallexample
17381
17382@need 1250
17383@noindent
17384This is where the error occurred; as the top line says:
17385
17386@smallexample
17387Debugger entered--Lisp error: (void-function 1=)
17388@end smallexample
17389
17390@noindent
17391You can correct the mistake, re-evaluate the function definition, and
17392then run your test again.
17393
17394@node debug-on-entry, debug-on-quit, debug, Debugging
17395@section @code{debug-on-entry}
17396@findex debug-on-entry
17397
17398GNU Emacs 21 starts the debugger automatically when your function has
17399an error. GNU Emacs version 20 and before did not; it simply
17400presented you with an error message. You had to start the debugger
17401manually.
17402
17403You can start the debugger manually for all versions of Emacs; the
17404advantage is that the debugger runs even if you do not have a bug in
17405your code. Sometimes your code will be free of bugs!
17406
17407You can enter the debugger when you call the function by calling
17408@code{debug-on-entry}.
17409
17410@need 1250
17411@noindent
17412Type:
17413
17414@smallexample
17415M-x debug-on-entry RET triangle-bugged RET
17416@end smallexample
17417
17418@need 1250
17419@noindent
17420Now, evaluate the following:
17421
17422@smallexample
17423(triangle-bugged 5)
17424@end smallexample
17425
17426@noindent
17427All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17428you that it is beginning to evaluate the @code{triangle-bugged}
17429function:
17430
17431@smallexample
17432@group
17433---------- Buffer: *Backtrace* ----------
17434Debugger entered--entering a function:
17435* triangle-bugged(5)
17436 eval((triangle-bugged 5))
17437@end group
17438@group
17439 eval-last-sexp-1(nil)
17440 eval-last-sexp(nil)
17441 call-interactively(eval-last-sexp)
17442---------- Buffer: *Backtrace* ----------
17443@end group
17444@end smallexample
17445
17446In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
17447the first expression in @code{triangle-bugged}; the buffer will look
17448like this:
17449
17450@smallexample
17451@group
17452---------- Buffer: *Backtrace* ----------
17453Debugger entered--beginning evaluation of function call form:
17454* (let ((total 0)) (while (> number 0) (setq total ...)
17455 (setq number ...)) total)
17456* triangle-bugged(5)
17457 eval((triangle-bugged 5))
17458@end group
17459@group
17460 eval-last-sexp-1(nil)
17461 eval-last-sexp(nil)
17462 call-interactively(eval-last-sexp)
17463---------- Buffer: *Backtrace* ----------
17464@end group
17465@end smallexample
17466
17467@noindent
17468Now, type @kbd{d} again, eight times, slowly. Each time you type
17469@kbd{d}, Emacs will evaluate another expression in the function
17470definition.
17471
17472@need 1750
17473Eventually, the buffer will look like this:
17474
17475@smallexample
17476@group
17477---------- Buffer: *Backtrace* ----------
17478Debugger entered--beginning evaluation of function call form:
17479* (setq number (1= number))
17480* (while (> number 0) (setq total (+ total number))
17481 (setq number (1= number)))
17482@group
17483@end group
17484* (let ((total 0)) (while (> number 0) (setq total ...)
17485 (setq number ...)) total)
17486* triangle-bugged(5)
17487 eval((triangle-bugged 5))
17488@group
17489@end group
17490 eval-last-sexp-1(nil)
17491 eval-last-sexp(nil)
17492 call-interactively(eval-last-sexp)
17493---------- Buffer: *Backtrace* ----------
17494@end group
17495@end smallexample
17496
17497@noindent
17498Finally, after you type @kbd{d} two more times, Emacs will reach the
17499error, and the top two lines of the @file{*Backtrace*} buffer will look
17500like this:
17501
17502@smallexample
17503@group
17504---------- Buffer: *Backtrace* ----------
17505Debugger entered--Lisp error: (void-function 1=)
17506* (1= number)
17507@dots{}
17508---------- Buffer: *Backtrace* ----------
17509@end group
17510@end smallexample
17511
17512By typing @kbd{d}, you were able to step through the function.
17513
17514You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17515quits the trace, but does not cancel @code{debug-on-entry}.
17516
17517@findex cancel-debug-on-entry
17518To cancel the effect of @code{debug-on-entry}, call
17519@code{cancel-debug-on-entry} and the name of the function, like this:
17520
17521@smallexample
17522M-x cancel-debug-on-entry RET triangle-bugged RET
17523@end smallexample
17524
17525@noindent
17526(If you are reading this in Info, cancel @code{debug-on-entry} now.)
17527
17528@node debug-on-quit, edebug, debug-on-entry, Debugging
17529@section @code{debug-on-quit} and @code{(debug)}
17530
17531In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17532there are two other ways to start @code{debug}.
17533
17534@findex debug-on-quit
17535You can start @code{debug} whenever you type @kbd{C-g}
17536(@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17537@code{t}. This is useful for debugging infinite loops.
17538
17539@need 1500
17540@cindex @code{(debug)} in code
17541Or, you can insert a line that says @code{(debug)} into your code
17542where you want the debugger to start, like this:
17543
17544@smallexample
17545@group
17546(defun triangle-bugged (number)
17547 "Return sum of numbers 1 through NUMBER inclusive."
17548 (let ((total 0))
17549 (while (> number 0)
17550 (setq total (+ total number))
17551 (debug) ; @r{Start debugger.}
17552 (setq number (1= number))) ; @r{Error here.}
17553 total))
17554@end group
17555@end smallexample
17556
17557The @code{debug} function is described in detail in @ref{Debugger, ,
17558The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17559
17560@node edebug, Debugging Exercises, debug-on-quit, Debugging
17561@section The @code{edebug} Source Level Debugger
17562@cindex Source level debugger
17563@findex edebug
17564
17565Edebug is a source level debugger. Edebug normally displays the
17566source of the code you are debugging, with an arrow at the left that
17567shows which line you are currently executing.
17568
17569You can walk through the execution of a function, line by line, or run
17570quickly until reaching a @dfn{breakpoint} where execution stops.
17571
17572Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17573Lisp Reference Manual}.
17574
17575Here is a bugged function definition for @code{triangle-recursively}.
17576@xref{Recursive triangle function, , Recursion in place of a counter},
17577for a review of it.
17578
17579@smallexample
17580@group
17581(defun triangle-recursively-bugged (number)
17582 "Return sum of numbers 1 through NUMBER inclusive.
17583Uses recursion."
17584 (if (= number 1)
17585 1
17586 (+ number
17587 (triangle-recursively-bugged
17588 (1= number))))) ; @r{Error here.}
17589@end group
17590@end smallexample
17591
17592@noindent
17593Normally, you would install this definition by positioning your cursor
17594after the function's closing parenthesis and typing @kbd{C-x C-e}
17595(@code{eval-last-sexp}) or else by positioning your cursor within the
17596definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
17597the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17598Interactive mode.)
17599
17600@need 1500
17601However, to prepare this function definition for Edebug, you must
17602first @dfn{instrument} the code using a different command. You can do
17603this by positioning your cursor within the definition and typing
17604
17605@smallexample
17606M-x edebug-defun RET
17607@end smallexample
17608
17609@noindent
17610This will cause Emacs to load Edebug automatically if it is not
17611already loaded, and properly instrument the function.
17612
17613After instrumenting the function, place your cursor after the
17614following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17615
17616@smallexample
17617(triangle-recursively-bugged 3)
17618@end smallexample
17619
17620@noindent
17621You will be jumped back to the source for
17622@code{triangle-recursively-bugged} and the cursor positioned at the
17623beginning of the @code{if} line of the function. Also, you will see
17624an arrowhead at the left hand side of that line. The arrowhead marks
17625the line where the function is executing. (In the following examples,
17626we show the arrowhead with @samp{=>}; in a windowing system, you may
17627see the arrowhead as a solid triangle in the window `fringe'.)
17628
17629@smallexample
17630=>@point{}(if (= number 1)
17631@end smallexample
17632
17633@noindent
17634@iftex
17635In the example, the location of point is displayed with a star,
17636@samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17637@end iftex
17638@ifnottex
17639In the example, the location of point is displayed as @samp{@point{}}
17640(in a printed book, it is displayed with a five pointed star).
17641@end ifnottex
17642
17643If you now press @key{SPC}, point will move to the next expression to
17644be executed; the line will look like this:
17645
17646@smallexample
17647=>(if @point{}(= number 1)
17648@end smallexample
17649
17650@noindent
17651As you continue to press @key{SPC}, point will move from expression to
17652expression. At the same time, whenever an expression returns a value,
17653that value will be displayed in the echo area. For example, after you
17654move point past @code{number}, you will see the following:
17655
17656@smallexample
17657Result: 3 = C-c
17658@end smallexample
17659
17660@noindent
17661This means the value of @code{number} is 3, which is @sc{ascii}
17662`control-c' (the third letter of the alphabet).
17663
17664You can continue moving through the code until you reach the line with
17665the error. Before evaluation, that line looks like this:
17666
17667@smallexample
17668=> @point{}(1= number))))) ; @r{Error here.}
17669@end smallexample
17670
17671@need 1250
17672@noindent
17673When you press @key{SPC} once again, you will produce an error message
17674that says:
17675
17676@smallexample
17677Symbol's function definition is void:@: 1=
17678@end smallexample
17679
17680@noindent
17681This is the bug.
17682
17683Press @kbd{q} to quit Edebug.
17684
17685To remove instrumentation from a function definition, simply
17686re-evaluate it with a command that does not instrument it.
17687For example, you could place your cursor after the definition's
17688closing parenthesis and type @kbd{C-x C-e}.
17689
17690Edebug does a great deal more than walk with you through a function.
17691You can set it so it races through on its own, stopping only at an
17692error or at specified stopping points; you can cause it to display the
17693changing values of various expressions; you can find out how many
17694times a function is called, and more.
17695
17696Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17697Lisp Reference Manual}.
17698
17699@need 1500
17700@node Debugging Exercises, , edebug, Debugging
17701@section Debugging Exercises
17702
17703@itemize @bullet
17704@item
17705Install the @code{count-words-region} function and then cause it to
17706enter the built-in debugger when you call it. Run the command on a
17707region containing two words. You will need to press @kbd{d} a
17708remarkable number of times. On your system, is a `hook' called after
17709the command finishes? (For information on hooks, see @ref{Command
17710Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17711Manual}.)
17712
17713@item
17714Copy @code{count-words-region} into the @file{*scratch*} buffer,
17715instrument the function for Edebug, and walk through its execution.
17716The function does not need to have a bug, although you can introduce
17717one if you wish. If the function lacks a bug, the walk-through
17718completes without problems.
17719
17720@item
17721While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17722(The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17723@kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17724for commands made outside of the Edebug debugging buffer.)
17725
17726@item
17727In the Edebug debugging buffer, use the @kbd{p}
17728(@code{edebug-bounce-point}) command to see where in the region the
17729@code{count-words-region} is working.
17730
17731@item
17732Move point to some spot further down function and then type the
17733@kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17734
17735@item
17736Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17737walk through the function on its own; use an upper case @kbd{T} for
17738@code{edebug-Trace-fast-mode}.
17739
17740@item
17741Set a breakpoint, then run Edebug in Trace mode until it reaches the
17742stopping point.
17743@end itemize
17744
17745@node Conclusion, the-the, Debugging, Top
17746@chapter Conclusion
17747
17748We have now reached the end of this Introduction. You have now
17749learned enough about programming in Emacs Lisp to set values, to write
17750simple @file{.emacs} files for yourself and your friends, and write
17751simple customizations and extensions to Emacs.
17752
17753This is a place to stop. Or, if you wish, you can now go onward, and
17754teach yourself.
17755
17756You have learned some of the basic nuts and bolts of programming. But
17757only some. There are a great many more brackets and hinges that are
17758easy to use that we have not touched.
17759
17760A path you can follow right now lies among the sources to GNU Emacs
17761and in
17762@ifnotinfo
17763@cite{The GNU Emacs Lisp Reference Manual}.
17764@end ifnotinfo
17765@ifinfo
17766@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17767Emacs Lisp Reference Manual}.
17768@end ifinfo
17769
17770The Emacs Lisp sources are an adventure. When you read the sources and
17771come across a function or expression that is unfamiliar, you need to
17772figure out or find out what it does.
17773
17774Go to the Reference Manual. It is a thorough, complete, and fairly
17775easy-to-read description of Emacs Lisp. It is written not only for
17776experts, but for people who know what you know. (The @cite{Reference
17777Manual} comes with the standard GNU Emacs distribution. Like this
17778introduction, it comes as a Texinfo source file, so you can read it
17779on-line and as a typeset, printed book.)
17780
17781Go to the other on-line help that is part of GNU Emacs: the on-line
17782documentation for all functions, and @code{find-tags}, the program
17783that takes you to sources.
17784
17785Here is an example of how I explore the sources. Because of its name,
17786@file{simple.el} is the file I looked at first, a long time ago. As
17787it happens some of the functions in @file{simple.el} are complicated,
17788or at least look complicated at first sight. The @code{open-line}
17789function, for example, looks complicated.
17790
17791You may want to walk through this function slowly, as we did with the
17792@code{forward-sentence} function.
17793@ifnottex
17794(@xref{forward-sentence}.)
17795@end ifnottex
17796@iftex
17797(@xref{forward-sentence, , @code{forward-sentence}}.)
17798@end iftex
17799Or you may want to skip that function and look at another, such as
17800@code{split-line}. You don't need to read all the functions.
17801According to @code{count-words-in-defun}, the @code{split-line}
17802function contains 27 words and symbols.
17803
17804Even though it is short, @code{split-line} contains four expressions
17805we have not studied: @code{skip-chars-forward}, @code{indent-to},
17806@code{current-column} and @samp{?\n}.
17807
17808Consider the @code{skip-chars-forward} function. (It is part of the
17809function definition for @code{back-to-indentation}, which is shown in
17810@ref{Review, , Review}.)
17811
17812In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17813typing @kbd{C-h f} (@code{describe-function}) and the name of the
17814function. This gives you the function documentation.
17815
17816You may be able to guess what is done by a well named function such as
17817@code{indent-to}; or you can look it up, too. Incidentally, the
17818@code{describe-function} function itself is in @file{help.el}; it is
17819one of those long, but decipherable functions. You can look up
17820@code{describe-function} using the @kbd{C-h f} command!
17821
17822In this instance, since the code is Lisp, the @file{*Help*} buffer
17823contains the name of the library containing the function's source.
17824You can put point over the name of the library and press the RET key,
17825which in this situation is bound to @code{help-follow}, and be taken
17826directly to the source, in the same way as @kbd{M-.}
17827(@code{find-tag}).
17828
17829The definition for @code{describe-function} illustrates how to
17830customize the @code{interactive} expression without using the standard
17831character codes; and it shows how to create a temporary buffer.
17832
17833(The @code{indent-to} function is written in C rather than Emacs Lisp;
17834it is a `built-in' function. @code{help-follow} only provides you
17835with the documentation of a built-in function; it does not take you to
17836the source. But @code{find-tag} will take you to the source, if
17837properly set up.)
17838
17839You can look at a function's source using @code{find-tag}, which is
17840bound to @kbd{M-.} Finally, you can find out what the Reference
17841Manual has to say by visiting the manual in Info, and typing @kbd{i}
17842(@code{Info-index}) and the name of the function, or by looking up
17843@code{skip-chars-forward} in the index to a printed copy of the
17844manual.
17845
17846Similarly, you can find out what is meant by @samp{?\n}. You can try
17847using @code{Info-index} with @samp{?\n}. It turns out that this
17848action won't help; but don't give up. If you search the index for
17849@samp{\n} without the @samp{?}, you will be taken directly to the
17850relevant section of the manual. (@xref{Character Type, , Character
17851Type, elisp, The GNU Emacs Lisp Reference Manual}. @samp{?\n} stands
17852for the newline character.)
17853
17854Other interesting source files include @file{paragraphs.el},
17855@file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
17856file includes short, easily understood functions as well as longer
17857ones. The @file{loaddefs.el} file contains the many standard
17858autoloads and many keymaps. I have never looked at it all; only at
17859parts. @file{loadup.el} is the file that loads the standard parts of
17860Emacs; it tells you a great deal about how Emacs is built.
17861(@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17862Reference Manual}, for more about building.)
17863
17864As I said, you have learned some nuts and bolts; however, and very
17865importantly, we have hardly touched major aspects of programming; I
17866have said nothing about how to sort information, except to use the
17867predefined @code{sort} function; I have said nothing about how to store
17868information, except to use variables and lists; I have said nothing
17869about how to write programs that write programs. These are topics for
17870another, and different kind of book, a different kind of learning.
17871
17872What you have done is learn enough for much practical work with GNU
17873Emacs. What you have done is get started. This is the end of a
17874beginning.
17875
17876@c ================ Appendix ================
17877
17878@node the-the, Kill Ring, Conclusion, Top
17879@appendix The @code{the-the} Function
17880@findex the-the
17881@cindex Duplicated words function
17882@cindex Words, duplicated
17883
17884Sometimes when you you write text, you duplicate words---as with ``you
17885you'' near the beginning of this sentence. I find that most
17886frequently, I duplicate ``the'; hence, I call the function for
17887detecting duplicated words, @code{the-the}.
17888
17889@need 1250
17890As a first step, you could use the following regular expression to
17891search for duplicates:
17892
17893@smallexample
17894\\(\\w+[ \t\n]+\\)\\1
17895@end smallexample
17896
17897@noindent
17898This regexp matches one or more word-constituent characters followed
17899by one or more spaces, tabs, or newlines. However, it does not detect
17900duplicated words on different lines, since the ending of the first
17901word, the end of the line, is different from the ending of the second
17902word, a space. (For more information about regular expressions, see
17903@ref{Regexp Search, , Regular Expression Searches}, as well as
17904@ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
17905Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
17906The GNU Emacs Lisp Reference Manual}.)
17907
17908You might try searching just for duplicated word-constituent
17909characters but that does not work since the pattern detects doubles
17910such as the two occurrences of `th' in `with the'.
17911
17912Another possible regexp searches for word-constituent characters
17913followed by non-word-constituent characters, reduplicated. Here,
17914@w{@samp{\\w+}} matches one or more word-constituent characters and
17915@w{@samp{\\W*}} matches zero or more non-word-constituent characters.
17916
17917@smallexample
17918\\(\\(\\w+\\)\\W*\\)\\1
17919@end smallexample
17920
17921@noindent
17922Again, not useful.
17923
17924Here is the pattern that I use. It is not perfect, but good enough.
17925@w{@samp{\\b}} matches the empty string, provided it is at the beginning
17926or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
17927any characters that are @emph{not} an @@-sign, space, newline, or tab.
17928
17929@smallexample
17930\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
17931@end smallexample
17932
17933One can write more complicated expressions, but I found that this
17934expression is good enough, so I use it.
17935
17936Here is the @code{the-the} function, as I include it in my
17937@file{.emacs} file, along with a handy global key binding:
17938
17939@smallexample
17940@group
17941(defun the-the ()
17942 "Search forward for for a duplicated word."
17943 (interactive)
17944 (message "Searching for for duplicated words ...")
17945 (push-mark)
17946@end group
17947@group
17948 ;; This regexp is not perfect
17949 ;; but is fairly good over all:
17950 (if (re-search-forward
17951 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
17952 (message "Found duplicated word.")
17953 (message "End of buffer")))
17954@end group
17955
17956@group
17957;; Bind `the-the' to C-c \
17958(global-set-key "\C-c\\" 'the-the)
17959@end group
17960@end smallexample
17961
17962@sp 1
17963Here is test text:
17964
17965@smallexample
17966@group
17967one two two three four five
17968five six seven
17969@end group
17970@end smallexample
17971
17972You can substitute the other regular expressions shown above in the
17973function definition and try each of them on this list.
17974
17975@node Kill Ring, Full Graph, the-the, Top
17976@appendix Handling the Kill Ring
17977@cindex Kill ring handling
17978@cindex Handling the kill ring
17979@cindex Ring, making a list like a
17980
17981The kill ring is a list that is transformed into a ring by the
17982workings of the @code{rotate-yank-pointer} function. The @code{yank}
17983and @code{yank-pop} commands use the @code{rotate-yank-pointer}
17984function. This appendix describes the @code{rotate-yank-pointer}
17985function as well as both the @code{yank} and the @code{yank-pop}
17986commands.
17987
17988@menu
17989* rotate-yank-pointer:: Move a pointer along a list and around.
17990* yank:: Paste a copy of a clipped element.
17991* yank-pop:: Insert first element pointed to.
17992@end menu
17993
17994@node rotate-yank-pointer, yank, Kill Ring, Kill Ring
17995@comment node-name, next, previous, up
17996@appendixsec The @code{rotate-yank-pointer} Function
17997@findex rotate-yank-pointer
17998
17999The @code{rotate-yank-pointer} function changes the element in the kill
18000ring to which @code{kill-ring-yank-pointer} points. For example, it can
18001change @code{kill-ring-yank-pointer} from pointing to the second
18002element to point to the third element.
18003
18004@need 800
18005Here is the code for @code{rotate-yank-pointer}:
18006
18007@smallexample
18008@group
18009(defun rotate-yank-pointer (arg)
18010 "Rotate the yanking point in the kill ring."
18011 (interactive "p")
18012 (let ((length (length kill-ring)))
18013@end group
18014@group
18015 (if (zerop length)
18016 ;; @r{then-part}
18017 (error "Kill ring is empty")
18018@end group
18019@group
18020 ;; @r{else-part}
18021 (setq kill-ring-yank-pointer
18022 (nthcdr (% (+ arg
18023 (- length
18024 (length
18025 kill-ring-yank-pointer)))
18026 length)
18027 kill-ring)))))
18028@end group
18029@end smallexample
18030
18031@menu
18032* Understanding rotate-yk-ptr::
18033* rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
18034@end menu
18035
18036@node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18037@ifnottex
18038@unnumberedsubsec @code{rotate-yank-pointer} in Outline
18039@end ifnottex
18040
18041The @code{rotate-yank-pointer} function looks complex, but as usual,
18042it can be understood by taking it apart piece by piece. First look at
18043it in skeletal form:
18044
18045@smallexample
18046@group
18047(defun rotate-yank-pointer (arg)
18048 "Rotate the yanking point in the kill ring."
18049 (interactive "p")
18050 (let @var{varlist}
18051 @var{body}@dots{})
18052@end group
18053@end smallexample
18054
18055This function takes one argument, called @code{arg}. It has a brief
18056documentation string; and it is interactive with a small @samp{p}, which
18057means that the argument must be a processed prefix passed to the
18058function as a number.
18059
18060The body of the function definition is a @code{let} expression, which
18061itself has a body as well as a @var{varlist}.
18062
18063The @code{let} expression declares a variable that will be only usable
18064within the bounds of this function. This variable is called
18065@code{length} and is bound to a value that is equal to the number of
18066items in the kill ring. This is done by using the function called
18067@code{length}. (Note that this function has the same name as the
18068variable called @code{length}; but one use of the word is to name the
18069function and the other is to name the variable. The two are quite
18070distinct. Similarly, an English speaker will distinguish between the
18071meanings of the word @samp{ship} when he says: "I must ship this package
18072immediately." and "I must get aboard the ship immediately.")
18073
18074The function @code{length} tells the number of items there are in a list,
18075so @code{(length kill-ring)} returns the number of items there are in the
18076kill ring.
18077
18078@node rotate-yk-ptr body, , Understanding rotate-yk-ptr, rotate-yank-pointer
18079@comment node-name, next, previous, up
18080@appendixsubsec The Body of @code{rotate-yank-pointer}
18081
18082The body of @code{rotate-yank-pointer} is a @code{let} expression and
18083the body of the @code{let} expression is an @code{if} expression.
18084
18085The purpose of the @code{if} expression is to find out whether there is
18086anything in the kill ring. If the kill ring is empty, the @code{error}
18087function stops evaluation of the function and prints a message in the
18088echo area. On the other hand, if the kill ring has something in it, the
18089work of the function is done.
18090
18091Here is the if-part and then-part of the @code{if} expression:
18092
18093@findex zerop
18094@findex error
18095@smallexample
18096@group
18097(if (zerop length) ; @r{if-part}
18098 (error "Kill ring is empty") ; @r{then-part}
18099 @dots{}
18100@end group
18101@end smallexample
18102
18103@noindent
18104If there is not anything in the kill ring, its length must be zero and
18105an error message sent to the user: @samp{Kill ring is empty}. The
18106@code{if} expression uses the function @code{zerop} which returns true
18107if the value it is testing is zero. When @code{zerop} tests true, the
18108then-part of the @code{if} is evaluated. The then-part is a list
18109starting with the function @code{error}, which is a function that is
18110similar to the @code{message} function (@pxref{message}), in that it
18111prints a one-line message in the echo area. However, in addition to
18112printing a message, @code{error} also stops evaluation of the function
18113within which it is embedded. This means that the rest of the function
18114will not be evaluated if the length of the kill ring is zero.
18115
18116@menu
18117* Digression concerning error:: How to mislead humans, but not computers.
18118* rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
18119* Remainder Function:: The remainder, @code{%}, function.
18120* rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
18121* kill-rng-yk-ptr last elt:: Pointing to the last element.
18122@end menu
18123
18124@node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18125@ifnottex
18126@unnumberedsubsubsec Digression about the word `error'
18127@end ifnottex
18128
18129(In my opinion, it is slightly misleading, at least to humans, to use
18130the term `error' as the name of the @code{error} function. A better
18131term would be `cancel'. Strictly speaking, of course, you cannot
18132point to, much less rotate a pointer to a list that has no length, so
18133from the point of view of the computer, the word `error' is correct.
18134But a human expects to attempt this sort of thing, if only to find out
18135whether the kill ring is full or empty. This is an act of
18136exploration.
18137
18138(From the human point of view, the act of exploration and discovery is
18139not necessarily an error, and therefore should not be labelled as one,
18140even in the bowels of a computer. As it is, the code in Emacs implies
18141that a human who is acting virtuously, by exploring his or her
18142environment, is making an error. This is bad. Even though the computer
18143takes the same steps as it does when there is an `error', a term such as
18144`cancel' would have a clearer connotation.)
18145
18146@node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18147@unnumberedsubsubsec The else-part of the @code{if} expression
18148
18149The else-part of the @code{if} expression is dedicated to setting the
18150value of @code{kill-ring-yank-pointer} when the kill ring has something
18151in it. The code looks like this:
18152
18153@smallexample
18154@group
18155(setq kill-ring-yank-pointer
18156 (nthcdr (% (+ arg
18157 (- length
18158 (length kill-ring-yank-pointer)))
18159 length)
18160 kill-ring)))))
18161@end group
18162@end smallexample
18163
18164This needs some examination. Clearly, @code{kill-ring-yank-pointer}
18165is being set to be equal to some @sc{cdr} of the kill ring, using the
18166@code{nthcdr} function that is described in an earlier section.
18167(@xref{copy-region-as-kill}.) But exactly how does it do this?
18168
18169Before looking at the details of the code let's first consider the
18170purpose of the @code{rotate-yank-pointer} function.
18171
18172The @code{rotate-yank-pointer} function changes what
18173@code{kill-ring-yank-pointer} points to. If
18174@code{kill-ring-yank-pointer} starts by pointing to the first element
18175of a list, a call to @code{rotate-yank-pointer} causes it to point to
18176the second element; and if @code{kill-ring-yank-pointer} points to the
18177second element, a call to @code{rotate-yank-pointer} causes it to
18178point to the third element. (And if @code{rotate-yank-pointer} is
18179given an argument greater than 1, it jumps the pointer that many
18180elements.)
18181
18182The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18183the @code{kill-ring-yank-pointer} points to. If
18184@code{kill-ring-yank-pointer} points to the first element of the kill
18185ring, then, in the simplest case, the @code{rotate-yank-pointer}
18186function must cause it to point to the second element. Put another
18187way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18188to the @sc{cdr} of the kill ring.
18189
18190@need 1250
18191That is, under these circumstances,
18192
18193@smallexample
18194@group
18195(setq kill-ring-yank-pointer
18196 ("some text" "a different piece of text" "yet more text"))
18197
18198(setq kill-ring
18199 ("some text" "a different piece of text" "yet more text"))
18200@end group
18201@end smallexample
18202
18203@need 800
18204@noindent
18205the code should do this:
18206
18207@smallexample
18208(setq kill-ring-yank-pointer (cdr kill-ring))
18209@end smallexample
18210
18211@need 1000
18212@noindent
18213As a result, the @code{kill-ring-yank-pointer} will look like this:
18214
18215@smallexample
18216@group
18217kill-ring-yank-pointer
18218 @result{} ("a different piece of text" "yet more text"))
18219@end group
18220@end smallexample
18221
18222The actual @code{setq} expression uses the @code{nthcdr} function to do
18223the job.
18224
18225As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18226works by repeatedly taking the @sc{cdr} of a list---it takes the
18227@sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18228
18229@need 800
18230The two following expressions produce the same result:
18231
18232@smallexample
18233@group
18234(setq kill-ring-yank-pointer (cdr kill-ring))
18235
18236(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18237@end group
18238@end smallexample
18239
18240In the @code{rotate-yank-pointer} function, however, the first
18241argument to @code{nthcdr} is a rather complex looking expression with
18242lots of arithmetic inside of it:
18243
18244@smallexample
18245@group
18246(% (+ arg
18247 (- length
18248 (length kill-ring-yank-pointer)))
18249 length)
18250@end group
18251@end smallexample
18252
18253As usual, we need to look at the most deeply embedded expression first
18254and then work our way towards the light.
18255
18256The most deeply embedded expression is @code{(length
18257kill-ring-yank-pointer)}. This finds the length of the current value of
18258the @code{kill-ring-yank-pointer}. (Remember that the
18259@code{kill-ring-yank-pointer} is the name of a variable whose value is a
18260list.)
18261
18262@need 800
18263The measurement of the length is inside the expression:
18264
18265@smallexample
18266(- length (length kill-ring-yank-pointer))
18267@end smallexample
18268
18269@noindent
18270In this expression, the first @code{length} is the variable that was
18271assigned the length of the kill ring in the @code{let} statement at the
18272beginning of the function. (One might think this function would be
18273clearer if the variable @code{length} were named
18274@code{length-of-kill-ring} instead; but if you look at the text of the
18275whole function, you will see that it is so short that naming this
18276variable @code{length} is not a bother, unless you are pulling the
18277function apart into very tiny pieces as we are doing here.)
18278
18279So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18280difference between the length of the kill ring and the length of the list
18281whose name is @code{kill-ring-yank-pointer}.
18282
18283To see how all this fits into the @code{rotate-yank-pointer}
18284function, let's begin by analyzing the case where
18285@code{kill-ring-yank-pointer} points to the first element of the kill
18286ring, just as @code{kill-ring} does, and see what happens when
18287@code{rotate-yank-pointer} is called with an argument of 1.
18288
18289The variable @code{length} and the value of the expression
18290@code{(length kill-ring-yank-pointer)} will be the same since the
18291variable @code{length} is the length of the kill ring and the
18292@code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18293Consequently, the value of
18294
18295@smallexample
18296(- length (length kill-ring-yank-pointer))
18297@end smallexample
18298
18299@noindent
18300will be zero. Since the value of @code{arg} will be 1, this will mean
18301that the value of the whole expression
18302
18303@smallexample
18304(+ arg (- length (length kill-ring-yank-pointer)))
18305@end smallexample
18306
18307@noindent
18308will be 1.
18309
18310Consequently, the argument to @code{nthcdr} will be found as the result of
18311the expression
18312
18313@smallexample
18314(% 1 length)
18315@end smallexample
18316
18317@node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18318@unnumberedsubsubsec The @code{%} remainder function
18319
18320To understand @code{(% 1 length)}, we need to understand @code{%}.
18321According to its documentation (which I just found by typing @kbd{C-h
18322f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18323its first argument divided by its second argument. For example, the
18324remainder of 5 divided by 2 is 1. (2 goes into 5 twice with a
18325remainder of 1.)
18326
18327What surprises people who don't often do arithmetic is that a smaller
18328number can be divided by a larger number and have a remainder. In the
18329example we just used, 5 was divided by 2. We can reverse that and ask,
18330what is the result of dividing 2 by 5? If you can use fractions, the
18331answer is obviously 2/5 or .4; but if, as here, you can only use whole
18332numbers, the result has to be something different. Clearly, 5 can go into
183332 zero times, but what of the remainder? To see what the answer is,
18334consider a case that has to be familiar from childhood:
18335
18336@itemize @bullet
18337@item
183385 divided by 5 is 1 with a remainder of 0;
18339
18340@item
183416 divided by 5 is 1 with a remainder of 1;
18342
18343@item
183447 divided by 5 is 1 with a remainder of 2.
18345
18346@item
18347Similarly, 10 divided by 5 is 2 with a remainder of 0;
18348
18349@item
1835011 divided by 5 is 2 with a remainder of 1;
18351
18352@item
1835312 divided by 5 is 1 with a remainder of 2.
18354@end itemize
18355
18356@need 1250
18357@noindent
18358By considering the cases as parallel, we can see that
18359
18360@itemize @bullet
18361@item
18362zero divided by 5 must be zero with a remainder of zero;
18363
18364@item
183651 divided by 5 must be zero with a remainder of 1;
18366
18367@item
183682 divided by 5 must be zero with a remainder of 2;
18369@end itemize
18370
18371@noindent
18372and so on.
18373
18374@need 1250
18375So, in this code, if the value of @code{length} is 5, then the result of
18376evaluating
18377
18378@smallexample
18379(% 1 5)
18380@end smallexample
18381
18382@noindent
18383is 1. (I just checked this by placing the cursor after the expression
18384and typing @kbd{C-x C-e}. Indeed, 1 is printed in the echo area.)
18385
18386@node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18387@unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18388
18389When the @code{kill-ring-yank-pointer} points to the
18390beginning of the kill ring, and the argument passed to
18391@code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18392
18393@smallexample
18394@group
18395(- length (length kill-ring-yank-pointer))
18396 @result{} 0
18397@end group
18398@end smallexample
18399
18400@need 1250
18401@noindent
18402therefore,
18403
18404@smallexample
18405@group
18406(+ arg (- length (length kill-ring-yank-pointer)))
18407 @result{} 1
18408@end group
18409@end smallexample
18410
18411@need 1250
18412@noindent
18413and consequently:
18414
18415@smallexample
18416@group
18417(% (+ arg (- length (length kill-ring-yank-pointer)))
18418 length)
18419 @result{} 1
18420@end group
18421@end smallexample
18422
18423@noindent
18424regardless of the value of @code{length}.
18425
18426@need 1250
18427@noindent
18428As a result of this, the @code{setq kill-ring-yank-pointer} expression
18429simplifies to:
18430
18431@smallexample
18432(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18433@end smallexample
18434
18435@noindent
18436What it does is now easy to understand. Instead of pointing as it did
18437to the first element of the kill ring, the
18438@code{kill-ring-yank-pointer} is set to point to the second element.
18439
18440Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18441the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18442and so on for different values of the argument.
18443
18444Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18445the second element of the kill ring, its length is shorter than the
18446length of the kill ring by 1, so the computation of the remainder is
18447based on the expression @code{(% (+ arg 1) length)}. This means that
18448the @code{kill-ring-yank-pointer} is moved from the second element of
18449the kill ring to the third element if the argument passed to
18450@code{rotate-yank-pointer} is 1.
18451
18452@node kill-rng-yk-ptr last elt, , rotate-yk-ptr remainder, rotate-yk-ptr body
18453@unnumberedsubsubsec Pointing to the last element
18454
18455The final question is, what happens if the @code{kill-ring-yank-pointer}
18456is set to the @emph{last} element of the kill ring? Will a call to
18457@code{rotate-yank-pointer} mean that nothing more can be taken from the
18458kill ring? The answer is no. What happens is different and useful.
18459The @code{kill-ring-yank-pointer} is set to point to the beginning of
18460the kill ring instead.
18461
18462Let's see how this works by looking at the code, assuming the length of the
18463kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18464When the @code{kill-ring-yank-pointer} points to the last element of
18465the kill ring, its length is 1. The code looks like this:
18466
18467@smallexample
18468(% (+ arg (- length (length kill-ring-yank-pointer))) length)
18469@end smallexample
18470
18471@need 1250
18472When the variables are replaced by their numeric values, the expression
18473looks like this:
18474
18475@smallexample
18476(% (+ 1 (- 5 1)) 5)
18477@end smallexample
18478
18479@noindent
18480This expression can be evaluated by looking at the most embedded inner
18481expression first and working outwards: The value of @code{(- 5 1)} is 4;
18482the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18483zero. So what @code{rotate-yank-pointer} will do is
18484
18485@smallexample
18486(setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18487@end smallexample
18488
18489@noindent
18490which will set the @code{kill-ring-yank-pointer} to point to the beginning
18491of the kill ring.
18492
18493So what happens with successive calls to @code{rotate-yank-pointer} is that
18494it moves the @code{kill-ring-yank-pointer} from element to element in the
18495kill ring until it reaches the end; then it jumps back to the beginning.
18496And this is why the kill ring is called a ring, since by jumping back to
18497the beginning, it is as if the list has no end! (And what is a ring, but
18498an entity with no end?)
18499
18500@node yank, yank-pop, rotate-yank-pointer, Kill Ring
18501@comment node-name, next, previous, up
18502@appendixsec @code{yank}
18503@findex yank
18504
18505After learning about @code{rotate-yank-pointer}, the code for the
18506@code{yank} function is almost easy. It has only one tricky part, which is
18507the computation of the argument to be passed to @code{rotate-yank-pointer}.
18508
18509@need 1250
18510The code looks like this:
18511
18512@smallexample
18513@group
18514(defun yank (&optional arg)
18515 "Reinsert the last stretch of killed text.
18516More precisely, reinsert the stretch of killed text most
18517recently killed OR yanked.
18518With just C-U as argument, same but put point in front
18519(and mark at end). With argument n, reinsert the nth
18520most recently killed stretch of killed text.
18521See also the command \\[yank-pop]."
18522@end group
18523@group
18524
18525 (interactive "*P")
18526 (rotate-yank-pointer (if (listp arg) 0
18527 (if (eq arg '-) -1
18528 (1- arg))))
18529 (push-mark (point))
18530 (insert (car kill-ring-yank-pointer))
18531 (if (consp arg)
18532 (exchange-point-and-mark)))
18533@end group
18534@end smallexample
18535
18536Glancing over this code, we can understand the last few lines readily
18537enough. The mark is pushed, that is, remembered; then the first element
18538(the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18539inserted; and then, if the argument passed the function is a
18540@code{cons}, point and mark are exchanged so the point is put in the
18541front of the inserted text rather than at the end. This option is
18542explained in the documentation. The function itself is interactive with
18543@code{"*P"}. This means it will not work on a read-only buffer, and that
18544the unprocessed prefix argument is passed to the function.
18545
18546@menu
18547* rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
18548* rotate-yk-ptr negative arg:: Pass a negative argument.
18549@end menu
18550
18551@node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18552@unnumberedsubsubsec Passing the argument
18553
18554The hard part of @code{yank} is understanding the computation that
18555determines the value of the argument passed to
18556@code{rotate-yank-pointer}. Fortunately, it is not so difficult as it
18557looks at first sight.
18558
18559What happens is that the result of evaluating one or both of the
18560@code{if} expressions will be a number and that number will be the
18561argument passed to @code{rotate-yank-pointer}.
18562
18563@need 1250
18564Laid out with comments, the code looks like this:
18565
18566@smallexample
18567@group
18568(if (listp arg) ; @r{if-part}
18569 0 ; @r{then-part}
18570 (if (eq arg '-) ; @r{else-part, inner if}
18571 -1 ; @r{inner if's then-part}
18572 (1- arg)))) ; @r{inner if's else-part}
18573@end group
18574@end smallexample
18575
18576@noindent
18577This code consists of two @code{if} expression, one the else-part of
18578the other.
18579
18580The first or outer @code{if} expression tests whether the argument
18581passed to @code{yank} is a list. Oddly enough, this will be true if
18582@code{yank} is called without an argument---because then it will be
18583passed the value of @code{nil} for the optional argument and an
18584evaluation of @code{(listp nil)} returns true! So, if no argument is
18585passed to @code{yank}, the argument passed to
18586@code{rotate-yank-pointer} inside of @code{yank} is zero. This means
18587the pointer is not moved and the first element to which
18588@code{kill-ring-yank-pointer} points is inserted, as we expect.
18589Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18590read as a list, so again, a zero will be passed to
18591@code{rotate-yank-pointer}. (@kbd{C-u} produces an unprocessed prefix
18592argument of @code{(4)}, which is a list of one element.) At the same
18593time, later in the function, this argument will be read as a
18594@code{cons} so point will be put in the front and mark at the end of
18595the insertion. (The @code{P} argument to @code{interactive} is
18596designed to provide these values for the case when an optional
18597argument is not provided or when it is @kbd{C-u}.)
18598
18599The then-part of the outer @code{if} expression handles the case when
18600there is no argument or when it is @kbd{C-u}. The else-part handles the
18601other situations. The else-part is itself another @code{if} expression.
18602
18603The inner @code{if} expression tests whether the argument is a minus
18604sign. (This is done by pressing the @key{META} and @kbd{-} keys at the
18605same time, or the @key{ESC} key and then the @kbd{-} key). In this
18606case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18607argument. This moves the @code{kill-ring-yank-pointer} backwards, which
18608is what is desired.
18609
18610If the true-or-false-test of the inner @code{if} expression is false
18611(that is, if the argument is not a minus sign), the else-part of the
18612expression is evaluated. This is the expression @code{(1- arg)}.
18613Because of the two @code{if} expressions, it will only occur when the
18614argument is a positive number or when it is a negative number (not
18615just a minus sign on its own). What @code{(1- arg)} does is decrement
18616the number and return it. (The @code{1-} function subtracts one from
18617its argument.) This means that if the argument to
18618@code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18619the first element to which @code{kill-ring-yank-pointer} points is
18620yanked back, as you would expect.
18621
18622@node rotate-yk-ptr negative arg, , rotate-yk-ptr arg, yank
18623@unnumberedsubsubsec Passing a negative argument
18624
18625Finally, the question arises, what happens if either the remainder
18626function, @code{%}, or the @code{nthcdr} function is passed a negative
18627argument, as they quite well may?
18628
18629The answers can be found by a quick test. When @code{(% -1 5)} is
18630evaluated, a negative number is returned; and if @code{nthcdr} is
18631called with a negative number, it returns the same value as if it were
e601d8fd 18632called with a first argument of zero. This can be seen by evaluating
8b096dce
EZ
18633the following code.
18634
18635Here the @samp{@result{}} points to the result of evaluating the code
18636preceding it. This was done by positioning the cursor after the code
18637and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18638You can do this if you are reading this in Info inside of GNU Emacs.
18639
18640@smallexample
18641@group
18642(% -1 5)
18643 @result{} -1
18644@end group
18645
18646@group
18647(setq animals '(cats dogs elephants))
18648 @result{} (cats dogs elephants)
18649@end group
18650
18651@group
18652(nthcdr 1 animals)
18653 @result{} (dogs elephants)
18654@end group
18655
18656@group
18657(nthcdr 0 animals)
18658 @result{} (cats dogs elephants)
18659@end group
18660
18661@group
18662(nthcdr -1 animals)
18663 @result{} (cats dogs elephants)
18664@end group
18665@end smallexample
18666
18667So, if a minus sign or a negative number is passed to @code{yank}, the
18668@code{kill-ring-yank-point} is rotated backwards until it reaches the
18669beginning of the list. Then it stays there. Unlike the other case,
18670when it jumps from the end of the list to the beginning of the list,
18671making a ring, it stops. This makes sense. You often want to get back
18672to the most recently clipped out piece of text, but you don't usually
18673want to insert text from as many as thirty kill commands ago. So you
18674need to work through the ring to get to the end, but won't cycle around
18675it inadvertently if you are trying to come back to the beginning.
18676
18677Incidentally, any number passed to @code{yank} with a minus sign
18678preceding it will be treated as @minus{}1. This is evidently a
18679simplification for writing the program. You don't need to jump back
18680towards the beginning of the kill ring more than one place at a time
18681and doing this is easier than writing a function to determine the
18682magnitude of the number that follows the minus sign.
18683
18684@node yank-pop, , yank, Kill Ring
18685@comment node-name, next, previous, up
18686@appendixsec @code{yank-pop}
18687@findex yank-pop
18688
18689After understanding @code{yank}, the @code{yank-pop} function is easy.
18690Leaving out the documentation to save space, it looks like this:
18691
18692@smallexample
18693@group
18694(defun yank-pop (arg)
18695 (interactive "*p")
18696 (if (not (eq last-command 'yank))
18697 (error "Previous command was not a yank"))
18698@end group
18699@group
18700 (setq this-command 'yank)
18701 (let ((before (< (point) (mark))))
18702 (delete-region (point) (mark))
18703 (rotate-yank-pointer arg)
18704@end group
18705@group
18706 (set-mark (point))
18707 (insert (car kill-ring-yank-pointer))
18708 (if before (exchange-point-and-mark))))
18709@end group
18710@end smallexample
18711
18712The function is interactive with a small @samp{p} so the prefix
18713argument is processed and passed to the function. The command can
18714only be used after a previous yank; otherwise an error message is
18715sent. This check uses the variable @code{last-command} which is
18716discussed elsewhere. (@xref{copy-region-as-kill}.)
18717
18718The @code{let} clause sets the variable @code{before} to true or false
18719depending whether point is before or after mark and then the region
18720between point and mark is deleted. This is the region that was just
18721inserted by the previous yank and it is this text that will be
18722replaced. Next the @code{kill-ring-yank-pointer} is rotated so that
18723the previously inserted text is not reinserted yet again. Mark is set
18724at the beginning of the place the new text will be inserted and then
18725the first element to which @code{kill-ring-yank-pointer} points is
18726inserted. This leaves point after the new text. If in the previous
18727yank, point was left before the inserted text, point and mark are now
18728exchanged so point is again left in front of the newly inserted text.
18729That is all there is to it!
18730
18731@node Full Graph, GNU Free Documentation License, Kill Ring, Top
18732@appendix A Graph with Labelled Axes
18733
18734Printed axes help you understand a graph. They convey scale. In an
18735earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
18736wrote the code to print the body of a graph. Here we write the code
18737for printing and labelling vertical and horizontal axes, along with the
18738body itself.
18739
18740@menu
18741* Labelled Example::
18742* print-graph Varlist:: @code{let} expression in @code{print-graph}.
18743* print-Y-axis:: Print a label for the vertical axis.
18744* print-X-axis:: Print a horizontal label.
18745* Print Whole Graph:: The function to print a complete graph.
18746@end menu
18747
18748@node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18749@ifnottex
18750@unnumberedsec Labelled Example Graph
18751@end ifnottex
18752
18753Since insertions fill a buffer to the right and below point, the new
18754graph printing function should first print the Y or vertical axis,
18755then the body of the graph, and finally the X or horizontal axis.
18756This sequence lays out for us the contents of the function:
18757
18758@enumerate
18759@item
18760Set up code.
18761
18762@item
18763Print Y axis.
18764
18765@item
18766Print body of graph.
18767
18768@item
18769Print X axis.
18770@end enumerate
18771
18772@need 800
18773Here is an example of how a finished graph should look:
18774
18775@smallexample
18776@group
18777 10 -
18778 *
18779 * *
18780 * **
18781 * ***
18782 5 - * *******
18783 * *** *******
18784 *************
18785 ***************
18786 1 - ****************
18787 | | | |
18788 1 5 10 15
18789@end group
18790@end smallexample
18791
18792@noindent
18793In this graph, both the vertical and the horizontal axes are labelled
18794with numbers. However, in some graphs, the horizontal axis is time
18795and would be better labelled with months, like this:
18796
18797@smallexample
18798@group
18799 5 - *
18800 * ** *
18801 *******
18802 ********** **
18803 1 - **************
18804 | ^ |
18805 Jan June Jan
18806@end group
18807@end smallexample
18808
18809Indeed, with a little thought, we can easily come up with a variety of
18810vertical and horizontal labelling schemes. Our task could become
18811complicated. But complications breed confusion. Rather than permit
18812this, it is better choose a simple labelling scheme for our first
18813effort, and to modify or replace it later.
18814
18815@need 1200
18816These considerations suggest the following outline for the
18817@code{print-graph} function:
18818
18819@smallexample
18820@group
18821(defun print-graph (numbers-list)
18822 "@var{documentation}@dots{}"
18823 (let ((height @dots{}
18824 @dots{}))
18825@end group
18826@group
18827 (print-Y-axis height @dots{} )
18828 (graph-body-print numbers-list)
18829 (print-X-axis @dots{} )))
18830@end group
18831@end smallexample
18832
18833We can work on each part of the @code{print-graph} function definition
18834in turn.
18835
18836@node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18837@comment node-name, next, previous, up
18838@appendixsec The @code{print-graph} Varlist
18839@cindex @code{print-graph} varlist
18840
18841In writing the @code{print-graph} function, the first task is to write
18842the varlist in the @code{let} expression. (We will leave aside for the
18843moment any thoughts about making the function interactive or about the
18844contents of its documentation string.)
18845
18846The varlist should set several values. Clearly, the top of the label
18847for the vertical axis must be at least the height of the graph, which
18848means that we must obtain this information here. Note that the
18849@code{print-graph-body} function also requires this information. There
18850is no reason to calculate the height of the graph in two different
18851places, so we should change @code{print-graph-body} from the way we
18852defined it earlier to take advantage of the calculation.
18853
18854Similarly, both the function for printing the X axis labels and the
18855@code{print-graph-body} function need to learn the value of the width of
18856each symbol. We can perform the calculation here and change the
18857definition for @code{print-graph-body} from the way we defined it in the
18858previous chapter.
18859
18860The length of the label for the horizontal axis must be at least as long
18861as the graph. However, this information is used only in the function
18862that prints the horizontal axis, so it does not need to be calculated here.
18863
18864These thoughts lead us directly to the following form for the varlist
18865in the @code{let} for @code{print-graph}:
18866
18867@smallexample
18868@group
18869(let ((height (apply 'max numbers-list)) ; @r{First version.}
18870 (symbol-width (length graph-blank)))
18871@end group
18872@end smallexample
18873
18874@noindent
18875As we shall see, this expression is not quite right.
18876
18877@node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
18878@comment node-name, next, previous, up
18879@appendixsec The @code{print-Y-axis} Function
18880@cindex Axis, print vertical
18881@cindex Y axis printing
18882@cindex Vertical axis printing
18883@cindex Print vertical axis
18884
18885The job of the @code{print-Y-axis} function is to print a label for
18886the vertical axis that looks like this:
18887
18888@smallexample
18889@group
18890 10 -
18891
18892
18893
18894
18895 5 -
18896
18897
18898
18899 1 -
18900@end group
18901@end smallexample
18902
18903@noindent
18904The function should be passed the height of the graph, and then should
18905construct and insert the appropriate numbers and marks.
18906
18907It is easy enough to see in the figure what the Y axis label should
18908look like; but to say in words, and then to write a function
18909definition to do the job is another matter. It is not quite true to
18910say that we want a number and a tic every five lines: there are only
18911three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
18912but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
18913and 9). It is better to say that we want a number and a tic mark on
18914the base line (number 1) and then that we want a number and a tic on
18915the fifth line from the bottom and on every line that is a multiple of
18916five.
18917
18918@menu
18919* Height of label:: What height for the Y axis?
18920* Compute a Remainder:: How to compute the remainder of a division.
18921* Y Axis Element:: Construct a line for the Y axis.
18922* Y-axis-column:: Generate a list of Y axis labels.
18923* print-Y-axis Penultimate:: A not quite final version.
18924@end menu
18925
18926@node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
18927@ifnottex
18928@unnumberedsubsec What height should the label be?
18929@end ifnottex
18930
18931The next issue is what height the label should be? Suppose the maximum
18932height of tallest column of the graph is seven. Should the highest
18933label on the Y axis be @samp{5 -}, and should the graph stick up above
18934the label? Or should the highest label be @samp{7 -}, and mark the peak
18935of the graph? Or should the highest label be @code{10 -}, which is a
18936multiple of five, and be higher than the topmost value of the graph?
18937
18938The latter form is preferred. Most graphs are drawn within rectangles
18939whose sides are an integral number of steps long---5, 10, 15, and so
18940on for a step distance of five. But as soon as we decide to use a
18941step height for the vertical axis, we discover that the simple
18942expression in the varlist for computing the height is wrong. The
18943expression is @code{(apply 'max numbers-list)}. This returns the
18944precise height, not the maximum height plus whatever is necessary to
18945round up to the nearest multiple of five. A more complex expression
18946is required.
18947
18948As usual in cases like this, a complex problem becomes simpler if it is
18949divided into several smaller problems.
18950
18951First, consider the case when the highest value of the graph is an
18952integral multiple of five---when it is 5, 10, 15 ,or some higher
18953multiple of five. We can use this value as the Y axis height.
18954
18955A fairly simply way to determine whether a number is a multiple of
18956five is to divide it by five and see if the division results in a
18957remainder. If there is no remainder, the number is a multiple of
18958five. Thus, seven divided by five has a remainder of two, and seven
18959is not an integral multiple of five. Put in slightly different
18960language, more reminiscent of the classroom, five goes into seven
18961once, with a remainder of two. However, five goes into ten twice,
18962with no remainder: ten is an integral multiple of five.
18963
18964@node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
18965@appendixsubsec Side Trip: Compute a Remainder
18966
18967@findex % @r{(remainder function)}
18968@cindex Remainder function, @code{%}
18969In Lisp, the function for computing a remainder is @code{%}. The
18970function returns the remainder of its first argument divided by its
18971second argument. As it happens, @code{%} is a function in Emacs Lisp
18972that you cannot discover using @code{apropos}: you find nothing if you
18973type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
18974learn of the existence of @code{%} is to read about it in a book such
18975as this or in the Emacs Lisp sources. The @code{%} function is used
18976in the code for @code{rotate-yank-pointer}, which is described in an
18977appendix. (@xref{rotate-yk-ptr body, , The Body of
18978@code{rotate-yank-pointer}}.)
18979
18980You can try the @code{%} function by evaluating the following two
18981expressions:
18982
18983@smallexample
18984@group
18985(% 7 5)
18986
18987(% 10 5)
18988@end group
18989@end smallexample
18990
18991@noindent
18992The first expression returns 2 and the second expression returns 0.
18993
18994To test whether the returned value is zero or some other number, we
18995can use the @code{zerop} function. This function returns @code{t} if
18996its argument, which must be a number, is zero.
18997
18998@smallexample
18999@group
19000(zerop (% 7 5))
19001 @result{} nil
19002
19003(zerop (% 10 5))
19004 @result{} t
19005@end group
19006@end smallexample
19007
19008Thus, the following expression will return @code{t} if the height
19009of the graph is evenly divisible by five:
19010
19011@smallexample
19012(zerop (% height 5))
19013@end smallexample
19014
19015@noindent
19016(The value of @code{height}, of course, can be found from @code{(apply
19017'max numbers-list)}.)
19018
19019On the other hand, if the value of @code{height} is not a multiple of
19020five, we want to reset the value to the next higher multiple of five.
19021This is straightforward arithmetic using functions with which we are
19022already familiar. First, we divide the value of @code{height} by five
19023to determine how many times five goes into the number. Thus, five
19024goes into twelve twice. If we add one to this quotient and multiply by
19025five, we will obtain the value of the next multiple of five that is
19026larger than the height. Five goes into twelve twice. Add one to two,
19027and multiply by five; the result is fifteen, which is the next multiple
19028of five that is higher than twelve. The Lisp expression for this is:
19029
19030@smallexample
19031(* (1+ (/ height 5)) 5)
19032@end smallexample
19033
19034@noindent
19035For example, if you evaluate the following, the result is 15:
19036
19037@smallexample
19038(* (1+ (/ 12 5)) 5)
19039@end smallexample
19040
19041All through this discussion, we have been using `five' as the value
19042for spacing labels on the Y axis; but we may want to use some other
19043value. For generality, we should replace `five' with a variable to
19044which we can assign a value. The best name I can think of for this
19045variable is @code{Y-axis-label-spacing}.
19046
19047@need 1250
19048Using this term, and an @code{if} expression, we produce the
19049following:
19050
19051@smallexample
19052@group
19053(if (zerop (% height Y-axis-label-spacing))
19054 height
19055 ;; @r{else}
19056 (* (1+ (/ height Y-axis-label-spacing))
19057 Y-axis-label-spacing))
19058@end group
19059@end smallexample
19060
19061@noindent
19062This expression returns the value of @code{height} itself if the height
19063is an even multiple of the value of the @code{Y-axis-label-spacing} or
19064else it computes and returns a value of @code{height} that is equal to
19065the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19066
19067We can now include this expression in the @code{let} expression of the
19068@code{print-graph} function (after first setting the value of
19069@code{Y-axis-label-spacing}):
19070@vindex Y-axis-label-spacing
19071
19072@smallexample
19073@group
19074(defvar Y-axis-label-spacing 5
19075 "Number of lines from one Y axis label to next.")
19076@end group
19077
19078@group
19079@dots{}
19080(let* ((height (apply 'max numbers-list))
19081 (height-of-top-line
19082 (if (zerop (% height Y-axis-label-spacing))
19083 height
19084@end group
19085@group
19086 ;; @r{else}
19087 (* (1+ (/ height Y-axis-label-spacing))
19088 Y-axis-label-spacing)))
19089 (symbol-width (length graph-blank))))
19090@dots{}
19091@end group
19092@end smallexample
19093
19094@noindent
19095(Note use of the @code{let*} function: the initial value of height is
19096computed once by the @code{(apply 'max numbers-list)} expression and
19097then the resulting value of @code{height} is used to compute its
19098final value. @xref{fwd-para let, , The @code{let*} expression}, for
19099more about @code{let*}.)
19100
19101@node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19102@appendixsubsec Construct a Y Axis Element
19103
19104When we print the vertical axis, we want to insert strings such as
19105@w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19106Moreover, we want the numbers and dashes to line up, so shorter
19107numbers must be padded with leading spaces. If some of the strings
19108use two digit numbers, the strings with single digit numbers must
19109include a leading blank space before the number.
19110
19111@findex number-to-string
19112To figure out the length of the number, the @code{length} function is
19113used. But the @code{length} function works only with a string, not with
19114a number. So the number has to be converted from being a number to
19115being a string. This is done with the @code{number-to-string} function.
19116For example,
19117
19118@smallexample
19119@group
19120(length (number-to-string 35))
19121 @result{} 2
19122
19123(length (number-to-string 100))
19124 @result{} 3
19125@end group
19126@end smallexample
19127
19128@noindent
19129(@code{number-to-string} is also called @code{int-to-string}; you will
19130see this alternative name in various sources.)
19131
19132In addition, in each label, each number is followed by a string such
19133as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19134This variable is defined with @code{defvar}:
19135
19136@vindex Y-axis-tic
19137@smallexample
19138@group
19139(defvar Y-axis-tic " - "
19140 "String that follows number in a Y axis label.")
19141@end group
19142@end smallexample
19143
19144The length of the Y label is the sum of the length of the Y axis tic
19145mark and the length of the number of the top of the graph.
19146
19147@smallexample
19148(length (concat (number-to-string height) Y-axis-tic)))
19149@end smallexample
19150
19151This value will be calculated by the @code{print-graph} function in
19152its varlist as @code{full-Y-label-width} and passed on. (Note that we
19153did not think to include this in the varlist when we first proposed it.)
19154
19155To make a complete vertical axis label, a tic mark is concatenated
19156with a number; and the two together may be preceded by one or more
19157spaces depending on how long the number is. The label consists of
19158three parts: the (optional) leading spaces, the number, and the tic
19159mark. The function is passed the value of the number for the specific
19160row, and the value of the width of the top line, which is calculated
19161(just once) by @code{print-graph}.
19162
19163@smallexample
19164@group
19165(defun Y-axis-element (number full-Y-label-width)
19166 "Construct a NUMBERed label element.
19167A numbered element looks like this ` 5 - ',
19168and is padded as needed so all line up with
19169the element for the largest number."
19170@end group
19171@group
19172 (let* ((leading-spaces
19173 (- full-Y-label-width
19174 (length
19175 (concat (number-to-string number)
19176 Y-axis-tic)))))
19177@end group
19178@group
19179 (concat
19180 (make-string leading-spaces ? )
19181 (number-to-string number)
19182 Y-axis-tic)))
19183@end group
19184@end smallexample
19185
19186The @code{Y-axis-element} function concatenates together the leading
19187spaces, if any; the number, as a string; and the tic mark.
19188
19189To figure out how many leading spaces the label will need, the
19190function subtracts the actual length of the label---the length of the
19191number plus the length of the tic mark---from the desired label width.
19192
19193@findex make-string
19194Blank spaces are inserted using the @code{make-string} function. This
19195function takes two arguments: the first tells it how long the string
19196will be and the second is a symbol for the character to insert, in a
19197special format. The format is a question mark followed by a blank
19198space, like this, @samp{? }. @xref{Character Type, , Character Type,
19199elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19200syntax for characters.
19201
19202The @code{number-to-string} function is used in the concatenation
19203expression, to convert the number to a string that is concatenated
19204with the leading spaces and the tic mark.
19205
19206@node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19207@appendixsubsec Create a Y Axis Column
19208
19209The preceding functions provide all the tools needed to construct a
19210function that generates a list of numbered and blank strings to insert
19211as the label for the vertical axis:
19212
19213@findex Y-axis-column
19214@smallexample
19215@group
19216(defun Y-axis-column (height width-of-label)
19217 "Construct list of Y axis labels and blank strings.
19218For HEIGHT of line above base and WIDTH-OF-LABEL."
19219 (let (Y-axis)
19220@group
19221@end group
19222 (while (> height 1)
19223 (if (zerop (% height Y-axis-label-spacing))
19224 ;; @r{Insert label.}
19225 (setq Y-axis
19226 (cons
19227 (Y-axis-element height width-of-label)
19228 Y-axis))
19229@group
19230@end group
19231 ;; @r{Else, insert blanks.}
19232 (setq Y-axis
19233 (cons
19234 (make-string width-of-label ? )
19235 Y-axis)))
19236 (setq height (1- height)))
19237 ;; @r{Insert base line.}
19238 (setq Y-axis
19239 (cons (Y-axis-element 1 width-of-label) Y-axis))
19240 (nreverse Y-axis)))
19241@end group
19242@end smallexample
19243
19244In this function, we start with the value of @code{height} and
19245repetitively subtract one from its value. After each subtraction, we
19246test to see whether the value is an integral multiple of the
19247@code{Y-axis-label-spacing}. If it is, we construct a numbered label
19248using the @code{Y-axis-element} function; if not, we construct a
19249blank label using the @code{make-string} function. The base line
19250consists of the number one followed by a tic mark.
19251
19252@node print-Y-axis Penultimate, , Y-axis-column, print-Y-axis
19253@appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19254
19255The list constructed by the @code{Y-axis-column} function is passed to
19256the @code{print-Y-axis} function, which inserts the list as a column.
19257
19258@findex print-Y-axis
19259@smallexample
19260@group
19261(defun print-Y-axis (height full-Y-label-width)
19262 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19263Height must be the maximum height of the graph.
19264Full width is the width of the highest label element."
19265;; Value of height and full-Y-label-width
19266;; are passed by `print-graph'.
19267@end group
19268@group
19269 (let ((start (point)))
19270 (insert-rectangle
19271 (Y-axis-column height full-Y-label-width))
19272 ;; @r{Place point ready for inserting graph.}
19273 (goto-char start)
19274 ;; @r{Move point forward by value of} full-Y-label-width
19275 (forward-char full-Y-label-width)))
19276@end group
19277@end smallexample
19278
19279The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19280insert the Y axis labels created by the @code{Y-axis-column} function.
19281In addition, it places point at the correct position for printing the body of
19282the graph.
19283
19284You can test @code{print-Y-axis}:
19285
19286@enumerate
19287@item
19288Install
19289
19290@smallexample
19291@group
19292Y-axis-label-spacing
19293Y-axis-tic
19294Y-axis-element
19295Y-axis-column
19296print-Y-axis
19297@end group
19298@end smallexample
19299
19300@item
19301Copy the following expression:
19302
19303@smallexample
19304(print-Y-axis 12 5)
19305@end smallexample
19306
19307@item
19308Switch to the @file{*scratch*} buffer and place the cursor where you
19309want the axis labels to start.
19310
19311@item
19312Type @kbd{M-:} (@code{eval-expression}).
19313
19314@item
19315Yank the @code{graph-body-print} expression into the minibuffer
19316with @kbd{C-y} (@code{yank)}.
19317
19318@item
19319Press @key{RET} to evaluate the expression.
19320@end enumerate
19321
19322Emacs will print labels vertically, the top one being
19323@w{@samp{10 -@w{ }}}. (The @code{print-graph} function
19324will pass the value of @code{height-of-top-line}, which
19325in this case would end up as 15.)
19326
19327@node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19328@appendixsec The @code{print-X-axis} Function
19329@cindex Axis, print horizontal
19330@cindex X axis printing
19331@cindex Print horizontal axis
19332@cindex Horizontal axis printing
19333
19334X axis labels are much like Y axis labels, except that the tics are on a
19335line above the numbers. Labels should look like this:
19336
19337@smallexample
19338@group
19339 | | | |
19340 1 5 10 15
19341@end group
19342@end smallexample
19343
19344The first tic is under the first column of the graph and is preceded by
19345several blank spaces. These spaces provide room in rows above for the Y
19346axis labels. The second, third, fourth, and subsequent tics are all
19347spaced equally, according to the value of @code{X-axis-label-spacing}.
19348
19349The second row of the X axis consists of numbers, preceded by several
19350blank spaces and also separated according to the value of the variable
19351@code{X-axis-label-spacing}.
19352
19353The value of the variable @code{X-axis-label-spacing} should itself be
19354measured in units of @code{symbol-width}, since you may want to change
19355the width of the symbols that you are using to print the body of the
19356graph without changing the ways the graph is labelled.
19357
19358@menu
19359* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
19360* X Axis Tic Marks:: Create tic marks for the horizontal axis.
19361@end menu
19362
19363@node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19364@ifnottex
19365@unnumberedsubsec Similarities and differences
19366@end ifnottex
19367
19368The @code{print-X-axis} function is constructed in more or less the
19369same fashion as the @code{print-Y-axis} function except that it has
19370two lines: the line of tic marks and the numbers. We will write a
19371separate function to print each line and then combine them within the
19372@code{print-X-axis} function.
19373
19374This is a three step process:
19375
19376@enumerate
19377@item
19378Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19379
19380@item
19381Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19382
19383@item
19384Write a function to print both lines, the @code{print-X-axis} function,
19385using @code{print-X-axis-tic-line} and
19386@code{print-X-axis-numbered-line}.
19387@end enumerate
19388
19389@node X Axis Tic Marks, , Similarities differences, print-X-axis
19390@appendixsubsec X Axis Tic Marks
19391
19392The first function should print the X axis tic marks. We must specify
19393the tic marks themselves and their spacing:
19394
19395@smallexample
19396@group
19397(defvar X-axis-label-spacing
19398 (if (boundp 'graph-blank)
19399 (* 5 (length graph-blank)) 5)
19400 "Number of units from one X axis label to next.")
19401@end group
19402@end smallexample
19403
19404@noindent
19405(Note that the value of @code{graph-blank} is set by another
19406@code{defvar}. The @code{boundp} predicate checks whether it has
19407already been set; @code{boundp} returns @code{nil} if it has not.
19408If @code{graph-blank} were unbound and we did not use this conditional
19409construction, in GNU Emacs 21, we would enter the debugger and see an
19410error message saying
19411@samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19412
19413@need 1200
19414Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19415
19416@smallexample
19417@group
19418(defvar X-axis-tic-symbol "|"
19419 "String to insert to point to a column in X axis.")
19420@end group
19421@end smallexample
19422
19423@need 1250
19424The goal is to make a line that looks like this:
19425
19426@smallexample
19427 | | | |
19428@end smallexample
19429
19430The first tic is indented so that it is under the first column, which is
19431indented to provide space for the Y axis labels.
19432
19433A tic element consists of the blank spaces that stretch from one tic to
19434the next plus a tic symbol. The number of blanks is determined by the
19435width of the tic symbol and the @code{X-axis-label-spacing}.
19436
19437@need 1250
19438The code looks like this:
19439
19440@smallexample
19441@group
19442;;; X-axis-tic-element
19443@dots{}
19444(concat
19445 (make-string
19446 ;; @r{Make a string of blanks.}
19447 (- (* symbol-width X-axis-label-spacing)
19448 (length X-axis-tic-symbol))
19449 ? )
19450 ;; @r{Concatenate blanks with tic symbol.}
19451 X-axis-tic-symbol)
19452@dots{}
19453@end group
19454@end smallexample
19455
19456Next, we determine how many blanks are needed to indent the first tic
19457mark to the first column of the graph. This uses the value of
19458@code{full-Y-label-width} passed it by the @code{print-graph} function.
19459
19460@need 1250
19461The code to make @code{X-axis-leading-spaces}
19462looks like this:
19463
19464@smallexample
19465@group
19466;; X-axis-leading-spaces
19467@dots{}
19468(make-string full-Y-label-width ? )
19469@dots{}
19470@end group
19471@end smallexample
19472
19473We also need to determine the length of the horizontal axis, which is
19474the length of the numbers list, and the number of tics in the horizontal
19475axis:
19476
19477@smallexample
19478@group
19479;; X-length
19480@dots{}
19481(length numbers-list)
19482@end group
19483
19484@group
19485;; tic-width
19486@dots{}
19487(* symbol-width X-axis-label-spacing)
19488@end group
19489
19490@group
19491;; number-of-X-tics
19492(if (zerop (% (X-length tic-width)))
19493 (/ (X-length tic-width))
19494 (1+ (/ (X-length tic-width))))
19495@end group
19496@end smallexample
19497
19498@need 1250
19499All this leads us directly to the function for printing the X axis tic line:
19500
19501@findex print-X-axis-tic-line
19502@smallexample
19503@group
19504(defun print-X-axis-tic-line
19505 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19506 "Print tics for X axis."
19507 (insert X-axis-leading-spaces)
19508 (insert X-axis-tic-symbol) ; @r{Under first column.}
19509@end group
19510@group
19511 ;; @r{Insert second tic in the right spot.}
19512 (insert (concat
19513 (make-string
19514 (- (* symbol-width X-axis-label-spacing)
19515 ;; @r{Insert white space up to second tic symbol.}
19516 (* 2 (length X-axis-tic-symbol)))
19517 ? )
19518 X-axis-tic-symbol))
19519@end group
19520@group
19521 ;; @r{Insert remaining tics.}
19522 (while (> number-of-X-tics 1)
19523 (insert X-axis-tic-element)
19524 (setq number-of-X-tics (1- number-of-X-tics))))
19525@end group
19526@end smallexample
19527
19528The line of numbers is equally straightforward:
19529
19530@need 1250
19531First, we create a numbered element with blank spaces before each number:
19532
19533@findex X-axis-element
19534@smallexample
19535@group
19536(defun X-axis-element (number)
19537 "Construct a numbered X axis element."
19538 (let ((leading-spaces
19539 (- (* symbol-width X-axis-label-spacing)
19540 (length (number-to-string number)))))
19541 (concat (make-string leading-spaces ? )
19542 (number-to-string number))))
19543@end group
19544@end smallexample
19545
19546Next, we create the function to print the numbered line, starting with
19547the number ``1'' under the first column:
19548
19549@findex print-X-axis-numbered-line
19550@smallexample
19551@group
19552(defun print-X-axis-numbered-line
19553 (number-of-X-tics X-axis-leading-spaces)
19554 "Print line of X-axis numbers"
19555 (let ((number X-axis-label-spacing))
19556 (insert X-axis-leading-spaces)
19557 (insert "1")
19558@end group
19559@group
19560 (insert (concat
19561 (make-string
19562 ;; @r{Insert white space up to next number.}
19563 (- (* symbol-width X-axis-label-spacing) 2)
19564 ? )
19565 (number-to-string number)))
19566@end group
19567@group
19568 ;; @r{Insert remaining numbers.}
19569 (setq number (+ number X-axis-label-spacing))
19570 (while (> number-of-X-tics 1)
19571 (insert (X-axis-element number))
19572 (setq number (+ number X-axis-label-spacing))
19573 (setq number-of-X-tics (1- number-of-X-tics)))))
19574@end group
19575@end smallexample
19576
19577Finally, we need to write the @code{print-X-axis} that uses
19578@code{print-X-axis-tic-line} and
19579@code{print-X-axis-numbered-line}.
19580
19581The function must determine the local values of the variables used by both
19582@code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19583then it must call them. Also, it must print the carriage return that
19584separates the two lines.
19585
19586The function consists of a varlist that specifies five local variables,
19587and calls to each of the two line printing functions:
19588
19589@findex print-X-axis
19590@smallexample
19591@group
19592(defun print-X-axis (numbers-list)
19593 "Print X axis labels to length of NUMBERS-LIST."
19594 (let* ((leading-spaces
19595 (make-string full-Y-label-width ? ))
19596@end group
19597@group
19598 ;; symbol-width @r{is provided by} graph-body-print
19599 (tic-width (* symbol-width X-axis-label-spacing))
19600 (X-length (length numbers-list))
19601@end group
19602@group
19603 (X-tic
19604 (concat
19605 (make-string
19606@end group
19607@group
19608 ;; @r{Make a string of blanks.}
19609 (- (* symbol-width X-axis-label-spacing)
19610 (length X-axis-tic-symbol))
19611 ? )
19612@end group
19613@group
19614 ;; @r{Concatenate blanks with tic symbol.}
19615 X-axis-tic-symbol))
19616@end group
19617@group
19618 (tic-number
19619 (if (zerop (% X-length tic-width))
19620 (/ X-length tic-width)
19621 (1+ (/ X-length tic-width)))))
19622@end group
19623@group
19624 (print-X-axis-tic-line tic-number leading-spaces X-tic)
19625 (insert "\n")
19626 (print-X-axis-numbered-line tic-number leading-spaces)))
19627@end group
19628@end smallexample
19629
19630@need 1250
19631You can test @code{print-X-axis}:
19632
19633@enumerate
19634@item
19635Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19636@code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19637@code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19638
19639@item
19640Copy the following expression:
19641
19642@smallexample
19643@group
19644(progn
19645 (let ((full-Y-label-width 5)
19646 (symbol-width 1))
19647 (print-X-axis
19648 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19649@end group
19650@end smallexample
19651
19652@item
19653Switch to the @file{*scratch*} buffer and place the cursor where you
19654want the axis labels to start.
19655
19656@item
19657Type @kbd{M-:} (@code{eval-expression}).
19658
19659@item
19660Yank the test expression into the minibuffer
19661with @kbd{C-y} (@code{yank)}.
19662
19663@item
19664Press @key{RET} to evaluate the expression.
19665@end enumerate
19666
19667@need 1250
19668Emacs will print the horizontal axis like this:
19669
19670@smallexample
19671@group
19672 | | | | |
19673 1 5 10 15 20
19674@end group
19675@end smallexample
19676
19677@node Print Whole Graph, , print-X-axis, Full Graph
19678@appendixsec Printing the Whole Graph
19679@cindex Printing the whole graph
19680@cindex Whole graph printing
19681@cindex Graph, printing all
19682
19683Now we are nearly ready to print the whole graph.
19684
19685The function to print the graph with the proper labels follows the
19686outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19687Axes}), but with additions.
19688
19689@need 1250
19690Here is the outline:
19691
19692@smallexample
19693@group
19694(defun print-graph (numbers-list)
19695 "@var{documentation}@dots{}"
19696 (let ((height @dots{}
19697 @dots{}))
19698@end group
19699@group
19700 (print-Y-axis height @dots{} )
19701 (graph-body-print numbers-list)
19702 (print-X-axis @dots{} )))
19703@end group
19704@end smallexample
19705
19706@menu
19707* The final version:: A few changes.
19708* Test print-graph:: Run a short test.
19709* Graphing words in defuns:: Executing the final code.
19710* lambda:: How to write an anonymous function.
19711* mapcar:: Apply a function to elements of a list.
19712* Another Bug:: Yet another bug @dots{} most insidious.
19713* Final printed graph:: The graph itself!
19714@end menu
19715
19716@node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19717@ifnottex
19718@unnumberedsubsec Changes for the Final Version
19719@end ifnottex
19720
19721The final version is different from what we planned in two ways:
19722first, it contains additional values calculated once in the varlist;
19723second, it carries an option to specify the labels' increment per row.
19724This latter feature turns out to be essential; otherwise, a graph may
19725have more rows than fit on a display or on a sheet of paper.
19726
19727@need 1500
19728This new feature requires a change to the @code{Y-axis-column}
19729function, to add @code{vertical-step} to it. The function looks like
19730this:
19731
19732@findex Y-axis-column @r{Final version.}
19733@smallexample
19734@group
19735;;; @r{Final version.}
19736(defun Y-axis-column
19737 (height width-of-label &optional vertical-step)
19738 "Construct list of labels for Y axis.
19739HEIGHT is maximum height of graph.
19740WIDTH-OF-LABEL is maximum width of label.
19741VERTICAL-STEP, an option, is a positive integer
19742that specifies how much a Y axis label increments
19743for each line. For example, a step of 5 means
19744that each line is five units of the graph."
19745@end group
19746@group
19747 (let (Y-axis
19748 (number-per-line (or vertical-step 1)))
19749 (while (> height 1)
19750 (if (zerop (% height Y-axis-label-spacing))
19751@end group
19752@group
19753 ;; @r{Insert label.}
19754 (setq Y-axis
19755 (cons
19756 (Y-axis-element
19757 (* height number-per-line)
19758 width-of-label)
19759 Y-axis))
19760@end group
19761@group
19762 ;; @r{Else, insert blanks.}
19763 (setq Y-axis
19764 (cons
19765 (make-string width-of-label ? )
19766 Y-axis)))
19767 (setq height (1- height)))
19768@end group
19769@group
19770 ;; @r{Insert base line.}
19771 (setq Y-axis (cons (Y-axis-element
19772 (or vertical-step 1)
19773 width-of-label)
19774 Y-axis))
19775 (nreverse Y-axis)))
19776@end group
19777@end smallexample
19778
19779The values for the maximum height of graph and the width of a symbol
19780are computed by @code{print-graph} in its @code{let} expression; so
19781@code{graph-body-print} must be changed to accept them.
19782
19783@findex graph-body-print @r{Final version.}
19784@smallexample
19785@group
19786;;; @r{Final version.}
19787(defun graph-body-print (numbers-list height symbol-width)
19788 "Print a bar graph of the NUMBERS-LIST.
19789The numbers-list consists of the Y-axis values.
19790HEIGHT is maximum height of graph.
19791SYMBOL-WIDTH is number of each column."
19792@end group
19793@group
19794 (let (from-position)
19795 (while numbers-list
19796 (setq from-position (point))
19797 (insert-rectangle
19798 (column-of-graph height (car numbers-list)))
19799 (goto-char from-position)
19800 (forward-char symbol-width)
19801@end group
19802@group
19803 ;; @r{Draw graph column by column.}
19804 (sit-for 0)
19805 (setq numbers-list (cdr numbers-list)))
19806 ;; @r{Place point for X axis labels.}
19807 (forward-line height)
19808 (insert "\n")))
19809@end group
19810@end smallexample
19811
19812@need 1250
19813Finally, the code for the @code{print-graph} function:
19814
19815@findex print-graph @r{Final version.}
19816@smallexample
19817@group
19818;;; @r{Final version.}
19819(defun print-graph
19820 (numbers-list &optional vertical-step)
19821 "Print labelled bar graph of the NUMBERS-LIST.
19822The numbers-list consists of the Y-axis values.
19823@end group
19824
19825@group
19826Optionally, VERTICAL-STEP, a positive integer,
19827specifies how much a Y axis label increments for
19828each line. For example, a step of 5 means that
19829each row is five units."
19830@end group
19831@group
19832 (let* ((symbol-width (length graph-blank))
19833 ;; @code{height} @r{is both the largest number}
19834 ;; @r{and the number with the most digits.}
19835 (height (apply 'max numbers-list))
19836@end group
19837@group
19838 (height-of-top-line
19839 (if (zerop (% height Y-axis-label-spacing))
19840 height
19841 ;; @r{else}
19842 (* (1+ (/ height Y-axis-label-spacing))
19843 Y-axis-label-spacing)))
19844@end group
19845@group
19846 (vertical-step (or vertical-step 1))
19847 (full-Y-label-width
19848 (length
19849@end group
19850@group
19851 (concat
19852 (number-to-string
19853 (* height-of-top-line vertical-step))
19854 Y-axis-tic))))
19855@end group
19856
19857@group
19858 (print-Y-axis
19859 height-of-top-line full-Y-label-width vertical-step)
19860@end group
19861@group
19862 (graph-body-print
19863 numbers-list height-of-top-line symbol-width)
19864 (print-X-axis numbers-list)))
19865@end group
19866@end smallexample
19867
19868@node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
19869@appendixsubsec Testing @code{print-graph}
19870
19871@need 1250
19872We can test the @code{print-graph} function with a short list of numbers:
19873
19874@enumerate
19875@item
19876Install the final versions of @code{Y-axis-column},
19877@code{graph-body-print}, and @code{print-graph} (in addition to the
19878rest of the code.)
19879
19880@item
19881Copy the following expression:
19882
19883@smallexample
19884(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
19885@end smallexample
19886
19887@item
19888Switch to the @file{*scratch*} buffer and place the cursor where you
19889want the axis labels to start.
19890
19891@item
19892Type @kbd{M-:} (@code{eval-expression}).
19893
19894@item
19895Yank the test expression into the minibuffer
19896with @kbd{C-y} (@code{yank)}.
19897
19898@item
19899Press @key{RET} to evaluate the expression.
19900@end enumerate
19901
19902@need 1250
19903Emacs will print a graph that looks like this:
19904
19905@smallexample
19906@group
1990710 -
19908
19909
19910 *
19911 ** *
19912 5 - **** *
19913 **** ***
19914 * *********
19915 ************
19916 1 - *************
19917
19918 | | | |
19919 1 5 10 15
19920@end group
19921@end smallexample
19922
19923On the other hand, if you pass @code{print-graph} a
19924@code{vertical-step} value of 2, by evaluating this expression:
19925
19926@smallexample
19927(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
19928@end smallexample
19929
19930@need 1250
19931@noindent
19932The graph looks like this:
19933
19934@smallexample
19935@group
1993620 -
19937
19938
19939 *
19940 ** *
1994110 - **** *
19942 **** ***
19943 * *********
19944 ************
19945 2 - *************
19946
19947 | | | |
19948 1 5 10 15
19949@end group
19950@end smallexample
19951
19952@noindent
19953(A question: is the `2' on the bottom of the vertical axis a bug or a
19954feature? If you think it is a bug, and should be a `1' instead, (or
19955even a `0'), you can modify the sources.)
19956
19957@node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
19958@appendixsubsec Graphing Numbers of Words and Symbols
19959
19960Now for the graph for which all this code was written: a graph that
19961shows how many function definitions contain fewer than 10 words and
19962symbols, how many contain between 10 and 19 words and symbols, how
19963many contain between 20 and 29 words and symbols, and so on.
19964
19965This is a multi-step process. First make sure you have loaded all the
19966requisite code.
19967
19968@need 1500
19969It is a good idea to reset the value of @code{top-of-ranges} in case
19970you have set it to some different value. You can evaluate the
19971following:
19972
19973@smallexample
19974@group
19975(setq top-of-ranges
19976 '(10 20 30 40 50
19977 60 70 80 90 100
19978 110 120 130 140 150
19979 160 170 180 190 200
19980 210 220 230 240 250
19981 260 270 280 290 300)
19982@end group
19983@end smallexample
19984
19985@noindent
19986Next create a list of the number of words and symbols in each range.
19987
19988@need 1500
19989@noindent
19990Evaluate the following:
19991
19992@smallexample
19993@group
19994(setq list-for-graph
19995 (defuns-per-range
19996 (sort
19997 (recursive-lengths-list-many-files
19998 (directory-files "/usr/local/emacs/lisp"
19999 t ".+el$"))
20000 '<)
20001 top-of-ranges))
20002@end group
20003@end smallexample
20004
20005@noindent
20006On my machine, this takes about an hour. It looks though 303 Lisp
20007files in my copy of Emacs version 19.23. After all that computing,
20008the @code{list-for-graph} has this value:
20009
20010@smallexample
20011@group
20012(537 1027 955 785 594 483 349 292 224 199 166 120 116 99
2001390 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20014@end group
20015@end smallexample
20016
20017@noindent
20018This means that my copy of Emacs has 537 function definitions with
20019fewer than 10 words or symbols in them, 1,027 function definitions
20020with 10 to 19 words or symbols in them, 955 function definitions with
2002120 to 29 words or symbols in them, and so on.
20022
20023Clearly, just by looking at this list we can see that most function
20024definitions contain ten to thirty words and symbols.
20025
20026Now for printing. We do @emph{not} want to print a graph that is
200271,030 lines high @dots{} Instead, we should print a graph that is
20028fewer than twenty-five lines high. A graph that height can be
20029displayed on almost any monitor, and easily printed on a sheet of paper.
20030
20031This means that each value in @code{list-for-graph} must be reduced to
20032one-fiftieth its present value.
20033
20034Here is a short function to do just that, using two functions we have
20035not yet seen, @code{mapcar} and @code{lambda}.
20036
20037@smallexample
20038@group
20039(defun one-fiftieth (full-range)
20040 "Return list, each number one-fiftieth of previous."
20041 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20042@end group
20043@end smallexample
20044
20045@node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20046@appendixsubsec A @code{lambda} Expression: Useful Anonymity
20047@cindex Anonymous function
20048@findex lambda
20049
20050@code{lambda} is the symbol for an anonymous function, a function
20051without a name. Every time you use an anonymous function, you need to
20052include its whole body.
20053
20054@need 1250
20055@noindent
20056Thus,
20057
20058@smallexample
20059(lambda (arg) (/ arg 50))
20060@end smallexample
20061
20062@noindent
20063is a function definition that says `return the value resulting from
20064dividing whatever is passed to me as @code{arg} by 50'.
20065
20066Earlier, for example, we had a function @code{multiply-by-seven}; it
20067multiplied its argument by 7. This function is similar, except it
20068divides its argument by 50; and, it has no name. The anonymous
20069equivalent of @code{multiply-by-seven} is:
20070
20071@smallexample
20072(lambda (number) (* 7 number))
20073@end smallexample
20074
20075@noindent
20076(@xref{defun, , The @code{defun} Special Form}.)
20077
20078@need 1250
20079@noindent
20080If we want to multiply 3 by 7, we can write:
20081
20082@c !!! Clear print-postscript-figures if the computer formatting this
20083@c document is too small and cannot handle all the diagrams and figures.
20084@c clear print-postscript-figures
20085@c set print-postscript-figures
20086@c lambda example diagram #1
20087@ifnottex
20088@smallexample
20089@group
20090(multiply-by-seven 3)
20091 \_______________/ ^
20092 | |
20093 function argument
20094@end group
20095@end smallexample
20096@end ifnottex
20097@ifset print-postscript-figures
20098@sp 1
20099@tex
20100@image{lambda-1}
20101%%%% old method of including an image
20102% \input /usr/local/lib/tex/inputs/psfig.tex
20103% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20104% \catcode`\@=0 %
20105@end tex
20106@sp 1
20107@end ifset
20108@ifclear print-postscript-figures
20109@iftex
20110@smallexample
20111@group
20112(multiply-by-seven 3)
20113 \_______________/ ^
20114 | |
20115 function argument
20116@end group
20117@end smallexample
20118@end iftex
20119@end ifclear
20120
20121@noindent
20122This expression returns 21.
20123
20124@need 1250
20125@noindent
20126Similarly, we can write:
20127
20128@c lambda example diagram #2
20129@ifnottex
20130@smallexample
20131@group
20132((lambda (number) (* 7 number)) 3)
20133 \____________________________/ ^
20134 | |
20135 anonymous function argument
20136@end group
20137@end smallexample
20138@end ifnottex
20139@ifset print-postscript-figures
20140@sp 1
20141@tex
20142@image{lambda-2}
20143%%%% old method of including an image
20144% \input /usr/local/lib/tex/inputs/psfig.tex
20145% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20146% \catcode`\@=0 %
20147@end tex
20148@sp 1
20149@end ifset
20150@ifclear print-postscript-figures
20151@iftex
20152@smallexample
20153@group
20154((lambda (number) (* 7 number)) 3)
20155 \____________________________/ ^
20156 | |
20157 anonymous function argument
20158@end group
20159@end smallexample
20160@end iftex
20161@end ifclear
20162
20163@need 1250
20164@noindent
20165If we want to divide 100 by 50, we can write:
20166
20167@c lambda example diagram #3
20168@ifnottex
20169@smallexample
20170@group
20171((lambda (arg) (/ arg 50)) 100)
20172 \______________________/ \_/
20173 | |
20174 anonymous function argument
20175@end group
20176@end smallexample
20177@end ifnottex
20178@ifset print-postscript-figures
20179@sp 1
20180@tex
20181@image{lambda-3}
20182%%%% old method of including an image
20183% \input /usr/local/lib/tex/inputs/psfig.tex
20184% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20185% \catcode`\@=0 %
20186@end tex
20187@sp 1
20188@end ifset
20189@ifclear print-postscript-figures
20190@iftex
20191@smallexample
20192@group
20193((lambda (arg) (/ arg 50)) 100)
20194 \______________________/ \_/
20195 | |
20196 anonymous function argument
20197@end group
20198@end smallexample
20199@end iftex
20200@end ifclear
20201
20202@noindent
20203This expression returns 2. The 100 is passed to the function, which
20204divides that number by 50.
20205
20206@xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20207Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
20208expressions derive from the Lambda Calculus.
20209
20210@node mapcar, Another Bug, lambda, Print Whole Graph
20211@appendixsubsec The @code{mapcar} Function
20212@findex mapcar
20213
20214@code{mapcar} is a function that calls its first argument with each
20215element of its second argument, in turn. The second argument must be
20216a sequence.
20217
20218The @samp{map} part of the name comes from the mathematical phrase,
20219`mapping over a domain', meaning to apply a function to each of the
20220elements in a domain. The mathematical phrase is based on the
20221metaphor of a surveyor walking, one step at a time, over an area he is
20222mapping. And @samp{car}, of course, comes from the Lisp notion of the
20223first of a list.
20224
20225@need 1250
20226@noindent
20227For example,
20228
20229@smallexample
20230@group
20231(mapcar '1+ '(2 4 6))
20232 @result{} (3 5 7)
20233@end group
20234@end smallexample
20235
20236@noindent
20237The function @code{1+} which adds one to its argument, is executed on
20238@emph{each} element of the list, and a new list is returned.
20239
20240Contrast this with @code{apply}, which applies its first argument to
20241all the remaining.
20242(@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20243@code{apply}.)
20244
20245@need 1250
20246In the definition of @code{one-fiftieth}, the first argument is the
20247anonymous function:
20248
20249@smallexample
20250(lambda (arg) (/ arg 50))
20251@end smallexample
20252
20253@noindent
20254and the second argument is @code{full-range}, which will be bound to
20255@code{list-for-graph}.
20256
20257@need 1250
20258The whole expression looks like this:
20259
20260@smallexample
20261(mapcar '(lambda (arg) (/ arg 50)) full-range))
20262@end smallexample
20263
20264@xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20265Lisp Reference Manual}, for more about @code{mapcar}.
20266
20267Using the @code{one-fiftieth} function, we can generate a list in
20268which each element is one-fiftieth the size of the corresponding
20269element in @code{list-for-graph}.
20270
20271@smallexample
20272@group
20273(setq fiftieth-list-for-graph
20274 (one-fiftieth list-for-graph))
20275@end group
20276@end smallexample
20277
20278@need 1250
20279The resulting list looks like this:
20280
20281@smallexample
20282@group
20283(10 20 19 15 11 9 6 5 4 3 3 2 2
202841 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20285@end group
20286@end smallexample
20287
20288@noindent
20289This, we are almost ready to print! (We also notice the loss of
20290information: many of the higher ranges are 0, meaning that fewer than
2029150 defuns had that many words or symbols---but not necessarily meaning
20292that none had that many words or symbols.)
20293
20294@node Another Bug, Final printed graph, mapcar, Print Whole Graph
20295@appendixsubsec Another Bug @dots{} Most Insidious
20296@cindex Bug, most insidious type
20297@cindex Insidious type of bug
20298
20299I said `almost ready to print'! Of course, there is a bug in the
20300@code{print-graph} function @dots{} It has a @code{vertical-step}
20301option, but not a @code{horizontal-step} option. The
20302@code{top-of-range} scale goes from 10 to 300 by tens. But the
20303@code{print-graph} function will print only by ones.
20304
20305This is a classic example of what some consider the most insidious
20306type of bug, the bug of omission. This is not the kind of bug you can
20307find by studying the code, for it is not in the code; it is an omitted
20308feature. Your best actions are to try your program early and often;
20309and try to arrange, as much as you can, to write code that is easy to
20310understand and easy to change. Try to be aware, whenever you can,
20311that whatever you have written, @emph{will} be rewritten, if not soon,
20312eventually. A hard maxim to follow.
20313
20314It is the @code{print-X-axis-numbered-line} function that needs the
20315work; and then the @code{print-X-axis} and the @code{print-graph}
20316functions need to be adapted. Not much needs to be done; there is one
20317nicety: the numbers ought to line up under the tic marks. This takes
20318a little thought.
20319
20320@need 1250
20321Here is the corrected @code{print-X-axis-numbered-line}:
20322
20323@smallexample
20324@group
20325(defun print-X-axis-numbered-line
20326 (number-of-X-tics X-axis-leading-spaces
20327 &optional horizontal-step)
20328 "Print line of X-axis numbers"
20329 (let ((number X-axis-label-spacing)
20330 (horizontal-step (or horizontal-step 1)))
20331@end group
20332@group
20333 (insert X-axis-leading-spaces)
20334 ;; @r{Delete extra leading spaces.}
20335 (delete-char
20336 (- (1-
20337 (length (number-to-string horizontal-step)))))
20338 (insert (concat
20339 (make-string
20340@end group
20341@group
20342 ;; @r{Insert white space.}
20343 (- (* symbol-width
20344 X-axis-label-spacing)
20345 (1-
20346 (length
20347 (number-to-string horizontal-step)))
20348 2)
20349 ? )
20350 (number-to-string
20351 (* number horizontal-step))))
20352@end group
20353@group
20354 ;; @r{Insert remaining numbers.}
20355 (setq number (+ number X-axis-label-spacing))
20356 (while (> number-of-X-tics 1)
20357 (insert (X-axis-element
20358 (* number horizontal-step)))
20359 (setq number (+ number X-axis-label-spacing))
20360 (setq number-of-X-tics (1- number-of-X-tics)))))
20361@end group
20362@end smallexample
20363
20364@need 1500
20365If you are reading this in Info, you can see the new versions of
20366@code{print-X-axis} @code{print-graph} and evaluate them. If you are
20367reading this in a printed book, you can see the changed lines here
20368(the full text is too much to print).
20369
20370@iftex
20371@smallexample
20372@group
20373(defun print-X-axis (numbers-list horizontal-step)
20374 @dots{}
20375 (print-X-axis-numbered-line
20376 tic-number leading-spaces horizontal-step))
20377@end group
20378@end smallexample
20379
20380@smallexample
20381@group
20382(defun print-graph
20383 (numbers-list
20384 &optional vertical-step horizontal-step)
20385 @dots{}
20386 (print-X-axis numbers-list horizontal-step))
20387@end group
20388@end smallexample
20389@end iftex
20390
20391@ifnottex
20392@smallexample
20393@group
20394(defun print-X-axis (numbers-list horizontal-step)
20395 "Print X axis labels to length of NUMBERS-LIST.
20396Optionally, HORIZONTAL-STEP, a positive integer,
20397specifies how much an X axis label increments for
20398each column."
20399@end group
20400@group
20401;; Value of symbol-width and full-Y-label-width
20402;; are passed by `print-graph'.
20403 (let* ((leading-spaces
20404 (make-string full-Y-label-width ? ))
20405 ;; symbol-width @r{is provided by} graph-body-print
20406 (tic-width (* symbol-width X-axis-label-spacing))
20407 (X-length (length numbers-list))
20408@end group
20409@group
20410 (X-tic
20411 (concat
20412 (make-string
20413 ;; @r{Make a string of blanks.}
20414 (- (* symbol-width X-axis-label-spacing)
20415 (length X-axis-tic-symbol))
20416 ? )
20417@end group
20418@group
20419 ;; @r{Concatenate blanks with tic symbol.}
20420 X-axis-tic-symbol))
20421 (tic-number
20422 (if (zerop (% X-length tic-width))
20423 (/ X-length tic-width)
20424 (1+ (/ X-length tic-width)))))
20425@end group
20426
20427@group
20428 (print-X-axis-tic-line
20429 tic-number leading-spaces X-tic)
20430 (insert "\n")
20431 (print-X-axis-numbered-line
20432 tic-number leading-spaces horizontal-step)))
20433@end group
20434@end smallexample
20435
20436@smallexample
20437@group
20438(defun print-graph
20439 (numbers-list &optional vertical-step horizontal-step)
20440 "Print labelled bar graph of the NUMBERS-LIST.
20441The numbers-list consists of the Y-axis values.
20442@end group
20443
20444@group
20445Optionally, VERTICAL-STEP, a positive integer,
20446specifies how much a Y axis label increments for
20447each line. For example, a step of 5 means that
20448each row is five units.
20449@end group
20450
20451@group
20452Optionally, HORIZONTAL-STEP, a positive integer,
20453specifies how much an X axis label increments for
20454each column."
20455 (let* ((symbol-width (length graph-blank))
20456 ;; @code{height} @r{is both the largest number}
20457 ;; @r{and the number with the most digits.}
20458 (height (apply 'max numbers-list))
20459@end group
20460@group
20461 (height-of-top-line
20462 (if (zerop (% height Y-axis-label-spacing))
20463 height
20464 ;; @r{else}
20465 (* (1+ (/ height Y-axis-label-spacing))
20466 Y-axis-label-spacing)))
20467@end group
20468@group
20469 (vertical-step (or vertical-step 1))
20470 (full-Y-label-width
20471 (length
20472 (concat
20473 (number-to-string
20474 (* height-of-top-line vertical-step))
20475 Y-axis-tic))))
20476@end group
20477@group
20478 (print-Y-axis
20479 height-of-top-line full-Y-label-width vertical-step)
20480 (graph-body-print
20481 numbers-list height-of-top-line symbol-width)
20482 (print-X-axis numbers-list horizontal-step)))
20483@end group
20484@end smallexample
20485@end ifnottex
20486
20487@ignore
20488Graphing Definitions Re-listed
20489
20490@need 1250
20491Here are all the graphing definitions in their final form:
20492
20493@smallexample
20494@group
20495(defvar top-of-ranges
20496 '(10 20 30 40 50
20497 60 70 80 90 100
20498 110 120 130 140 150
20499 160 170 180 190 200
20500 210 220 230 240 250)
20501 "List specifying ranges for `defuns-per-range'.")
20502@end group
20503
20504@group
20505(defvar graph-symbol "*"
20506 "String used as symbol in graph, usually an asterisk.")
20507@end group
20508
20509@group
20510(defvar graph-blank " "
20511 "String used as blank in graph, usually a blank space.
20512graph-blank must be the same number of columns wide
20513as graph-symbol.")
20514@end group
20515
20516@group
20517(defvar Y-axis-tic " - "
20518 "String that follows number in a Y axis label.")
20519@end group
20520
20521@group
20522(defvar Y-axis-label-spacing 5
20523 "Number of lines from one Y axis label to next.")
20524@end group
20525
20526@group
20527(defvar X-axis-tic-symbol "|"
20528 "String to insert to point to a column in X axis.")
20529@end group
20530
20531@group
20532(defvar X-axis-label-spacing
20533 (if (boundp 'graph-blank)
20534 (* 5 (length graph-blank)) 5)
20535 "Number of units from one X axis label to next.")
20536@end group
20537@end smallexample
20538
20539@smallexample
20540@group
20541(defun count-words-in-defun ()
20542 "Return the number of words and symbols in a defun."
20543 (beginning-of-defun)
20544 (let ((count 0)
20545 (end (save-excursion (end-of-defun) (point))))
20546@end group
20547
20548@group
20549 (while
20550 (and (< (point) end)
20551 (re-search-forward
20552 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20553 end t))
20554 (setq count (1+ count)))
20555 count))
20556@end group
20557@end smallexample
20558
20559@smallexample
20560@group
20561(defun lengths-list-file (filename)
20562 "Return list of definitions' lengths within FILE.
20563The returned list is a list of numbers.
20564Each number is the number of words or
20565symbols in one function definition."
20566@end group
20567
20568@group
20569 (message "Working on `%s' ... " filename)
20570 (save-excursion
20571 (let ((buffer (find-file-noselect filename))
20572 (lengths-list))
20573 (set-buffer buffer)
20574 (setq buffer-read-only t)
20575 (widen)
20576 (goto-char (point-min))
20577@end group
20578
20579@group
20580 (while (re-search-forward "^(defun" nil t)
20581 (setq lengths-list
20582 (cons (count-words-in-defun) lengths-list)))
20583 (kill-buffer buffer)
20584 lengths-list)))
20585@end group
20586@end smallexample
20587
20588@smallexample
20589@group
20590(defun lengths-list-many-files (list-of-files)
20591 "Return list of lengths of defuns in LIST-OF-FILES."
20592 (let (lengths-list)
20593;;; @r{true-or-false-test}
20594 (while list-of-files
20595 (setq lengths-list
20596 (append
20597 lengths-list
20598@end group
20599@group
20600;;; @r{Generate a lengths' list.}
20601 (lengths-list-file
20602 (expand-file-name (car list-of-files)))))
20603;;; @r{Make files' list shorter.}
20604 (setq list-of-files (cdr list-of-files)))
20605;;; @r{Return final value of lengths' list.}
20606 lengths-list))
20607@end group
20608@end smallexample
20609
20610@smallexample
20611@group
20612(defun defuns-per-range (sorted-lengths top-of-ranges)
20613 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20614 (let ((top-of-range (car top-of-ranges))
20615 (number-within-range 0)
20616 defuns-per-range-list)
20617@end group
20618
20619@group
20620 ;; @r{Outer loop.}
20621 (while top-of-ranges
20622
20623 ;; @r{Inner loop.}
20624 (while (and
20625 ;; @r{Need number for numeric test.}
20626 (car sorted-lengths)
20627 (< (car sorted-lengths) top-of-range))
20628
20629 ;; @r{Count number of definitions within current range.}
20630 (setq number-within-range (1+ number-within-range))
20631 (setq sorted-lengths (cdr sorted-lengths)))
20632@end group
20633
20634@group
20635 ;; @r{Exit inner loop but remain within outer loop.}
20636
20637 (setq defuns-per-range-list
20638 (cons number-within-range defuns-per-range-list))
20639 (setq number-within-range 0) ; @r{Reset count to zero.}
20640
20641 ;; @r{Move to next range.}
20642 (setq top-of-ranges (cdr top-of-ranges))
20643 ;; @r{Specify next top of range value.}
20644 (setq top-of-range (car top-of-ranges)))
20645@end group
20646
20647@group
20648 ;; @r{Exit outer loop and count the number of defuns larger than}
20649 ;; @r{ the largest top-of-range value.}
20650 (setq defuns-per-range-list
20651 (cons
20652 (length sorted-lengths)
20653 defuns-per-range-list))
20654
20655 ;; @r{Return a list of the number of definitions within each range,}
20656 ;; @r{ smallest to largest.}
20657 (nreverse defuns-per-range-list)))
20658@end group
20659@end smallexample
20660
20661@smallexample
20662@group
20663(defun column-of-graph (max-graph-height actual-height)
20664 "Return list of MAX-GRAPH-HEIGHT strings;
20665ACTUAL-HEIGHT are graph-symbols.
20666The graph-symbols are contiguous entries at the end
20667of the list.
20668The list will be inserted as one column of a graph.
20669The strings are either graph-blank or graph-symbol."
20670@end group
20671
20672@group
20673 (let ((insert-list nil)
20674 (number-of-top-blanks
20675 (- max-graph-height actual-height)))
20676
20677 ;; @r{Fill in @code{graph-symbols}.}
20678 (while (> actual-height 0)
20679 (setq insert-list (cons graph-symbol insert-list))
20680 (setq actual-height (1- actual-height)))
20681@end group
20682
20683@group
20684 ;; @r{Fill in @code{graph-blanks}.}
20685 (while (> number-of-top-blanks 0)
20686 (setq insert-list (cons graph-blank insert-list))
20687 (setq number-of-top-blanks
20688 (1- number-of-top-blanks)))
20689
20690 ;; @r{Return whole list.}
20691 insert-list))
20692@end group
20693@end smallexample
20694
20695@smallexample
20696@group
20697(defun Y-axis-element (number full-Y-label-width)
20698 "Construct a NUMBERed label element.
20699A numbered element looks like this ` 5 - ',
20700and is padded as needed so all line up with
20701the element for the largest number."
20702@end group
20703@group
20704 (let* ((leading-spaces
20705 (- full-Y-label-width
20706 (length
20707 (concat (number-to-string number)
20708 Y-axis-tic)))))
20709@end group
20710@group
20711 (concat
20712 (make-string leading-spaces ? )
20713 (number-to-string number)
20714 Y-axis-tic)))
20715@end group
20716@end smallexample
20717
20718@smallexample
20719@group
20720(defun print-Y-axis
20721 (height full-Y-label-width &optional vertical-step)
20722 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20723Height must be the maximum height of the graph.
20724Full width is the width of the highest label element.
20725Optionally, print according to VERTICAL-STEP."
20726@end group
20727@group
20728;; Value of height and full-Y-label-width
20729;; are passed by `print-graph'.
20730 (let ((start (point)))
20731 (insert-rectangle
20732 (Y-axis-column height full-Y-label-width vertical-step))
20733@end group
20734@group
20735 ;; @r{Place point ready for inserting graph.}
20736 (goto-char start)
20737 ;; @r{Move point forward by value of} full-Y-label-width
20738 (forward-char full-Y-label-width)))
20739@end group
20740@end smallexample
20741
20742@smallexample
20743@group
20744(defun print-X-axis-tic-line
20745 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20746 "Print tics for X axis."
20747 (insert X-axis-leading-spaces)
20748 (insert X-axis-tic-symbol) ; @r{Under first column.}
20749@end group
20750@group
20751 ;; @r{Insert second tic in the right spot.}
20752 (insert (concat
20753 (make-string
20754 (- (* symbol-width X-axis-label-spacing)
20755 ;; @r{Insert white space up to second tic symbol.}
20756 (* 2 (length X-axis-tic-symbol)))
20757 ? )
20758 X-axis-tic-symbol))
20759@end group
20760@group
20761 ;; @r{Insert remaining tics.}
20762 (while (> number-of-X-tics 1)
20763 (insert X-axis-tic-element)
20764 (setq number-of-X-tics (1- number-of-X-tics))))
20765@end group
20766@end smallexample
20767
20768@smallexample
20769@group
20770(defun X-axis-element (number)
20771 "Construct a numbered X axis element."
20772 (let ((leading-spaces
20773 (- (* symbol-width X-axis-label-spacing)
20774 (length (number-to-string number)))))
20775 (concat (make-string leading-spaces ? )
20776 (number-to-string number))))
20777@end group
20778@end smallexample
20779
20780@smallexample
20781@group
20782(defun graph-body-print (numbers-list height symbol-width)
20783 "Print a bar graph of the NUMBERS-LIST.
20784The numbers-list consists of the Y-axis values.
20785HEIGHT is maximum height of graph.
20786SYMBOL-WIDTH is number of each column."
20787@end group
20788@group
20789 (let (from-position)
20790 (while numbers-list
20791 (setq from-position (point))
20792 (insert-rectangle
20793 (column-of-graph height (car numbers-list)))
20794 (goto-char from-position)
20795 (forward-char symbol-width)
20796@end group
20797@group
20798 ;; @r{Draw graph column by column.}
20799 (sit-for 0)
20800 (setq numbers-list (cdr numbers-list)))
20801 ;; @r{Place point for X axis labels.}
20802 (forward-line height)
20803 (insert "\n")))
20804@end group
20805@end smallexample
20806
20807@smallexample
20808@group
20809(defun Y-axis-column
20810 (height width-of-label &optional vertical-step)
20811 "Construct list of labels for Y axis.
20812HEIGHT is maximum height of graph.
20813WIDTH-OF-LABEL is maximum width of label.
20814@end group
20815@group
20816VERTICAL-STEP, an option, is a positive integer
20817that specifies how much a Y axis label increments
20818for each line. For example, a step of 5 means
20819that each line is five units of the graph."
20820 (let (Y-axis
20821 (number-per-line (or vertical-step 1)))
20822@end group
20823@group
20824 (while (> height 1)
20825 (if (zerop (% height Y-axis-label-spacing))
20826 ;; @r{Insert label.}
20827 (setq Y-axis
20828 (cons
20829 (Y-axis-element
20830 (* height number-per-line)
20831 width-of-label)
20832 Y-axis))
20833@end group
20834@group
20835 ;; @r{Else, insert blanks.}
20836 (setq Y-axis
20837 (cons
20838 (make-string width-of-label ? )
20839 Y-axis)))
20840 (setq height (1- height)))
20841@end group
20842@group
20843 ;; @r{Insert base line.}
20844 (setq Y-axis (cons (Y-axis-element
20845 (or vertical-step 1)
20846 width-of-label)
20847 Y-axis))
20848 (nreverse Y-axis)))
20849@end group
20850@end smallexample
20851
20852@smallexample
20853@group
20854(defun print-X-axis-numbered-line
20855 (number-of-X-tics X-axis-leading-spaces
20856 &optional horizontal-step)
20857 "Print line of X-axis numbers"
20858 (let ((number X-axis-label-spacing)
20859 (horizontal-step (or horizontal-step 1)))
20860@end group
20861@group
20862 (insert X-axis-leading-spaces)
20863 ;; line up number
20864 (delete-char (- (1- (length (number-to-string horizontal-step)))))
20865 (insert (concat
20866 (make-string
20867 ;; @r{Insert white space up to next number.}
20868 (- (* symbol-width X-axis-label-spacing)
20869 (1- (length (number-to-string horizontal-step)))
20870 2)
20871 ? )
20872 (number-to-string (* number horizontal-step))))
20873@end group
20874@group
20875 ;; @r{Insert remaining numbers.}
20876 (setq number (+ number X-axis-label-spacing))
20877 (while (> number-of-X-tics 1)
20878 (insert (X-axis-element (* number horizontal-step)))
20879 (setq number (+ number X-axis-label-spacing))
20880 (setq number-of-X-tics (1- number-of-X-tics)))))
20881@end group
20882@end smallexample
20883
20884@smallexample
20885@group
20886(defun print-X-axis (numbers-list horizontal-step)
20887 "Print X axis labels to length of NUMBERS-LIST.
20888Optionally, HORIZONTAL-STEP, a positive integer,
20889specifies how much an X axis label increments for
20890each column."
20891@end group
20892@group
20893;; Value of symbol-width and full-Y-label-width
20894;; are passed by `print-graph'.
20895 (let* ((leading-spaces
20896 (make-string full-Y-label-width ? ))
20897 ;; symbol-width @r{is provided by} graph-body-print
20898 (tic-width (* symbol-width X-axis-label-spacing))
20899 (X-length (length numbers-list))
20900@end group
20901@group
20902 (X-tic
20903 (concat
20904 (make-string
20905 ;; @r{Make a string of blanks.}
20906 (- (* symbol-width X-axis-label-spacing)
20907 (length X-axis-tic-symbol))
20908 ? )
20909@end group
20910@group
20911 ;; @r{Concatenate blanks with tic symbol.}
20912 X-axis-tic-symbol))
20913 (tic-number
20914 (if (zerop (% X-length tic-width))
20915 (/ X-length tic-width)
20916 (1+ (/ X-length tic-width)))))
20917@end group
20918
20919@group
20920 (print-X-axis-tic-line
20921 tic-number leading-spaces X-tic)
20922 (insert "\n")
20923 (print-X-axis-numbered-line
20924 tic-number leading-spaces horizontal-step)))
20925@end group
20926@end smallexample
20927
20928@smallexample
20929@group
20930(defun one-fiftieth (full-range)
20931 "Return list, each number of which is 1/50th previous."
20932 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20933@end group
20934@end smallexample
20935
20936@smallexample
20937@group
20938(defun print-graph
20939 (numbers-list &optional vertical-step horizontal-step)
20940 "Print labelled bar graph of the NUMBERS-LIST.
20941The numbers-list consists of the Y-axis values.
20942@end group
20943
20944@group
20945Optionally, VERTICAL-STEP, a positive integer,
20946specifies how much a Y axis label increments for
20947each line. For example, a step of 5 means that
20948each row is five units.
20949@end group
20950
20951@group
20952Optionally, HORIZONTAL-STEP, a positive integer,
20953specifies how much an X axis label increments for
20954each column."
20955 (let* ((symbol-width (length graph-blank))
20956 ;; @code{height} @r{is both the largest number}
20957 ;; @r{and the number with the most digits.}
20958 (height (apply 'max numbers-list))
20959@end group
20960@group
20961 (height-of-top-line
20962 (if (zerop (% height Y-axis-label-spacing))
20963 height
20964 ;; @r{else}
20965 (* (1+ (/ height Y-axis-label-spacing))
20966 Y-axis-label-spacing)))
20967@end group
20968@group
20969 (vertical-step (or vertical-step 1))
20970 (full-Y-label-width
20971 (length
20972 (concat
20973 (number-to-string
20974 (* height-of-top-line vertical-step))
20975 Y-axis-tic))))
20976@end group
20977@group
20978
20979 (print-Y-axis
20980 height-of-top-line full-Y-label-width vertical-step)
20981 (graph-body-print
20982 numbers-list height-of-top-line symbol-width)
20983 (print-X-axis numbers-list horizontal-step)))
20984@end group
20985@end smallexample
20986@end ignore
20987
20988@page
20989@node Final printed graph, , Another Bug, Print Whole Graph
20990@appendixsubsec The Printed Graph
20991
20992When made and installed, you can call the @code{print-graph} command
20993like this:
20994
20995@smallexample
20996@group
20997(print-graph fiftieth-list-for-graph 50 10)
20998@end group
20999@end smallexample
21000
21001Here is the graph:
21002
21003@sp 2
21004
21005@smallexample
21006@group
210071000 - *
21008 **
21009 **
21010 **
21011 **
21012 750 - ***
21013 ***
21014 ***
21015 ***
21016 ****
21017 500 - *****
21018 ******
21019 ******
21020 ******
21021 *******
21022 250 - ********
21023 ********* *
21024 *********** *
21025 ************* *
21026 50 - ***************** * *
21027 | | | | | | | |
21028 10 50 100 150 200 250 300 350
21029@end group
21030@end smallexample
21031
21032@sp 2
21033
21034The largest group of functions contain 10 -- 19 words and symbols each.
21035
21036@node GNU Free Documentation License, Index, Full Graph, Top
21037@appendix GNU Free Documentation License
21038
21039@cindex FDL, GNU Free Documentation License
21040@center Version 1.1, March 2000
21041
21042@display
21043Copyright @copyright{} 2000 Free Software Foundation, Inc.
2104459 Temple Place, Suite 330, Boston, MA 02111-1307, USA
21045
21046Everyone is permitted to copy and distribute verbatim copies
21047of this license document, but changing it is not allowed.
21048@end display
21049
21050@enumerate 0
21051@item
21052PREAMBLE
21053
21054The purpose of this License is to make a manual, textbook, or other
21055written document @dfn{free} in the sense of freedom: to assure everyone
21056the effective freedom to copy and redistribute it, with or without
21057modifying it, either commercially or noncommercially. Secondarily,
21058this License preserves for the author and publisher a way to get
21059credit for their work, while not being considered responsible for
21060modifications made by others.
21061
21062This License is a kind of ``copyleft'', which means that derivative
21063works of the document must themselves be free in the same sense. It
21064complements the GNU General Public License, which is a copyleft
21065license designed for free software.
21066
21067We have designed this License in order to use it for manuals for free
21068software, because free software needs free documentation: a free
21069program should come with manuals providing the same freedoms that the
21070software does. But this License is not limited to software manuals;
21071it can be used for any textual work, regardless of subject matter or
21072whether it is published as a printed book. We recommend this License
21073principally for works whose purpose is instruction or reference.
21074
21075@item
21076APPLICABILITY AND DEFINITIONS
21077
21078This License applies to any manual or other work that contains a
21079notice placed by the copyright holder saying it can be distributed
21080under the terms of this License. The ``Document'', below, refers to any
21081such manual or work. Any member of the public is a licensee, and is
21082addressed as ``you''.
21083
21084A ``Modified Version'' of the Document means any work containing the
21085Document or a portion of it, either copied verbatim, or with
21086modifications and/or translated into another language.
21087
21088A ``Secondary Section'' is a named appendix or a front-matter section of
21089the Document that deals exclusively with the relationship of the
21090publishers or authors of the Document to the Document's overall subject
21091(or to related matters) and contains nothing that could fall directly
21092within that overall subject. (For example, if the Document is in part a
21093textbook of mathematics, a Secondary Section may not explain any
21094mathematics.) The relationship could be a matter of historical
21095connection with the subject or with related matters, or of legal,
21096commercial, philosophical, ethical or political position regarding
21097them.
21098
21099The ``Invariant Sections'' are certain Secondary Sections whose titles
21100are designated, as being those of Invariant Sections, in the notice
21101that says that the Document is released under this License.
21102
21103The ``Cover Texts'' are certain short passages of text that are listed,
21104as Front-Cover Texts or Back-Cover Texts, in the notice that says that
21105the Document is released under this License.
21106
21107A ``Transparent'' copy of the Document means a machine-readable copy,
21108represented in a format whose specification is available to the
21109general public, whose contents can be viewed and edited directly and
21110straightforwardly with generic text editors or (for images composed of
21111pixels) generic paint programs or (for drawings) some widely available
21112drawing editor, and that is suitable for input to text formatters or
21113for automatic translation to a variety of formats suitable for input
21114to text formatters. A copy made in an otherwise Transparent file
21115format whose markup has been designed to thwart or discourage
21116subsequent modification by readers is not Transparent. A copy that is
21117not ``Transparent'' is called ``Opaque''.
21118
21119Examples of suitable formats for Transparent copies include plain
21120@sc{ascii} without markup, Texinfo input format, La@TeX{} input format,
21121@acronym{SGML} or @acronym{XML} using a publicly available
21122@acronym{DTD}, and standard-conforming simple @acronym{HTML} designed
21123for human modification. Opaque formats include PostScript,
21124@acronym{PDF}, proprietary formats that can be read and edited only by
21125proprietary word processors, @acronym{SGML} or @acronym{XML} for which
21126the @acronym{DTD} and/or processing tools are not generally available,
21127and the machine-generated @acronym{HTML} produced by some word
21128processors for output purposes only.
21129
21130The ``Title Page'' means, for a printed book, the title page itself,
21131plus such following pages as are needed to hold, legibly, the material
21132this License requires to appear in the title page. For works in
21133formats which do not have any title page as such, ``Title Page'' means
21134the text near the most prominent appearance of the work's title,
21135preceding the beginning of the body of the text.
21136
21137@item
21138VERBATIM COPYING
21139
21140You may copy and distribute the Document in any medium, either
21141commercially or noncommercially, provided that this License, the
21142copyright notices, and the license notice saying this License applies
21143to the Document are reproduced in all copies, and that you add no other
21144conditions whatsoever to those of this License. You may not use
21145technical measures to obstruct or control the reading or further
21146copying of the copies you make or distribute. However, you may accept
21147compensation in exchange for copies. If you distribute a large enough
21148number of copies you must also follow the conditions in section 3.
21149
21150You may also lend copies, under the same conditions stated above, and
21151you may publicly display copies.
21152
21153@item
21154COPYING IN QUANTITY
21155
21156If you publish printed copies of the Document numbering more than 100,
21157and the Document's license notice requires Cover Texts, you must enclose
21158the copies in covers that carry, clearly and legibly, all these Cover
21159Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21160the back cover. Both covers must also clearly and legibly identify
21161you as the publisher of these copies. The front cover must present
21162the full title with all words of the title equally prominent and
21163visible. You may add other material on the covers in addition.
21164Copying with changes limited to the covers, as long as they preserve
21165the title of the Document and satisfy these conditions, can be treated
21166as verbatim copying in other respects.
21167
21168If the required texts for either cover are too voluminous to fit
21169legibly, you should put the first ones listed (as many as fit
21170reasonably) on the actual cover, and continue the rest onto adjacent
21171pages.
21172
21173If you publish or distribute Opaque copies of the Document numbering
21174more than 100, you must either include a machine-readable Transparent
21175copy along with each Opaque copy, or state in or with each Opaque copy
21176a publicly-accessible computer-network location containing a complete
21177Transparent copy of the Document, free of added material, which the
21178general network-using public has access to download anonymously at no
21179charge using public-standard network protocols. If you use the latter
21180option, you must take reasonably prudent steps, when you begin
21181distribution of Opaque copies in quantity, to ensure that this
21182Transparent copy will remain thus accessible at the stated location
21183until at least one year after the last time you distribute an Opaque
21184copy (directly or through your agents or retailers) of that edition to
21185the public.
21186
21187It is requested, but not required, that you contact the authors of the
21188Document well before redistributing any large number of copies, to give
21189them a chance to provide you with an updated version of the Document.
21190
21191@item
21192MODIFICATIONS
21193
21194You may copy and distribute a Modified Version of the Document under
21195the conditions of sections 2 and 3 above, provided that you release
21196the Modified Version under precisely this License, with the Modified
21197Version filling the role of the Document, thus licensing distribution
21198and modification of the Modified Version to whoever possesses a copy
21199of it. In addition, you must do these things in the Modified Version:
21200
21201@enumerate A
21202@item
21203Use in the Title Page (and on the covers, if any) a title distinct
21204from that of the Document, and from those of previous versions
21205(which should, if there were any, be listed in the History section
21206of the Document). You may use the same title as a previous version
21207if the original publisher of that version gives permission.
21208
21209@item
21210List on the Title Page, as authors, one or more persons or entities
21211responsible for authorship of the modifications in the Modified
21212Version, together with at least five of the principal authors of the
21213Document (all of its principal authors, if it has less than five).
21214
21215@item
21216State on the Title page the name of the publisher of the
21217Modified Version, as the publisher.
21218
21219@item
21220Preserve all the copyright notices of the Document.
21221
21222@item
21223Add an appropriate copyright notice for your modifications
21224adjacent to the other copyright notices.
21225
21226@item
21227Include, immediately after the copyright notices, a license notice
21228giving the public permission to use the Modified Version under the
21229terms of this License, in the form shown in the Addendum below.
21230
21231@item
21232Preserve in that license notice the full lists of Invariant Sections
21233and required Cover Texts given in the Document's license notice.
21234
21235@item
21236Include an unaltered copy of this License.
21237
21238@item
21239Preserve the section entitled ``History'', and its title, and add to
21240it an item stating at least the title, year, new authors, and
21241publisher of the Modified Version as given on the Title Page. If
21242there is no section entitled ``History'' in the Document, create one
21243stating the title, year, authors, and publisher of the Document as
21244given on its Title Page, then add an item describing the Modified
21245Version as stated in the previous sentence.
21246
21247@item
21248Preserve the network location, if any, given in the Document for
21249public access to a Transparent copy of the Document, and likewise
21250the network locations given in the Document for previous versions
21251it was based on. These may be placed in the ``History'' section.
21252You may omit a network location for a work that was published at
21253least four years before the Document itself, or if the original
21254publisher of the version it refers to gives permission.
21255
21256@item
21257In any section entitled ``Acknowledgments'' or ``Dedications'',
21258preserve the section's title, and preserve in the section all the
21259substance and tone of each of the contributor acknowledgments
21260and/or dedications given therein.
21261
21262@item
21263Preserve all the Invariant Sections of the Document,
21264unaltered in their text and in their titles. Section numbers
21265or the equivalent are not considered part of the section titles.
21266
21267@item
21268Delete any section entitled ``Endorsements''. Such a section
21269may not be included in the Modified Version.
21270
21271@item
21272Do not retitle any existing section as ``Endorsements''
21273or to conflict in title with any Invariant Section.
21274@end enumerate
21275
21276If the Modified Version includes new front-matter sections or
21277appendices that qualify as Secondary Sections and contain no material
21278copied from the Document, you may at your option designate some or all
21279of these sections as invariant. To do this, add their titles to the
21280list of Invariant Sections in the Modified Version's license notice.
21281These titles must be distinct from any other section titles.
21282
21283You may add a section entitled ``Endorsements'', provided it contains
21284nothing but endorsements of your Modified Version by various
21285parties---for example, statements of peer review or that the text has
21286been approved by an organization as the authoritative definition of a
21287standard.
21288
21289You may add a passage of up to five words as a Front-Cover Text, and a
21290passage of up to 25 words as a Back-Cover Text, to the end of the list
21291of Cover Texts in the Modified Version. Only one passage of
21292Front-Cover Text and one of Back-Cover Text may be added by (or
21293through arrangements made by) any one entity. If the Document already
21294includes a cover text for the same cover, previously added by you or
21295by arrangement made by the same entity you are acting on behalf of,
21296you may not add another; but you may replace the old one, on explicit
21297permission from the previous publisher that added the old one.
21298
21299The author(s) and publisher(s) of the Document do not by this License
21300give permission to use their names for publicity for or to assert or
21301imply endorsement of any Modified Version.
21302
21303@item
21304COMBINING DOCUMENTS
21305
21306You may combine the Document with other documents released under this
21307License, under the terms defined in section 4 above for modified
21308versions, provided that you include in the combination all of the
21309Invariant Sections of all of the original documents, unmodified, and
21310list them all as Invariant Sections of your combined work in its
21311license notice.
21312
21313The combined work need only contain one copy of this License, and
21314multiple identical Invariant Sections may be replaced with a single
21315copy. If there are multiple Invariant Sections with the same name but
21316different contents, make the title of each such section unique by
21317adding at the end of it, in parentheses, the name of the original
21318author or publisher of that section if known, or else a unique number.
21319Make the same adjustment to the section titles in the list of
21320Invariant Sections in the license notice of the combined work.
21321
21322In the combination, you must combine any sections entitled ``History''
21323in the various original documents, forming one section entitled
21324``History''; likewise combine any sections entitled ``Acknowledgments'',
21325and any sections entitled ``Dedications''. You must delete all sections
21326entitled ``Endorsements.''
21327
21328@item
21329COLLECTIONS OF DOCUMENTS
21330
21331You may make a collection consisting of the Document and other documents
21332released under this License, and replace the individual copies of this
21333License in the various documents with a single copy that is included in
21334the collection, provided that you follow the rules of this License for
21335verbatim copying of each of the documents in all other respects.
21336
21337You may extract a single document from such a collection, and distribute
21338it individually under this License, provided you insert a copy of this
21339License into the extracted document, and follow this License in all
21340other respects regarding verbatim copying of that document.
21341
21342@item
21343AGGREGATION WITH INDEPENDENT WORKS
21344
21345A compilation of the Document or its derivatives with other separate
21346and independent documents or works, in or on a volume of a storage or
21347distribution medium, does not as a whole count as a Modified Version
21348of the Document, provided no compilation copyright is claimed for the
21349compilation. Such a compilation is called an ``aggregate'', and this
21350License does not apply to the other self-contained works thus compiled
21351with the Document, on account of their being thus compiled, if they
21352are not themselves derivative works of the Document.
21353
21354If the Cover Text requirement of section 3 is applicable to these
21355copies of the Document, then if the Document is less than one quarter
21356of the entire aggregate, the Document's Cover Texts may be placed on
21357covers that surround only the Document within the aggregate.
21358Otherwise they must appear on covers around the whole aggregate.
21359
21360@item
21361TRANSLATION
21362
21363Translation is considered a kind of modification, so you may
21364distribute translations of the Document under the terms of section 4.
21365Replacing Invariant Sections with translations requires special
21366permission from their copyright holders, but you may include
21367translations of some or all Invariant Sections in addition to the
21368original versions of these Invariant Sections. You may include a
21369translation of this License provided that you also include the
21370original English version of this License. In case of a disagreement
21371between the translation and the original English version of this
21372License, the original English version will prevail.
21373
21374@item
21375TERMINATION
21376
21377You may not copy, modify, sublicense, or distribute the Document except
21378as expressly provided for under this License. Any other attempt to
21379copy, modify, sublicense or distribute the Document is void, and will
21380automatically terminate your rights under this License. However,
21381parties who have received copies, or rights, from you under this
21382License will not have their licenses terminated so long as such
21383parties remain in full compliance.
21384
21385@item
21386FUTURE REVISIONS OF THIS LICENSE
21387
21388The Free Software Foundation may publish new, revised versions
21389of the GNU Free Documentation License from time to time. Such new
21390versions will be similar in spirit to the present version, but may
21391differ in detail to address new problems or concerns. See
21392@uref{http://www.gnu.org/copyleft/}.
21393
21394Each version of the License is given a distinguishing version number.
21395If the Document specifies that a particular numbered version of this
21396License ``or any later version'' applies to it, you have the option of
21397following the terms and conditions either of that specified version or
21398of any later version that has been published (not as a draft) by the
21399Free Software Foundation. If the Document does not specify a version
21400number of this License, you may choose any version ever published (not
21401as a draft) by the Free Software Foundation.
21402@end enumerate
21403
21404@node Index, About the Author, GNU Free Documentation License, Top
21405@comment node-name, next, previous, up
21406@unnumbered Index
21407
d586ab6c 21408@ignore
8b096dce 21409MENU ENTRY: NODE NAME.
d586ab6c 21410@end ignore
8b096dce
EZ
21411
21412@printindex cp
21413
21414@iftex
21415@c Place biographical information on right-hand (verso) page
21416
21417@tex
21418\ifodd\pageno
21419 \par\vfill\supereject
21420 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21421 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21422 \page\hbox{}\page
21423\else
21424 \par\vfill\supereject
21425 \par\vfill\supereject
21426 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21427 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21428 \page\hbox{}\page
21429 \page\hbox{}\page
21430\fi
21431@end tex
21432
21433@page
21434@w{ }
21435
21436@c ================ Biographical information ================
21437
21438@w{ }
21439@sp 8
21440@center About the Author
21441@sp 1
21442@end iftex
21443
21444@ifnottex
21445@node About the Author, , Index, Top
21446@unnumbered About the Author
21447@end ifnottex
21448
21449@quotation
21450Robert J. Chassell has worked with GNU Emacs since 1985. He writes
21451and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21452world on software freedom. Chassell was a founding Director and
21453Treasurer of the Free Software Foundation, Inc. He is co-author of
21454the @cite{Texinfo} manual, and has edited more than a dozen other
21455books. He graduated from Cambridge University, in England. He has an
21456abiding interest in social and economic history and flies his own
21457airplane.
21458@end quotation
21459
21460@page
21461@w{ }
21462
21463@c Prevent page number on blank verso, so eject it first.
21464@tex
21465\par\vfill\supereject
21466@end tex
21467
21468@iftex
21469@headings off
21470@evenheading @thispage @| @| @thistitle
21471@oddheading @| @| @thispage
21472@end iftex
21473
8b096dce 21474@bye