* progmodes/scheme.el: Add indentation and font-locking for λ.
[bpt/emacs.git] / doc / lispintro / emacs-lisp-intro.texi
CommitLineData
8cda6f8f
GM
1\input texinfo @c -*-texinfo-*-
2@comment %**start of header
fb3dc846 3@setfilename ../../info/eintr
8cda6f8f
GM
4@c setfilename emacs-lisp-intro.info
5@c sethtmlfilename emacs-lisp-intro.html
6@settitle Programming in Emacs Lisp
7@syncodeindex vr cp
8@syncodeindex fn cp
8cda6f8f
GM
9@finalout
10
11@c ---------
12@c <<<< For hard copy printing, this file is now
13@c set for smallbook, which works for all sizes
7877f373 14@c of paper, and with PostScript figures >>>>
a9097c6d
KB
15@set smallbook
16@ifset smallbook
8cda6f8f
GM
17@smallbook
18@clear largebook
a9097c6d 19@end ifset
8cda6f8f
GM
20@set print-postscript-figures
21@c set largebook
22@c clear print-postscript-figures
23@c ---------
24
25@comment %**end of header
26
a9097c6d 27@c per rms and peterb, use 10pt fonts for the main text, mostly to
867d4bb3 28@c save on paper cost.
a9097c6d
KB
29@c Do this inside @tex for now, so current makeinfo does not complain.
30@tex
31@ifset smallbook
32@fonttextsize 10
6e3da0ae 33
a9097c6d
KB
34@end ifset
35\global\hbadness=6666 % don't worry about not-too-underfull boxes
36@end tex
37
6e3da0ae
RC
38@set edition-number 3.10
39@set update-date 28 October 2009
45cf6cbd 40
8cda6f8f
GM
41@ignore
42 ## Summary of shell commands to create various output formats:
43
44 pushd /usr/local/src/emacs/lispintro/
45 ## pushd /u/intro/
46
47 ## Info output
48 makeinfo --paragraph-indent=0 --verbose emacs-lisp-intro.texi
49
50 ## ;; (progn (when (bufferp (get-buffer "*info*")) (kill-buffer "*info*")) (info "/usr/local/src/emacs/info/eintr"))
51
52 ## DVI output
53 texi2dvi emacs-lisp-intro.texi
54
55 ## xdvi -margins 24pt -topmargin 4pt -offsets 24pt -geometry 760x1140 -s 5 -useTeXpages -mousemode 1 emacs-lisp-intro.dvi &
56
57 ## HTML output
58 makeinfo --html --no-split --verbose emacs-lisp-intro.texi
59
60 ## galeon emacs-lisp-intro.html
61
62 ## Plain text output
63 makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
64 --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
65
66 popd
67
68# as user `root'
69# insert thumbdrive
70 mtusb # mount -v -t ext3 /dev/sda /mnt
71 cp -v /u/intro/emacs-lisp-intro.texi /mnt/backup/intro/emacs-lisp-intro.texi
72 umtusb # umount -v /mnt
73# remove thumbdrive
74
75 ## Other shell commands
76
77 pushd /usr/local/src/emacs/lispintro/
78 ## pushd /u/intro/
79
80 ## PDF
81 texi2dvi --pdf emacs-lisp-intro.texi
82 # xpdf emacs-lisp-intro.pdf &
83
84 ## DocBook -- note file extension
85 makeinfo --docbook --no-split --paragraph-indent=0 \
86 --verbose --output=emacs-lisp-intro.docbook emacs-lisp-intro.texi
87
88 ## XML with a Texinfo DTD -- note file extension
89 makeinfo --xml --no-split --paragraph-indent=0 \
90 --verbose --output=emacs-lisp-intro.texinfoxml emacs-lisp-intro.texi
91
92 ## PostScript (needs DVI)
93 # gv emacs-lisp-intro.ps &
94 # Create DVI if we lack it
95 # texi2dvi emacs-lisp-intro.texi
96 dvips emacs-lisp-intro.dvi -o emacs-lisp-intro.ps
97
98 ## RTF (needs HTML)
99 # Use OpenOffice to view RTF
100 # Create HTML if we lack it
101 # makeinfo --no-split --html emacs-lisp-intro.texi
102 /usr/local/src/html2rtf.pl emacs-lisp-intro.html
103
104 ## LaTeX (needs RTF)
105 /usr/bin/rtf2latex emacs-lisp-intro.rtf
106
107 popd
108
109@end ignore
110
111@c ================ Included Figures ================
112
113@c Set print-postscript-figures if you print PostScript figures.
114@c If you clear this, the ten figures will be printed as ASCII diagrams.
115@c (This is not relevant to Info, since Info only handles ASCII.)
116@c Your site may require editing changes to print PostScript; in this
117@c case, search for `print-postscript-figures' and make appropriate changes.
118
119@c ================ How to Create an Info file ================
120
121@c If you have `makeinfo' installed, run the following command
122
123@c makeinfo emacs-lisp-intro.texi
124
125@c or, if you want a single, large Info file, and no paragraph indents:
126@c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
127
128@c After creating the Info file, edit your Info `dir' file, if the
129@c `dircategory' section below does not enable your system to
130@c install the manual automatically.
131@c (The `dir' file is often in the `/usr/local/share/info/' directory.)
132
133@c ================ How to Create an HTML file ================
134
135@c To convert to HTML format
136@c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
137
138@c ================ How to Print a Book in Various Sizes ================
139
140@c This book can be printed in any of three different sizes.
141@c In the above header, set @-commands appropriately.
142
143@c 7 by 9.25 inches:
144@c @smallbook
145@c @clear largebook
146
147@c 8.5 by 11 inches:
148@c @c smallbook
149@c @set largebook
150
151@c European A4 size paper:
152@c @c smallbook
153@c @afourpaper
154@c @set largebook
155
156@c ================ How to Typeset and Print ================
157
158@c If you do not include PostScript figures, run either of the
159@c following command sequences, or similar commands suited to your
160@c system:
161
162@c texi2dvi emacs-lisp-intro.texi
163@c lpr -d emacs-lisp-intro.dvi
164
165@c or else:
166
167@c tex emacs-lisp-intro.texi
168@c texindex emacs-lisp-intro.??
169@c tex emacs-lisp-intro.texi
170@c lpr -d emacs-lisp-intro.dvi
171
172@c If you include the PostScript figures, and you have old software,
173@c you may need to convert the .dvi file to a .ps file before
174@c printing. Run either of the following command sequences, or one
175@c similar:
176@c
177@c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
178@c
179@c or else:
180@c
181@c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
182@c
183
184@c (Note: if you edit the book so as to change the length of the
185@c table of contents, you may have to change the value of `pageno' below.)
186
187@c ================ End of Formatting Sections ================
188
189@c For next or subsequent edition:
190@c create function using with-output-to-temp-buffer
191@c create a major mode, with keymaps
192@c run an asynchronous process, like grep or diff
193
194@c For 8.5 by 11 inch format: do not use such a small amount of
195@c whitespace between paragraphs as smallbook format
196@ifset largebook
197@tex
198\global\parskip 6pt plus 1pt
199@end tex
200@end ifset
201
202@c For all sized formats: print within-book cross
203@c reference with ``...'' rather than [...]
204
205@c This works with the texinfo.tex file, version 2003-05-04.08,
206@c in the Texinfo version 4.6 of the 2003 Jun 13 distribution.
207
208@tex
209\if \xrefprintnodename
210 \global\def\xrefprintnodename#1{\unskip, ``#1''}
211 \else
212 \global\def\xrefprintnodename#1{ ``#1''}
213\fi
214% \global\def\xrefprintnodename#1{, ``#1''}
215@end tex
216
217@c ----------------------------------------------------
218
e979a521 219@dircategory GNU Emacs Lisp
8cda6f8f
GM
220@direntry
221* Emacs Lisp Intro: (eintr).
222 A simple introduction to Emacs Lisp programming.
223@end direntry
224
225@copying
226This is an @cite{Introduction to Programming in Emacs Lisp}, for
227people who are not programmers.
228@sp 1
229Edition @value{edition-number}, @value{update-date}
c0765905
GM
230@ifset WWW_GNU_ORG
231@html
232<p>The homepage for GNU Emacs is at
233<a href="http://www.gnu.org/software/emacs/">http://www.gnu.org/software/emacs/</a>.
234<br>To view this manual in other formats, click
235<a href="/software/emacs/emacs-lisp-intro/emacs-lisp-intro.html">here</a>.
236@end html
237@end ifset
8cda6f8f 238@sp 1
ab422c4d 239Copyright @copyright{} 1990--1995, 1997, 2001--2013 Free Software
f99f1641 240Foundation, Inc.
8cda6f8f
GM
241@sp 1
242
243@iftex
244Published by the:@*
245
aa89a0ef
GM
246GNU Press, @hfill @uref{http://www.fsf.org/campaigns/gnu-press/}@*
247a division of the @hfill email: @email{sales@@fsf.org}@*
248Free Software Foundation, Inc. @hfill Tel: +1 (617) 542-5942@*
24951 Franklin Street, Fifth Floor @hfill Fax: +1 (617) 542-2652@*
72ec96fb 250Boston, MA 02110-1301 USA
8cda6f8f
GM
251@end iftex
252
253@ifnottex
254Published by the:
255
256@example
aa89a0ef
GM
257GNU Press, http://www.fsf.org/campaigns/gnu-press/
258a division of the email: sales@@fsf.org
259Free Software Foundation, Inc. Tel: +1 (617) 542-5942
26051 Franklin Street, Fifth Floor Fax: +1 (617) 542-2652
72ec96fb 261Boston, MA 02110-1301 USA
8cda6f8f
GM
262@end example
263@end ifnottex
264
265@sp 1
aa89a0ef 266@c Printed copies are available from @uref{http://shop.fsf.org/} for $35 each.@*
8cda6f8f
GM
267ISBN 1-882114-43-4
268
269Permission is granted to copy, distribute and/or modify this document
e41dfb1e 270under the terms of the GNU Free Documentation License, Version 1.3 or
8cda6f8f
GM
271any later version published by the Free Software Foundation; there
272being no Invariant Section, with the Front-Cover Texts being ``A GNU
273Manual'', and with the Back-Cover Texts as in (a) below. A copy of
274the license is included in the section entitled ``GNU Free
275Documentation License''.
276
868a6b71
RC
277(a) The FSF's Back-Cover Text is: ``You have the freedom to
278copy and modify this GNU manual. Buying copies from the FSF
279supports it in developing GNU and promoting software freedom.''
8cda6f8f
GM
280@end copying
281
282@c half title; two lines here, so do not use `shorttitlepage'
283@tex
284{\begingroup%
285 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
286 \endgroup}%
287{\begingroup\hbox{}\vskip 0.25in \chaprm%
288 \centerline{Programming in Emacs Lisp}%
289 \endgroup\page\hbox{}\page}
290@end tex
291
292@titlepage
293@sp 6
294@center @titlefont{An Introduction to}
295@sp 2
296@center @titlefont{Programming in Emacs Lisp}
297@sp 2
298@center Revised Third Edition
299@sp 4
300@center by Robert J. Chassell
301
302@page
303@vskip 0pt plus 1filll
304@insertcopying
305@end titlepage
306
307@iftex
308@headings off
309@evenheading @thispage @| @| @thischapter
310@oddheading @thissection @| @| @thispage
311@end iftex
312
313@ifnothtml
314@c Keep T.O.C. short by tightening up for largebook
315@ifset largebook
316@tex
317\global\parskip 2pt plus 1pt
318\global\advance\baselineskip by -1pt
319@end tex
320@end ifset
321@end ifnothtml
322
323@shortcontents
324@contents
325
326@ifnottex
d6adf7e7 327@node Top
8cda6f8f
GM
328@top An Introduction to Programming in Emacs Lisp
329
330@insertcopying
331
332This master menu first lists each chapter and index; then it lists
333every node in every chapter.
334@end ifnottex
335
336@c >>>> Set pageno appropriately <<<<
337
338@c The first page of the Preface is a roman numeral; it is the first
339@c right handed page after the Table of Contents; hence the following
340@c setting must be for an odd negative number.
341
a9097c6d
KB
342@c iftex
343@c global@pageno = -11
344@c end iftex
8cda6f8f 345
cb97cd2a
AS
346@set COUNT-WORDS count-words-example
347@c Length of variable name chosen so that things still line up when expanded.
348
8cda6f8f
GM
349@menu
350* Preface:: What to look for.
351* List Processing:: What is Lisp?
352* Practicing Evaluation:: Running several programs.
353* Writing Defuns:: How to write function definitions.
354* Buffer Walk Through:: Exploring a few buffer-related functions.
355* More Complex:: A few, even more complex functions.
356* Narrowing & Widening:: Restricting your and Emacs attention to
357 a region.
358* car cdr & cons:: Fundamental functions in Lisp.
359* Cutting & Storing Text:: Removing text and saving it.
360* List Implementation:: How lists are implemented in the computer.
361* Yanking:: Pasting stored text.
362* Loops & Recursion:: How to repeat a process.
363* Regexp Search:: Regular expression searches.
364* Counting Words:: A review of repetition and regexps.
365* Words in a defun:: Counting words in a @code{defun}.
366* Readying a Graph:: A prototype graph printing function.
367* Emacs Initialization:: How to write a @file{.emacs} file.
368* Debugging:: How to run the Emacs Lisp debuggers.
369* Conclusion:: Now you have the basics.
370* the-the:: An appendix: how to find reduplicated words.
371* Kill Ring:: An appendix: how the kill ring works.
09e80d9f 372* Full Graph:: How to create a graph with labeled axes.
8cda6f8f
GM
373* Free Software and Free Manuals::
374* GNU Free Documentation License::
375* Index::
376* About the Author::
377
378@detailmenu
379 --- The Detailed Node Listing ---
380
381Preface
382
383* Why:: Why learn Emacs Lisp?
384* On Reading this Text:: Read, gain familiarity, pick up habits....
385* Who You Are:: For whom this is written.
386* Lisp History::
387* Note for Novices:: You can read this as a novice.
388* Thank You::
389
390List Processing
391
392* Lisp Lists:: What are lists?
393* Run a Program:: Any list in Lisp is a program ready to run.
394* Making Errors:: Generating an error message.
395* Names & Definitions:: Names of symbols and function definitions.
396* Lisp Interpreter:: What the Lisp interpreter does.
397* Evaluation:: Running a program.
398* Variables:: Returning a value from a variable.
399* Arguments:: Passing information to a function.
400* set & setq:: Setting the value of a variable.
401* Summary:: The major points.
402* Error Message Exercises::
403
404Lisp Lists
405
406* Numbers Lists:: List have numbers, other lists, in them.
407* Lisp Atoms:: Elemental entities.
408* Whitespace in Lists:: Formatting lists to be readable.
409* Typing Lists:: How GNU Emacs helps you type lists.
410
411The Lisp Interpreter
412
413* Complications:: Variables, Special forms, Lists within.
414* Byte Compiling:: Specially processing code for speed.
415
416Evaluation
417
418* How the Interpreter Acts:: Returns and Side Effects...
419* Evaluating Inner Lists:: Lists within lists...
420
421Variables
422
423* fill-column Example::
424* Void Function:: The error message for a symbol
425 without a function.
426* Void Variable:: The error message for a symbol without a value.
427
428Arguments
429
430* Data types:: Types of data passed to a function.
431* Args as Variable or List:: An argument can be the value
432 of a variable or list.
433* Variable Number of Arguments:: Some functions may take a
434 variable number of arguments.
435* Wrong Type of Argument:: Passing an argument of the wrong type
436 to a function.
437* message:: A useful function for sending messages.
438
439Setting the Value of a Variable
440
441* Using set:: Setting values.
442* Using setq:: Setting a quoted value.
443* Counting:: Using @code{setq} to count.
444
445Practicing Evaluation
446
447* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
448 causes evaluation.
449* Buffer Names:: Buffers and files are different.
450* Getting Buffers:: Getting a buffer itself, not merely its name.
451* Switching Buffers:: How to change to another buffer.
452* Buffer Size & Locations:: Where point is located and the size of
453 the buffer.
454* Evaluation Exercise::
455
456How To Write Function Definitions
457
458* Primitive Functions::
459* defun:: The @code{defun} special form.
460* Install:: Install a function definition.
461* Interactive:: Making a function interactive.
462* Interactive Options:: Different options for @code{interactive}.
463* Permanent Installation:: Installing code permanently.
464* let:: Creating and initializing local variables.
465* if:: What if?
466* else:: If--then--else expressions.
467* Truth & Falsehood:: What Lisp considers false and true.
468* save-excursion:: Keeping track of point, mark, and buffer.
469* Review::
470* defun Exercises::
471
472Install a Function Definition
473
474* Effect of installation::
475* Change a defun:: How to change a function definition.
476
477Make a Function Interactive
478
479* Interactive multiply-by-seven:: An overview.
480* multiply-by-seven in detail:: The interactive version.
481
482@code{let}
483
484* Prevent confusion::
485* Parts of let Expression::
486* Sample let Expression::
487* Uninitialized let Variables::
488
489The @code{if} Special Form
490
491* if in more detail::
492* type-of-animal in detail:: An example of an @code{if} expression.
493
494Truth and Falsehood in Emacs Lisp
495
496* nil explained:: @code{nil} has two meanings.
497
498@code{save-excursion}
499
500* Point and mark:: A review of various locations.
501* Template for save-excursion::
502
503A Few Buffer--Related Functions
504
505* Finding More:: How to find more information.
506* simplified-beginning-of-buffer:: Shows @code{goto-char},
507 @code{point-min}, and @code{push-mark}.
508* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
509* append-to-buffer:: Uses @code{save-excursion} and
510 @code{insert-buffer-substring}.
511* Buffer Related Review:: Review.
512* Buffer Exercises::
513
514The Definition of @code{mark-whole-buffer}
515
516* mark-whole-buffer overview::
517* Body of mark-whole-buffer:: Only three lines of code.
518
519The Definition of @code{append-to-buffer}
520
521* append-to-buffer overview::
522* append interactive:: A two part interactive expression.
523* append-to-buffer body:: Incorporates a @code{let} expression.
524* append save-excursion:: How the @code{save-excursion} works.
525
526A Few More Complex Functions
527
528* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
529* insert-buffer:: Read-only, and with @code{or}.
530* beginning-of-buffer:: Shows @code{goto-char},
531 @code{point-min}, and @code{push-mark}.
532* Second Buffer Related Review::
533* optional Exercise::
534
535The Definition of @code{insert-buffer}
536
537* insert-buffer code::
538* insert-buffer interactive:: When you can read, but not write.
539* insert-buffer body:: The body has an @code{or} and a @code{let}.
540* if & or:: Using an @code{if} instead of an @code{or}.
541* Insert or:: How the @code{or} expression works.
542* Insert let:: Two @code{save-excursion} expressions.
543* New insert-buffer::
544
545The Interactive Expression in @code{insert-buffer}
546
547* Read-only buffer:: When a buffer cannot be modified.
548* b for interactive:: An existing buffer or else its name.
549
550Complete Definition of @code{beginning-of-buffer}
551
552* Optional Arguments::
553* beginning-of-buffer opt arg:: Example with optional argument.
554* beginning-of-buffer complete::
555
556@code{beginning-of-buffer} with an Argument
557
558* Disentangle beginning-of-buffer::
559* Large buffer case::
560* Small buffer case::
561
562Narrowing and Widening
563
564* Narrowing advantages:: The advantages of narrowing
565* save-restriction:: The @code{save-restriction} special form.
566* what-line:: The number of the line that point is on.
567* narrow Exercise::
568
569@code{car}, @code{cdr}, @code{cons}: Fundamental Functions
570
571* Strange Names:: An historical aside: why the strange names?
572* car & cdr:: Functions for extracting part of a list.
573* cons:: Constructing a list.
574* nthcdr:: Calling @code{cdr} repeatedly.
575* nth::
576* setcar:: Changing the first element of a list.
577* setcdr:: Changing the rest of a list.
578* cons Exercise::
579
580@code{cons}
581
582* Build a list::
583* length:: How to find the length of a list.
584
585Cutting and Storing Text
586
587* Storing Text:: Text is stored in a list.
588* zap-to-char:: Cutting out text up to a character.
589* kill-region:: Cutting text out of a region.
590* copy-region-as-kill:: A definition for copying text.
591* Digression into C:: Minor note on C programming language macros.
592* defvar:: How to give a variable an initial value.
593* cons & search-fwd Review::
594* search Exercises::
595
596@code{zap-to-char}
597
598* Complete zap-to-char:: The complete implementation.
599* zap-to-char interactive:: A three part interactive expression.
600* zap-to-char body:: A short overview.
601* search-forward:: How to search for a string.
602* progn:: The @code{progn} special form.
603* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
604
605@code{kill-region}
606
607* Complete kill-region:: The function definition.
608* condition-case:: Dealing with a problem.
609* Lisp macro::
610
611@code{copy-region-as-kill}
612
613* Complete copy-region-as-kill:: The complete function definition.
614* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
615
616The Body of @code{copy-region-as-kill}
617
618* last-command & this-command::
619* kill-append function::
620* kill-new function::
621
622Initializing a Variable with @code{defvar}
623
624* See variable current value::
625* defvar and asterisk::
626
627How Lists are Implemented
628
629* Lists diagrammed::
630* Symbols as Chest:: Exploring a powerful metaphor.
631* List Exercise::
632
633Yanking Text Back
634
635* Kill Ring Overview::
636* kill-ring-yank-pointer:: The kill ring is a list.
637* yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
638
639Loops and Recursion
640
641* while:: Causing a stretch of code to repeat.
642* dolist dotimes::
643* Recursion:: Causing a function to call itself.
644* Looping exercise::
645
646@code{while}
647
648* Looping with while:: Repeat so long as test returns true.
649* Loop Example:: A @code{while} loop that uses a list.
650* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
651* Incrementing Loop:: A loop with an incrementing counter.
652* Incrementing Loop Details::
653* Decrementing Loop:: A loop with a decrementing counter.
654
655Details of an Incrementing Loop
656
657* Incrementing Example:: Counting pebbles in a triangle.
658* Inc Example parts:: The parts of the function definition.
659* Inc Example altogether:: Putting the function definition together.
660
661Loop with a Decrementing Counter
662
663* Decrementing Example:: More pebbles on the beach.
664* Dec Example parts:: The parts of the function definition.
665* Dec Example altogether:: Putting the function definition together.
666
667Save your time: @code{dolist} and @code{dotimes}
668
669* dolist::
670* dotimes::
671
672Recursion
673
674* Building Robots:: Same model, different serial number ...
675* Recursive Definition Parts:: Walk until you stop ...
676* Recursion with list:: Using a list as the test whether to recurse.
677* Recursive triangle function::
678* Recursion with cond::
679* Recursive Patterns:: Often used templates.
680* No Deferment:: Don't store up work ...
681* No deferment solution::
682
683Recursion in Place of a Counter
684
685* Recursive Example arg of 1 or 2::
686* Recursive Example arg of 3 or 4::
687
688Recursive Patterns
689
690* Every::
691* Accumulate::
692* Keep::
693
694Regular Expression Searches
695
696* sentence-end:: The regular expression for @code{sentence-end}.
697* re-search-forward:: Very similar to @code{search-forward}.
698* forward-sentence:: A straightforward example of regexp search.
699* forward-paragraph:: A somewhat complex example.
700* etags:: How to create your own @file{TAGS} table.
701* Regexp Review::
702* re-search Exercises::
703
704@code{forward-sentence}
705
706* Complete forward-sentence::
707* fwd-sentence while loops:: Two @code{while} loops.
708* fwd-sentence re-search:: A regular expression search.
709
710@code{forward-paragraph}: a Goldmine of Functions
711
712* forward-paragraph in brief:: Key parts of the function definition.
713* fwd-para let:: The @code{let*} expression.
714* fwd-para while:: The forward motion @code{while} loop.
715
716Counting: Repetition and Regexps
717
718* Why Count Words::
ea4f7750 719* @value{COUNT-WORDS}:: Use a regexp, but find a problem.
8cda6f8f
GM
720* recursive-count-words:: Start with case of no words in region.
721* Counting Exercise::
722
ea4f7750 723The @code{@value{COUNT-WORDS}} Function
8cda6f8f 724
ea4f7750
GM
725* Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
726* Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
727
728Counting Words in a @code{defun}
729
730* Divide and Conquer::
731* Words and Symbols:: What to count?
732* Syntax:: What constitutes a word or symbol?
ea4f7750 733* count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
734* Several defuns:: Counting several defuns in a file.
735* Find a File:: Do you want to look at a file?
736* lengths-list-file:: A list of the lengths of many definitions.
737* Several files:: Counting in definitions in different files.
738* Several files recursively:: Recursively counting in different files.
739* Prepare the data:: Prepare the data for display in a graph.
740
741Count Words in @code{defuns} in Different Files
742
743* lengths-list-many-files:: Return a list of the lengths of defuns.
744* append:: Attach one list to another.
745
746Prepare the Data for Display in a Graph
747
748* Data for Display in Detail::
749* Sorting:: Sorting lists.
750* Files List:: Making a list of files.
751* Counting function definitions::
752
753Readying a Graph
754
755* Columns of a graph::
756* graph-body-print:: How to print the body of a graph.
757* recursive-graph-body-print::
758* Printed Axes::
759* Line Graph Exercise::
760
761Your @file{.emacs} File
762
763* Default Configuration::
764* Site-wide Init:: You can write site-wide init files.
765* defcustom:: Emacs will write code for you.
766* Beginning a .emacs File:: How to write a @code{.emacs file}.
767* Text and Auto-fill:: Automatically wrap lines.
768* Mail Aliases:: Use abbreviations for email addresses.
769* Indent Tabs Mode:: Don't use tabs with @TeX{}
770* Keybindings:: Create some personal keybindings.
771* Keymaps:: More about key binding.
772* Loading Files:: Load (i.e., evaluate) files automatically.
773* Autoload:: Make functions available.
774* Simple Extension:: Define a function; bind it to a key.
775* X11 Colors:: Colors in X.
776* Miscellaneous::
777* Mode Line:: How to customize your mode line.
778
779Debugging
780
781* debug:: How to use the built-in debugger.
782* debug-on-entry:: Start debugging when you call a function.
783* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
784* edebug:: How to use Edebug, a source level debugger.
785* Debugging Exercises::
786
787Handling the Kill Ring
788
789* What the Kill Ring Does::
790* current-kill::
791* yank:: Paste a copy of a clipped element.
792* yank-pop:: Insert element pointed to.
793* ring file::
794
795The @code{current-kill} Function
796
45d77375 797* Code for current-kill::
8cda6f8f
GM
798* Understanding current-kill::
799
800@code{current-kill} in Outline
801
802* Body of current-kill::
803* Digression concerning error:: How to mislead humans, but not computers.
804* Determining the Element::
805
09e80d9f 806A Graph with Labeled Axes
8cda6f8f 807
09e80d9f 808* Labeled Example::
8cda6f8f
GM
809* print-graph Varlist:: @code{let} expression in @code{print-graph}.
810* print-Y-axis:: Print a label for the vertical axis.
811* print-X-axis:: Print a horizontal label.
812* Print Whole Graph:: The function to print a complete graph.
813
814The @code{print-Y-axis} Function
815
816* print-Y-axis in Detail::
817* Height of label:: What height for the Y axis?
818* Compute a Remainder:: How to compute the remainder of a division.
819* Y Axis Element:: Construct a line for the Y axis.
820* Y-axis-column:: Generate a list of Y axis labels.
821* print-Y-axis Penultimate:: A not quite final version.
822
823The @code{print-X-axis} Function
824
825* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
826* X Axis Tic Marks:: Create tic marks for the horizontal axis.
827
828Printing the Whole Graph
829
830* The final version:: A few changes.
831* Test print-graph:: Run a short test.
832* Graphing words in defuns:: Executing the final code.
833* lambda:: How to write an anonymous function.
834* mapcar:: Apply a function to elements of a list.
835* Another Bug:: Yet another bug @dots{} most insidious.
836* Final printed graph:: The graph itself!
837
838@end detailmenu
839@end menu
840
d6adf7e7 841@node Preface
8cda6f8f
GM
842@unnumbered Preface
843
844Most of the GNU Emacs integrated environment is written in the programming
845language called Emacs Lisp. The code written in this programming
846language is the software---the sets of instructions---that tell the
847computer what to do when you give it commands. Emacs is designed so
848that you can write new code in Emacs Lisp and easily install it as an
849extension to the editor.
850
851(GNU Emacs is sometimes called an ``extensible editor'', but it does
852much more than provide editing capabilities. It is better to refer to
853Emacs as an ``extensible computing environment''. However, that
854phrase is quite a mouthful. It is easier to refer to Emacs simply as
855an editor. Moreover, everything you do in Emacs---find the Mayan date
856and phases of the moon, simplify polynomials, debug code, manage
857files, read letters, write books---all these activities are kinds of
858editing in the most general sense of the word.)
859
860@menu
861* Why:: Why learn Emacs Lisp?
862* On Reading this Text:: Read, gain familiarity, pick up habits....
863* Who You Are:: For whom this is written.
864* Lisp History::
865* Note for Novices:: You can read this as a novice.
866* Thank You::
867@end menu
868
8cda6f8f 869@ifnottex
d6adf7e7 870@node Why
8cda6f8f
GM
871@unnumberedsec Why Study Emacs Lisp?
872@end ifnottex
873
874Although Emacs Lisp is usually thought of in association only with Emacs,
875it is a full computer programming language. You can use Emacs Lisp as
876you would any other programming language.
877
878Perhaps you want to understand programming; perhaps you want to extend
879Emacs; or perhaps you want to become a programmer. This introduction to
880Emacs Lisp is designed to get you started: to guide you in learning the
881fundamentals of programming, and more importantly, to show you how you
882can teach yourself to go further.
883
d6adf7e7 884@node On Reading this Text
8cda6f8f
GM
885@unnumberedsec On Reading this Text
886
887All through this document, you will see little sample programs you can
888run inside of Emacs. If you read this document in Info inside of GNU
889Emacs, you can run the programs as they appear. (This is easy to do and
890is explained when the examples are presented.) Alternatively, you can
891read this introduction as a printed book while sitting beside a computer
892running Emacs. (This is what I like to do; I like printed books.) If
893you don't have a running Emacs beside you, you can still read this book,
894but in this case, it is best to treat it as a novel or as a travel guide
895to a country not yet visited: interesting, but not the same as being
896there.
897
40ba43b4 898Much of this introduction is dedicated to walkthroughs or guided tours
8cda6f8f
GM
899of code used in GNU Emacs. These tours are designed for two purposes:
900first, to give you familiarity with real, working code (code you use
901every day); and, second, to give you familiarity with the way Emacs
902works. It is interesting to see how a working environment is
903implemented.
904Also, I
905hope that you will pick up the habit of browsing through source code.
906You can learn from it and mine it for ideas. Having GNU Emacs is like
907having a dragon's cave of treasures.
908
909In addition to learning about Emacs as an editor and Emacs Lisp as a
910programming language, the examples and guided tours will give you an
911opportunity to get acquainted with Emacs as a Lisp programming
912environment. GNU Emacs supports programming and provides tools that
913you will want to become comfortable using, such as @kbd{M-.} (the key
914which invokes the @code{find-tag} command). You will also learn about
915buffers and other objects that are part of the environment.
916Learning about these features of Emacs is like learning new routes
917around your home town.
918
919@ignore
920In addition, I have written several programs as extended examples.
921Although these are examples, the programs are real. I use them.
922Other people use them. You may use them. Beyond the fragments of
923programs used for illustrations, there is very little in here that is
924`just for teaching purposes'; what you see is used. This is a great
925advantage of Emacs Lisp: it is easy to learn to use it for work.
926@end ignore
927
928Finally, I hope to convey some of the skills for using Emacs to
929learn aspects of programming that you don't know. You can often use
930Emacs to help you understand what puzzles you or to find out how to do
931something new. This self-reliance is not only a pleasure, but an
932advantage.
933
d6adf7e7 934@node Who You Are
8cda6f8f
GM
935@unnumberedsec For Whom This is Written
936
937This text is written as an elementary introduction for people who are
938not programmers. If you are a programmer, you may not be satisfied with
939this primer. The reason is that you may have become expert at reading
940reference manuals and be put off by the way this text is organized.
941
942An expert programmer who reviewed this text said to me:
943
944@quotation
945@i{I prefer to learn from reference manuals. I ``dive into'' each
946paragraph, and ``come up for air'' between paragraphs.}
947
948@i{When I get to the end of a paragraph, I assume that that subject is
949done, finished, that I know everything I need (with the
950possible exception of the case when the next paragraph starts talking
951about it in more detail). I expect that a well written reference manual
952will not have a lot of redundancy, and that it will have excellent
953pointers to the (one) place where the information I want is.}
954@end quotation
955
956This introduction is not written for this person!
957
958Firstly, I try to say everything at least three times: first, to
959introduce it; second, to show it in context; and third, to show it in a
960different context, or to review it.
961
962Secondly, I hardly ever put all the information about a subject in one
963place, much less in one paragraph. To my way of thinking, that imposes
964too heavy a burden on the reader. Instead I try to explain only what
965you need to know at the time. (Sometimes I include a little extra
966information so you won't be surprised later when the additional
967information is formally introduced.)
968
969When you read this text, you are not expected to learn everything the
970first time. Frequently, you need only make, as it were, a `nodding
971acquaintance' with some of the items mentioned. My hope is that I have
972structured the text and given you enough hints that you will be alert to
973what is important, and concentrate on it.
974
975You will need to ``dive into'' some paragraphs; there is no other way
976to read them. But I have tried to keep down the number of such
977paragraphs. This book is intended as an approachable hill, rather than
978as a daunting mountain.
979
980This introduction to @cite{Programming in Emacs Lisp} has a companion
981document,
982@iftex
983@cite{The GNU Emacs Lisp Reference Manual}.
984@end iftex
985@ifnottex
986@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
987Emacs Lisp Reference Manual}.
988@end ifnottex
989The reference manual has more detail than this introduction. In the
990reference manual, all the information about one topic is concentrated
991in one place. You should turn to it if you are like the programmer
992quoted above. And, of course, after you have read this
993@cite{Introduction}, you will find the @cite{Reference Manual} useful
994when you are writing your own programs.
995
d6adf7e7 996@node Lisp History
8cda6f8f
GM
997@unnumberedsec Lisp History
998@cindex Lisp history
999
1000Lisp was first developed in the late 1950s at the Massachusetts
1001Institute of Technology for research in artificial intelligence. The
1002great power of the Lisp language makes it superior for other purposes as
1003well, such as writing editor commands and integrated environments.
1004
1005@cindex Maclisp
1006@cindex Common Lisp
1007GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1008in the 1960s. It is somewhat inspired by Common Lisp, which became a
1009standard in the 1980s. However, Emacs Lisp is much simpler than Common
1010Lisp. (The standard Emacs distribution contains an optional extensions
1011file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1012
d6adf7e7 1013@node Note for Novices
8cda6f8f
GM
1014@unnumberedsec A Note for Novices
1015
1016If you don't know GNU Emacs, you can still read this document
1017profitably. However, I recommend you learn Emacs, if only to learn to
1018move around your computer screen. You can teach yourself how to use
1019Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1020means you press and release the @key{CTRL} key and the @kbd{h} at the
1021same time, and then press and release @kbd{t}.)
1022
44e97401 1023Also, I often refer to one of Emacs's standard commands by listing the
8cda6f8f
GM
1024keys which you press to invoke the command and then giving the name of
1025the command in parentheses, like this: @kbd{M-C-\}
1026(@code{indent-region}). What this means is that the
1027@code{indent-region} command is customarily invoked by typing
1028@kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1029invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1030Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1031@key{META} key, @key{CTRL} key and @key{\} key all at the same time.
09e80d9f 1032(On many modern keyboards the @key{META} key is labeled
8cda6f8f
GM
1033@key{ALT}.)
1034Sometimes a combination like this is called a keychord, since it is
1035similar to the way you play a chord on a piano. If your keyboard does
1036not have a @key{META} key, the @key{ESC} key prefix is used in place
1037of it. In this case, @kbd{M-C-\} means that you press and release your
1038@key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1039the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
09e80d9f 1040along with the key that is labeled @key{ALT} and, at the same time,
8cda6f8f
GM
1041press the @key{\} key.
1042
1043In addition to typing a lone keychord, you can prefix what you type
1044with @kbd{C-u}, which is called the `universal argument'. The
1045@kbd{C-u} keychord passes an argument to the subsequent command.
1046Thus, to indent a region of plain text by 6 spaces, mark the region,
1047and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1048Emacs either passes the number 4 to the command or otherwise runs the
1049command differently than it would otherwise.) @xref{Arguments, ,
1050Numeric Arguments, emacs, The GNU Emacs Manual}.
1051
1052If you are reading this in Info using GNU Emacs, you can read through
1053this whole document just by pressing the space bar, @key{SPC}.
1054(To learn about Info, type @kbd{C-h i} and then select Info.)
1055
1056A note on terminology: when I use the word Lisp alone, I often am
1057referring to the various dialects of Lisp in general, but when I speak
1058of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1059
d6adf7e7 1060@node Thank You
8cda6f8f
GM
1061@unnumberedsec Thank You
1062
1063My thanks to all who helped me with this book. My especial thanks to
1064@r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1df7defd 1065McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.
8cda6f8f
GM
1066Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1067@w{Philip Johnson} and @w{David Stampe} for their patient
1068encouragement. My mistakes are my own.
1069
1070@flushright
1071Robert J. Chassell
4724cafb 1072@email{bob@@gnu.org}
8cda6f8f
GM
1073@end flushright
1074
1075@c ================ Beginning of main text ================
1076
1077@c Start main text on right-hand (verso) page
1078
1079@tex
1080\par\vfill\supereject
1081\headings off
1082\ifodd\pageno
1083 \par\vfill\supereject
1084\else
1085 \par\vfill\supereject
1086 \page\hbox{}\page
1087 \par\vfill\supereject
1088\fi
1089@end tex
1090
52af8e0a
GM
1091@c Note: this resetting of the page number back to 1 causes TeX to gripe
1092@c about already having seen page numbers 1-4 before (in the preface):
1093@c pdfTeX warning (ext4): destination with the same identifier (name{1})
1094@c has been already used, duplicate ignored
1095@c I guess that is harmless (what happens if a later part of the text
1096@c makes a link to something in the first 4 pages though?).
1df7defd 1097@c E.g., note that the Emacs manual has a preface, but does not bother
52af8e0a 1098@c resetting the page numbers back to 1 after that.
8cda6f8f
GM
1099@iftex
1100@headings off
1101@evenheading @thispage @| @| @thischapter
1102@oddheading @thissection @| @| @thispage
1103@global@pageno = 1
1104@end iftex
1105
d6adf7e7 1106@node List Processing
8cda6f8f
GM
1107@chapter List Processing
1108
1109To the untutored eye, Lisp is a strange programming language. In Lisp
1110code there are parentheses everywhere. Some people even claim that
1111the name stands for `Lots of Isolated Silly Parentheses'. But the
1112claim is unwarranted. Lisp stands for LISt Processing, and the
1113programming language handles @emph{lists} (and lists of lists) by
1114putting them between parentheses. The parentheses mark the boundaries
1115of the list. Sometimes a list is preceded by a single apostrophe or
1116quotation mark, @samp{'}@footnote{The single apostrophe or quotation
1117mark is an abbreviation for the function @code{quote}; you need not
1118think about functions now; functions are defined in @ref{Making
1119Errors, , Generate an Error Message}.} Lists are the basis of Lisp.
1120
1121@menu
1122* Lisp Lists:: What are lists?
1123* Run a Program:: Any list in Lisp is a program ready to run.
1124* Making Errors:: Generating an error message.
1125* Names & Definitions:: Names of symbols and function definitions.
1126* Lisp Interpreter:: What the Lisp interpreter does.
1127* Evaluation:: Running a program.
1128* Variables:: Returning a value from a variable.
1129* Arguments:: Passing information to a function.
1130* set & setq:: Setting the value of a variable.
1131* Summary:: The major points.
1132* Error Message Exercises::
1133@end menu
1134
d6adf7e7 1135@node Lisp Lists
8cda6f8f
GM
1136@section Lisp Lists
1137@cindex Lisp Lists
1138
1139In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1140This list is preceded by a single apostrophe. It could just as well be
1141written as follows, which looks more like the kind of list you are likely
1142to be familiar with:
1143
1144@smallexample
1145@group
1146'(rose
1147 violet
1148 daisy
1149 buttercup)
1150@end group
1151@end smallexample
1152
1153@noindent
1154The elements of this list are the names of the four different flowers,
1155separated from each other by whitespace and surrounded by parentheses,
1156like flowers in a field with a stone wall around them.
1157@cindex Flowers in a field
1158
1159@menu
1160* Numbers Lists:: List have numbers, other lists, in them.
1161* Lisp Atoms:: Elemental entities.
1162* Whitespace in Lists:: Formatting lists to be readable.
1163* Typing Lists:: How GNU Emacs helps you type lists.
1164@end menu
1165
8cda6f8f 1166@ifnottex
d6adf7e7 1167@node Numbers Lists
8cda6f8f
GM
1168@unnumberedsubsec Numbers, Lists inside of Lists
1169@end ifnottex
1170
1171Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1172This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1173separated by whitespace.
1174
1175In Lisp, both data and programs are represented the same way; that is,
1176they are both lists of words, numbers, or other lists, separated by
1177whitespace and surrounded by parentheses. (Since a program looks like
1178data, one program may easily serve as data for another; this is a very
1179powerful feature of Lisp.) (Incidentally, these two parenthetical
1180remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1181@samp{.} as punctuation marks.)
1182
1183@need 1200
1184Here is another list, this time with a list inside of it:
1185
1186@smallexample
1187'(this list has (a list inside of it))
1188@end smallexample
1189
1190The components of this list are the words @samp{this}, @samp{list},
1191@samp{has}, and the list @samp{(a list inside of it)}. The interior
1192list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1193@samp{of}, @samp{it}.
1194
d6adf7e7 1195@node Lisp Atoms
8cda6f8f
GM
1196@subsection Lisp Atoms
1197@cindex Lisp Atoms
1198
1199In Lisp, what we have been calling words are called @dfn{atoms}. This
1200term comes from the historical meaning of the word atom, which means
1201`indivisible'. As far as Lisp is concerned, the words we have been
1202using in the lists cannot be divided into any smaller parts and still
1203mean the same thing as part of a program; likewise with numbers and
1204single character symbols like @samp{+}. On the other hand, unlike an
1205ancient atom, a list can be split into parts. (@xref{car cdr & cons,
1206, @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1207
1208In a list, atoms are separated from each other by whitespace. They can be
1209right next to a parenthesis.
1210
1211@cindex @samp{empty list} defined
1212Technically speaking, a list in Lisp consists of parentheses surrounding
1213atoms separated by whitespace or surrounding other lists or surrounding
1214both atoms and other lists. A list can have just one atom in it or
1215have nothing in it at all. A list with nothing in it looks like this:
1216@code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1217empty list is considered both an atom and a list at the same time.
1218
1219@cindex Symbolic expressions, introduced
1220@cindex @samp{expression} defined
1221@cindex @samp{form} defined
1222The printed representation of both atoms and lists are called
1223@dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1224The word @dfn{expression} by itself can refer to either the printed
1225representation, or to the atom or list as it is held internally in the
1226computer. Often, people use the term @dfn{expression}
1227indiscriminately. (Also, in many texts, the word @dfn{form} is used
1228as a synonym for expression.)
1229
1230Incidentally, the atoms that make up our universe were named such when
1231they were thought to be indivisible; but it has been found that physical
1232atoms are not indivisible. Parts can split off an atom or it can
1233fission into two parts of roughly equal size. Physical atoms were named
1234prematurely, before their truer nature was found. In Lisp, certain
1235kinds of atom, such as an array, can be separated into parts; but the
1236mechanism for doing this is different from the mechanism for splitting a
1237list. As far as list operations are concerned, the atoms of a list are
1238unsplittable.
1239
1240As in English, the meanings of the component letters of a Lisp atom
1241are different from the meaning the letters make as a word. For
1242example, the word for the South American sloth, the @samp{ai}, is
1243completely different from the two words, @samp{a}, and @samp{i}.
1244
1245There are many kinds of atom in nature but only a few in Lisp: for
1246example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1247as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1248listed in the examples above are all symbols. In everyday Lisp
1249conversation, the word ``atom'' is not often used, because programmers
1250usually try to be more specific about what kind of atom they are dealing
1251with. Lisp programming is mostly about symbols (and sometimes numbers)
1252within lists. (Incidentally, the preceding three word parenthetical
1253remark is a proper list in Lisp, since it consists of atoms, which in
1254this case are symbols, separated by whitespace and enclosed by
1255parentheses, without any non-Lisp punctuation.)
1256
1257@need 1250
6c499932
CY
1258Text between double quotation marks---even sentences or
1259paragraphs---is also an atom. Here is an example:
8cda6f8f
GM
1260@cindex Text between double quotation marks
1261
1262@smallexample
1263'(this list includes "text between quotation marks.")
1264@end smallexample
1265
1266@cindex @samp{string} defined
1267@noindent
1268In Lisp, all of the quoted text including the punctuation mark and the
1269blank spaces is a single atom. This kind of atom is called a
1270@dfn{string} (for `string of characters') and is the sort of thing that
1271is used for messages that a computer can print for a human to read.
1272Strings are a different kind of atom than numbers or symbols and are
1273used differently.
1274
d6adf7e7 1275@node Whitespace in Lists
8cda6f8f
GM
1276@subsection Whitespace in Lists
1277@cindex Whitespace in lists
1278
1279@need 1200
1280The amount of whitespace in a list does not matter. From the point of view
1281of the Lisp language,
1282
1283@smallexample
1284@group
1285'(this list
1286 looks like this)
1287@end group
1288@end smallexample
1289
1290@need 800
1291@noindent
1292is exactly the same as this:
1293
1294@smallexample
1295'(this list looks like this)
1296@end smallexample
1297
1298Both examples show what to Lisp is the same list, the list made up of
1299the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1300@samp{this} in that order.
1301
1302Extra whitespace and newlines are designed to make a list more readable
1303by humans. When Lisp reads the expression, it gets rid of all the extra
1304whitespace (but it needs to have at least one space between atoms in
1305order to tell them apart.)
1306
1307Odd as it seems, the examples we have seen cover almost all of what Lisp
1308lists look like! Every other list in Lisp looks more or less like one
1309of these examples, except that the list may be longer and more complex.
1310In brief, a list is between parentheses, a string is between quotation
1311marks, a symbol looks like a word, and a number looks like a number.
1312(For certain situations, square brackets, dots and a few other special
1313characters may be used; however, we will go quite far without them.)
1314
d6adf7e7 1315@node Typing Lists
8cda6f8f
GM
1316@subsection GNU Emacs Helps You Type Lists
1317@cindex Help typing lists
1318@cindex Formatting help
1319
1320When you type a Lisp expression in GNU Emacs using either Lisp
1321Interaction mode or Emacs Lisp mode, you have available to you several
1322commands to format the Lisp expression so it is easy to read. For
1323example, pressing the @key{TAB} key automatically indents the line the
1324cursor is on by the right amount. A command to properly indent the
1325code in a region is customarily bound to @kbd{M-C-\}. Indentation is
1326designed so that you can see which elements of a list belong to which
1327list---elements of a sub-list are indented more than the elements of
1328the enclosing list.
1329
1330In addition, when you type a closing parenthesis, Emacs momentarily
1331jumps the cursor back to the matching opening parenthesis, so you can
1332see which one it is. This is very useful, since every list you type
1333in Lisp must have its closing parenthesis match its opening
1334parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
44e97401 1335Manual}, for more information about Emacs's modes.)
8cda6f8f 1336
d6adf7e7 1337@node Run a Program
8cda6f8f
GM
1338@section Run a Program
1339@cindex Run a program
1340@cindex Program, running one
1341
1342@cindex @samp{evaluate} defined
1343A list in Lisp---any list---is a program ready to run. If you run it
1344(for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1345of three things: do nothing except return to you the list itself; send
1346you an error message; or, treat the first symbol in the list as a
1347command to do something. (Usually, of course, it is the last of these
1348three things that you really want!)
1349
1350@c use code for the single apostrophe, not samp.
1351The single apostrophe, @code{'}, that I put in front of some of the
1352example lists in preceding sections is called a @dfn{quote}; when it
1353precedes a list, it tells Lisp to do nothing with the list, other than
1354take it as it is written. But if there is no quote preceding a list,
1355the first item of the list is special: it is a command for the computer
1356to obey. (In Lisp, these commands are called @emph{functions}.) The list
1357@code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1358understands that the @code{+} is an instruction to do something with the
1359rest of the list: add the numbers that follow.
1360
1361@need 1250
1362If you are reading this inside of GNU Emacs in Info, here is how you can
1363evaluate such a list: place your cursor immediately after the right
1364hand parenthesis of the following list and then type @kbd{C-x C-e}:
1365
1366@smallexample
1367(+ 2 2)
1368@end smallexample
1369
1370@c use code for the number four, not samp.
1371@noindent
1372You will see the number @code{4} appear in the echo area. (In the
1373jargon, what you have just done is ``evaluate the list.'' The echo area
1374is the line at the bottom of the screen that displays or ``echoes''
1375text.) Now try the same thing with a quoted list: place the cursor
1376right after the following list and type @kbd{C-x C-e}:
1377
1378@smallexample
1379'(this is a quoted list)
1380@end smallexample
1381
1382@noindent
1383You will see @code{(this is a quoted list)} appear in the echo area.
1384
1385@cindex Lisp interpreter, explained
1386@cindex Interpreter, Lisp, explained
1387In both cases, what you are doing is giving a command to the program
1388inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1389interpreter a command to evaluate the expression. The name of the Lisp
1390interpreter comes from the word for the task done by a human who comes
1391up with the meaning of an expression---who ``interprets'' it.
1392
1393You can also evaluate an atom that is not part of a list---one that is
1394not surrounded by parentheses; again, the Lisp interpreter translates
1395from the humanly readable expression to the language of the computer.
1396But before discussing this (@pxref{Variables}), we will discuss what the
1397Lisp interpreter does when you make an error.
1398
d6adf7e7 1399@node Making Errors
8cda6f8f
GM
1400@section Generate an Error Message
1401@cindex Generate an error message
1402@cindex Error message generation
1403
1404Partly so you won't worry if you do it accidentally, we will now give
1405a command to the Lisp interpreter that generates an error message.
1406This is a harmless activity; and indeed, we will often try to generate
1407error messages intentionally. Once you understand the jargon, error
1408messages can be informative. Instead of being called ``error''
1409messages, they should be called ``help'' messages. They are like
ee7683eb 1410signposts to a traveler in a strange country; deciphering them can be
8cda6f8f
GM
1411hard, but once understood, they can point the way.
1412
1413The error message is generated by a built-in GNU Emacs debugger. We
1414will `enter the debugger'. You get out of the debugger by typing @code{q}.
1415
1416What we will do is evaluate a list that is not quoted and does not
1417have a meaningful command as its first element. Here is a list almost
1418exactly the same as the one we just used, but without the single-quote
1419in front of it. Position the cursor right after it and type @kbd{C-x
1420C-e}:
1421
1422@smallexample
1423(this is an unquoted list)
1424@end smallexample
1425
8f4ea8e0 1426@ignore
8cda6f8f
GM
1427@noindent
1428What you see depends on which version of Emacs you are running. GNU
1429Emacs version 22 provides more information than version 20 and before.
1430First, the more recent result of generating an error; then the
1431earlier, version 20 result.
1432
1433@need 1250
1434@noindent
1435In GNU Emacs version 22, a @file{*Backtrace*} window will open up and
1436you will see the following in it:
8f4ea8e0
GM
1437@end ignore
1438
1439A @file{*Backtrace*} window will open up and you should see the
1440following in it:
8cda6f8f
GM
1441
1442@smallexample
1443@group
1444---------- Buffer: *Backtrace* ----------
1445Debugger entered--Lisp error: (void-function this)
1446 (this is an unquoted list)
1447 eval((this is an unquoted list))
1448 eval-last-sexp-1(nil)
1449 eval-last-sexp(nil)
1450 call-interactively(eval-last-sexp)
1451---------- Buffer: *Backtrace* ----------
1452@end group
1453@end smallexample
1454
1455@need 1200
1456@noindent
1457Your cursor will be in this window (you may have to wait a few seconds
1458before it becomes visible). To quit the debugger and make the
1459debugger window go away, type:
1460
1461@smallexample
1462q
1463@end smallexample
1464
1465@noindent
1466Please type @kbd{q} right now, so you become confident that you can
1467get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1468it.
1469
1470@cindex @samp{function} defined
1471Based on what we already know, we can almost read this error message.
1472
1473You read the @file{*Backtrace*} buffer from the bottom up; it tells
1474you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1475interactive call to the command @code{eval-last-sexp}. @code{eval} is
1476an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1477`symbolic expression'. The command means `evaluate last symbolic
1478expression', which is the expression just before your cursor.
1479
1480Each line above tells you what the Lisp interpreter evaluated next.
1481The most recent action is at the top. The buffer is called the
1482@file{*Backtrace*} buffer because it enables you to track Emacs
1483backwards.
1484
1485@need 800
1486At the top of the @file{*Backtrace*} buffer, you see the line:
1487
1488@smallexample
1489Debugger entered--Lisp error: (void-function this)
1490@end smallexample
1491
1492@noindent
1493The Lisp interpreter tried to evaluate the first atom of the list, the
1494word @samp{this}. It is this action that generated the error message
1495@samp{void-function this}.
1496
1497The message contains the words @samp{void-function} and @samp{this}.
1498
1499@cindex @samp{function} defined
1500The word @samp{function} was mentioned once before. It is a very
1501important word. For our purposes, we can define it by saying that a
1502@dfn{function} is a set of instructions to the computer that tell the
1503computer to do something.
1504
1505Now we can begin to understand the error message: @samp{void-function
1506this}. The function (that is, the word @samp{this}) does not have a
1507definition of any set of instructions for the computer to carry out.
1508
1509The slightly odd word, @samp{void-function}, is designed to cover the
1510way Emacs Lisp is implemented, which is that when a symbol does not
1511have a function definition attached to it, the place that should
1512contain the instructions is `void'.
1513
1514On the other hand, since we were able to add 2 plus 2 successfully, by
1515evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1516have a set of instructions for the computer to obey and those
1517instructions must be to add the numbers that follow the @code{+}.
1518
8f4ea8e0
GM
1519It is possible to prevent Emacs entering the debugger in cases like
1520this. We do not explain how to do that here, but we will mention what
1521the result looks like, because you may encounter a similar situation
1522if there is a bug in some Emacs code that you are using. In such
1523cases, you will see only one line of error message; it will appear in
1524the echo area and look like this:
8cda6f8f
GM
1525
1526@smallexample
1527Symbol's function definition is void:@: this
1528@end smallexample
1529
1530@noindent
8f4ea8e0 1531@ignore
8cda6f8f 1532(Also, your terminal may beep at you---some do, some don't; and others
8f4ea8e0
GM
1533blink. This is just a device to get your attention.)
1534@end ignore
1535The message goes away as soon as you type a key, even just to
1536move the cursor.
8cda6f8f
GM
1537
1538We know the meaning of the word @samp{Symbol}. It refers to the first
1539atom of the list, the word @samp{this}. The word @samp{function}
1540refers to the instructions that tell the computer what to do.
1541(Technically, the symbol tells the computer where to find the
1542instructions, but this is a complication we can ignore for the
1543moment.)
1544
1545The error message can be understood: @samp{Symbol's function
1546definition is void:@: this}. The symbol (that is, the word
1547@samp{this}) lacks instructions for the computer to carry out.
1548
d6adf7e7 1549@node Names & Definitions
8cda6f8f
GM
1550@section Symbol Names and Function Definitions
1551@cindex Symbol names
1552
1553We can articulate another characteristic of Lisp based on what we have
1554discussed so far---an important characteristic: a symbol, like
1555@code{+}, is not itself the set of instructions for the computer to
1556carry out. Instead, the symbol is used, perhaps temporarily, as a way
1557of locating the definition or set of instructions. What we see is the
1558name through which the instructions can be found. Names of people
1559work the same way. I can be referred to as @samp{Bob}; however, I am
1560not the letters @samp{B}, @samp{o}, @samp{b} but am, or was, the
1561consciousness consistently associated with a particular life-form.
1562The name is not me, but it can be used to refer to me.
1563
1564In Lisp, one set of instructions can be attached to several names.
1565For example, the computer instructions for adding numbers can be
1566linked to the symbol @code{plus} as well as to the symbol @code{+}
1567(and are in some dialects of Lisp). Among humans, I can be referred
1568to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1569
1570On the other hand, a symbol can have only one function definition
1571attached to it at a time. Otherwise, the computer would be confused as
1572to which definition to use. If this were the case among people, only
1573one person in the world could be named @samp{Bob}. However, the function
1574definition to which the name refers can be changed readily.
1575(@xref{Install, , Install a Function Definition}.)
1576
1577Since Emacs Lisp is large, it is customary to name symbols in a way
1578that identifies the part of Emacs to which the function belongs.
1579Thus, all the names for functions that deal with Texinfo start with
1580@samp{texinfo-} and those for functions that deal with reading mail
1581start with @samp{rmail-}.
1582
d6adf7e7 1583@node Lisp Interpreter
8cda6f8f
GM
1584@section The Lisp Interpreter
1585@cindex Lisp interpreter, what it does
1586@cindex Interpreter, what it does
1587
1588Based on what we have seen, we can now start to figure out what the
1589Lisp interpreter does when we command it to evaluate a list.
1590First, it looks to see whether there is a quote before the list; if
1591there is, the interpreter just gives us the list. On the other
1592hand, if there is no quote, the interpreter looks at the first element
1593in the list and sees whether it has a function definition. If it does,
1594the interpreter carries out the instructions in the function definition.
1595Otherwise, the interpreter prints an error message.
1596
1597This is how Lisp works. Simple. There are added complications which we
1598will get to in a minute, but these are the fundamentals. Of course, to
1599write Lisp programs, you need to know how to write function definitions
1600and attach them to names, and how to do this without confusing either
1601yourself or the computer.
1602
1603@menu
1604* Complications:: Variables, Special forms, Lists within.
1605* Byte Compiling:: Specially processing code for speed.
1606@end menu
1607
8cda6f8f 1608@ifnottex
d6adf7e7 1609@node Complications
8cda6f8f
GM
1610@unnumberedsubsec Complications
1611@end ifnottex
1612
1613Now, for the first complication. In addition to lists, the Lisp
1614interpreter can evaluate a symbol that is not quoted and does not have
1615parentheses around it. The Lisp interpreter will attempt to determine
1616the symbol's value as a @dfn{variable}. This situation is described
1617in the section on variables. (@xref{Variables}.)
1618
1619@cindex Special form
1620The second complication occurs because some functions are unusual and do
1621not work in the usual manner. Those that don't are called @dfn{special
1622forms}. They are used for special jobs, like defining a function, and
1623there are not many of them. In the next few chapters, you will be
1624introduced to several of the more important special forms.
1625
1626The third and final complication is this: if the function that the
1627Lisp interpreter is looking at is not a special form, and if it is part
1628of a list, the Lisp interpreter looks to see whether the list has a list
1629inside of it. If there is an inner list, the Lisp interpreter first
1630figures out what it should do with the inside list, and then it works on
1631the outside list. If there is yet another list embedded inside the
1632inner list, it works on that one first, and so on. It always works on
1633the innermost list first. The interpreter works on the innermost list
1634first, to evaluate the result of that list. The result may be
1635used by the enclosing expression.
1636
1637Otherwise, the interpreter works left to right, from one expression to
1638the next.
1639
d6adf7e7 1640@node Byte Compiling
8cda6f8f
GM
1641@subsection Byte Compiling
1642@cindex Byte compiling
1643
1644One other aspect of interpreting: the Lisp interpreter is able to
1645interpret two kinds of entity: humanly readable code, on which we will
1646focus exclusively, and specially processed code, called @dfn{byte
1647compiled} code, which is not humanly readable. Byte compiled code
1648runs faster than humanly readable code.
1649
1650You can transform humanly readable code into byte compiled code by
1651running one of the compile commands such as @code{byte-compile-file}.
1652Byte compiled code is usually stored in a file that ends with a
1653@file{.elc} extension rather than a @file{.el} extension. You will
1654see both kinds of file in the @file{emacs/lisp} directory; the files
1655to read are those with @file{.el} extensions.
1656
1657As a practical matter, for most things you might do to customize or
1658extend Emacs, you do not need to byte compile; and I will not discuss
1659the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1660The GNU Emacs Lisp Reference Manual}, for a full description of byte
1661compilation.
1662
d6adf7e7 1663@node Evaluation
8cda6f8f
GM
1664@section Evaluation
1665@cindex Evaluation
1666
1667When the Lisp interpreter works on an expression, the term for the
1668activity is called @dfn{evaluation}. We say that the interpreter
1669`evaluates the expression'. I've used this term several times before.
1670The word comes from its use in everyday language, `to ascertain the
1671value or amount of; to appraise', according to @cite{Webster's New
1672Collegiate Dictionary}.
1673
1674@menu
1675* How the Interpreter Acts:: Returns and Side Effects...
1676* Evaluating Inner Lists:: Lists within lists...
1677@end menu
1678
8cda6f8f 1679@ifnottex
d6adf7e7 1680@node How the Interpreter Acts
8cda6f8f
GM
1681@unnumberedsubsec How the Lisp Interpreter Acts
1682@end ifnottex
1683
1684@cindex @samp{returned value} explained
1685After evaluating an expression, the Lisp interpreter will most likely
1686@dfn{return} the value that the computer produces by carrying out the
1687instructions it found in the function definition, or perhaps it will
1688give up on that function and produce an error message. (The interpreter
1689may also find itself tossed, so to speak, to a different function or it
1690may attempt to repeat continually what it is doing for ever and ever in
1691what is called an `infinite loop'. These actions are less common; and
1692we can ignore them.) Most frequently, the interpreter returns a value.
1693
1694@cindex @samp{side effect} defined
1695At the same time the interpreter returns a value, it may do something
1696else as well, such as move a cursor or copy a file; this other kind of
1697action is called a @dfn{side effect}. Actions that we humans think are
1698important, such as printing results, are often ``side effects'' to the
1699Lisp interpreter. The jargon can sound peculiar, but it turns out that
1700it is fairly easy to learn to use side effects.
1701
1702In summary, evaluating a symbolic expression most commonly causes the
1703Lisp interpreter to return a value and perhaps carry out a side effect;
1704or else produce an error.
1705
d6adf7e7 1706@node Evaluating Inner Lists
8cda6f8f
GM
1707@subsection Evaluating Inner Lists
1708@cindex Inner list evaluation
1709@cindex Evaluating inner lists
1710
1711If evaluation applies to a list that is inside another list, the outer
1712list may use the value returned by the first evaluation as information
1713when the outer list is evaluated. This explains why inner expressions
1714are evaluated first: the values they return are used by the outer
1715expressions.
1716
1717@need 1250
1718We can investigate this process by evaluating another addition example.
1719Place your cursor after the following expression and type @kbd{C-x C-e}:
1720
1721@smallexample
1722(+ 2 (+ 3 3))
1723@end smallexample
1724
1725@noindent
1726The number 8 will appear in the echo area.
1727
1728What happens is that the Lisp interpreter first evaluates the inner
1729expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1730evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1731returns the value 8. Since there are no more enclosing expressions to
1732evaluate, the interpreter prints that value in the echo area.
1733
1734Now it is easy to understand the name of the command invoked by the
1735keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1736letters @code{sexp} are an abbreviation for `symbolic expression', and
1737@code{eval} is an abbreviation for `evaluate'. The command means
1738`evaluate last symbolic expression'.
1739
1740As an experiment, you can try evaluating the expression by putting the
1741cursor at the beginning of the next line immediately following the
1742expression, or inside the expression.
1743
1744@need 800
1745Here is another copy of the expression:
1746
1747@smallexample
1748(+ 2 (+ 3 3))
1749@end smallexample
1750
1751@noindent
1752If you place the cursor at the beginning of the blank line that
1753immediately follows the expression and type @kbd{C-x C-e}, you will
1754still get the value 8 printed in the echo area. Now try putting the
1755cursor inside the expression. If you put it right after the next to
1756last parenthesis (so it appears to sit on top of the last parenthesis),
1757you will get a 6 printed in the echo area! This is because the command
1758evaluates the expression @code{(+ 3 3)}.
1759
1760Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1761you will get the number itself. In Lisp, if you evaluate a number, you
1762get the number itself---this is how numbers differ from symbols. If you
1763evaluate a list starting with a symbol like @code{+}, you will get a
1764value returned that is the result of the computer carrying out the
1765instructions in the function definition attached to that name. If a
1766symbol by itself is evaluated, something different happens, as we will
1767see in the next section.
1768
d6adf7e7 1769@node Variables
8cda6f8f
GM
1770@section Variables
1771@cindex Variables
1772
1773In Emacs Lisp, a symbol can have a value attached to it just as it can
1774have a function definition attached to it. The two are different.
1775The function definition is a set of instructions that a computer will
1776obey. A value, on the other hand, is something, such as number or a
1777name, that can vary (which is why such a symbol is called a variable).
1778The value of a symbol can be any expression in Lisp, such as a symbol,
1779number, list, or string. A symbol that has a value is often called a
1780@dfn{variable}.
1781
1782A symbol can have both a function definition and a value attached to
1783it at the same time. Or it can have just one or the other.
1784The two are separate. This is somewhat similar
1785to the way the name Cambridge can refer to the city in Massachusetts
1786and have some information attached to the name as well, such as
1787``great programming center''.
1788
1789@ignore
1790(Incidentally, in Emacs Lisp, a symbol can have two
1791other things attached to it, too: a property list and a documentation
1792string; these are discussed later.)
1793@end ignore
1794
1795Another way to think about this is to imagine a symbol as being a chest
1796of drawers. The function definition is put in one drawer, the value in
1797another, and so on. What is put in the drawer holding the value can be
1798changed without affecting the contents of the drawer holding the
1799function definition, and vice-verse.
1800
1801@menu
1802* fill-column Example::
1803* Void Function:: The error message for a symbol
1804 without a function.
1805* Void Variable:: The error message for a symbol without a value.
1806@end menu
1807
8cda6f8f 1808@ifnottex
d6adf7e7 1809@node fill-column Example
8cda6f8f
GM
1810@unnumberedsubsec @code{fill-column}, an Example Variable
1811@end ifnottex
1812
1813@findex fill-column, @r{an example variable}
1814@cindex Example variable, @code{fill-column}
1815@cindex Variable, example of, @code{fill-column}
1816The variable @code{fill-column} illustrates a symbol with a value
1817attached to it: in every GNU Emacs buffer, this symbol is set to some
1818value, usually 72 or 70, but sometimes to some other value. To find the
1819value of this symbol, evaluate it by itself. If you are reading this in
1820Info inside of GNU Emacs, you can do this by putting the cursor after
1821the symbol and typing @kbd{C-x C-e}:
1822
1823@smallexample
1824fill-column
1825@end smallexample
1826
1827@noindent
1828After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1829area. This is the value for which @code{fill-column} is set for me as I
1830write this. It may be different for you in your Info buffer. Notice
1831that the value returned as a variable is printed in exactly the same way
1832as the value returned by a function carrying out its instructions. From
1833the point of view of the Lisp interpreter, a value returned is a value
1834returned. What kind of expression it came from ceases to matter once
1835the value is known.
1836
1837A symbol can have any value attached to it or, to use the jargon, we can
1838@dfn{bind} the variable to a value: to a number, such as 72; to a
1839string, @code{"such as this"}; to a list, such as @code{(spruce pine
1840oak)}; we can even bind a variable to a function definition.
1841
1842A symbol can be bound to a value in several ways. @xref{set & setq, ,
1843Setting the Value of a Variable}, for information about one way to do
1844this.
1845
d6adf7e7 1846@node Void Function
8cda6f8f
GM
1847@subsection Error Message for a Symbol Without a Function
1848@cindex Symbol without function error
1849@cindex Error for symbol without function
1850
1851When we evaluated @code{fill-column} to find its value as a variable,
1852we did not place parentheses around the word. This is because we did
1853not intend to use it as a function name.
1854
1855If @code{fill-column} were the first or only element of a list, the
1856Lisp interpreter would attempt to find the function definition
1857attached to it. But @code{fill-column} has no function definition.
1858Try evaluating this:
1859
1860@smallexample
1861(fill-column)
1862@end smallexample
1863
1864@need 1250
1865@noindent
8f4ea8e0 1866You will create a @file{*Backtrace*} buffer that says:
8cda6f8f
GM
1867
1868@smallexample
1869@group
1870---------- Buffer: *Backtrace* ----------
1871Debugger entered--Lisp error: (void-function fill-column)
1872 (fill-column)
1873 eval((fill-column))
1874 eval-last-sexp-1(nil)
1875 eval-last-sexp(nil)
1876 call-interactively(eval-last-sexp)
1877---------- Buffer: *Backtrace* ----------
1878@end group
1879@end smallexample
1880
1881@noindent
1882(Remember, to quit the debugger and make the debugger window go away,
1883type @kbd{q} in the @file{*Backtrace*} buffer.)
1884
1885@ignore
1886@need 800
1887In GNU Emacs 20 and before, you will produce an error message that says:
1888
1889@smallexample
1890Symbol's function definition is void:@: fill-column
1891@end smallexample
1892
1893@noindent
1894(The message will go away as soon as you move the cursor or type
1895another key.)
1896@end ignore
1897
d6adf7e7 1898@node Void Variable
8cda6f8f
GM
1899@subsection Error Message for a Symbol Without a Value
1900@cindex Symbol without value error
1901@cindex Error for symbol without value
1902
1903If you attempt to evaluate a symbol that does not have a value bound to
1904it, you will receive an error message. You can see this by
1905experimenting with our 2 plus 2 addition. In the following expression,
1906put your cursor right after the @code{+}, before the first number 2,
1907type @kbd{C-x C-e}:
1908
1909@smallexample
1910(+ 2 2)
1911@end smallexample
1912
1913@need 1500
1914@noindent
1915In GNU Emacs 22, you will create a @file{*Backtrace*} buffer that
1916says:
1917
1918@smallexample
1919@group
1920---------- Buffer: *Backtrace* ----------
1921Debugger entered--Lisp error: (void-variable +)
1922 eval(+)
1923 eval-last-sexp-1(nil)
1924 eval-last-sexp(nil)
1925 call-interactively(eval-last-sexp)
1926---------- Buffer: *Backtrace* ----------
1927@end group
1928@end smallexample
1929
1930@noindent
8f4ea8e0 1931(Again, you can quit the debugger by
8cda6f8f
GM
1932typing @kbd{q} in the @file{*Backtrace*} buffer.)
1933
1934This backtrace is different from the very first error message we saw,
1935which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1936In this case, the function does not have a value as a variable; while
1937in the other error message, the function (the word `this') did not
1938have a definition.
1939
1940In this experiment with the @code{+}, what we did was cause the Lisp
1941interpreter to evaluate the @code{+} and look for the value of the
1942variable instead of the function definition. We did this by placing the
1943cursor right after the symbol rather than after the parenthesis of the
1944enclosing list as we did before. As a consequence, the Lisp interpreter
8f4ea8e0 1945evaluated the preceding s-expression, which in this case was
8cda6f8f
GM
1946@code{+} by itself.
1947
1948Since @code{+} does not have a value bound to it, just the function
1949definition, the error message reported that the symbol's value as a
1950variable was void.
1951
1952@ignore
1953@need 800
1954In GNU Emacs version 20 and before, your error message will say:
1955
1956@example
1957Symbol's value as variable is void:@: +
1958@end example
1959
1960@noindent
1961The meaning is the same as in GNU Emacs 22.
1962@end ignore
1963
d6adf7e7 1964@node Arguments
8cda6f8f
GM
1965@section Arguments
1966@cindex Arguments
1967@cindex Passing information to functions
1968
1969To see how information is passed to functions, let's look again at
1970our old standby, the addition of two plus two. In Lisp, this is written
1971as follows:
1972
1973@smallexample
1974(+ 2 2)
1975@end smallexample
1976
1977If you evaluate this expression, the number 4 will appear in your echo
1978area. What the Lisp interpreter does is add the numbers that follow
1979the @code{+}.
1980
1981@cindex @samp{argument} defined
1982The numbers added by @code{+} are called the @dfn{arguments} of the
1983function @code{+}. These numbers are the information that is given to
1984or @dfn{passed} to the function.
1985
1986The word `argument' comes from the way it is used in mathematics and
1987does not refer to a disputation between two people; instead it refers to
1988the information presented to the function, in this case, to the
1989@code{+}. In Lisp, the arguments to a function are the atoms or lists
1990that follow the function. The values returned by the evaluation of
1991these atoms or lists are passed to the function. Different functions
1992require different numbers of arguments; some functions require none at
1993all.@footnote{It is curious to track the path by which the word `argument'
1994came to have two different meanings, one in mathematics and the other in
1995everyday English. According to the @cite{Oxford English Dictionary},
1996the word derives from the Latin for @samp{to make clear, prove}; thus it
1997came to mean, by one thread of derivation, `the evidence offered as
1998proof', which is to say, `the information offered', which led to its
1999meaning in Lisp. But in the other thread of derivation, it came to mean
2000`to assert in a manner against which others may make counter
2001assertions', which led to the meaning of the word as a disputation.
2002(Note here that the English word has two different definitions attached
2003to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
2004have two different function definitions at the same time.)}
2005
2006@menu
2007* Data types:: Types of data passed to a function.
2008* Args as Variable or List:: An argument can be the value
2009 of a variable or list.
2010* Variable Number of Arguments:: Some functions may take a
2011 variable number of arguments.
2012* Wrong Type of Argument:: Passing an argument of the wrong type
2013 to a function.
2014* message:: A useful function for sending messages.
2015@end menu
2016
d6adf7e7 2017@node Data types
8cda6f8f
GM
2018@subsection Arguments' Data Types
2019@cindex Data types
2020@cindex Types of data
2021@cindex Arguments' data types
2022
2023The type of data that should be passed to a function depends on what
2024kind of information it uses. The arguments to a function such as
2025@code{+} must have values that are numbers, since @code{+} adds numbers.
2026Other functions use different kinds of data for their arguments.
2027
2028@need 1250
2029@findex concat
2030For example, the @code{concat} function links together or unites two or
2031more strings of text to produce a string. The arguments are strings.
2032Concatenating the two character strings @code{abc}, @code{def} produces
2033the single string @code{abcdef}. This can be seen by evaluating the
2034following:
2035
2036@smallexample
2037(concat "abc" "def")
2038@end smallexample
2039
2040@noindent
2041The value produced by evaluating this expression is @code{"abcdef"}.
2042
2043A function such as @code{substring} uses both a string and numbers as
2044arguments. The function returns a part of the string, a substring of
2045the first argument. This function takes three arguments. Its first
2046argument is the string of characters, the second and third arguments are
2047numbers that indicate the beginning and end of the substring. The
2048numbers are a count of the number of characters (including spaces and
e4920bc9 2049punctuation) from the beginning of the string.
8cda6f8f
GM
2050
2051@need 800
2052For example, if you evaluate the following:
2053
2054@smallexample
2055(substring "The quick brown fox jumped." 16 19)
2056@end smallexample
2057
2058@noindent
2059you will see @code{"fox"} appear in the echo area. The arguments are the
2060string and the two numbers.
2061
2062Note that the string passed to @code{substring} is a single atom even
2063though it is made up of several words separated by spaces. Lisp counts
2064everything between the two quotation marks as part of the string,
2065including the spaces. You can think of the @code{substring} function as
2066a kind of `atom smasher' since it takes an otherwise indivisible atom
2067and extracts a part. However, @code{substring} is only able to extract
2068a substring from an argument that is a string, not from another type of
2069atom such as a number or symbol.
2070
d6adf7e7 2071@node Args as Variable or List
8cda6f8f
GM
2072@subsection An Argument as the Value of a Variable or List
2073
2074An argument can be a symbol that returns a value when it is evaluated.
2075For example, when the symbol @code{fill-column} by itself is evaluated,
2076it returns a number. This number can be used in an addition.
2077
2078@need 1250
2079Position the cursor after the following expression and type @kbd{C-x
2080C-e}:
2081
2082@smallexample
2083(+ 2 fill-column)
2084@end smallexample
2085
2086@noindent
2087The value will be a number two more than what you get by evaluating
2088@code{fill-column} alone. For me, this is 74, because my value of
2089@code{fill-column} is 72.
2090
2091As we have just seen, an argument can be a symbol that returns a value
2092when evaluated. In addition, an argument can be a list that returns a
2093value when it is evaluated. For example, in the following expression,
2094the arguments to the function @code{concat} are the strings
2095@w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2096@code{(number-to-string (+ 2 fill-column))}.
2097
2098@c For GNU Emacs 22, need number-to-string
2099@smallexample
2100(concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2101@end smallexample
2102
2103@noindent
2104If you evaluate this expression---and if, as with my Emacs,
2105@code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2106appear in the echo area. (Note that you must put spaces after the
2107word @samp{The} and before the word @samp{red} so they will appear in
2108the final string. The function @code{number-to-string} converts the
2109integer that the addition function returns to a string.
2110@code{number-to-string} is also known as @code{int-to-string}.)
2111
d6adf7e7 2112@node Variable Number of Arguments
8cda6f8f
GM
2113@subsection Variable Number of Arguments
2114@cindex Variable number of arguments
2115@cindex Arguments, variable number of
2116
2117Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2118number of arguments. (The @code{*} is the symbol for multiplication.)
2119This can be seen by evaluating each of the following expressions in
2120the usual way. What you will see in the echo area is printed in this
2121text after @samp{@result{}}, which you may read as `evaluates to'.
2122
2123@need 1250
2124In the first set, the functions have no arguments:
2125
2126@smallexample
2127@group
2128(+) @result{} 0
2129
2130(*) @result{} 1
2131@end group
2132@end smallexample
2133
2134@need 1250
2135In this set, the functions have one argument each:
2136
2137@smallexample
2138@group
2139(+ 3) @result{} 3
2140
2141(* 3) @result{} 3
2142@end group
2143@end smallexample
2144
2145@need 1250
2146In this set, the functions have three arguments each:
2147
2148@smallexample
2149@group
2150(+ 3 4 5) @result{} 12
2151
2152(* 3 4 5) @result{} 60
2153@end group
2154@end smallexample
2155
d6adf7e7 2156@node Wrong Type of Argument
8cda6f8f
GM
2157@subsection Using the Wrong Type Object as an Argument
2158@cindex Wrong type of argument
2159@cindex Argument, wrong type of
2160
2161When a function is passed an argument of the wrong type, the Lisp
2162interpreter produces an error message. For example, the @code{+}
2163function expects the values of its arguments to be numbers. As an
2164experiment we can pass it the quoted symbol @code{hello} instead of a
2165number. Position the cursor after the following expression and type
2166@kbd{C-x C-e}:
2167
2168@smallexample
2169(+ 2 'hello)
2170@end smallexample
2171
2172@noindent
2173When you do this you will generate an error message. What has happened
2174is that @code{+} has tried to add the 2 to the value returned by
2175@code{'hello}, but the value returned by @code{'hello} is the symbol
2176@code{hello}, not a number. Only numbers can be added. So @code{+}
2177could not carry out its addition.
2178
2179@need 1250
8f4ea8e0 2180You will create and enter a @file{*Backtrace*} buffer that says:
8cda6f8f
GM
2181
2182@noindent
2183@smallexample
2184@group
2185---------- Buffer: *Backtrace* ----------
2186Debugger entered--Lisp error:
2187 (wrong-type-argument number-or-marker-p hello)
2188 +(2 hello)
2189 eval((+ 2 (quote hello)))
2190 eval-last-sexp-1(nil)
2191 eval-last-sexp(nil)
2192 call-interactively(eval-last-sexp)
2193---------- Buffer: *Backtrace* ----------
2194@end group
2195@end smallexample
2196
2197@need 1250
2198As usual, the error message tries to be helpful and makes sense after you
2199learn how to read it.@footnote{@code{(quote hello)} is an expansion of
2200the abbreviation @code{'hello}.}
2201
2202The first part of the error message is straightforward; it says
2203@samp{wrong type argument}. Next comes the mysterious jargon word
2204@w{@samp{number-or-marker-p}}. This word is trying to tell you what
2205kind of argument the @code{+} expected.
2206
2207The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2208trying to determine whether the information presented it (the value of
2209the argument) is a number or a marker (a special object representing a
2210buffer position). What it does is test to see whether the @code{+} is
2211being given numbers to add. It also tests to see whether the
2212argument is something called a marker, which is a specific feature of
2213Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2214When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2215its position is kept as a marker. The mark can be considered a
2216number---the number of characters the location is from the beginning
2217of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2218numeric value of marker positions as numbers.
2219
2220The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2221practice started in the early days of Lisp programming. The @samp{p}
2222stands for `predicate'. In the jargon used by the early Lisp
2223researchers, a predicate refers to a function to determine whether some
2224property is true or false. So the @samp{p} tells us that
2225@code{number-or-marker-p} is the name of a function that determines
2226whether it is true or false that the argument supplied is a number or
2227a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2228a function that tests whether its argument has the value of zero, and
2229@code{listp}, a function that tests whether its argument is a list.
2230
2231Finally, the last part of the error message is the symbol @code{hello}.
2232This is the value of the argument that was passed to @code{+}. If the
2233addition had been passed the correct type of object, the value passed
2234would have been a number, such as 37, rather than a symbol like
2235@code{hello}. But then you would not have got the error message.
2236
2237@ignore
2238@need 1250
2239In GNU Emacs version 20 and before, the echo area displays an error
2240message that says:
2241
2242@smallexample
2243Wrong type argument:@: number-or-marker-p, hello
2244@end smallexample
2245
2246This says, in different words, the same as the top line of the
2247@file{*Backtrace*} buffer.
2248@end ignore
2249
d6adf7e7 2250@node message
8cda6f8f
GM
2251@subsection The @code{message} Function
2252@findex message
2253
2254Like @code{+}, the @code{message} function takes a variable number of
2255arguments. It is used to send messages to the user and is so useful
2256that we will describe it here.
2257
2258@need 1250
2259A message is printed in the echo area. For example, you can print a
2260message in your echo area by evaluating the following list:
2261
2262@smallexample
2263(message "This message appears in the echo area!")
2264@end smallexample
2265
2266The whole string between double quotation marks is a single argument
2267and is printed @i{in toto}. (Note that in this example, the message
2268itself will appear in the echo area within double quotes; that is
2269because you see the value returned by the @code{message} function. In
2270most uses of @code{message} in programs that you write, the text will
2271be printed in the echo area as a side-effect, without the quotes.
2272@xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2273detail}, for an example of this.)
2274
2275However, if there is a @samp{%s} in the quoted string of characters, the
2276@code{message} function does not print the @samp{%s} as such, but looks
2277to the argument that follows the string. It evaluates the second
2278argument and prints the value at the location in the string where the
2279@samp{%s} is.
2280
2281@need 1250
2282You can see this by positioning the cursor after the following
2283expression and typing @kbd{C-x C-e}:
2284
2285@smallexample
2286(message "The name of this buffer is: %s." (buffer-name))
2287@end smallexample
2288
2289@noindent
2290In Info, @code{"The name of this buffer is: *info*."} will appear in the
2291echo area. The function @code{buffer-name} returns the name of the
2292buffer as a string, which the @code{message} function inserts in place
2293of @code{%s}.
2294
2295To print a value as an integer, use @samp{%d} in the same way as
2296@samp{%s}. For example, to print a message in the echo area that
2297states the value of the @code{fill-column}, evaluate the following:
2298
2299@smallexample
2300(message "The value of fill-column is %d." fill-column)
2301@end smallexample
2302
2303@noindent
2304On my system, when I evaluate this list, @code{"The value of
2305fill-column is 72."} appears in my echo area@footnote{Actually, you
2306can use @code{%s} to print a number. It is non-specific. @code{%d}
2307prints only the part of a number left of a decimal point, and not
2308anything that is not a number.}.
2309
2310If there is more than one @samp{%s} in the quoted string, the value of
2311the first argument following the quoted string is printed at the
2312location of the first @samp{%s} and the value of the second argument is
2313printed at the location of the second @samp{%s}, and so on.
2314
2315@need 1250
2316For example, if you evaluate the following,
2317
2318@smallexample
2319@group
2320(message "There are %d %s in the office!"
2321 (- fill-column 14) "pink elephants")
2322@end group
2323@end smallexample
2324
2325@noindent
2326a rather whimsical message will appear in your echo area. On my system
2327it says, @code{"There are 58 pink elephants in the office!"}.
2328
2329The expression @code{(- fill-column 14)} is evaluated and the resulting
2330number is inserted in place of the @samp{%d}; and the string in double
2331quotes, @code{"pink elephants"}, is treated as a single argument and
2332inserted in place of the @samp{%s}. (That is to say, a string between
2333double quotes evaluates to itself, like a number.)
2334
2335Finally, here is a somewhat complex example that not only illustrates
2336the computation of a number, but also shows how you can use an
2337expression within an expression to generate the text that is substituted
2338for @samp{%s}:
2339
2340@smallexample
2341@group
2342(message "He saw %d %s"
2343 (- fill-column 32)
2344 (concat "red "
2345 (substring
2346 "The quick brown foxes jumped." 16 21)
2347 " leaping."))
2348@end group
2349@end smallexample
2350
2351In this example, @code{message} has three arguments: the string,
2352@code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2353the expression beginning with the function @code{concat}. The value
2354resulting from the evaluation of @code{(- fill-column 32)} is inserted
2355in place of the @samp{%d}; and the value returned by the expression
2356beginning with @code{concat} is inserted in place of the @samp{%s}.
2357
2358When your fill column is 70 and you evaluate the expression, the
2359message @code{"He saw 38 red foxes leaping."} appears in your echo
2360area.
2361
d6adf7e7 2362@node set & setq
8cda6f8f
GM
2363@section Setting the Value of a Variable
2364@cindex Variable, setting value
2365@cindex Setting value of variable
2366
2367@cindex @samp{bind} defined
2368There are several ways by which a variable can be given a value. One of
2369the ways is to use either the function @code{set} or the function
2370@code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2371jargon for this process is to @dfn{bind} a variable to a value.)
2372
2373The following sections not only describe how @code{set} and @code{setq}
2374work but also illustrate how arguments are passed.
2375
2376@menu
2377* Using set:: Setting values.
2378* Using setq:: Setting a quoted value.
2379* Counting:: Using @code{setq} to count.
2380@end menu
2381
d6adf7e7 2382@node Using set
8cda6f8f
GM
2383@subsection Using @code{set}
2384@findex set
2385
2386To set the value of the symbol @code{flowers} to the list @code{'(rose
2387violet daisy buttercup)}, evaluate the following expression by
2388positioning the cursor after the expression and typing @kbd{C-x C-e}.
2389
2390@smallexample
2391(set 'flowers '(rose violet daisy buttercup))
2392@end smallexample
2393
2394@noindent
2395The list @code{(rose violet daisy buttercup)} will appear in the echo
2396area. This is what is @emph{returned} by the @code{set} function. As a
2397side effect, the symbol @code{flowers} is bound to the list; that is,
2398the symbol @code{flowers}, which can be viewed as a variable, is given
2399the list as its value. (This process, by the way, illustrates how a
2400side effect to the Lisp interpreter, setting the value, can be the
2401primary effect that we humans are interested in. This is because every
2402Lisp function must return a value if it does not get an error, but it
2403will only have a side effect if it is designed to have one.)
2404
2405After evaluating the @code{set} expression, you can evaluate the symbol
2406@code{flowers} and it will return the value you just set. Here is the
2407symbol. Place your cursor after it and type @kbd{C-x C-e}.
2408
2409@smallexample
2410flowers
2411@end smallexample
2412
2413@noindent
2414When you evaluate @code{flowers}, the list
2415@code{(rose violet daisy buttercup)} appears in the echo area.
2416
2417Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2418in front of it, what you will see in the echo area is the symbol itself,
2419@code{flowers}. Here is the quoted symbol, so you can try this:
2420
2421@smallexample
2422'flowers
2423@end smallexample
2424
2425Note also, that when you use @code{set}, you need to quote both
2426arguments to @code{set}, unless you want them evaluated. Since we do
2427not want either argument evaluated, neither the variable
2428@code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2429are quoted. (When you use @code{set} without quoting its first
2430argument, the first argument is evaluated before anything else is
2431done. If you did this and @code{flowers} did not have a value
2432already, you would get an error message that the @samp{Symbol's value
2433as variable is void}; on the other hand, if @code{flowers} did return
2434a value after it was evaluated, the @code{set} would attempt to set
2435the value that was returned. There are situations where this is the
2436right thing for the function to do; but such situations are rare.)
2437
d6adf7e7 2438@node Using setq
8cda6f8f
GM
2439@subsection Using @code{setq}
2440@findex setq
2441
2442As a practical matter, you almost always quote the first argument to
2443@code{set}. The combination of @code{set} and a quoted first argument
2444is so common that it has its own name: the special form @code{setq}.
2445This special form is just like @code{set} except that the first argument
2446is quoted automatically, so you don't need to type the quote mark
2447yourself. Also, as an added convenience, @code{setq} permits you to set
2448several different variables to different values, all in one expression.
2449
2450To set the value of the variable @code{carnivores} to the list
2451@code{'(lion tiger leopard)} using @code{setq}, the following expression
2452is used:
2453
2454@smallexample
2455(setq carnivores '(lion tiger leopard))
2456@end smallexample
2457
2458@noindent
2459This is exactly the same as using @code{set} except the first argument
2460is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2461means @code{quote}.)
2462
2463@need 1250
2464With @code{set}, the expression would look like this:
2465
2466@smallexample
2467(set 'carnivores '(lion tiger leopard))
2468@end smallexample
2469
2470Also, @code{setq} can be used to assign different values to
2471different variables. The first argument is bound to the value
2472of the second argument, the third argument is bound to the value of the
2473fourth argument, and so on. For example, you could use the following to
2474assign a list of trees to the symbol @code{trees} and a list of herbivores
2475to the symbol @code{herbivores}:
2476
2477@smallexample
2478@group
2479(setq trees '(pine fir oak maple)
2480 herbivores '(gazelle antelope zebra))
2481@end group
2482@end smallexample
2483
2484@noindent
2485(The expression could just as well have been on one line, but it might
2486not have fit on a page; and humans find it easier to read nicely
2487formatted lists.)
2488
2489Although I have been using the term `assign', there is another way of
2490thinking about the workings of @code{set} and @code{setq}; and that is to
2491say that @code{set} and @code{setq} make the symbol @emph{point} to the
2492list. This latter way of thinking is very common and in forthcoming
2493chapters we shall come upon at least one symbol that has `pointer' as
2494part of its name. The name is chosen because the symbol has a value,
2495specifically a list, attached to it; or, expressed another way,
2496the symbol is set to ``point'' to the list.
2497
d6adf7e7 2498@node Counting
8cda6f8f
GM
2499@subsection Counting
2500@cindex Counting
2501
2502Here is an example that shows how to use @code{setq} in a counter. You
2503might use this to count how many times a part of your program repeats
2504itself. First set a variable to zero; then add one to the number each
2505time the program repeats itself. To do this, you need a variable that
2506serves as a counter, and two expressions: an initial @code{setq}
2507expression that sets the counter variable to zero; and a second
2508@code{setq} expression that increments the counter each time it is
2509evaluated.
2510
2511@smallexample
2512@group
2513(setq counter 0) ; @r{Let's call this the initializer.}
2514
2515(setq counter (+ counter 1)) ; @r{This is the incrementer.}
2516
2517counter ; @r{This is the counter.}
2518@end group
2519@end smallexample
2520
2521@noindent
2522(The text following the @samp{;} are comments. @xref{Change a
2523defun, , Change a Function Definition}.)
2524
2525If you evaluate the first of these expressions, the initializer,
2526@code{(setq counter 0)}, and then evaluate the third expression,
2527@code{counter}, the number @code{0} will appear in the echo area. If
2528you then evaluate the second expression, the incrementer, @code{(setq
2529counter (+ counter 1))}, the counter will get the value 1. So if you
2530again evaluate @code{counter}, the number @code{1} will appear in the
2531echo area. Each time you evaluate the second expression, the value of
2532the counter will be incremented.
2533
2534When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2535the Lisp interpreter first evaluates the innermost list; this is the
2536addition. In order to evaluate this list, it must evaluate the variable
2537@code{counter} and the number @code{1}. When it evaluates the variable
2538@code{counter}, it receives its current value. It passes this value and
2539the number @code{1} to the @code{+} which adds them together. The sum
2540is then returned as the value of the inner list and passed to the
2541@code{setq} which sets the variable @code{counter} to this new value.
2542Thus, the value of the variable, @code{counter}, is changed.
2543
d6adf7e7 2544@node Summary
8cda6f8f
GM
2545@section Summary
2546
2547Learning Lisp is like climbing a hill in which the first part is the
2548steepest. You have now climbed the most difficult part; what remains
2549becomes easier as you progress onwards.
2550
2551@need 1000
2552In summary,
2553
2554@itemize @bullet
2555
2556@item
2557Lisp programs are made up of expressions, which are lists or single atoms.
2558
2559@item
2560Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2561surrounded by parentheses. A list can be empty.
2562
2563@item
2564Atoms are multi-character symbols, like @code{forward-paragraph}, single
2565character symbols like @code{+}, strings of characters between double
2566quotation marks, or numbers.
2567
2568@item
2569A number evaluates to itself.
2570
2571@item
2572A string between double quotes also evaluates to itself.
2573
2574@item
2575When you evaluate a symbol by itself, its value is returned.
2576
2577@item
2578When you evaluate a list, the Lisp interpreter looks at the first symbol
2579in the list and then at the function definition bound to that symbol.
2580Then the instructions in the function definition are carried out.
2581
2582@item
2583A single quotation mark,
2584@ifinfo
2585'
2586@end ifinfo
2587@ifnotinfo
2588@code{'}
2589@end ifnotinfo
2590, tells the Lisp interpreter that it should
2591return the following expression as written, and not evaluate it as it
2592would if the quote were not there.
2593
2594@item
2595Arguments are the information passed to a function. The arguments to a
2596function are computed by evaluating the rest of the elements of the list
2597of which the function is the first element.
2598
2599@item
2600A function always returns a value when it is evaluated (unless it gets
2601an error); in addition, it may also carry out some action called a
2602``side effect''. In many cases, a function's primary purpose is to
2603create a side effect.
2604@end itemize
2605
d6adf7e7 2606@node Error Message Exercises
8cda6f8f
GM
2607@section Exercises
2608
2609A few simple exercises:
2610
2611@itemize @bullet
2612@item
2613Generate an error message by evaluating an appropriate symbol that is
2614not within parentheses.
2615
2616@item
2617Generate an error message by evaluating an appropriate symbol that is
2618between parentheses.
2619
2620@item
2621Create a counter that increments by two rather than one.
2622
2623@item
2624Write an expression that prints a message in the echo area when
2625evaluated.
2626@end itemize
2627
d6adf7e7 2628@node Practicing Evaluation
8cda6f8f
GM
2629@chapter Practicing Evaluation
2630@cindex Practicing evaluation
2631@cindex Evaluation practice
2632
2633Before learning how to write a function definition in Emacs Lisp, it is
2634useful to spend a little time evaluating various expressions that have
2635already been written. These expressions will be lists with the
2636functions as their first (and often only) element. Since some of the
2637functions associated with buffers are both simple and interesting, we
2638will start with those. In this section, we will evaluate a few of
2639these. In another section, we will study the code of several other
2640buffer-related functions, to see how they were written.
2641
2642@menu
2643* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2644 causes evaluation.
2645* Buffer Names:: Buffers and files are different.
2646* Getting Buffers:: Getting a buffer itself, not merely its name.
2647* Switching Buffers:: How to change to another buffer.
2648* Buffer Size & Locations:: Where point is located and the size of
2649 the buffer.
2650* Evaluation Exercise::
2651@end menu
2652
8cda6f8f 2653@ifnottex
d6adf7e7 2654@node How to Evaluate
8cda6f8f
GM
2655@unnumberedsec How to Evaluate
2656@end ifnottex
2657
2658@i{Whenever you give an editing command} to Emacs Lisp, such as the
2659command to move the cursor or to scroll the screen, @i{you are evaluating
2660an expression,} the first element of which is a function. @i{This is
2661how Emacs works.}
2662
2663@cindex @samp{interactive function} defined
2664@cindex @samp{command} defined
2665When you type keys, you cause the Lisp interpreter to evaluate an
2666expression and that is how you get your results. Even typing plain text
2667involves evaluating an Emacs Lisp function, in this case, one that uses
2668@code{self-insert-command}, which simply inserts the character you
2669typed. The functions you evaluate by typing keystrokes are called
2670@dfn{interactive} functions, or @dfn{commands}; how you make a function
2671interactive will be illustrated in the chapter on how to write function
2672definitions. @xref{Interactive, , Making a Function Interactive}.
2673
2674In addition to typing keyboard commands, we have seen a second way to
2675evaluate an expression: by positioning the cursor after a list and
2676typing @kbd{C-x C-e}. This is what we will do in the rest of this
2677section. There are other ways to evaluate an expression as well; these
2678will be described as we come to them.
2679
2680Besides being used for practicing evaluation, the functions shown in the
2681next few sections are important in their own right. A study of these
2682functions makes clear the distinction between buffers and files, how to
2683switch to a buffer, and how to determine a location within it.
2684
d6adf7e7 2685@node Buffer Names
8cda6f8f
GM
2686@section Buffer Names
2687@findex buffer-name
2688@findex buffer-file-name
2689
2690The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2691the difference between a file and a buffer. When you evaluate the
2692following expression, @code{(buffer-name)}, the name of the buffer
2693appears in the echo area. When you evaluate @code{(buffer-file-name)},
2694the name of the file to which the buffer refers appears in the echo
2695area. Usually, the name returned by @code{(buffer-name)} is the same as
2696the name of the file to which it refers, and the name returned by
2697@code{(buffer-file-name)} is the full path-name of the file.
2698
2699A file and a buffer are two different entities. A file is information
2700recorded permanently in the computer (unless you delete it). A buffer,
2701on the other hand, is information inside of Emacs that will vanish at
2702the end of the editing session (or when you kill the buffer). Usually,
2703a buffer contains information that you have copied from a file; we say
2704the buffer is @dfn{visiting} that file. This copy is what you work on
2705and modify. Changes to the buffer do not change the file, until you
2706save the buffer. When you save the buffer, the buffer is copied to the file
2707and is thus saved permanently.
2708
2709@need 1250
2710If you are reading this in Info inside of GNU Emacs, you can evaluate
2711each of the following expressions by positioning the cursor after it and
2712typing @kbd{C-x C-e}.
2713
2714@example
2715@group
2716(buffer-name)
2717
2718(buffer-file-name)
2719@end group
2720@end example
2721
2722@noindent
2723When I do this in Info, the value returned by evaluating
2724@code{(buffer-name)} is @file{"*info*"}, and the value returned by
2725evaluating @code{(buffer-file-name)} is @file{nil}.
2726
a9097c6d 2727On the other hand, while I am writing this document, the value
8cda6f8f
GM
2728returned by evaluating @code{(buffer-name)} is
2729@file{"introduction.texinfo"}, and the value returned by evaluating
2730@code{(buffer-file-name)} is
2731@file{"/gnu/work/intro/introduction.texinfo"}.
2732
2733@cindex @code{nil}, history of word
2734The former is the name of the buffer and the latter is the name of the
2735file. In Info, the buffer name is @file{"*info*"}. Info does not
2736point to any file, so the result of evaluating
2737@code{(buffer-file-name)} is @file{nil}. The symbol @code{nil} is
2738from the Latin word for `nothing'; in this case, it means that the
2739buffer is not associated with any file. (In Lisp, @code{nil} is also
2740used to mean `false' and is a synonym for the empty list, @code{()}.)
2741
2742When I am writing, the name of my buffer is
2743@file{"introduction.texinfo"}. The name of the file to which it
2744points is @file{"/gnu/work/intro/introduction.texinfo"}.
2745
2746(In the expressions, the parentheses tell the Lisp interpreter to
2747treat @w{@code{buffer-name}} and @w{@code{buffer-file-name}} as
2748functions; without the parentheses, the interpreter would attempt to
2749evaluate the symbols as variables. @xref{Variables}.)
2750
2751In spite of the distinction between files and buffers, you will often
2752find that people refer to a file when they mean a buffer and vice-verse.
2753Indeed, most people say, ``I am editing a file,'' rather than saying,
2754``I am editing a buffer which I will soon save to a file.'' It is
2755almost always clear from context what people mean. When dealing with
2756computer programs, however, it is important to keep the distinction in mind,
2757since the computer is not as smart as a person.
2758
2759@cindex Buffer, history of word
2760The word `buffer', by the way, comes from the meaning of the word as a
2761cushion that deadens the force of a collision. In early computers, a
2762buffer cushioned the interaction between files and the computer's
2763central processing unit. The drums or tapes that held a file and the
2764central processing unit were pieces of equipment that were very
2765different from each other, working at their own speeds, in spurts. The
2766buffer made it possible for them to work together effectively.
2767Eventually, the buffer grew from being an intermediary, a temporary
2768holding place, to being the place where work is done. This
2769transformation is rather like that of a small seaport that grew into a
2770great city: once it was merely the place where cargo was warehoused
2771temporarily before being loaded onto ships; then it became a business
2772and cultural center in its own right.
2773
2774Not all buffers are associated with files. For example, a
2775@file{*scratch*} buffer does not visit any file. Similarly, a
2776@file{*Help*} buffer is not associated with any file.
2777
2778In the old days, when you lacked a @file{~/.emacs} file and started an
2779Emacs session by typing the command @code{emacs} alone, without naming
2780any files, Emacs started with the @file{*scratch*} buffer visible.
2781Nowadays, you will see a splash screen. You can follow one of the
2782commands suggested on the splash screen, visit a file, or press the
2783spacebar to reach the @file{*scratch*} buffer.
2784
2785If you switch to the @file{*scratch*} buffer, type
2786@code{(buffer-name)}, position the cursor after it, and then type
2787@kbd{C-x C-e} to evaluate the expression. The name @code{"*scratch*"}
2788will be returned and will appear in the echo area. @code{"*scratch*"}
2789is the name of the buffer. When you type @code{(buffer-file-name)} in
2790the @file{*scratch*} buffer and evaluate that, @code{nil} will appear
2791in the echo area, just as it does when you evaluate
2792@code{(buffer-file-name)} in Info.
2793
2794Incidentally, if you are in the @file{*scratch*} buffer and want the
2795value returned by an expression to appear in the @file{*scratch*}
2796buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2797instead of @kbd{C-x C-e}. This causes the value returned to appear
2798after the expression. The buffer will look like this:
2799
2800@smallexample
2801(buffer-name)"*scratch*"
2802@end smallexample
2803
2804@noindent
2805You cannot do this in Info since Info is read-only and it will not allow
2806you to change the contents of the buffer. But you can do this in any
2807buffer you can edit; and when you write code or documentation (such as
2808this book), this feature is very useful.
2809
d6adf7e7 2810@node Getting Buffers
8cda6f8f
GM
2811@section Getting Buffers
2812@findex current-buffer
2813@findex other-buffer
2814@cindex Getting a buffer
2815
2816The @code{buffer-name} function returns the @emph{name} of the buffer;
2817to get the buffer @emph{itself}, a different function is needed: the
2818@code{current-buffer} function. If you use this function in code, what
2819you get is the buffer itself.
2820
2821A name and the object or entity to which the name refers are different
2822from each other. You are not your name. You are a person to whom
2823others refer by name. If you ask to speak to George and someone hands you
2824a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2825@samp{g}, and @samp{e} written on it, you might be amused, but you would
2826not be satisfied. You do not want to speak to the name, but to the
2827person to whom the name refers. A buffer is similar: the name of the
2828scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2829get a buffer itself, you need to use a function such as
2830@code{current-buffer}.
2831
2832However, there is a slight complication: if you evaluate
2833@code{current-buffer} in an expression on its own, as we will do here,
2834what you see is a printed representation of the name of the buffer
2835without the contents of the buffer. Emacs works this way for two
2836reasons: the buffer may be thousands of lines long---too long to be
2837conveniently displayed; and, another buffer may have the same contents
2838but a different name, and it is important to distinguish between them.
2839
2840@need 800
2841Here is an expression containing the function:
2842
2843@smallexample
2844(current-buffer)
2845@end smallexample
2846
2847@noindent
2848If you evaluate this expression in Info in Emacs in the usual way,
2849@file{#<buffer *info*>} will appear in the echo area. The special
2850format indicates that the buffer itself is being returned, rather than
2851just its name.
2852
2853Incidentally, while you can type a number or symbol into a program, you
2854cannot do that with the printed representation of a buffer: the only way
2855to get a buffer itself is with a function such as @code{current-buffer}.
2856
2857A related function is @code{other-buffer}. This returns the most
2858recently selected buffer other than the one you are in currently, not
2859a printed representation of its name. If you have recently switched
2860back and forth from the @file{*scratch*} buffer, @code{other-buffer}
2861will return that buffer.
2862
2863@need 800
2864You can see this by evaluating the expression:
2865
2866@smallexample
2867(other-buffer)
2868@end smallexample
2869
2870@noindent
2871You should see @file{#<buffer *scratch*>} appear in the echo area, or
2872the name of whatever other buffer you switched back from most
2873recently@footnote{Actually, by default, if the buffer from which you
2874just switched is visible to you in another window, @code{other-buffer}
2875will choose the most recent buffer that you cannot see; this is a
2876subtlety that I often forget.}.
2877
d6adf7e7 2878@node Switching Buffers
8cda6f8f
GM
2879@section Switching Buffers
2880@findex switch-to-buffer
2881@findex set-buffer
2882@cindex Switching to a buffer
2883
2884The @code{other-buffer} function actually provides a buffer when it is
2885used as an argument to a function that requires one. We can see this
2886by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2887different buffer.
2888
2889But first, a brief introduction to the @code{switch-to-buffer}
2890function. When you switched back and forth from Info to the
2891@file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2892likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2893rather, to save typing, you probably only typed @kbd{RET} if the
2894default buffer was @file{*scratch*}, or if it was different, then you
2895typed just part of the name, such as @code{*sc}, pressed your
2896@kbd{TAB} key to cause it to expand to the full name, and then typed
8f4ea8e0 2897@kbd{RET}.} when prompted in the minibuffer for the name of
8cda6f8f
GM
2898the buffer to which you wanted to switch. The keystrokes, @kbd{C-x
2899b}, cause the Lisp interpreter to evaluate the interactive function
2900@code{switch-to-buffer}. As we said before, this is how Emacs works:
2901different keystrokes call or run different functions. For example,
2902@kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2903@code{forward-sentence}, and so on.
2904
2905By writing @code{switch-to-buffer} in an expression, and giving it a
2906buffer to switch to, we can switch buffers just the way @kbd{C-x b}
8f4ea8e0 2907does:
8cda6f8f
GM
2908
2909@smallexample
2910(switch-to-buffer (other-buffer))
2911@end smallexample
2912
2913@noindent
2914The symbol @code{switch-to-buffer} is the first element of the list,
2915so the Lisp interpreter will treat it as a function and carry out the
2916instructions that are attached to it. But before doing that, the
2917interpreter will note that @code{other-buffer} is inside parentheses
2918and work on that symbol first. @code{other-buffer} is the first (and
2919in this case, the only) element of this list, so the Lisp interpreter
2920calls or runs the function. It returns another buffer. Next, the
2921interpreter runs @code{switch-to-buffer}, passing to it, as an
2922argument, the other buffer, which is what Emacs will switch to. If
2923you are reading this in Info, try this now. Evaluate the expression.
2924(To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2925expression will move you to your most recent other buffer that you
2926cannot see. If you really want to go to your most recently selected
2927buffer, even if you can still see it, you need to evaluate the
2928following more complex expression:
2929
2930@smallexample
2931(switch-to-buffer (other-buffer (current-buffer) t))
2932@end smallexample
2933
2934@c noindent
2935In this case, the first argument to @code{other-buffer} tells it which
2936buffer to skip---the current one---and the second argument tells
2937@code{other-buffer} it is OK to switch to a visible buffer.
2938In regular use, @code{switch-to-buffer} takes you to an invisible
2939window since you would most likely use @kbd{C-x o} (@code{other-window})
2940to go to another visible buffer.}
2941
2942In the programming examples in later sections of this document, you will
2943see the function @code{set-buffer} more often than
2944@code{switch-to-buffer}. This is because of a difference between
2945computer programs and humans: humans have eyes and expect to see the
2946buffer on which they are working on their computer terminals. This is
2947so obvious, it almost goes without saying. However, programs do not
2948have eyes. When a computer program works on a buffer, that buffer does
2949not need to be visible on the screen.
2950
2951@code{switch-to-buffer} is designed for humans and does two different
44e97401 2952things: it switches the buffer to which Emacs's attention is directed; and
8cda6f8f
GM
2953it switches the buffer displayed in the window to the new buffer.
2954@code{set-buffer}, on the other hand, does only one thing: it switches
2955the attention of the computer program to a different buffer. The buffer
2956on the screen remains unchanged (of course, normally nothing happens
2957there until the command finishes running).
2958
2959@cindex @samp{call} defined
2960Also, we have just introduced another jargon term, the word @dfn{call}.
2961When you evaluate a list in which the first symbol is a function, you
2962are calling that function. The use of the term comes from the notion of
2963the function as an entity that can do something for you if you `call'
2964it---just as a plumber is an entity who can fix a leak if you call him
2965or her.
2966
d6adf7e7 2967@node Buffer Size & Locations
8cda6f8f
GM
2968@section Buffer Size and the Location of Point
2969@cindex Size of buffer
2970@cindex Buffer size
2971@cindex Point location
2972@cindex Location of point
2973
2974Finally, let's look at several rather simple functions,
2975@code{buffer-size}, @code{point}, @code{point-min}, and
2976@code{point-max}. These give information about the size of a buffer and
2977the location of point within it.
2978
2979The function @code{buffer-size} tells you the size of the current
2980buffer; that is, the function returns a count of the number of
2981characters in the buffer.
2982
2983@smallexample
2984(buffer-size)
2985@end smallexample
2986
2987@noindent
2988You can evaluate this in the usual way, by positioning the
2989cursor after the expression and typing @kbd{C-x C-e}.
2990
2991@cindex @samp{point} defined
2992In Emacs, the current position of the cursor is called @dfn{point}.
2993The expression @code{(point)} returns a number that tells you where the
2994cursor is located as a count of the number of characters from the
2995beginning of the buffer up to point.
2996
2997@need 1250
2998You can see the character count for point in this buffer by evaluating
2999the following expression in the usual way:
3000
3001@smallexample
3002(point)
3003@end smallexample
3004
3005@noindent
3006As I write this, the value of @code{point} is 65724. The @code{point}
3007function is frequently used in some of the examples later in this
3008book.
3009
3010@need 1250
3011The value of point depends, of course, on its location within the
3012buffer. If you evaluate point in this spot, the number will be larger:
3013
3014@smallexample
3015(point)
3016@end smallexample
3017
3018@noindent
3019For me, the value of point in this location is 66043, which means that
3020there are 319 characters (including spaces) between the two
3021expressions. (Doubtless, you will see different numbers, since I will
3022have edited this since I first evaluated point.)
3023
3024@cindex @samp{narrowing} defined
3025The function @code{point-min} is somewhat similar to @code{point}, but
3026it returns the value of the minimum permissible value of point in the
3027current buffer. This is the number 1 unless @dfn{narrowing} is in
3028effect. (Narrowing is a mechanism whereby you can restrict yourself,
3029or a program, to operations on just a part of a buffer.
3030@xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
3031function @code{point-max} returns the value of the maximum permissible
3032value of point in the current buffer.
3033
d6adf7e7 3034@node Evaluation Exercise
8cda6f8f
GM
3035@section Exercise
3036
3037Find a file with which you are working and move towards its middle.
3038Find its buffer name, file name, length, and your position in the file.
3039
d6adf7e7 3040@node Writing Defuns
8cda6f8f
GM
3041@chapter How To Write Function Definitions
3042@cindex Definition writing
3043@cindex Function definition writing
3044@cindex Writing a function definition
3045
3046When the Lisp interpreter evaluates a list, it looks to see whether the
3047first symbol on the list has a function definition attached to it; or,
3048put another way, whether the symbol points to a function definition. If
3049it does, the computer carries out the instructions in the definition. A
3050symbol that has a function definition is called, simply, a function
3051(although, properly speaking, the definition is the function and the
3052symbol refers to it.)
3053
3054@menu
3055* Primitive Functions::
3056* defun:: The @code{defun} special form.
3057* Install:: Install a function definition.
3058* Interactive:: Making a function interactive.
3059* Interactive Options:: Different options for @code{interactive}.
3060* Permanent Installation:: Installing code permanently.
3061* let:: Creating and initializing local variables.
3062* if:: What if?
3063* else:: If--then--else expressions.
3064* Truth & Falsehood:: What Lisp considers false and true.
3065* save-excursion:: Keeping track of point, mark, and buffer.
3066* Review::
3067* defun Exercises::
3068@end menu
3069
8cda6f8f 3070@ifnottex
d6adf7e7 3071@node Primitive Functions
8cda6f8f
GM
3072@unnumberedsec An Aside about Primitive Functions
3073@end ifnottex
3074@cindex Primitive functions
3075@cindex Functions, primitive
3076
3077@cindex C language primitives
3078@cindex Primitives written in C
3079All functions are defined in terms of other functions, except for a few
3080@dfn{primitive} functions that are written in the C programming
3081language. When you write functions' definitions, you will write them in
3082Emacs Lisp and use other functions as your building blocks. Some of the
3083functions you will use will themselves be written in Emacs Lisp (perhaps
1df7defd 3084by you) and some will be primitives written in C@. The primitive
8cda6f8f
GM
3085functions are used exactly like those written in Emacs Lisp and behave
3086like them. They are written in C so we can easily run GNU Emacs on any
3087computer that has sufficient power and can run C.
3088
3089Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3090distinguish between the use of functions written in C and the use of
3091functions written in Emacs Lisp. The difference is irrelevant. I
3092mention the distinction only because it is interesting to know. Indeed,
3093unless you investigate, you won't know whether an already-written
3094function is written in Emacs Lisp or C.
3095
d6adf7e7 3096@node defun
8cda6f8f
GM
3097@section The @code{defun} Special Form
3098@findex defun
3099@cindex Special form of @code{defun}
3100
3101@cindex @samp{function definition} defined
3102In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3103it that tells the computer what to do when the function is called.
3104This code is called the @dfn{function definition} and is created by
3105evaluating a Lisp expression that starts with the symbol @code{defun}
3106(which is an abbreviation for @emph{define function}). Because
3107@code{defun} does not evaluate its arguments in the usual way, it is
3108called a @dfn{special form}.
3109
3110In subsequent sections, we will look at function definitions from the
3111Emacs source code, such as @code{mark-whole-buffer}. In this section,
3112we will describe a simple function definition so you can see how it
3113looks. This function definition uses arithmetic because it makes for a
3114simple example. Some people dislike examples using arithmetic; however,
3115if you are such a person, do not despair. Hardly any of the code we
3116will study in the remainder of this introduction involves arithmetic or
3117mathematics. The examples mostly involve text in one way or another.
3118
3119A function definition has up to five parts following the word
3120@code{defun}:
3121
3122@enumerate
3123@item
3124The name of the symbol to which the function definition should be
3125attached.
3126
3127@item
3128A list of the arguments that will be passed to the function. If no
3129arguments will be passed to the function, this is an empty list,
3130@code{()}.
3131
3132@item
3133Documentation describing the function. (Technically optional, but
3134strongly recommended.)
3135
3136@item
3137Optionally, an expression to make the function interactive so you can
3138use it by typing @kbd{M-x} and then the name of the function; or by
3139typing an appropriate key or keychord.
3140
3141@cindex @samp{body} defined
3142@item
3143The code that instructs the computer what to do: the @dfn{body} of the
3144function definition.
3145@end enumerate
3146
3147It is helpful to think of the five parts of a function definition as
3148being organized in a template, with slots for each part:
3149
3150@smallexample
3151@group
3152(defun @var{function-name} (@var{arguments}@dots{})
3153 "@var{optional-documentation}@dots{}"
3154 (interactive @var{argument-passing-info}) ; @r{optional}
3155 @var{body}@dots{})
3156@end group
3157@end smallexample
3158
3159As an example, here is the code for a function that multiplies its
3160argument by 7. (This example is not interactive. @xref{Interactive,
3161, Making a Function Interactive}, for that information.)
3162
3163@smallexample
3164@group
3165(defun multiply-by-seven (number)
3166 "Multiply NUMBER by seven."
3167 (* 7 number))
3168@end group
3169@end smallexample
3170
3171This definition begins with a parenthesis and the symbol @code{defun},
3172followed by the name of the function.
3173
3174@cindex @samp{argument list} defined
3175The name of the function is followed by a list that contains the
3176arguments that will be passed to the function. This list is called
3177the @dfn{argument list}. In this example, the list has only one
3178element, the symbol, @code{number}. When the function is used, the
3179symbol will be bound to the value that is used as the argument to the
3180function.
3181
3182Instead of choosing the word @code{number} for the name of the argument,
3183I could have picked any other name. For example, I could have chosen
3184the word @code{multiplicand}. I picked the word `number' because it
3185tells what kind of value is intended for this slot; but I could just as
3186well have chosen the word `multiplicand' to indicate the role that the
3187value placed in this slot will play in the workings of the function. I
3188could have called it @code{foogle}, but that would have been a bad
3189choice because it would not tell humans what it means. The choice of
3190name is up to the programmer and should be chosen to make the meaning of
3191the function clear.
3192
3193Indeed, you can choose any name you wish for a symbol in an argument
3194list, even the name of a symbol used in some other function: the name
3195you use in an argument list is private to that particular definition.
3196In that definition, the name refers to a different entity than any use
3197of the same name outside the function definition. Suppose you have a
3198nick-name `Shorty' in your family; when your family members refer to
3199`Shorty', they mean you. But outside your family, in a movie, for
3200example, the name `Shorty' refers to someone else. Because a name in an
3201argument list is private to the function definition, you can change the
3202value of such a symbol inside the body of a function without changing
3203its value outside the function. The effect is similar to that produced
3204by a @code{let} expression. (@xref{let, , @code{let}}.)
3205
3206@ignore
3207Note also that we discuss the word `number' in two different ways: as a
3208symbol that appears in the code, and as the name of something that will
3209be replaced by a something else during the evaluation of the function.
3210In the first case, @code{number} is a symbol, not a number; it happens
3211that within the function, it is a variable who value is the number in
3212question, but our primary interest in it is as a symbol. On the other
3213hand, when we are talking about the function, our interest is that we
3214will substitute a number for the word @var{number}. To keep this
3215distinction clear, we use different typography for the two
3216circumstances. When we talk about this function, or about how it works,
3217we refer to this number by writing @var{number}. In the function
3218itself, we refer to it by writing @code{number}.
3219@end ignore
3220
3221The argument list is followed by the documentation string that
3222describes the function. This is what you see when you type
3223@w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3224write a documentation string like this, you should make the first line
3225a complete sentence since some commands, such as @code{apropos}, print
3226only the first line of a multi-line documentation string. Also, you
3227should not indent the second line of a documentation string, if you
3228have one, because that looks odd when you use @kbd{C-h f}
3229(@code{describe-function}). The documentation string is optional, but
3230it is so useful, it should be included in almost every function you
3231write.
3232
3233@findex * @r{(multiplication)}
3234The third line of the example consists of the body of the function
3235definition. (Most functions' definitions, of course, are longer than
3236this.) In this function, the body is the list, @code{(* 7 number)}, which
3237says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3238@code{*} is the function for multiplication, just as @code{+} is the
3239function for addition.)
3240
3241When you use the @code{multiply-by-seven} function, the argument
3242@code{number} evaluates to the actual number you want used. Here is an
3243example that shows how @code{multiply-by-seven} is used; but don't try
3244to evaluate this yet!
3245
3246@smallexample
3247(multiply-by-seven 3)
3248@end smallexample
3249
3250@noindent
3251The symbol @code{number}, specified in the function definition in the
3252next section, is given or ``bound to'' the value 3 in the actual use of
3253the function. Note that although @code{number} was inside parentheses
3254in the function definition, the argument passed to the
3255@code{multiply-by-seven} function is not in parentheses. The
3256parentheses are written in the function definition so the computer can
3257figure out where the argument list ends and the rest of the function
3258definition begins.
3259
3260If you evaluate this example, you are likely to get an error message.
3261(Go ahead, try it!) This is because we have written the function
3262definition, but not yet told the computer about the definition---we have
3263not yet installed (or `loaded') the function definition in Emacs.
3264Installing a function is the process that tells the Lisp interpreter the
3265definition of the function. Installation is described in the next
3266section.
3267
d6adf7e7 3268@node Install
8cda6f8f
GM
3269@section Install a Function Definition
3270@cindex Install a Function Definition
3271@cindex Definition installation
3272@cindex Function definition installation
3273
3274If you are reading this inside of Info in Emacs, you can try out the
3275@code{multiply-by-seven} function by first evaluating the function
3276definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3277the function definition follows. Place the cursor after the last
3278parenthesis of the function definition and type @kbd{C-x C-e}. When you
3279do this, @code{multiply-by-seven} will appear in the echo area. (What
3280this means is that when a function definition is evaluated, the value it
3281returns is the name of the defined function.) At the same time, this
3282action installs the function definition.
3283
3284@smallexample
3285@group
3286(defun multiply-by-seven (number)
3287 "Multiply NUMBER by seven."
3288 (* 7 number))
3289@end group
3290@end smallexample
3291
3292@noindent
3293By evaluating this @code{defun}, you have just installed
3294@code{multiply-by-seven} in Emacs. The function is now just as much a
3295part of Emacs as @code{forward-word} or any other editing function you
3296use. (@code{multiply-by-seven} will stay installed until you quit
3297Emacs. To reload code automatically whenever you start Emacs, see
3298@ref{Permanent Installation, , Installing Code Permanently}.)
3299
3300@menu
3301* Effect of installation::
3302* Change a defun:: How to change a function definition.
3303@end menu
3304
8cda6f8f 3305@ifnottex
d6adf7e7 3306@node Effect of installation
8cda6f8f
GM
3307@unnumberedsubsec The effect of installation
3308@end ifnottex
3309
3310You can see the effect of installing @code{multiply-by-seven} by
3311evaluating the following sample. Place the cursor after the following
3312expression and type @kbd{C-x C-e}. The number 21 will appear in the
3313echo area.
3314
3315@smallexample
3316(multiply-by-seven 3)
3317@end smallexample
3318
3319If you wish, you can read the documentation for the function by typing
3320@kbd{C-h f} (@code{describe-function}) and then the name of the
3321function, @code{multiply-by-seven}. When you do this, a
3322@file{*Help*} window will appear on your screen that says:
3323
3324@smallexample
3325@group
3326multiply-by-seven is a Lisp function.
3327(multiply-by-seven NUMBER)
3328
3329Multiply NUMBER by seven.
3330@end group
3331@end smallexample
3332
3333@noindent
3334(To return to a single window on your screen, type @kbd{C-x 1}.)
3335
d6adf7e7 3336@node Change a defun
8cda6f8f
GM
3337@subsection Change a Function Definition
3338@cindex Changing a function definition
3339@cindex Function definition, how to change
3340@cindex Definition, how to change
3341
3342If you want to change the code in @code{multiply-by-seven}, just rewrite
3343it. To install the new version in place of the old one, evaluate the
3344function definition again. This is how you modify code in Emacs. It is
3345very simple.
3346
3347As an example, you can change the @code{multiply-by-seven} function to
3348add the number to itself seven times instead of multiplying the number
3349by seven. It produces the same answer, but by a different path. At
3350the same time, we will add a comment to the code; a comment is text
3351that the Lisp interpreter ignores, but that a human reader may find
3352useful or enlightening. The comment is that this is the ``second
3353version''.
3354
3355@smallexample
3356@group
3357(defun multiply-by-seven (number) ; @r{Second version.}
3358 "Multiply NUMBER by seven."
3359 (+ number number number number number number number))
3360@end group
3361@end smallexample
3362
3363@cindex Comments in Lisp code
3364The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3365line that follows a semicolon is a comment. The end of the line is the
3366end of the comment. To stretch a comment over two or more lines, begin
3367each line with a semicolon.
3368
3369@xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3370File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3371Reference Manual}, for more about comments.
3372
3373You can install this version of the @code{multiply-by-seven} function by
3374evaluating it in the same way you evaluated the first function: place
3375the cursor after the last parenthesis and type @kbd{C-x C-e}.
3376
3377In summary, this is how you write code in Emacs Lisp: you write a
3378function; install it; test it; and then make fixes or enhancements and
3379install it again.
3380
d6adf7e7 3381@node Interactive
8cda6f8f
GM
3382@section Make a Function Interactive
3383@cindex Interactive functions
3384@findex interactive
3385
3386You make a function interactive by placing a list that begins with
3387the special form @code{interactive} immediately after the
3388documentation. A user can invoke an interactive function by typing
3389@kbd{M-x} and then the name of the function; or by typing the keys to
3390which it is bound, for example, by typing @kbd{C-n} for
3391@code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3392
3393Interestingly, when you call an interactive function interactively,
3394the value returned is not automatically displayed in the echo area.
3395This is because you often call an interactive function for its side
3396effects, such as moving forward by a word or line, and not for the
3397value returned. If the returned value were displayed in the echo area
3398each time you typed a key, it would be very distracting.
3399
3400@menu
3401* Interactive multiply-by-seven:: An overview.
3402* multiply-by-seven in detail:: The interactive version.
3403@end menu
3404
8cda6f8f 3405@ifnottex
d6adf7e7 3406@node Interactive multiply-by-seven
8cda6f8f
GM
3407@unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3408@end ifnottex
3409
3410Both the use of the special form @code{interactive} and one way to
3411display a value in the echo area can be illustrated by creating an
3412interactive version of @code{multiply-by-seven}.
3413
3414@need 1250
3415Here is the code:
3416
3417@smallexample
3418@group
3419(defun multiply-by-seven (number) ; @r{Interactive version.}
3420 "Multiply NUMBER by seven."
3421 (interactive "p")
3422 (message "The result is %d" (* 7 number)))
3423@end group
3424@end smallexample
3425
3426@noindent
3427You can install this code by placing your cursor after it and typing
3428@kbd{C-x C-e}. The name of the function will appear in your echo area.
3429Then, you can use this code by typing @kbd{C-u} and a number and then
3430typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3431@samp{The result is @dots{}} followed by the product will appear in the
3432echo area.
3433
3434Speaking more generally, you invoke a function like this in either of two
3435ways:
3436
3437@enumerate
3438@item
3439By typing a prefix argument that contains the number to be passed, and
3440then typing @kbd{M-x} and the name of the function, as with
3441@kbd{C-u 3 M-x forward-sentence}; or,
3442
3443@item
3444By typing whatever key or keychord the function is bound to, as with
3445@kbd{C-u 3 M-e}.
3446@end enumerate
3447
3448@noindent
3449Both the examples just mentioned work identically to move point forward
3450three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3451it could not be used as an example of key binding.)
3452
3453(@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3454to a key.)
3455
3456A prefix argument is passed to an interactive function by typing the
3457@key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3458typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3459type @kbd{C-u} without a number, it defaults to 4).
3460
d6adf7e7 3461@node multiply-by-seven in detail
8cda6f8f
GM
3462@subsection An Interactive @code{multiply-by-seven}
3463
3464Let's look at the use of the special form @code{interactive} and then at
3465the function @code{message} in the interactive version of
3466@code{multiply-by-seven}. You will recall that the function definition
3467looks like this:
3468
3469@smallexample
3470@group
3471(defun multiply-by-seven (number) ; @r{Interactive version.}
3472 "Multiply NUMBER by seven."
3473 (interactive "p")
3474 (message "The result is %d" (* 7 number)))
3475@end group
3476@end smallexample
3477
3478In this function, the expression, @code{(interactive "p")}, is a list of
3479two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3480the function and use its value for the argument of the function.
3481
3482@need 1000
3483The argument will be a number. This means that the symbol
3484@code{number} will be bound to a number in the line:
3485
3486@smallexample
3487(message "The result is %d" (* 7 number))
3488@end smallexample
3489
3490@need 1250
3491@noindent
3492For example, if your prefix argument is 5, the Lisp interpreter will
3493evaluate the line as if it were:
3494
3495@smallexample
3496(message "The result is %d" (* 7 5))
3497@end smallexample
3498
3499@noindent
3500(If you are reading this in GNU Emacs, you can evaluate this expression
3501yourself.) First, the interpreter will evaluate the inner list, which
3502is @code{(* 7 5)}. This returns a value of 35. Next, it
3503will evaluate the outer list, passing the values of the second and
3504subsequent elements of the list to the function @code{message}.
3505
3506As we have seen, @code{message} is an Emacs Lisp function especially
3507designed for sending a one line message to a user. (@xref{message, ,
3508The @code{message} function}.) In summary, the @code{message}
3509function prints its first argument in the echo area as is, except for
3510occurrences of @samp{%d} or @samp{%s} (and various other %-sequences
3511which we have not mentioned). When it sees a control sequence, the
3512function looks to the second or subsequent arguments and prints the
3513value of the argument in the location in the string where the control
3514sequence is located.
3515
3516In the interactive @code{multiply-by-seven} function, the control string
3517is @samp{%d}, which requires a number, and the value returned by
3518evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3519is printed in place of the @samp{%d} and the message is @samp{The result
3520is 35}.
3521
3522(Note that when you call the function @code{multiply-by-seven}, the
3523message is printed without quotes, but when you call @code{message}, the
3524text is printed in double quotes. This is because the value returned by
3525@code{message} is what appears in the echo area when you evaluate an
3526expression whose first element is @code{message}; but when embedded in a
3527function, @code{message} prints the text as a side effect without
3528quotes.)
3529
d6adf7e7 3530@node Interactive Options
8cda6f8f
GM
3531@section Different Options for @code{interactive}
3532@cindex Options for @code{interactive}
3533@cindex Interactive options
3534
3535In the example, @code{multiply-by-seven} used @code{"p"} as the
3536argument to @code{interactive}. This argument told Emacs to interpret
3537your typing either @kbd{C-u} followed by a number or @key{META}
3538followed by a number as a command to pass that number to the function
3539as its argument. Emacs has more than twenty characters predefined for
3540use with @code{interactive}. In almost every case, one of these
3541options will enable you to pass the right information interactively to
3542a function. (@xref{Interactive Codes, , Code Characters for
3543@code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3544
3545@need 1250
3546Consider the function @code{zap-to-char}. Its interactive expression
3547is
3548
3549@smallexample
3550(interactive "p\ncZap to char: ")
3551@end smallexample
3552
3553The first part of the argument to @code{interactive} is @samp{p}, with
3554which you are already familiar. This argument tells Emacs to
3555interpret a `prefix', as a number to be passed to the function. You
3556can specify a prefix either by typing @kbd{C-u} followed by a number
3557or by typing @key{META} followed by a number. The prefix is the
3558number of specified characters. Thus, if your prefix is three and the
3559specified character is @samp{x}, then you will delete all the text up
3560to and including the third next @samp{x}. If you do not set a prefix,
3561then you delete all the text up to and including the specified
3562character, but no more.
3563
3564The @samp{c} tells the function the name of the character to which to delete.
3565
3566More formally, a function with two or more arguments can have
3567information passed to each argument by adding parts to the string that
3568follows @code{interactive}. When you do this, the information is
3569passed to each argument in the same order it is specified in the
3570@code{interactive} list. In the string, each part is separated from
3571the next part by a @samp{\n}, which is a newline. For example, you
3572can follow @samp{p} with a @samp{\n} and an @samp{cZap to char:@: }.
3573This causes Emacs to pass the value of the prefix argument (if there
3574is one) and the character.
3575
3576In this case, the function definition looks like the following, where
3577@code{arg} and @code{char} are the symbols to which @code{interactive}
3578binds the prefix argument and the specified character:
3579
3580@smallexample
3581@group
3582(defun @var{name-of-function} (arg char)
3583 "@var{documentation}@dots{}"
3584 (interactive "p\ncZap to char: ")
3585 @var{body-of-function}@dots{})
3586@end group
3587@end smallexample
3588
3589@noindent
3590(The space after the colon in the prompt makes it look better when you
3591are prompted. @xref{copy-to-buffer, , The Definition of
3592@code{copy-to-buffer}}, for an example.)
3593
3594When a function does not take arguments, @code{interactive} does not
3595require any. Such a function contains the simple expression
3596@code{(interactive)}. The @code{mark-whole-buffer} function is like
3597this.
3598
3599Alternatively, if the special letter-codes are not right for your
3600application, you can pass your own arguments to @code{interactive} as
3601a list.
3602
3603@xref{append-to-buffer, , The Definition of @code{append-to-buffer}},
3604for an example. @xref{Using Interactive, , Using @code{Interactive},
3605elisp, The GNU Emacs Lisp Reference Manual}, for a more complete
3606explanation about this technique.
3607
d6adf7e7 3608@node Permanent Installation
8cda6f8f
GM
3609@section Install Code Permanently
3610@cindex Install code permanently
3611@cindex Permanent code installation
3612@cindex Code installation
3613
3614When you install a function definition by evaluating it, it will stay
3615installed until you quit Emacs. The next time you start a new session
3616of Emacs, the function will not be installed unless you evaluate the
3617function definition again.
3618
3619At some point, you may want to have code installed automatically
3620whenever you start a new session of Emacs. There are several ways of
3621doing this:
3622
3623@itemize @bullet
3624@item
3625If you have code that is just for yourself, you can put the code for the
3626function definition in your @file{.emacs} initialization file. When you
3627start Emacs, your @file{.emacs} file is automatically evaluated and all
3628the function definitions within it are installed.
3629@xref{Emacs Initialization, , Your @file{.emacs} File}.
3630
3631@item
3632Alternatively, you can put the function definitions that you want
3633installed in one or more files of their own and use the @code{load}
3634function to cause Emacs to evaluate and thereby install each of the
3635functions in the files.
3636@xref{Loading Files, , Loading Files}.
3637
3638@item
3639Thirdly, if you have code that your whole site will use, it is usual
3640to put it in a file called @file{site-init.el} that is loaded when
3641Emacs is built. This makes the code available to everyone who uses
3642your machine. (See the @file{INSTALL} file that is part of the Emacs
3643distribution.)
3644@end itemize
3645
3646Finally, if you have code that everyone who uses Emacs may want, you
3647can post it on a computer network or send a copy to the Free Software
3648Foundation. (When you do this, please license the code and its
3649documentation under a license that permits other people to run, copy,
3650study, modify, and redistribute the code and which protects you from
3651having your work taken from you.) If you send a copy of your code to
3652the Free Software Foundation, and properly protect yourself and
3653others, it may be included in the next release of Emacs. In large
3654part, this is how Emacs has grown over the past years, by donations.
3655
d6adf7e7 3656@node let
8cda6f8f
GM
3657@section @code{let}
3658@findex let
3659
3660The @code{let} expression is a special form in Lisp that you will need
3661to use in most function definitions.
3662
3663@code{let} is used to attach or bind a symbol to a value in such a way
3664that the Lisp interpreter will not confuse the variable with a
3665variable of the same name that is not part of the function.
3666
3667To understand why the @code{let} special form is necessary, consider
3668the situation in which you own a home that you generally refer to as
3669`the house', as in the sentence, ``The house needs painting.'' If you
3670are visiting a friend and your host refers to `the house', he is
3671likely to be referring to @emph{his} house, not yours, that is, to a
3672different house.
3673
3674If your friend is referring to his house and you think he is referring
3675to your house, you may be in for some confusion. The same thing could
3676happen in Lisp if a variable that is used inside of one function has
3677the same name as a variable that is used inside of another function,
3678and the two are not intended to refer to the same value. The
3679@code{let} special form prevents this kind of confusion.
3680
3681@menu
3682* Prevent confusion::
3683* Parts of let Expression::
3684* Sample let Expression::
3685* Uninitialized let Variables::
3686@end menu
3687
8cda6f8f 3688@ifnottex
d6adf7e7 3689@node Prevent confusion
8cda6f8f
GM
3690@unnumberedsubsec @code{let} Prevents Confusion
3691@end ifnottex
3692
3693@cindex @samp{local variable} defined
3694@cindex @samp{variable, local}, defined
3695The @code{let} special form prevents confusion. @code{let} creates a
3696name for a @dfn{local variable} that overshadows any use of the same
3697name outside the @code{let} expression. This is like understanding
3698that whenever your host refers to `the house', he means his house, not
3699yours. (Symbols used in argument lists work the same way.
3700@xref{defun, , The @code{defun} Special Form}.)
3701
3702Local variables created by a @code{let} expression retain their value
3703@emph{only} within the @code{let} expression itself (and within
3704expressions called within the @code{let} expression); the local
3705variables have no effect outside the @code{let} expression.
3706
3707Another way to think about @code{let} is that it is like a @code{setq}
3708that is temporary and local. The values set by @code{let} are
3709automatically undone when the @code{let} is finished. The setting
3710only affects expressions that are inside the bounds of the @code{let}
3711expression. In computer science jargon, we would say ``the binding of
3712a symbol is visible only in functions called in the @code{let} form;
3713in Emacs Lisp, scoping is dynamic, not lexical.''
3714
3715@code{let} can create more than one variable at once. Also,
3716@code{let} gives each variable it creates an initial value, either a
3717value specified by you, or @code{nil}. (In the jargon, this is called
3718`binding the variable to the value'.) After @code{let} has created
3719and bound the variables, it executes the code in the body of the
3720@code{let}, and returns the value of the last expression in the body,
3721as the value of the whole @code{let} expression. (`Execute' is a jargon
3722term that means to evaluate a list; it comes from the use of the word
3723meaning `to give practical effect to' (@cite{Oxford English
3724Dictionary}). Since you evaluate an expression to perform an action,
3725`execute' has evolved as a synonym to `evaluate'.)
3726
d6adf7e7 3727@node Parts of let Expression
8cda6f8f
GM
3728@subsection The Parts of a @code{let} Expression
3729@cindex @code{let} expression, parts of
3730@cindex Parts of @code{let} expression
3731
3732@cindex @samp{varlist} defined
3733A @code{let} expression is a list of three parts. The first part is
3734the symbol @code{let}. The second part is a list, called a
3735@dfn{varlist}, each element of which is either a symbol by itself or a
3736two-element list, the first element of which is a symbol. The third
3737part of the @code{let} expression is the body of the @code{let}. The
3738body usually consists of one or more lists.
3739
3740@need 800
3741A template for a @code{let} expression looks like this:
3742
3743@smallexample
3744(let @var{varlist} @var{body}@dots{})
3745@end smallexample
3746
3747@noindent
3748The symbols in the varlist are the variables that are given initial
3749values by the @code{let} special form. Symbols by themselves are given
3750the initial value of @code{nil}; and each symbol that is the first
3751element of a two-element list is bound to the value that is returned
3752when the Lisp interpreter evaluates the second element.
3753
3754Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3755this case, in a @code{let} expression, Emacs binds the symbol
3756@code{thread} to an initial value of @code{nil}, and binds the symbol
3757@code{needles} to an initial value of 3.
3758
3759When you write a @code{let} expression, what you do is put the
3760appropriate expressions in the slots of the @code{let} expression
3761template.
3762
3763If the varlist is composed of two-element lists, as is often the case,
3764the template for the @code{let} expression looks like this:
3765
3766@smallexample
3767@group
3768(let ((@var{variable} @var{value})
3769 (@var{variable} @var{value})
3770 @dots{})
3771 @var{body}@dots{})
3772@end group
3773@end smallexample
3774
d6adf7e7 3775@node Sample let Expression
8cda6f8f
GM
3776@subsection Sample @code{let} Expression
3777@cindex Sample @code{let} expression
3778@cindex @code{let} expression sample
3779
3780The following expression creates and gives initial values
3781to the two variables @code{zebra} and @code{tiger}. The body of the
3782@code{let} expression is a list which calls the @code{message} function.
3783
3784@smallexample
3785@group
3786(let ((zebra 'stripes)
3787 (tiger 'fierce))
3788 (message "One kind of animal has %s and another is %s."
3789 zebra tiger))
3790@end group
3791@end smallexample
3792
3793Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3794
3795The two variables are @code{zebra} and @code{tiger}. Each variable is
3796the first element of a two-element list and each value is the second
3797element of its two-element list. In the varlist, Emacs binds the
3798variable @code{zebra} to the value @code{stripes}@footnote{According
3799to Jared Diamond in @cite{Guns, Germs, and Steel}, ``@dots{} zebras
3800become impossibly dangerous as they grow older'' but the claim here is
3801that they do not become fierce like a tiger. (1997, W. W. Norton and
3802Co., ISBN 0-393-03894-2, page 171)}, and binds the
3803variable @code{tiger} to the value @code{fierce}. In this example,
3804both values are symbols preceded by a quote. The values could just as
3805well have been another list or a string. The body of the @code{let}
3806follows after the list holding the variables. In this example, the
3807body is a list that uses the @code{message} function to print a string
3808in the echo area.
3809
3810@need 1500
3811You may evaluate the example in the usual fashion, by placing the
3812cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3813this, the following will appear in the echo area:
3814
3815@smallexample
3816"One kind of animal has stripes and another is fierce."
3817@end smallexample
3818
3819As we have seen before, the @code{message} function prints its first
3820argument, except for @samp{%s}. In this example, the value of the variable
3821@code{zebra} is printed at the location of the first @samp{%s} and the
3822value of the variable @code{tiger} is printed at the location of the
3823second @samp{%s}.
3824
d6adf7e7 3825@node Uninitialized let Variables
8cda6f8f
GM
3826@subsection Uninitialized Variables in a @code{let} Statement
3827@cindex Uninitialized @code{let} variables
3828@cindex @code{let} variables uninitialized
3829
3830If you do not bind the variables in a @code{let} statement to specific
3831initial values, they will automatically be bound to an initial value of
3832@code{nil}, as in the following expression:
3833
3834@smallexample
3835@group
3836(let ((birch 3)
3837 pine
3838 fir
3839 (oak 'some))
3840 (message
3841 "Here are %d variables with %s, %s, and %s value."
3842 birch pine fir oak))
3843@end group
3844@end smallexample
3845
3846@noindent
3847Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3848
3849@need 1250
3850If you evaluate this expression in the usual way, the following will
3851appear in your echo area:
3852
3853@smallexample
3854"Here are 3 variables with nil, nil, and some value."
3855@end smallexample
3856
3857@noindent
3858In this example, Emacs binds the symbol @code{birch} to the number 3,
3859binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3860the symbol @code{oak} to the value @code{some}.
3861
3862Note that in the first part of the @code{let}, the variables @code{pine}
3863and @code{fir} stand alone as atoms that are not surrounded by
3864parentheses; this is because they are being bound to @code{nil}, the
3865empty list. But @code{oak} is bound to @code{some} and so is a part of
3866the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3867number 3 and so is in a list with that number. (Since a number
3868evaluates to itself, the number does not need to be quoted. Also, the
3869number is printed in the message using a @samp{%d} rather than a
3870@samp{%s}.) The four variables as a group are put into a list to
3871delimit them from the body of the @code{let}.
3872
d6adf7e7 3873@node if
8cda6f8f
GM
3874@section The @code{if} Special Form
3875@findex if
3876@cindex Conditional with @code{if}
3877
3878A third special form, in addition to @code{defun} and @code{let}, is the
3879conditional @code{if}. This form is used to instruct the computer to
3880make decisions. You can write function definitions without using
3881@code{if}, but it is used often enough, and is important enough, to be
3882included here. It is used, for example, in the code for the
3883function @code{beginning-of-buffer}.
3884
3885The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3886@emph{then} an expression is evaluated.'' If the test is not true, the
3887expression is not evaluated. For example, you might make a decision
3888such as, ``if it is warm and sunny, then go to the beach!''
3889
3890@menu
3891* if in more detail::
3892* type-of-animal in detail:: An example of an @code{if} expression.
3893@end menu
3894
8cda6f8f 3895@ifnottex
d6adf7e7 3896@node if in more detail
8cda6f8f
GM
3897@unnumberedsubsec @code{if} in more detail
3898@end ifnottex
3899
3900@cindex @samp{if-part} defined
3901@cindex @samp{then-part} defined
3902An @code{if} expression written in Lisp does not use the word `then';
3903the test and the action are the second and third elements of the list
3904whose first element is @code{if}. Nonetheless, the test part of an
3905@code{if} expression is often called the @dfn{if-part} and the second
3906argument is often called the @dfn{then-part}.
3907
3908Also, when an @code{if} expression is written, the true-or-false-test
3909is usually written on the same line as the symbol @code{if}, but the
3910action to carry out if the test is true, the ``then-part'', is written
3911on the second and subsequent lines. This makes the @code{if}
3912expression easier to read.
3913
3914@smallexample
3915@group
3916(if @var{true-or-false-test}
3917 @var{action-to-carry-out-if-test-is-true})
3918@end group
3919@end smallexample
3920
3921@noindent
3922The true-or-false-test will be an expression that
3923is evaluated by the Lisp interpreter.
3924
3925Here is an example that you can evaluate in the usual manner. The test
3926is whether the number 5 is greater than the number 4. Since it is, the
3927message @samp{5 is greater than 4!} will be printed.
3928
3929@smallexample
3930@group
3931(if (> 5 4) ; @r{if-part}
3932 (message "5 is greater than 4!")) ; @r{then-part}
3933@end group
3934@end smallexample
3935
3936@noindent
3937(The function @code{>} tests whether its first argument is greater than
3938its second argument and returns true if it is.)
3939@findex > (greater than)
3940
3941Of course, in actual use, the test in an @code{if} expression will not
3942be fixed for all time as it is by the expression @code{(> 5 4)}.
3943Instead, at least one of the variables used in the test will be bound to
3944a value that is not known ahead of time. (If the value were known ahead
3945of time, we would not need to run the test!)
3946
3947For example, the value may be bound to an argument of a function
3948definition. In the following function definition, the character of the
3949animal is a value that is passed to the function. If the value bound to
3950@code{characteristic} is @code{fierce}, then the message, @samp{It's a
3951tiger!} will be printed; otherwise, @code{nil} will be returned.
3952
3953@smallexample
3954@group
3955(defun type-of-animal (characteristic)
3956 "Print message in echo area depending on CHARACTERISTIC.
3957If the CHARACTERISTIC is the symbol `fierce',
3958then warn of a tiger."
3959 (if (equal characteristic 'fierce)
3960 (message "It's a tiger!")))
3961@end group
3962@end smallexample
3963
3964@need 1500
3965@noindent
3966If you are reading this inside of GNU Emacs, you can evaluate the
3967function definition in the usual way to install it in Emacs, and then you
3968can evaluate the following two expressions to see the results:
3969
3970@smallexample
3971@group
3972(type-of-animal 'fierce)
3973
3974(type-of-animal 'zebra)
3975
3976@end group
3977@end smallexample
3978
3979@c Following sentences rewritten to prevent overfull hbox.
3980@noindent
3981When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3982following message printed in the echo area: @code{"It's a tiger!"}; and
3983when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3984printed in the echo area.
3985
d6adf7e7 3986@node type-of-animal in detail
8cda6f8f
GM
3987@subsection The @code{type-of-animal} Function in Detail
3988
3989Let's look at the @code{type-of-animal} function in detail.
3990
3991The function definition for @code{type-of-animal} was written by filling
3992the slots of two templates, one for a function definition as a whole, and
3993a second for an @code{if} expression.
3994
3995@need 1250
3996The template for every function that is not interactive is:
3997
3998@smallexample
3999@group
4000(defun @var{name-of-function} (@var{argument-list})
4001 "@var{documentation}@dots{}"
4002 @var{body}@dots{})
4003@end group
4004@end smallexample
4005
4006@need 800
4007The parts of the function that match this template look like this:
4008
4009@smallexample
4010@group
4011(defun type-of-animal (characteristic)
4012 "Print message in echo area depending on CHARACTERISTIC.
4013If the CHARACTERISTIC is the symbol `fierce',
4014then warn of a tiger."
4015 @var{body: the} @code{if} @var{expression})
4016@end group
4017@end smallexample
4018
4019The name of function is @code{type-of-animal}; it is passed the value
4020of one argument. The argument list is followed by a multi-line
4021documentation string. The documentation string is included in the
4022example because it is a good habit to write documentation string for
4023every function definition. The body of the function definition
4024consists of the @code{if} expression.
4025
4026@need 800
4027The template for an @code{if} expression looks like this:
4028
4029@smallexample
4030@group
4031(if @var{true-or-false-test}
4032 @var{action-to-carry-out-if-the-test-returns-true})
4033@end group
4034@end smallexample
4035
4036@need 1250
4037In the @code{type-of-animal} function, the code for the @code{if}
4038looks like this:
4039
4040@smallexample
4041@group
4042(if (equal characteristic 'fierce)
4043 (message "It's a tiger!")))
4044@end group
4045@end smallexample
4046
4047@need 800
4048Here, the true-or-false-test is the expression:
4049
4050@smallexample
4051(equal characteristic 'fierce)
4052@end smallexample
4053
4054@noindent
4055In Lisp, @code{equal} is a function that determines whether its first
4056argument is equal to its second argument. The second argument is the
4057quoted symbol @code{'fierce} and the first argument is the value of the
4058symbol @code{characteristic}---in other words, the argument passed to
4059this function.
4060
4061In the first exercise of @code{type-of-animal}, the argument
4062@code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4063is equal to @code{fierce}, the expression, @code{(equal characteristic
4064'fierce)}, returns a value of true. When this happens, the @code{if}
4065evaluates the second argument or then-part of the @code{if}:
4066@code{(message "It's tiger!")}.
4067
4068On the other hand, in the second exercise of @code{type-of-animal}, the
4069argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4070is not equal to @code{fierce}, so the then-part is not evaluated and
4071@code{nil} is returned by the @code{if} expression.
4072
d6adf7e7 4073@node else
8cda6f8f
GM
4074@section If--then--else Expressions
4075@cindex Else
4076
4077An @code{if} expression may have an optional third argument, called
4078the @dfn{else-part}, for the case when the true-or-false-test returns
4079false. When this happens, the second argument or then-part of the
4080overall @code{if} expression is @emph{not} evaluated, but the third or
4081else-part @emph{is} evaluated. You might think of this as the cloudy
4082day alternative for the decision ``if it is warm and sunny, then go to
4083the beach, else read a book!''.
4084
4085The word ``else'' is not written in the Lisp code; the else-part of an
4086@code{if} expression comes after the then-part. In the written Lisp, the
4087else-part is usually written to start on a line of its own and is
4088indented less than the then-part:
4089
4090@smallexample
4091@group
4092(if @var{true-or-false-test}
4093 @var{action-to-carry-out-if-the-test-returns-true}
4094 @var{action-to-carry-out-if-the-test-returns-false})
4095@end group
4096@end smallexample
4097
4098For example, the following @code{if} expression prints the message @samp{4
4099is not greater than 5!} when you evaluate it in the usual way:
4100
4101@smallexample
4102@group
4103(if (> 4 5) ; @r{if-part}
4104 (message "4 falsely greater than 5!") ; @r{then-part}
4105 (message "4 is not greater than 5!")) ; @r{else-part}
4106@end group
4107@end smallexample
4108
4109@noindent
4110Note that the different levels of indentation make it easy to
4111distinguish the then-part from the else-part. (GNU Emacs has several
4112commands that automatically indent @code{if} expressions correctly.
4113@xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4114
4115We can extend the @code{type-of-animal} function to include an
4116else-part by simply incorporating an additional part to the @code{if}
4117expression.
4118
4119@need 1500
4120You can see the consequences of doing this if you evaluate the following
4121version of the @code{type-of-animal} function definition to install it
4122and then evaluate the two subsequent expressions to pass different
4123arguments to the function.
4124
4125@smallexample
4126@group
4127(defun type-of-animal (characteristic) ; @r{Second version.}
4128 "Print message in echo area depending on CHARACTERISTIC.
4129If the CHARACTERISTIC is the symbol `fierce',
4130then warn of a tiger;
4131else say it's not fierce."
4132 (if (equal characteristic 'fierce)
4133 (message "It's a tiger!")
4134 (message "It's not fierce!")))
4135@end group
4136@end smallexample
4137@sp 1
4138
4139@smallexample
4140@group
4141(type-of-animal 'fierce)
4142
4143(type-of-animal 'zebra)
4144
4145@end group
4146@end smallexample
4147
4148@c Following sentence rewritten to prevent overfull hbox.
4149@noindent
4150When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4151following message printed in the echo area: @code{"It's a tiger!"}; but
4152when you evaluate @code{(type-of-animal 'zebra)}, you will see
4153@code{"It's not fierce!"}.
4154
4155(Of course, if the @var{characteristic} were @code{ferocious}, the
4156message @code{"It's not fierce!"} would be printed; and it would be
4157misleading! When you write code, you need to take into account the
4158possibility that some such argument will be tested by the @code{if}
4159and write your program accordingly.)
4160
d6adf7e7 4161@node Truth & Falsehood
8cda6f8f
GM
4162@section Truth and Falsehood in Emacs Lisp
4163@cindex Truth and falsehood in Emacs Lisp
4164@cindex Falsehood and truth in Emacs Lisp
4165@findex nil
4166
4167There is an important aspect to the truth test in an @code{if}
4168expression. So far, we have spoken of `true' and `false' as values of
4169predicates as if they were new kinds of Emacs Lisp objects. In fact,
4170`false' is just our old friend @code{nil}. Anything else---anything
4171at all---is `true'.
4172
4173The expression that tests for truth is interpreted as @dfn{true}
4174if the result of evaluating it is a value that is not @code{nil}. In
4175other words, the result of the test is considered true if the value
4176returned is a number such as 47, a string such as @code{"hello"}, or a
4177symbol (other than @code{nil}) such as @code{flowers}, or a list (so
4178long as it is not empty), or even a buffer!
4179
4180@menu
4181* nil explained:: @code{nil} has two meanings.
4182@end menu
4183
8cda6f8f 4184@ifnottex
d6adf7e7 4185@node nil explained
8cda6f8f
GM
4186@unnumberedsubsec An explanation of @code{nil}
4187@end ifnottex
4188
4189Before illustrating a test for truth, we need an explanation of @code{nil}.
4190
4191In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4192empty list. Second, it means false and is the value returned when a
4193true-or-false-test tests false. @code{nil} can be written as an empty
4194list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4195concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4196to use @code{nil} for false and @code{()} for the empty list.
4197
4198In Emacs Lisp, any value that is not @code{nil}---is not the empty
4199list---is considered true. This means that if an evaluation returns
4200something that is not an empty list, an @code{if} expression will test
4201true. For example, if a number is put in the slot for the test, it
4202will be evaluated and will return itself, since that is what numbers
4203do when evaluated. In this conditional, the @code{if} expression will
4204test true. The expression tests false only when @code{nil}, an empty
4205list, is returned by evaluating the expression.
4206
4207You can see this by evaluating the two expressions in the following examples.
4208
4209In the first example, the number 4 is evaluated as the test in the
4210@code{if} expression and returns itself; consequently, the then-part
4211of the expression is evaluated and returned: @samp{true} appears in
4212the echo area. In the second example, the @code{nil} indicates false;
4213consequently, the else-part of the expression is evaluated and
4214returned: @samp{false} appears in the echo area.
4215
4216@smallexample
4217@group
4218(if 4
4219 'true
4220 'false)
4221@end group
4222
4223@group
4224(if nil
4225 'true
4226 'false)
4227@end group
4228@end smallexample
4229
4230@need 1250
4231Incidentally, if some other useful value is not available for a test that
4232returns true, then the Lisp interpreter will return the symbol @code{t}
4233for true. For example, the expression @code{(> 5 4)} returns @code{t}
4234when evaluated, as you can see by evaluating it in the usual way:
4235
4236@smallexample
4237(> 5 4)
4238@end smallexample
4239
4240@need 1250
4241@noindent
4242On the other hand, this function returns @code{nil} if the test is false.
4243
4244@smallexample
4245(> 4 5)
4246@end smallexample
4247
d6adf7e7 4248@node save-excursion
8cda6f8f
GM
4249@section @code{save-excursion}
4250@findex save-excursion
4251@cindex Region, what it is
4252@cindex Preserving point, mark, and buffer
4253@cindex Point, mark, buffer preservation
4254@findex point
4255@findex mark
4256
4257The @code{save-excursion} function is the fourth and final special form
4258that we will discuss in this chapter.
4259
4260In Emacs Lisp programs used for editing, the @code{save-excursion}
4261function is very common. It saves the location of point and mark,
4262executes the body of the function, and then restores point and mark to
4263their previous positions if their locations were changed. Its primary
4264purpose is to keep the user from being surprised and disturbed by
4265unexpected movement of point or mark.
4266
4267@menu
4268* Point and mark:: A review of various locations.
4269* Template for save-excursion::
4270@end menu
4271
8cda6f8f 4272@ifnottex
d6adf7e7 4273@node Point and mark
8cda6f8f
GM
4274@unnumberedsubsec Point and Mark
4275@end ifnottex
4276
4277Before discussing @code{save-excursion}, however, it may be useful
4278first to review what point and mark are in GNU Emacs. @dfn{Point} is
4279the current location of the cursor. Wherever the cursor
4280is, that is point. More precisely, on terminals where the cursor
4281appears to be on top of a character, point is immediately before the
4282character. In Emacs Lisp, point is an integer. The first character in
4283a buffer is number one, the second is number two, and so on. The
4284function @code{point} returns the current position of the cursor as a
4285number. Each buffer has its own value for point.
4286
4287The @dfn{mark} is another position in the buffer; its value can be set
4288with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4289a mark has been set, you can use the command @kbd{C-x C-x}
4290(@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4291and set the mark to be the previous position of point. In addition, if
4292you set another mark, the position of the previous mark is saved in the
4293mark ring. Many mark positions can be saved this way. You can jump the
4294cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4295times.
4296
4297The part of the buffer between point and mark is called @dfn{the
4298region}. Numerous commands work on the region, including
4299@code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4300@code{print-region}.
4301
4302The @code{save-excursion} special form saves the locations of point and
4303mark and restores those positions after the code within the body of the
4304special form is evaluated by the Lisp interpreter. Thus, if point were
4305in the beginning of a piece of text and some code moved point to the end
4306of the buffer, the @code{save-excursion} would put point back to where
4307it was before, after the expressions in the body of the function were
4308evaluated.
4309
4310In Emacs, a function frequently moves point as part of its internal
4311workings even though a user would not expect this. For example,
4312@code{count-lines-region} moves point. To prevent the user from being
4313bothered by jumps that are both unexpected and (from the user's point of
4314view) unnecessary, @code{save-excursion} is often used to keep point and
4315mark in the location expected by the user. The use of
4316@code{save-excursion} is good housekeeping.
4317
4318To make sure the house stays clean, @code{save-excursion} restores the
4319values of point and mark even if something goes wrong in the code inside
4320of it (or, to be more precise and to use the proper jargon, ``in case of
4321abnormal exit''). This feature is very helpful.
4322
4323In addition to recording the values of point and mark,
4324@code{save-excursion} keeps track of the current buffer, and restores
4325it, too. This means you can write code that will change the buffer and
4326have @code{save-excursion} switch you back to the original buffer.
4327This is how @code{save-excursion} is used in @code{append-to-buffer}.
4328(@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4329
d6adf7e7 4330@node Template for save-excursion
8cda6f8f
GM
4331@subsection Template for a @code{save-excursion} Expression
4332
4333@need 800
4334The template for code using @code{save-excursion} is simple:
4335
4336@smallexample
4337@group
4338(save-excursion
4339 @var{body}@dots{})
4340@end group
4341@end smallexample
4342
4343@noindent
4344The body of the function is one or more expressions that will be
4345evaluated in sequence by the Lisp interpreter. If there is more than
4346one expression in the body, the value of the last one will be returned
4347as the value of the @code{save-excursion} function. The other
4348expressions in the body are evaluated only for their side effects; and
4349@code{save-excursion} itself is used only for its side effect (which
4350is restoring the positions of point and mark).
4351
4352@need 1250
4353In more detail, the template for a @code{save-excursion} expression
4354looks like this:
4355
4356@smallexample
4357@group
4358(save-excursion
4359 @var{first-expression-in-body}
4360 @var{second-expression-in-body}
4361 @var{third-expression-in-body}
4362 @dots{}
4363 @var{last-expression-in-body})
4364@end group
4365@end smallexample
4366
4367@noindent
4368An expression, of course, may be a symbol on its own or a list.
4369
4370In Emacs Lisp code, a @code{save-excursion} expression often occurs
4371within the body of a @code{let} expression. It looks like this:
4372
4373@smallexample
4374@group
4375(let @var{varlist}
4376 (save-excursion
4377 @var{body}@dots{}))
4378@end group
4379@end smallexample
4380
d6adf7e7 4381@node Review
8cda6f8f
GM
4382@section Review
4383
4384In the last few chapters we have introduced a fair number of functions
4385and special forms. Here they are described in brief, along with a few
4386similar functions that have not been mentioned yet.
4387
4388@table @code
4389@item eval-last-sexp
4390Evaluate the last symbolic expression before the current location of
4391point. The value is printed in the echo area unless the function is
4392invoked with an argument; in that case, the output is printed in the
4393current buffer. This command is normally bound to @kbd{C-x C-e}.
4394
4395@item defun
4396Define function. This special form has up to five parts: the name,
4397a template for the arguments that will be passed to the function,
4398documentation, an optional interactive declaration, and the body of the
4399definition.
4400
4401@need 1250
4402For example, in an early version of Emacs, the function definition was
4403as follows. (It is slightly more complex now that it seeks the first
4404non-whitespace character rather than the first visible character.)
4405
4406@smallexample
4407@group
4408(defun back-to-indentation ()
4409 "Move point to first visible character on line."
4410 (interactive)
4411 (beginning-of-line 1)
4412 (skip-chars-forward " \t"))
4413@end group
4414@end smallexample
4415
4416@ignore
4417In GNU Emacs 22,
4418
4419(defun backward-to-indentation (&optional arg)
4420 "Move backward ARG lines and position at first nonblank character."
4421 (interactive "p")
4422 (forward-line (- (or arg 1)))
4423 (skip-chars-forward " \t"))
4424
4425(defun back-to-indentation ()
4426 "Move point to the first non-whitespace character on this line."
4427 (interactive)
4428 (beginning-of-line 1)
4429 (skip-syntax-forward " " (line-end-position))
4430 ;; Move back over chars that have whitespace syntax but have the p flag.
4431 (backward-prefix-chars))
4432@end ignore
4433
4434@item interactive
4435Declare to the interpreter that the function can be used
4436interactively. This special form may be followed by a string with one
4437or more parts that pass the information to the arguments of the
4438function, in sequence. These parts may also tell the interpreter to
4439prompt for information. Parts of the string are separated by
4440newlines, @samp{\n}.
4441
4442@need 1000
4443Common code characters are:
4444
4445@table @code
4446@item b
4447The name of an existing buffer.
4448
4449@item f
4450The name of an existing file.
4451
4452@item p
4453The numeric prefix argument. (Note that this `p' is lower case.)
4454
4455@item r
4456Point and the mark, as two numeric arguments, smallest first. This
4457is the only code letter that specifies two successive arguments
4458rather than one.
4459@end table
4460
4461@xref{Interactive Codes, , Code Characters for @samp{interactive},
4462elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4463code characters.
4464
4465@item let
4466Declare that a list of variables is for use within the body of the
4467@code{let} and give them an initial value, either @code{nil} or a
4468specified value; then evaluate the rest of the expressions in the body
4469of the @code{let} and return the value of the last one. Inside the
4470body of the @code{let}, the Lisp interpreter does not see the values of
4471the variables of the same names that are bound outside of the
4472@code{let}.
4473
4474@need 1250
4475For example,
4476
4477@smallexample
4478@group
4479(let ((foo (buffer-name))
4480 (bar (buffer-size)))
4481 (message
4482 "This buffer is %s and has %d characters."
4483 foo bar))
4484@end group
4485@end smallexample
4486
4487@item save-excursion
4488Record the values of point and mark and the current buffer before
4489evaluating the body of this special form. Restore the values of point
4490and mark and buffer afterward.
4491
4492@need 1250
4493For example,
4494
4495@smallexample
4496@group
4497(message "We are %d characters into this buffer."
4498 (- (point)
4499 (save-excursion
4500 (goto-char (point-min)) (point))))
4501@end group
4502@end smallexample
4503
4504@item if
4505Evaluate the first argument to the function; if it is true, evaluate
4506the second argument; else evaluate the third argument, if there is one.
4507
4508The @code{if} special form is called a @dfn{conditional}. There are
4509other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4510commonly used.
4511
4512@need 1250
4513For example,
4514
4515@smallexample
4516@group
4517(if (= 22 emacs-major-version)
4518 (message "This is version 22 Emacs")
4519 (message "This is not version 22 Emacs"))
4520@end group
4521@end smallexample
4522
4523@need 1250
4524@item <
4525@itemx >
4526@itemx <=
4527@itemx >=
4528The @code{<} function tests whether its first argument is smaller than
4529its second argument. A corresponding function, @code{>}, tests whether
4530the first argument is greater than the second. Likewise, @code{<=}
4531tests whether the first argument is less than or equal to the second and
4532@code{>=} tests whether the first argument is greater than or equal to
4533the second. In all cases, both arguments must be numbers or markers
4534(markers indicate positions in buffers).
4535
4536@need 800
4537@item =
4538The @code{=} function tests whether two arguments, both numbers or
4539markers, are equal.
4540
4541@need 1250
4542@item equal
4543@itemx eq
4544Test whether two objects are the same. @code{equal} uses one meaning
4545of the word `same' and @code{eq} uses another: @code{equal} returns
4546true if the two objects have a similar structure and contents, such as
4547two copies of the same book. On the other hand, @code{eq}, returns
4548true if both arguments are actually the same object.
4549@findex equal
4550@findex eq
4551
4552@need 1250
4553@item string<
4554@itemx string-lessp
4555@itemx string=
4556@itemx string-equal
4557The @code{string-lessp} function tests whether its first argument is
4558smaller than the second argument. A shorter, alternative name for the
4559same function (a @code{defalias}) is @code{string<}.
4560
4561The arguments to @code{string-lessp} must be strings or symbols; the
4562ordering is lexicographic, so case is significant. The print names of
4563symbols are used instead of the symbols themselves.
4564
4565@cindex @samp{empty string} defined
4566An empty string, @samp{""}, a string with no characters in it, is
4567smaller than any string of characters.
4568
4569@code{string-equal} provides the corresponding test for equality. Its
4570shorter, alternative name is @code{string=}. There are no string test
4571functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4572
4573@item message
4574Print a message in the echo area. The first argument is a string that
4575can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4576arguments that follow the string. The argument used by @samp{%s} must
4577be a string or a symbol; the argument used by @samp{%d} must be a
4578number. The argument used by @samp{%c} must be an @sc{ascii} code
4579number; it will be printed as the character with that @sc{ascii} code.
4580(Various other %-sequences have not been mentioned.)
4581
4582@item setq
4583@itemx set
4584The @code{setq} function sets the value of its first argument to the
4585value of the second argument. The first argument is automatically
4586quoted by @code{setq}. It does the same for succeeding pairs of
4587arguments. Another function, @code{set}, takes only two arguments and
4588evaluates both of them before setting the value returned by its first
4589argument to the value returned by its second argument.
4590
4591@item buffer-name
4592Without an argument, return the name of the buffer, as a string.
4593
e26aa21a 4594@item buffer-file-name
8cda6f8f
GM
4595Without an argument, return the name of the file the buffer is
4596visiting.
4597
4598@item current-buffer
4599Return the buffer in which Emacs is active; it may not be
4600the buffer that is visible on the screen.
4601
4602@item other-buffer
4603Return the most recently selected buffer (other than the buffer passed
4604to @code{other-buffer} as an argument and other than the current
4605buffer).
4606
4607@item switch-to-buffer
4608Select a buffer for Emacs to be active in and display it in the current
4609window so users can look at it. Usually bound to @kbd{C-x b}.
4610
4611@item set-buffer
44e97401 4612Switch Emacs's attention to a buffer on which programs will run. Don't
8cda6f8f
GM
4613alter what the window is showing.
4614
4615@item buffer-size
4616Return the number of characters in the current buffer.
4617
4618@item point
4619Return the value of the current position of the cursor, as an
4620integer counting the number of characters from the beginning of the
4621buffer.
4622
4623@item point-min
4624Return the minimum permissible value of point in
4625the current buffer. This is 1, unless narrowing is in effect.
4626
4627@item point-max
4628Return the value of the maximum permissible value of point in the
4629current buffer. This is the end of the buffer, unless narrowing is in
4630effect.
4631@end table
4632
4633@need 1500
d6adf7e7 4634@node defun Exercises
8cda6f8f
GM
4635@section Exercises
4636
4637@itemize @bullet
4638@item
4639Write a non-interactive function that doubles the value of its
4640argument, a number. Make that function interactive.
4641
4642@item
4643Write a function that tests whether the current value of
4644@code{fill-column} is greater than the argument passed to the function,
4645and if so, prints an appropriate message.
4646@end itemize
4647
d6adf7e7 4648@node Buffer Walk Through
8cda6f8f
GM
4649@chapter A Few Buffer--Related Functions
4650
4651In this chapter we study in detail several of the functions used in GNU
4652Emacs. This is called a ``walk-through''. These functions are used as
4653examples of Lisp code, but are not imaginary examples; with the
4654exception of the first, simplified function definition, these functions
4655show the actual code used in GNU Emacs. You can learn a great deal from
4656these definitions. The functions described here are all related to
4657buffers. Later, we will study other functions.
4658
4659@menu
4660* Finding More:: How to find more information.
4661* simplified-beginning-of-buffer:: Shows @code{goto-char},
4662 @code{point-min}, and @code{push-mark}.
4663* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4664* append-to-buffer:: Uses @code{save-excursion} and
4665 @code{insert-buffer-substring}.
4666* Buffer Related Review:: Review.
4667* Buffer Exercises::
4668@end menu
4669
d6adf7e7 4670@node Finding More
8cda6f8f
GM
4671@section Finding More Information
4672
4673@findex describe-function, @r{introduced}
4674@cindex Find function documentation
4675In this walk-through, I will describe each new function as we come to
4676it, sometimes in detail and sometimes briefly. If you are interested,
4677you can get the full documentation of any Emacs Lisp function at any
4678time by typing @kbd{C-h f} and then the name of the function (and then
4679@key{RET}). Similarly, you can get the full documentation for a
4680variable by typing @kbd{C-h v} and then the name of the variable (and
4681then @key{RET}).
4682
4683@cindex Find source of function
4684@c In version 22, tells location both of C and of Emacs Lisp
4685Also, @code{describe-function} will tell you the location of the
4686function definition.
4687
4688Put point into the name of the file that contains the function and
4689press the @key{RET} key. In this case, @key{RET} means
4690@code{push-button} rather than `return' or `enter'. Emacs will take
4691you directly to the function definition.
4692
4693@ignore
4694Not In version 22
4695
4696If you move point over the file name and press
4697the @key{RET} key, which in this case means @code{help-follow} rather
4698than `return' or `enter', Emacs will take you directly to the function
4699definition.
4700@end ignore
4701
4702More generally, if you want to see a function in its original source
88c26f5c
GM
4703file, you can use the @code{find-tag} function to jump to it.
4704@code{find-tag} works with a wide variety of languages, not just
8cda6f8f 4705Lisp, and C, and it works with non-programming text as well. For
88c26f5c 4706example, @code{find-tag} will jump to the various nodes in the
8cda6f8f 4707Texinfo source file of this document.
88c26f5c 4708The @code{find-tag} function depends on `tags tables' that record
8cda6f8f 4709the locations of the functions, variables, and other items to which
88c26f5c 4710@code{find-tag} jumps.
8cda6f8f 4711
88c26f5c 4712To use the @code{find-tag} command, type @kbd{M-.} (i.e., press the
8cda6f8f
GM
4713period key while holding down the @key{META} key, or else type the
4714@key{ESC} key and then type the period key), and then, at the prompt,
4715type in the name of the function whose source code you want to see,
4716such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4717switch buffers and display the source code for the function on your
4718screen. To switch back to your current buffer, type @kbd{C-x b
09e80d9f 4719@key{RET}}. (On some keyboards, the @key{META} key is labeled
8cda6f8f
GM
4720@key{ALT}.)
4721
4722@c !!! 22.1.1 tags table location in this paragraph
4723@cindex TAGS table, specifying
88c26f5c 4724@findex find-tag
8cda6f8f
GM
4725Depending on how the initial default values of your copy of Emacs are
4726set, you may also need to specify the location of your `tags table',
4727which is a file called @file{TAGS}. For example, if you are
4728interested in Emacs sources, the tags table you will most likely want,
4729if it has already been created for you, will be in a subdirectory of
4730the @file{/usr/local/share/emacs/} directory; thus you would use the
4731@code{M-x visit-tags-table} command and specify a pathname such as
4732@file{/usr/local/share/emacs/22.1.1/lisp/TAGS}. If the tags table
4733has not already been created, you will have to create it yourself. It
0ca10bb7 4734will be in a file such as @file{/usr/local/src/emacs/src/TAGS}.
8cda6f8f
GM
4735
4736@need 1250
4737To create a @file{TAGS} file in a specific directory, switch to that
4738directory in Emacs using @kbd{M-x cd} command, or list the directory
4739with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4740@w{@code{etags *.el}} as the command to execute:
4741
4742@smallexample
4743M-x compile RET etags *.el RET
4744@end smallexample
4745
4746For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4747
4748After you become more familiar with Emacs Lisp, you will find that you will
88c26f5c 4749frequently use @code{find-tag} to navigate your way around source code;
8cda6f8f
GM
4750and you will create your own @file{TAGS} tables.
4751
4752@cindex Library, as term for `file'
4753Incidentally, the files that contain Lisp code are conventionally
4754called @dfn{libraries}. The metaphor is derived from that of a
4755specialized library, such as a law library or an engineering library,
4756rather than a general library. Each library, or file, contains
4757functions that relate to a particular topic or activity, such as
4758@file{abbrev.el} for handling abbreviations and other typing
4759shortcuts, and @file{help.el} for on-line help. (Sometimes several
4760libraries provide code for a single activity, as the various
4761@file{rmail@dots{}} files provide code for reading electronic mail.)
4762In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4763@kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4764by topic keywords.''
4765
d6adf7e7 4766@node simplified-beginning-of-buffer
8cda6f8f
GM
4767@section A Simplified @code{beginning-of-buffer} Definition
4768@findex simplified-beginning-of-buffer
4769
4770The @code{beginning-of-buffer} command is a good function to start with
4771since you are likely to be familiar with it and it is easy to
4772understand. Used as an interactive command, @code{beginning-of-buffer}
4773moves the cursor to the beginning of the buffer, leaving the mark at the
4774previous position. It is generally bound to @kbd{M-<}.
4775
4776In this section, we will discuss a shortened version of the function
4777that shows how it is most frequently used. This shortened function
4778works as written, but it does not contain the code for a complex option.
4779In another section, we will describe the entire function.
4780(@xref{beginning-of-buffer, , Complete Definition of
4781@code{beginning-of-buffer}}.)
4782
4783Before looking at the code, let's consider what the function
4784definition has to contain: it must include an expression that makes
4785the function interactive so it can be called by typing @kbd{M-x
4786beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4787must include code to leave a mark at the original position in the
4788buffer; and it must include code to move the cursor to the beginning
4789of the buffer.
4790
4791@need 1250
4792Here is the complete text of the shortened version of the function:
4793
4794@smallexample
4795@group
4796(defun simplified-beginning-of-buffer ()
4797 "Move point to the beginning of the buffer;
4798leave mark at previous position."
4799 (interactive)
4800 (push-mark)
4801 (goto-char (point-min)))
4802@end group
4803@end smallexample
4804
4805Like all function definitions, this definition has five parts following
4806the special form @code{defun}:
4807
4808@enumerate
4809@item
4810The name: in this example, @code{simplified-beginning-of-buffer}.
4811
4812@item
4813A list of the arguments: in this example, an empty list, @code{()},
4814
4815@item
4816The documentation string.
4817
4818@item
4819The interactive expression.
4820
4821@item
4822The body.
4823@end enumerate
4824
4825@noindent
4826In this function definition, the argument list is empty; this means that
4827this function does not require any arguments. (When we look at the
4828definition for the complete function, we will see that it may be passed
4829an optional argument.)
4830
4831The interactive expression tells Emacs that the function is intended to
4832be used interactively. In this example, @code{interactive} does not have
4833an argument because @code{simplified-beginning-of-buffer} does not
4834require one.
4835
4836@need 800
4837The body of the function consists of the two lines:
4838
4839@smallexample
4840@group
4841(push-mark)
4842(goto-char (point-min))
4843@end group
4844@end smallexample
4845
4846The first of these lines is the expression, @code{(push-mark)}. When
4847this expression is evaluated by the Lisp interpreter, it sets a mark at
4848the current position of the cursor, wherever that may be. The position
4849of this mark is saved in the mark ring.
4850
4851The next line is @code{(goto-char (point-min))}. This expression
4852jumps the cursor to the minimum point in the buffer, that is, to the
4853beginning of the buffer (or to the beginning of the accessible portion
4854of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4855Narrowing and Widening}.)
4856
4857The @code{push-mark} command sets a mark at the place where the cursor
4858was located before it was moved to the beginning of the buffer by the
4859@code{(goto-char (point-min))} expression. Consequently, you can, if
4860you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4861
4862That is all there is to the function definition!
4863
4864@findex describe-function
4865When you are reading code such as this and come upon an unfamiliar
4866function, such as @code{goto-char}, you can find out what it does by
4867using the @code{describe-function} command. To use this command, type
4868@kbd{C-h f} and then type in the name of the function and press
4869@key{RET}. The @code{describe-function} command will print the
4870function's documentation string in a @file{*Help*} window. For
4871example, the documentation for @code{goto-char} is:
4872
4873@smallexample
4874@group
4875Set point to POSITION, a number or marker.
4876Beginning of buffer is position (point-min), end is (point-max).
4877@end group
4878@end smallexample
4879
4880@noindent
4881The function's one argument is the desired position.
4882
4883@noindent
4884(The prompt for @code{describe-function} will offer you the symbol
4885under or preceding the cursor, so you can save typing by positioning
4886the cursor right over or after the function and then typing @kbd{C-h f
4887@key{RET}}.)
4888
4889The @code{end-of-buffer} function definition is written in the same way as
4890the @code{beginning-of-buffer} definition except that the body of the
4891function contains the expression @code{(goto-char (point-max))} in place
4892of @code{(goto-char (point-min))}.
4893
d6adf7e7 4894@node mark-whole-buffer
8cda6f8f
GM
4895@section The Definition of @code{mark-whole-buffer}
4896@findex mark-whole-buffer
4897
4898The @code{mark-whole-buffer} function is no harder to understand than the
4899@code{simplified-beginning-of-buffer} function. In this case, however,
4900we will look at the complete function, not a shortened version.
4901
4902The @code{mark-whole-buffer} function is not as commonly used as the
4903@code{beginning-of-buffer} function, but is useful nonetheless: it
4904marks a whole buffer as a region by putting point at the beginning and
4905a mark at the end of the buffer. It is generally bound to @kbd{C-x
4906h}.
4907
4908@menu
4909* mark-whole-buffer overview::
4910* Body of mark-whole-buffer:: Only three lines of code.
4911@end menu
4912
8cda6f8f 4913@ifnottex
d6adf7e7 4914@node mark-whole-buffer overview
8cda6f8f
GM
4915@unnumberedsubsec An overview of @code{mark-whole-buffer}
4916@end ifnottex
4917
4918@need 1250
4919In GNU Emacs 22, the code for the complete function looks like this:
4920
4921@smallexample
4922@group
4923(defun mark-whole-buffer ()
4924 "Put point at beginning and mark at end of buffer.
4925You probably should not use this function in Lisp programs;
4926it is usually a mistake for a Lisp function to use any subroutine
4927that uses or sets the mark."
4928 (interactive)
4929 (push-mark (point))
4930 (push-mark (point-max) nil t)
4931 (goto-char (point-min)))
4932@end group
4933@end smallexample
4934
4935@need 1250
4936Like all other functions, the @code{mark-whole-buffer} function fits
4937into the template for a function definition. The template looks like
4938this:
4939
4940@smallexample
4941@group
4942(defun @var{name-of-function} (@var{argument-list})
4943 "@var{documentation}@dots{}"
4944 (@var{interactive-expression}@dots{})
4945 @var{body}@dots{})
4946@end group
4947@end smallexample
4948
4949Here is how the function works: the name of the function is
4950@code{mark-whole-buffer}; it is followed by an empty argument list,
4951@samp{()}, which means that the function does not require arguments.
4952The documentation comes next.
4953
4954The next line is an @code{(interactive)} expression that tells Emacs
4955that the function will be used interactively. These details are similar
4956to the @code{simplified-beginning-of-buffer} function described in the
4957previous section.
4958
4959@need 1250
d6adf7e7 4960@node Body of mark-whole-buffer
8cda6f8f
GM
4961@subsection Body of @code{mark-whole-buffer}
4962
4963The body of the @code{mark-whole-buffer} function consists of three
4964lines of code:
4965
4966@c GNU Emacs 22
4967@smallexample
4968@group
4969(push-mark (point))
4970(push-mark (point-max) nil t)
4971(goto-char (point-min))
4972@end group
4973@end smallexample
4974
4975The first of these lines is the expression, @code{(push-mark (point))}.
4976
4977This line does exactly the same job as the first line of the body of
4978the @code{simplified-beginning-of-buffer} function, which is written
4979@code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4980at the current position of the cursor.
4981
4982I don't know why the expression in @code{mark-whole-buffer} is written
4983@code{(push-mark (point))} and the expression in
4984@code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4985whoever wrote the code did not know that the arguments for
4986@code{push-mark} are optional and that if @code{push-mark} is not
4987passed an argument, the function automatically sets mark at the
4988location of point by default. Or perhaps the expression was written
4989so as to parallel the structure of the next line. In any case, the
4990line causes Emacs to determine the position of point and set a mark
4991there.
4992
4993In earlier versions of GNU Emacs, the next line of
4994@code{mark-whole-buffer} was @code{(push-mark (point-max))}. This
4995expression sets a mark at the point in the buffer that has the highest
4996number. This will be the end of the buffer (or, if the buffer is
4997narrowed, the end of the accessible portion of the buffer.
4998@xref{Narrowing & Widening, , Narrowing and Widening}, for more about
4999narrowing.) After this mark has been set, the previous mark, the one
5000set at point, is no longer set, but Emacs remembers its position, just
5001as all other recent marks are always remembered. This means that you
5002can, if you wish, go back to that position by typing @kbd{C-u
5003C-@key{SPC}} twice.
5004
5005@need 1250
5006In GNU Emacs 22, the @code{(point-max)} is slightly more complicated.
5007The line reads
5008
5009@smallexample
5010(push-mark (point-max) nil t)
5011@end smallexample
5012
5013@noindent
5014The expression works nearly the same as before. It sets a mark at the
5015highest numbered place in the buffer that it can. However, in this
5016version, @code{push-mark} has two additional arguments. The second
5017argument to @code{push-mark} is @code{nil}. This tells the function
5018it @emph{should} display a message that says `Mark set' when it pushes
5019the mark. The third argument is @code{t}. This tells
5020@code{push-mark} to activate the mark when Transient Mark mode is
5021turned on. Transient Mark mode highlights the currently active
5022region. It is often turned off.
5023
5024Finally, the last line of the function is @code{(goto-char
5025(point-min)))}. This is written exactly the same way as it is written
5026in @code{beginning-of-buffer}. The expression moves the cursor to
5027the minimum point in the buffer, that is, to the beginning of the buffer
5028(or to the beginning of the accessible portion of the buffer). As a
5029result of this, point is placed at the beginning of the buffer and mark
5030is set at the end of the buffer. The whole buffer is, therefore, the
5031region.
5032
d6adf7e7 5033@node append-to-buffer
8cda6f8f
GM
5034@section The Definition of @code{append-to-buffer}
5035@findex append-to-buffer
5036
5037The @code{append-to-buffer} command is more complex than the
5038@code{mark-whole-buffer} command. What it does is copy the region
5039(that is, the part of the buffer between point and mark) from the
5040current buffer to a specified buffer.
5041
5042@menu
5043* append-to-buffer overview::
5044* append interactive:: A two part interactive expression.
5045* append-to-buffer body:: Incorporates a @code{let} expression.
5046* append save-excursion:: How the @code{save-excursion} works.
5047@end menu
5048
8cda6f8f 5049@ifnottex
d6adf7e7 5050@node append-to-buffer overview
8cda6f8f
GM
5051@unnumberedsubsec An Overview of @code{append-to-buffer}
5052@end ifnottex
5053
5054@findex insert-buffer-substring
5055The @code{append-to-buffer} command uses the
5056@code{insert-buffer-substring} function to copy the region.
5057@code{insert-buffer-substring} is described by its name: it takes a
5058string of characters from part of a buffer, a ``substring'', and
5059inserts them into another buffer.
5060
5061Most of @code{append-to-buffer} is
5062concerned with setting up the conditions for
5063@code{insert-buffer-substring} to work: the code must specify both the
5064buffer to which the text will go, the window it comes from and goes
5065to, and the region that will be copied.
5066
5067@need 1250
5068Here is the complete text of the function:
5069
5070@smallexample
5071@group
5072(defun append-to-buffer (buffer start end)
5073 "Append to specified buffer the text of the region.
5074It is inserted into that buffer before its point.
5075@end group
5076
5077@group
5078When calling from a program, give three arguments:
5079BUFFER (or buffer name), START and END.
5080START and END specify the portion of the current buffer to be copied."
5081 (interactive
5082 (list (read-buffer "Append to buffer: " (other-buffer
5083 (current-buffer) t))
5084 (region-beginning) (region-end)))
5085@end group
5086@group
5087 (let ((oldbuf (current-buffer)))
5088 (save-excursion
5089 (let* ((append-to (get-buffer-create buffer))
5090 (windows (get-buffer-window-list append-to t t))
5091 point)
5092 (set-buffer append-to)
5093 (setq point (point))
5094 (barf-if-buffer-read-only)
5095 (insert-buffer-substring oldbuf start end)
5096 (dolist (window windows)
5097 (when (= (window-point window) point)
5098 (set-window-point window (point))))))))
5099@end group
5100@end smallexample
5101
5102The function can be understood by looking at it as a series of
5103filled-in templates.
5104
5105The outermost template is for the function definition. In this
5106function, it looks like this (with several slots filled in):
5107
5108@smallexample
5109@group
5110(defun append-to-buffer (buffer start end)
5111 "@var{documentation}@dots{}"
5112 (interactive @dots{})
5113 @var{body}@dots{})
5114@end group
5115@end smallexample
5116
5117The first line of the function includes its name and three arguments.
5118The arguments are the @code{buffer} to which the text will be copied, and
5119the @code{start} and @code{end} of the region in the current buffer that
5120will be copied.
5121
5122The next part of the function is the documentation, which is clear and
5123complete. As is conventional, the three arguments are written in
5124upper case so you will notice them easily. Even better, they are
5125described in the same order as in the argument list.
5126
5127Note that the documentation distinguishes between a buffer and its
5128name. (The function can handle either.)
5129
d6adf7e7 5130@node append interactive
8cda6f8f
GM
5131@subsection The @code{append-to-buffer} Interactive Expression
5132
5133Since the @code{append-to-buffer} function will be used interactively,
5134the function must have an @code{interactive} expression. (For a
5135review of @code{interactive}, see @ref{Interactive, , Making a
5136Function Interactive}.) The expression reads as follows:
5137
5138@smallexample
5139@group
5140(interactive
5141 (list (read-buffer
5142 "Append to buffer: "
5143 (other-buffer (current-buffer) t))
5144 (region-beginning)
5145 (region-end)))
5146@end group
5147@end smallexample
5148
5149@noindent
5150This expression is not one with letters standing for parts, as
5151described earlier. Instead, it starts a list with these parts:
5152
5153The first part of the list is an expression to read the name of a
5154buffer and return it as a string. That is @code{read-buffer}. The
5155function requires a prompt as its first argument, @samp{"Append to
5156buffer: "}. Its second argument tells the command what value to
5157provide if you don't specify anything.
5158
5159In this case that second argument is an expression containing the
5160function @code{other-buffer}, an exception, and a @samp{t}, standing
5161for true.
5162
5163The first argument to @code{other-buffer}, the exception, is yet
5164another function, @code{current-buffer}. That is not going to be
5165returned. The second argument is the symbol for true, @code{t}. that
5166tells @code{other-buffer} that it may show visible buffers (except in
5167this case, it will not show the current buffer, which makes sense).
5168
5169@need 1250
5170The expression looks like this:
5171
5172@smallexample
5173(other-buffer (current-buffer) t)
5174@end smallexample
5175
5176The second and third arguments to the @code{list} expression are
5177@code{(region-beginning)} and @code{(region-end)}. These two
5178functions specify the beginning and end of the text to be appended.
5179
5180@need 1250
5181Originally, the command used the letters @samp{B} and @samp{r}.
5182The whole @code{interactive} expression looked like this:
5183
5184@smallexample
5185(interactive "BAppend to buffer:@: \nr")
5186@end smallexample
5187
5188@noindent
5189But when that was done, the default value of the buffer switched to
5190was invisible. That was not wanted.
5191
5192(The prompt was separated from the second argument with a newline,
5193@samp{\n}. It was followed by an @samp{r} that told Emacs to bind the
5194two arguments that follow the symbol @code{buffer} in the function's
5195argument list (that is, @code{start} and @code{end}) to the values of
5196point and mark. That argument worked fine.)
5197
d6adf7e7 5198@node append-to-buffer body
8cda6f8f
GM
5199@subsection The Body of @code{append-to-buffer}
5200
5201@ignore
5202in GNU Emacs 22 in /usr/local/src/emacs/lisp/simple.el
5203
5204(defun append-to-buffer (buffer start end)
5205 "Append to specified buffer the text of the region.
5206It is inserted into that buffer before its point.
5207
5208When calling from a program, give three arguments:
5209BUFFER (or buffer name), START and END.
5210START and END specify the portion of the current buffer to be copied."
5211 (interactive
5212 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5213 (region-beginning) (region-end)))
5214 (let ((oldbuf (current-buffer)))
5215 (save-excursion
5216 (let* ((append-to (get-buffer-create buffer))
5217 (windows (get-buffer-window-list append-to t t))
5218 point)
5219 (set-buffer append-to)
5220 (setq point (point))
5221 (barf-if-buffer-read-only)
5222 (insert-buffer-substring oldbuf start end)
5223 (dolist (window windows)
5224 (when (= (window-point window) point)
5225 (set-window-point window (point))))))))
5226@end ignore
5227
5228The body of the @code{append-to-buffer} function begins with @code{let}.
5229
5230As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5231@code{let} expression is to create and give initial values to one or
5232more variables that will only be used within the body of the
5233@code{let}. This means that such a variable will not be confused with
5234any variable of the same name outside the @code{let} expression.
5235
5236We can see how the @code{let} expression fits into the function as a
5237whole by showing a template for @code{append-to-buffer} with the
5238@code{let} expression in outline:
5239
5240@smallexample
5241@group
5242(defun append-to-buffer (buffer start end)
5243 "@var{documentation}@dots{}"
5244 (interactive @dots{})
5245 (let ((@var{variable} @var{value}))
5246 @var{body}@dots{})
5247@end group
5248@end smallexample
5249
5250The @code{let} expression has three elements:
5251
5252@enumerate
5253@item
5254The symbol @code{let};
5255
5256@item
5257A varlist containing, in this case, a single two-element list,
5258@code{(@var{variable} @var{value})};
5259
5260@item
5261The body of the @code{let} expression.
5262@end enumerate
5263
5264@need 800
5265In the @code{append-to-buffer} function, the varlist looks like this:
5266
5267@smallexample
5268(oldbuf (current-buffer))
5269@end smallexample
5270
5271@noindent
5272In this part of the @code{let} expression, the one variable,
5273@code{oldbuf}, is bound to the value returned by the
5274@code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5275used to keep track of the buffer in which you are working and from
5276which you will copy.
5277
5278The element or elements of a varlist are surrounded by a set of
5279parentheses so the Lisp interpreter can distinguish the varlist from
5280the body of the @code{let}. As a consequence, the two-element list
5281within the varlist is surrounded by a circumscribing set of parentheses.
5282The line looks like this:
5283
5284@smallexample
5285@group
5286(let ((oldbuf (current-buffer)))
5287 @dots{} )
5288@end group
5289@end smallexample
5290
5291@noindent
5292The two parentheses before @code{oldbuf} might surprise you if you did
5293not realize that the first parenthesis before @code{oldbuf} marks the
5294boundary of the varlist and the second parenthesis marks the beginning
5295of the two-element list, @code{(oldbuf (current-buffer))}.
5296
d6adf7e7 5297@node append save-excursion
8cda6f8f
GM
5298@subsection @code{save-excursion} in @code{append-to-buffer}
5299
5300The body of the @code{let} expression in @code{append-to-buffer}
5301consists of a @code{save-excursion} expression.
5302
5303The @code{save-excursion} function saves the locations of point and
5304mark, and restores them to those positions after the expressions in the
5305body of the @code{save-excursion} complete execution. In addition,
5306@code{save-excursion} keeps track of the original buffer, and
5307restores it. This is how @code{save-excursion} is used in
5308@code{append-to-buffer}.
5309
5310@need 1500
5311@cindex Indentation for formatting
5312@cindex Formatting convention
5313Incidentally, it is worth noting here that a Lisp function is normally
5314formatted so that everything that is enclosed in a multi-line spread is
5315indented more to the right than the first symbol. In this function
5316definition, the @code{let} is indented more than the @code{defun}, and
5317the @code{save-excursion} is indented more than the @code{let}, like
5318this:
5319
5320@smallexample
5321@group
5322(defun @dots{}
5323 @dots{}
5324 @dots{}
5325 (let@dots{}
5326 (save-excursion
5327 @dots{}
5328@end group
5329@end smallexample
5330
5331@need 1500
5332@noindent
5333This formatting convention makes it easy to see that the lines in
5334the body of the @code{save-excursion} are enclosed by the parentheses
5335associated with @code{save-excursion}, just as the
5336@code{save-excursion} itself is enclosed by the parentheses associated
5337with the @code{let}:
5338
5339@smallexample
5340@group
5341(let ((oldbuf (current-buffer)))
5342 (save-excursion
5343 @dots{}
5344 (set-buffer @dots{})
5345 (insert-buffer-substring oldbuf start end)
5346 @dots{}))
5347@end group
5348@end smallexample
5349
5350@need 1200
5351The use of the @code{save-excursion} function can be viewed as a process
5352of filling in the slots of a template:
5353
5354@smallexample
5355@group
5356(save-excursion
5357 @var{first-expression-in-body}
5358 @var{second-expression-in-body}
5359 @dots{}
5360 @var{last-expression-in-body})
5361@end group
5362@end smallexample
5363
5364@need 1200
5365@noindent
5366In this function, the body of the @code{save-excursion} contains only
5367one expression, the @code{let*} expression. You know about a
5368@code{let} function. The @code{let*} function is different. It has a
5369@samp{*} in its name. It enables Emacs to set each variable in its
5370varlist in sequence, one after another.
5371
5372Its critical feature is that variables later in the varlist can make
5373use of the values to which Emacs set variables earlier in the varlist.
5374@xref{fwd-para let, , The @code{let*} expression}.
5375
5376We will skip functions like @code{let*} and focus on two: the
5377@code{set-buffer} function and the @code{insert-buffer-substring}
5378function.
5379
5380@need 1250
5381In the old days, the @code{set-buffer} expression was simply
5382
5383@smallexample
5384(set-buffer (get-buffer-create buffer))
5385@end smallexample
5386
5387@need 1250
5388@noindent
5389but now it is
5390
5391@smallexample
5392(set-buffer append-to)
5393@end smallexample
5394
5395@noindent
5396@code{append-to} is bound to @code{(get-buffer-create buffer)} earlier
5397on in the @code{let*} expression. That extra binding would not be
5398necessary except for that @code{append-to} is used later in the
5399varlist as an argument to @code{get-buffer-window-list}.
5400
5401@ignore
5402in GNU Emacs 22
5403
5404 (let ((oldbuf (current-buffer)))
5405 (save-excursion
5406 (let* ((append-to (get-buffer-create buffer))
5407 (windows (get-buffer-window-list append-to t t))
5408 point)
5409 (set-buffer append-to)
5410 (setq point (point))
5411 (barf-if-buffer-read-only)
5412 (insert-buffer-substring oldbuf start end)
5413 (dolist (window windows)
5414 (when (= (window-point window) point)
5415 (set-window-point window (point))))))))
5416@end ignore
5417
5418The @code{append-to-buffer} function definition inserts text from the
5419buffer in which you are currently to a named buffer. It happens that
5420@code{insert-buffer-substring} copies text from another buffer to the
5421current buffer, just the reverse---that is why the
5422@code{append-to-buffer} definition starts out with a @code{let} that
5423binds the local symbol @code{oldbuf} to the value returned by
5424@code{current-buffer}.
5425
5426@need 1250
5427The @code{insert-buffer-substring} expression looks like this:
5428
5429@smallexample
5430(insert-buffer-substring oldbuf start end)
5431@end smallexample
5432
5433@noindent
5434The @code{insert-buffer-substring} function copies a string
5435@emph{from} the buffer specified as its first argument and inserts the
5436string into the present buffer. In this case, the argument to
5437@code{insert-buffer-substring} is the value of the variable created
5438and bound by the @code{let}, namely the value of @code{oldbuf}, which
5439was the current buffer when you gave the @code{append-to-buffer}
5440command.
5441
5442After @code{insert-buffer-substring} has done its work,
5443@code{save-excursion} will restore the action to the original buffer
5444and @code{append-to-buffer} will have done its job.
5445
5446@need 800
5447Written in skeletal form, the workings of the body look like this:
5448
5449@smallexample
5450@group
5451(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5452 (save-excursion ; @r{Keep track of buffer.}
5453 @var{change-buffer}
5454 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5455
5456 @var{change-back-to-original-buffer-when-finished}
5457@var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5458@end group
5459@end smallexample
5460
5461In summary, @code{append-to-buffer} works as follows: it saves the
5462value of the current buffer in the variable called @code{oldbuf}. It
44e97401 5463gets the new buffer (creating one if need be) and switches Emacs's
8cda6f8f
GM
5464attention to it. Using the value of @code{oldbuf}, it inserts the
5465region of text from the old buffer into the new buffer; and then using
5466@code{save-excursion}, it brings you back to your original buffer.
5467
5468In looking at @code{append-to-buffer}, you have explored a fairly
5469complex function. It shows how to use @code{let} and
5470@code{save-excursion}, and how to change to and come back from another
5471buffer. Many function definitions use @code{let},
5472@code{save-excursion}, and @code{set-buffer} this way.
5473
d6adf7e7 5474@node Buffer Related Review
8cda6f8f
GM
5475@section Review
5476
5477Here is a brief summary of the various functions discussed in this chapter.
5478
5479@table @code
5480@item describe-function
5481@itemx describe-variable
5482Print the documentation for a function or variable.
5483Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5484
5485@item find-tag
5486Find the file containing the source for a function or variable and
5487switch buffers to it, positioning point at the beginning of the item.
5488Conventionally bound to @kbd{M-.} (that's a period following the
5489@key{META} key).
5490
5491@item save-excursion
5492Save the location of point and mark and restore their values after the
5493arguments to @code{save-excursion} have been evaluated. Also, remember
5494the current buffer and return to it.
5495
5496@item push-mark
5497Set mark at a location and record the value of the previous mark on the
5498mark ring. The mark is a location in the buffer that will keep its
5499relative position even if text is added to or removed from the buffer.
5500
5501@item goto-char
5502Set point to the location specified by the value of the argument, which
5503can be a number, a marker, or an expression that returns the number of
5504a position, such as @code{(point-min)}.
5505
5506@item insert-buffer-substring
5507Copy a region of text from a buffer that is passed to the function as
5508an argument and insert the region into the current buffer.
5509
5510@item mark-whole-buffer
5511Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5512
5513@item set-buffer
5514Switch the attention of Emacs to another buffer, but do not change the
5515window being displayed. Used when the program rather than a human is
5516to work on a different buffer.
5517
5518@item get-buffer-create
5519@itemx get-buffer
5520Find a named buffer or create one if a buffer of that name does not
5521exist. The @code{get-buffer} function returns @code{nil} if the named
5522buffer does not exist.
5523@end table
5524
5525@need 1500
d6adf7e7 5526@node Buffer Exercises
8cda6f8f
GM
5527@section Exercises
5528
5529@itemize @bullet
5530@item
5531Write your own @code{simplified-end-of-buffer} function definition;
5532then test it to see whether it works.
5533
5534@item
5535Use @code{if} and @code{get-buffer} to write a function that prints a
5536message telling you whether a buffer exists.
5537
5538@item
5539Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5540function.
5541@end itemize
5542
d6adf7e7 5543@node More Complex
8cda6f8f
GM
5544@chapter A Few More Complex Functions
5545
5546In this chapter, we build on what we have learned in previous chapters
5547by looking at more complex functions. The @code{copy-to-buffer}
5548function illustrates use of two @code{save-excursion} expressions in
5549one definition, while the @code{insert-buffer} function illustrates
5550use of an asterisk in an @code{interactive} expression, use of
5551@code{or}, and the important distinction between a name and the object
5552to which the name refers.
5553
5554@menu
5555* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5556* insert-buffer:: Read-only, and with @code{or}.
5557* beginning-of-buffer:: Shows @code{goto-char},
5558 @code{point-min}, and @code{push-mark}.
5559* Second Buffer Related Review::
5560* optional Exercise::
5561@end menu
5562
d6adf7e7 5563@node copy-to-buffer
8cda6f8f
GM
5564@section The Definition of @code{copy-to-buffer}
5565@findex copy-to-buffer
5566
5567After understanding how @code{append-to-buffer} works, it is easy to
5568understand @code{copy-to-buffer}. This function copies text into a
5569buffer, but instead of adding to the second buffer, it replaces all the
5570previous text in the second buffer.
5571
5572@need 800
5573The body of @code{copy-to-buffer} looks like this,
5574
5575@smallexample
5576@group
5577@dots{}
5578(interactive "BCopy to buffer: \nr")
5579(let ((oldbuf (current-buffer)))
5580 (with-current-buffer (get-buffer-create buffer)
5581 (barf-if-buffer-read-only)
5582 (erase-buffer)
5583 (save-excursion
5584 (insert-buffer-substring oldbuf start end)))))
5585@end group
5586@end smallexample
5587
5588The @code{copy-to-buffer} function has a simpler @code{interactive}
5589expression than @code{append-to-buffer}.
5590
5591@need 800
5592The definition then says
5593
5594@smallexample
5595(with-current-buffer (get-buffer-create buffer) @dots{}
5596@end smallexample
5597
5598First, look at the earliest inner expression; that is evaluated first.
5599That expression starts with @code{get-buffer-create buffer}. The
5600function tells the computer to use the buffer with the name specified
5601as the one to which you are copying, or if such a buffer does not
5602exist, to create it. Then, the @code{with-current-buffer} function
5603evaluates its body with that buffer temporarily current.
5604
5605(This demonstrates another way to shift the computer's attention but
5606not the user's. The @code{append-to-buffer} function showed how to do
5607the same with @code{save-excursion} and @code{set-buffer}.
5608@code{with-current-buffer} is a newer, and arguably easier,
5609mechanism.)
5610
5611The @code{barf-if-buffer-read-only} function sends you an error
5612message saying the buffer is read-only if you cannot modify it.
5613
5614The next line has the @code{erase-buffer} function as its sole
5615contents. That function erases the buffer.
5616
5617Finally, the last two lines contain the @code{save-excursion}
5618expression with @code{insert-buffer-substring} as its body.
5619The @code{insert-buffer-substring} expression copies the text from
5620the buffer you are in (and you have not seen the computer shift its
5621attention, so you don't know that that buffer is now called
5622@code{oldbuf}).
5623
5624Incidentally, this is what is meant by `replacement'. To replace text,
5625Emacs erases the previous text and then inserts new text.
5626
5627@need 1250
5628In outline, the body of @code{copy-to-buffer} looks like this:
5629
5630@smallexample
5631@group
5632(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5633 (@var{with-the-buffer-you-are-copying-to}
5634 (@var{but-do-not-erase-or-copy-to-a-read-only-buffer})
5635 (erase-buffer)
5636 (save-excursion
5637 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5638@end group
5639@end smallexample
5640
d6adf7e7 5641@node insert-buffer
8cda6f8f
GM
5642@section The Definition of @code{insert-buffer}
5643@findex insert-buffer
5644
5645@code{insert-buffer} is yet another buffer-related function. This
5646command copies another buffer @emph{into} the current buffer. It is the
5647reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5648copy a region of text @emph{from} the current buffer to another buffer.
5649
5650Here is a discussion based on the original code. The code was
5651simplified in 2003 and is harder to understand.
5652
5653(@xref{New insert-buffer, , New Body for @code{insert-buffer}}, to see
5654a discussion of the new body.)
5655
5656In addition, this code illustrates the use of @code{interactive} with a
5657buffer that might be @dfn{read-only} and the important distinction
5658between the name of an object and the object actually referred to.
5659
5660@menu
5661* insert-buffer code::
5662* insert-buffer interactive:: When you can read, but not write.
5663* insert-buffer body:: The body has an @code{or} and a @code{let}.
5664* if & or:: Using an @code{if} instead of an @code{or}.
5665* Insert or:: How the @code{or} expression works.
5666* Insert let:: Two @code{save-excursion} expressions.
5667* New insert-buffer::
5668@end menu
5669
8cda6f8f 5670@ifnottex
d6adf7e7 5671@node insert-buffer code
8cda6f8f
GM
5672@unnumberedsubsec The Code for @code{insert-buffer}
5673@end ifnottex
5674
5675@need 800
5676Here is the earlier code:
5677
5678@smallexample
5679@group
5680(defun insert-buffer (buffer)
5681 "Insert after point the contents of BUFFER.
5682Puts mark after the inserted text.
5683BUFFER may be a buffer or a buffer name."
5684 (interactive "*bInsert buffer:@: ")
5685@end group
5686@group
5687 (or (bufferp buffer)
5688 (setq buffer (get-buffer buffer)))
5689 (let (start end newmark)
5690 (save-excursion
5691 (save-excursion
5692 (set-buffer buffer)
5693 (setq start (point-min) end (point-max)))
5694@end group
5695@group
5696 (insert-buffer-substring buffer start end)
5697 (setq newmark (point)))
5698 (push-mark newmark)))
5699@end group
5700@end smallexample
5701
5702@need 1200
5703As with other function definitions, you can use a template to see an
5704outline of the function:
5705
5706@smallexample
5707@group
5708(defun insert-buffer (buffer)
5709 "@var{documentation}@dots{}"
5710 (interactive "*bInsert buffer:@: ")
5711 @var{body}@dots{})
5712@end group
5713@end smallexample
5714
d6adf7e7 5715@node insert-buffer interactive
8cda6f8f
GM
5716@subsection The Interactive Expression in @code{insert-buffer}
5717@findex interactive, @r{example use of}
5718
5719In @code{insert-buffer}, the argument to the @code{interactive}
5720declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5721buffer:@: }.
5722
5723@menu
5724* Read-only buffer:: When a buffer cannot be modified.
5725* b for interactive:: An existing buffer or else its name.
5726@end menu
5727
d6adf7e7 5728@node Read-only buffer
8cda6f8f
GM
5729@unnumberedsubsubsec A Read-only Buffer
5730@cindex Read-only buffer
5731@cindex Asterisk for read-only buffer
5732@findex * @r{for read-only buffer}
5733
5734The asterisk is for the situation when the current buffer is a
5735read-only buffer---a buffer that cannot be modified. If
5736@code{insert-buffer} is called when the current buffer is read-only, a
5737message to this effect is printed in the echo area and the terminal
5738may beep or blink at you; you will not be permitted to insert anything
5739into current buffer. The asterisk does not need to be followed by a
5740newline to separate it from the next argument.
5741
d6adf7e7 5742@node b for interactive
8cda6f8f
GM
5743@unnumberedsubsubsec @samp{b} in an Interactive Expression
5744
5745The next argument in the interactive expression starts with a lower
5746case @samp{b}. (This is different from the code for
5747@code{append-to-buffer}, which uses an upper-case @samp{B}.
5748@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5749The lower-case @samp{b} tells the Lisp interpreter that the argument
5750for @code{insert-buffer} should be an existing buffer or else its
5751name. (The upper-case @samp{B} option provides for the possibility
5752that the buffer does not exist.) Emacs will prompt you for the name
5753of the buffer, offering you a default buffer, with name completion
5754enabled. If the buffer does not exist, you receive a message that
5755says ``No match''; your terminal may beep at you as well.
5756
5757The new and simplified code generates a list for @code{interactive}.
5758It uses the @code{barf-if-buffer-read-only} and @code{read-buffer}
5759functions with which we are already familiar and the @code{progn}
5760special form with which we are not. (It will be described later.)
5761
d6adf7e7 5762@node insert-buffer body
8cda6f8f
GM
5763@subsection The Body of the @code{insert-buffer} Function
5764
5765The body of the @code{insert-buffer} function has two major parts: an
5766@code{or} expression and a @code{let} expression. The purpose of the
5767@code{or} expression is to ensure that the argument @code{buffer} is
5768bound to a buffer and not just the name of a buffer. The body of the
5769@code{let} expression contains the code which copies the other buffer
5770into the current buffer.
5771
5772@need 1250
5773In outline, the two expressions fit into the @code{insert-buffer}
5774function like this:
5775
5776@smallexample
5777@group
5778(defun insert-buffer (buffer)
5779 "@var{documentation}@dots{}"
5780 (interactive "*bInsert buffer:@: ")
5781 (or @dots{}
5782 @dots{}
5783@end group
5784@group
5785 (let (@var{varlist})
5786 @var{body-of-}@code{let}@dots{} )
5787@end group
5788@end smallexample
5789
5790To understand how the @code{or} expression ensures that the argument
5791@code{buffer} is bound to a buffer and not to the name of a buffer, it
5792is first necessary to understand the @code{or} function.
5793
5794Before doing this, let me rewrite this part of the function using
5795@code{if} so that you can see what is done in a manner that will be familiar.
5796
d6adf7e7 5797@node if & or
8cda6f8f
GM
5798@subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5799
5800The job to be done is to make sure the value of @code{buffer} is a
5801buffer itself and not the name of a buffer. If the value is the name,
5802then the buffer itself must be got.
5803
5804You can imagine yourself at a conference where an usher is wandering
5805around holding a list with your name on it and looking for you: the
5806usher is ``bound'' to your name, not to you; but when the usher finds
5807you and takes your arm, the usher becomes ``bound'' to you.
5808
5809@need 800
5810In Lisp, you might describe this situation like this:
5811
5812@smallexample
5813@group
5814(if (not (holding-on-to-guest))
5815 (find-and-take-arm-of-guest))
5816@end group
5817@end smallexample
5818
5819We want to do the same thing with a buffer---if we do not have the
5820buffer itself, we want to get it.
5821
5822@need 1200
5823Using a predicate called @code{bufferp} that tells us whether we have a
5824buffer (rather than its name), we can write the code like this:
5825
5826@smallexample
5827@group
5828(if (not (bufferp buffer)) ; @r{if-part}
5829 (setq buffer (get-buffer buffer))) ; @r{then-part}
5830@end group
5831@end smallexample
5832
5833@noindent
5834Here, the true-or-false-test of the @code{if} expression is
5835@w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5836@w{@code{(setq buffer (get-buffer buffer))}}.
5837
5838In the test, the function @code{bufferp} returns true if its argument is
5839a buffer---but false if its argument is the name of the buffer. (The
5840last character of the function name @code{bufferp} is the character
5841@samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5842indicates that the function is a predicate, which is a term that means
5843that the function will determine whether some property is true or false.
5844@xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5845Argument}.)
5846
5847@need 1200
5848The function @code{not} precedes the expression @code{(bufferp buffer)},
5849so the true-or-false-test looks like this:
5850
5851@smallexample
5852(not (bufferp buffer))
5853@end smallexample
5854
5855@noindent
5856@code{not} is a function that returns true if its argument is false
5857and false if its argument is true. So if @code{(bufferp buffer)}
5858returns true, the @code{not} expression returns false and vice-verse:
5859what is ``not true'' is false and what is ``not false'' is true.
5860
5861Using this test, the @code{if} expression works as follows: when the
5862value of the variable @code{buffer} is actually a buffer rather than
5863its name, the true-or-false-test returns false and the @code{if}
5864expression does not evaluate the then-part. This is fine, since we do
5865not need to do anything to the variable @code{buffer} if it really is
5866a buffer.
5867
5868On the other hand, when the value of @code{buffer} is not a buffer
5869itself, but the name of a buffer, the true-or-false-test returns true
5870and the then-part of the expression is evaluated. In this case, the
5871then-part is @code{(setq buffer (get-buffer buffer))}. This
5872expression uses the @code{get-buffer} function to return an actual
5873buffer itself, given its name. The @code{setq} then sets the variable
5874@code{buffer} to the value of the buffer itself, replacing its previous
5875value (which was the name of the buffer).
5876
d6adf7e7 5877@node Insert or
8cda6f8f
GM
5878@subsection The @code{or} in the Body
5879
5880The purpose of the @code{or} expression in the @code{insert-buffer}
5881function is to ensure that the argument @code{buffer} is bound to a
5882buffer and not just to the name of a buffer. The previous section shows
5883how the job could have been done using an @code{if} expression.
5884However, the @code{insert-buffer} function actually uses @code{or}.
5885To understand this, it is necessary to understand how @code{or} works.
5886
5887@findex or
5888An @code{or} function can have any number of arguments. It evaluates
5889each argument in turn and returns the value of the first of its
5890arguments that is not @code{nil}. Also, and this is a crucial feature
5891of @code{or}, it does not evaluate any subsequent arguments after
5892returning the first non-@code{nil} value.
5893
5894@need 800
5895The @code{or} expression looks like this:
5896
5897@smallexample
5898@group
5899(or (bufferp buffer)
5900 (setq buffer (get-buffer buffer)))
5901@end group
5902@end smallexample
5903
5904@noindent
5905The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5906This expression returns true (a non-@code{nil} value) if the buffer is
5907actually a buffer, and not just the name of a buffer. In the @code{or}
5908expression, if this is the case, the @code{or} expression returns this
5909true value and does not evaluate the next expression---and this is fine
5910with us, since we do not want to do anything to the value of
5911@code{buffer} if it really is a buffer.
5912
5913On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5914which it will be if the value of @code{buffer} is the name of a buffer,
5915the Lisp interpreter evaluates the next element of the @code{or}
5916expression. This is the expression @code{(setq buffer (get-buffer
5917buffer))}. This expression returns a non-@code{nil} value, which
5918is the value to which it sets the variable @code{buffer}---and this
5919value is a buffer itself, not the name of a buffer.
5920
5921The result of all this is that the symbol @code{buffer} is always
5922bound to a buffer itself rather than to the name of a buffer. All
5923this is necessary because the @code{set-buffer} function in a
5924following line only works with a buffer itself, not with the name to a
5925buffer.
5926
5927@need 1250
5928Incidentally, using @code{or}, the situation with the usher would be
5929written like this:
5930
5931@smallexample
5932(or (holding-on-to-guest) (find-and-take-arm-of-guest))
5933@end smallexample
5934
d6adf7e7 5935@node Insert let
8cda6f8f
GM
5936@subsection The @code{let} Expression in @code{insert-buffer}
5937
5938After ensuring that the variable @code{buffer} refers to a buffer itself
5939and not just to the name of a buffer, the @code{insert-buffer function}
5940continues with a @code{let} expression. This specifies three local
5941variables, @code{start}, @code{end}, and @code{newmark} and binds them
5942to the initial value @code{nil}. These variables are used inside the
5943remainder of the @code{let} and temporarily hide any other occurrence of
5944variables of the same name in Emacs until the end of the @code{let}.
5945
5946@need 1200
5947The body of the @code{let} contains two @code{save-excursion}
5948expressions. First, we will look at the inner @code{save-excursion}
5949expression in detail. The expression looks like this:
5950
5951@smallexample
5952@group
5953(save-excursion
5954 (set-buffer buffer)
5955 (setq start (point-min) end (point-max)))
5956@end group
5957@end smallexample
5958
5959@noindent
44e97401 5960The expression @code{(set-buffer buffer)} changes Emacs's attention
8cda6f8f
GM
5961from the current buffer to the one from which the text will copied.
5962In that buffer, the variables @code{start} and @code{end} are set to
5963the beginning and end of the buffer, using the commands
5964@code{point-min} and @code{point-max}. Note that we have here an
5965illustration of how @code{setq} is able to set two variables in the
5966same expression. The first argument of @code{setq} is set to the
5967value of its second, and its third argument is set to the value of its
5968fourth.
5969
5970After the body of the inner @code{save-excursion} is evaluated, the
5971@code{save-excursion} restores the original buffer, but @code{start} and
5972@code{end} remain set to the values of the beginning and end of the
5973buffer from which the text will be copied.
5974
5975@need 1250
5976The outer @code{save-excursion} expression looks like this:
5977
5978@smallexample
5979@group
5980(save-excursion
5981 (@var{inner-}@code{save-excursion}@var{-expression}
5982 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5983 (insert-buffer-substring buffer start end)
5984 (setq newmark (point)))
5985@end group
5986@end smallexample
5987
5988@noindent
5989The @code{insert-buffer-substring} function copies the text
5990@emph{into} the current buffer @emph{from} the region indicated by
5991@code{start} and @code{end} in @code{buffer}. Since the whole of the
5992second buffer lies between @code{start} and @code{end}, the whole of
5993the second buffer is copied into the buffer you are editing. Next,
5994the value of point, which will be at the end of the inserted text, is
5995recorded in the variable @code{newmark}.
5996
5997After the body of the outer @code{save-excursion} is evaluated, point
5998and mark are relocated to their original places.
5999
6000However, it is convenient to locate a mark at the end of the newly
6001inserted text and locate point at its beginning. The @code{newmark}
6002variable records the end of the inserted text. In the last line of
6003the @code{let} expression, the @code{(push-mark newmark)} expression
6004function sets a mark to this location. (The previous location of the
6005mark is still accessible; it is recorded on the mark ring and you can
6006go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
6007located at the beginning of the inserted text, which is where it was
6008before you called the insert function, the position of which was saved
6009by the first @code{save-excursion}.
6010
6011@need 1250
6012The whole @code{let} expression looks like this:
6013
6014@smallexample
6015@group
6016(let (start end newmark)
6017 (save-excursion
6018 (save-excursion
6019 (set-buffer buffer)
6020 (setq start (point-min) end (point-max)))
6021 (insert-buffer-substring buffer start end)
6022 (setq newmark (point)))
6023 (push-mark newmark))
6024@end group
6025@end smallexample
6026
6027Like the @code{append-to-buffer} function, the @code{insert-buffer}
6028function uses @code{let}, @code{save-excursion}, and
6029@code{set-buffer}. In addition, the function illustrates one way to
6030use @code{or}. All these functions are building blocks that we will
6031find and use again and again.
6032
d6adf7e7 6033@node New insert-buffer
8cda6f8f
GM
6034@subsection New Body for @code{insert-buffer}
6035@findex insert-buffer, new version body
6036@findex new version body for insert-buffer
6037
6038The body in the GNU Emacs 22 version is more confusing than the original.
6039
6040@need 1250
6041It consists of two expressions,
6042
6043@smallexample
6044@group
6045 (push-mark
6046 (save-excursion
6047 (insert-buffer-substring (get-buffer buffer))
6048 (point)))
6049
6050 nil
6051@end group
6052@end smallexample
6053
6054@noindent
6055except, and this is what confuses novices, very important work is done
6056inside the @code{push-mark} expression.
6057
6058The @code{get-buffer} function returns a buffer with the name
6059provided. You will note that the function is @emph{not} called
6060@code{get-buffer-create}; it does not create a buffer if one does not
6061already exist. The buffer returned by @code{get-buffer}, an existing
6062buffer, is passed to @code{insert-buffer-substring}, which inserts the
6063whole of the buffer (since you did not specify anything else).
6064
6065The location into which the buffer is inserted is recorded by
6066@code{push-mark}. Then the function returns @code{nil}, the value of
6067its last command. Put another way, the @code{insert-buffer} function
6068exists only to produce a side effect, inserting another buffer, not to
6069return any value.
6070
d6adf7e7 6071@node beginning-of-buffer
8cda6f8f
GM
6072@section Complete Definition of @code{beginning-of-buffer}
6073@findex beginning-of-buffer
6074
6075The basic structure of the @code{beginning-of-buffer} function has
6076already been discussed. (@xref{simplified-beginning-of-buffer, , A
6077Simplified @code{beginning-of-buffer} Definition}.)
6078This section describes the complex part of the definition.
6079
6080As previously described, when invoked without an argument,
6081@code{beginning-of-buffer} moves the cursor to the beginning of the
6082buffer (in truth, the beginning of the accessible portion of the
6083buffer), leaving the mark at the previous position. However, when the
6084command is invoked with a number between one and ten, the function
6085considers that number to be a fraction of the length of the buffer,
6086measured in tenths, and Emacs moves the cursor that fraction of the
6087way from the beginning of the buffer. Thus, you can either call this
6088function with the key command @kbd{M-<}, which will move the cursor to
6089the beginning of the buffer, or with a key command such as @kbd{C-u 7
6090M-<} which will move the cursor to a point 70% of the way through the
6091buffer. If a number bigger than ten is used for the argument, it
6092moves to the end of the buffer.
6093
6094The @code{beginning-of-buffer} function can be called with or without an
6095argument. The use of the argument is optional.
6096
6097@menu
6098* Optional Arguments::
6099* beginning-of-buffer opt arg:: Example with optional argument.
6100* beginning-of-buffer complete::
6101@end menu
6102
d6adf7e7 6103@node Optional Arguments
8cda6f8f
GM
6104@subsection Optional Arguments
6105
6106Unless told otherwise, Lisp expects that a function with an argument in
6107its function definition will be called with a value for that argument.
6108If that does not happen, you get an error and a message that says
6109@samp{Wrong number of arguments}.
6110
6111@cindex Optional arguments
6112@cindex Keyword
6113@findex optional
6114However, optional arguments are a feature of Lisp: a particular
6115@dfn{keyword} is used to tell the Lisp interpreter that an argument is
6116optional. The keyword is @code{&optional}. (The @samp{&} in front of
6117@samp{optional} is part of the keyword.) In a function definition, if
6118an argument follows the keyword @code{&optional}, no value need be
6119passed to that argument when the function is called.
6120
6121@need 1200
6122The first line of the function definition of @code{beginning-of-buffer}
6123therefore looks like this:
6124
6125@smallexample
6126(defun beginning-of-buffer (&optional arg)
6127@end smallexample
6128
6129@need 1250
6130In outline, the whole function looks like this:
6131
6132@smallexample
6133@group
6134(defun beginning-of-buffer (&optional arg)
6135 "@var{documentation}@dots{}"
6136 (interactive "P")
6137 (or (@var{is-the-argument-a-cons-cell} arg)
6138 (and @var{are-both-transient-mark-mode-and-mark-active-true})
6139 (push-mark))
6140 (let (@var{determine-size-and-set-it})
6141 (goto-char
6142 (@var{if-there-is-an-argument}
6143 @var{figure-out-where-to-go}
6144 @var{else-go-to}
6145 (point-min))))
6146 @var{do-nicety}
6147@end group
6148@end smallexample
6149
6150The function is similar to the @code{simplified-beginning-of-buffer}
6151function except that the @code{interactive} expression has @code{"P"}
6152as an argument and the @code{goto-char} function is followed by an
6153if-then-else expression that figures out where to put the cursor if
6154there is an argument that is not a cons cell.
6155
6156(Since I do not explain a cons cell for many more chapters, please
6157consider ignoring the function @code{consp}. @xref{List
6158Implementation, , How Lists are Implemented}, and @ref{Cons Cell Type,
6159, Cons Cell and List Types, elisp, The GNU Emacs Lisp Reference
6160Manual}.)
6161
6162The @code{"P"} in the @code{interactive} expression tells Emacs to
6163pass a prefix argument, if there is one, to the function in raw form.
6164A prefix argument is made by typing the @key{META} key followed by a
6165number, or by typing @kbd{C-u} and then a number. (If you don't type
6166a number, @kbd{C-u} defaults to a cons cell with a 4. A lowercase
6167@code{"p"} in the @code{interactive} expression causes the function to
6168convert a prefix arg to a number.)
6169
6170The true-or-false-test of the @code{if} expression looks complex, but
6171it is not: it checks whether @code{arg} has a value that is not
6172@code{nil} and whether it is a cons cell. (That is what @code{consp}
6173does; it checks whether its argument is a cons cell.) If @code{arg}
6174has a value that is not @code{nil} (and is not a cons cell), which
6175will be the case if @code{beginning-of-buffer} is called with a
6176numeric argument, then this true-or-false-test will return true and
6177the then-part of the @code{if} expression will be evaluated. On the
6178other hand, if @code{beginning-of-buffer} is not called with an
6179argument, the value of @code{arg} will be @code{nil} and the else-part
6180of the @code{if} expression will be evaluated. The else-part is
6181simply @code{point-min}, and when this is the outcome, the whole
6182@code{goto-char} expression is @code{(goto-char (point-min))}, which
6183is how we saw the @code{beginning-of-buffer} function in its
6184simplified form.
6185
d6adf7e7 6186@node beginning-of-buffer opt arg
8cda6f8f
GM
6187@subsection @code{beginning-of-buffer} with an Argument
6188
6189When @code{beginning-of-buffer} is called with an argument, an
6190expression is evaluated which calculates what value to pass to
6191@code{goto-char}. This expression is rather complicated at first sight.
6192It includes an inner @code{if} expression and much arithmetic. It looks
6193like this:
6194
6195@smallexample
6196@group
6197(if (> (buffer-size) 10000)
6198 ;; @r{Avoid overflow for large buffer sizes!}
6199 (* (prefix-numeric-value arg)
6200 (/ size 10))
6201 (/
6202 (+ 10
6203 (*
6204 size (prefix-numeric-value arg))) 10)))
6205@end group
6206@end smallexample
6207
6208@menu
6209* Disentangle beginning-of-buffer::
6210* Large buffer case::
6211* Small buffer case::
6212@end menu
6213
8cda6f8f 6214@ifnottex
d6adf7e7 6215@node Disentangle beginning-of-buffer
8cda6f8f
GM
6216@unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
6217@end ifnottex
6218
6219Like other complex-looking expressions, the conditional expression
6220within @code{beginning-of-buffer} can be disentangled by looking at it
6221as parts of a template, in this case, the template for an if-then-else
6222expression. In skeletal form, the expression looks like this:
6223
6224@smallexample
6225@group
6226(if (@var{buffer-is-large}
6227 @var{divide-buffer-size-by-10-and-multiply-by-arg}
6228 @var{else-use-alternate-calculation}
6229@end group
6230@end smallexample
6231
6232The true-or-false-test of this inner @code{if} expression checks the
6233size of the buffer. The reason for this is that the old version 18
6234Emacs used numbers that are no bigger than eight million or so and in
6235the computation that followed, the programmer feared that Emacs might
6236try to use over-large numbers if the buffer were large. The term
6237`overflow', mentioned in the comment, means numbers that are over
6238large. More recent versions of Emacs use larger numbers, but this
6239code has not been touched, if only because people now look at buffers
6240that are far, far larger than ever before.
6241
6242There are two cases: if the buffer is large and if it is not.
6243
d6adf7e7 6244@node Large buffer case
8cda6f8f
GM
6245@unnumberedsubsubsec What happens in a large buffer
6246
6247In @code{beginning-of-buffer}, the inner @code{if} expression tests
6248whether the size of the buffer is greater than 10,000 characters. To do
6249this, it uses the @code{>} function and the computation of @code{size}
6250that comes from the let expression.
6251
6252In the old days, the function @code{buffer-size} was used. Not only
6253was that function called several times, it gave the size of the whole
6254buffer, not the accessible part. The computation makes much more
6255sense when it handles just the accessible part. (@xref{Narrowing &
6256Widening, , Narrowing and Widening}, for more information on focusing
6257attention to an `accessible' part.)
6258
6259@need 800
6260The line looks like this:
6261
6262@smallexample
6263(if (> size 10000)
6264@end smallexample
6265
6266@need 1200
6267@noindent
6268When the buffer is large, the then-part of the @code{if} expression is
6269evaluated. It reads like this (after formatting for easy reading):
6270
6271@smallexample
6272@group
6273(*
6274 (prefix-numeric-value arg)
6275 (/ size 10))
6276@end group
6277@end smallexample
6278
6279@noindent
6280This expression is a multiplication, with two arguments to the function
6281@code{*}.
6282
6283The first argument is @code{(prefix-numeric-value arg)}. When
6284@code{"P"} is used as the argument for @code{interactive}, the value
6285passed to the function as its argument is passed a ``raw prefix
6286argument'', and not a number. (It is a number in a list.) To perform
6287the arithmetic, a conversion is necessary, and
6288@code{prefix-numeric-value} does the job.
6289
6290@findex / @r{(division)}
6291@cindex Division
6292The second argument is @code{(/ size 10)}. This expression divides
f99f1641 6293the numeric value by ten---the numeric value of the size of the
8cda6f8f
GM
6294accessible portion of the buffer. This produces a number that tells
6295how many characters make up one tenth of the buffer size. (In Lisp,
6296@code{/} is used for division, just as @code{*} is used for
6297multiplication.)
6298
6299@need 1200
6300In the multiplication expression as a whole, this amount is multiplied
6301by the value of the prefix argument---the multiplication looks like this:
6302
6303@smallexample
6304@group
6305(* @var{numeric-value-of-prefix-arg}
6306 @var{number-of-characters-in-one-tenth-of-the-accessible-buffer})
6307@end group
6308@end smallexample
6309
6310@noindent
6311If, for example, the prefix argument is @samp{7}, the one-tenth value
6312will be multiplied by 7 to give a position 70% of the way through.
6313
6314@need 1200
6315The result of all this is that if the accessible portion of the buffer
6316is large, the @code{goto-char} expression reads like this:
6317
6318@smallexample
6319@group
6320(goto-char (* (prefix-numeric-value arg)
6321 (/ size 10)))
6322@end group
6323@end smallexample
6324
6325This puts the cursor where we want it.
6326
d6adf7e7 6327@node Small buffer case
8cda6f8f
GM
6328@unnumberedsubsubsec What happens in a small buffer
6329
6330If the buffer contains fewer than 10,000 characters, a slightly
6331different computation is performed. You might think this is not
6332necessary, since the first computation could do the job. However, in
6333a small buffer, the first method may not put the cursor on exactly the
6334desired line; the second method does a better job.
6335
6336@need 800
6337The code looks like this:
6338
6339@c Keep this on one line.
6340@smallexample
6341(/ (+ 10 (* size (prefix-numeric-value arg))) 10))
6342@end smallexample
6343
6344@need 1200
6345@noindent
6346This is code in which you figure out what happens by discovering how the
6347functions are embedded in parentheses. It is easier to read if you
6348reformat it with each expression indented more deeply than its
6349enclosing expression:
6350
6351@smallexample
6352@group
6353 (/
6354 (+ 10
6355 (*
6356 size
6357 (prefix-numeric-value arg)))
6358 10))
6359@end group
6360@end smallexample
6361
6362@need 1200
6363@noindent
6364Looking at parentheses, we see that the innermost operation is
6365@code{(prefix-numeric-value arg)}, which converts the raw argument to
6366a number. In the following expression, this number is multiplied by
6367the size of the accessible portion of the buffer:
6368
6369@smallexample
6370(* size (prefix-numeric-value arg))
6371@end smallexample
6372
6373@noindent
6374This multiplication creates a number that may be larger than the size of
6375the buffer---seven times larger if the argument is 7, for example. Ten
6376is then added to this number and finally the large number is divided by
6377ten to provide a value that is one character larger than the percentage
6378position in the buffer.
6379
6380The number that results from all this is passed to @code{goto-char} and
6381the cursor is moved to that point.
6382
6383@need 1500
d6adf7e7 6384@node beginning-of-buffer complete
8cda6f8f
GM
6385@subsection The Complete @code{beginning-of-buffer}
6386
6387@need 1000
6388Here is the complete text of the @code{beginning-of-buffer} function:
6389@sp 1
6390
6391@c In GNU Emacs 22
6392@smallexample
6393@group
6394(defun beginning-of-buffer (&optional arg)
6395 "Move point to the beginning of the buffer;
6396leave mark at previous position.
6397With \\[universal-argument] prefix,
6398do not set mark at previous position.
6399With numeric arg N,
6400put point N/10 of the way from the beginning.
6401
6402If the buffer is narrowed,
6403this command uses the beginning and size
6404of the accessible part of the buffer.
6405@end group
6406
6407@group
6408Don't use this command in Lisp programs!
6409\(goto-char (point-min)) is faster
6410and avoids clobbering the mark."
6411 (interactive "P")
6412 (or (consp arg)
6413 (and transient-mark-mode mark-active)
6414 (push-mark))
6415@end group
6416@group
6417 (let ((size (- (point-max) (point-min))))
6418 (goto-char (if (and arg (not (consp arg)))
6419 (+ (point-min)
6420 (if (> size 10000)
6421 ;; Avoid overflow for large buffer sizes!
6422 (* (prefix-numeric-value arg)
6423 (/ size 10))
a9097c6d
KB
6424 (/ (+ 10 (* size (prefix-numeric-value arg)))
6425 10)))
8cda6f8f
GM
6426 (point-min))))
6427 (if arg (forward-line 1)))
6428@end group
6429@end smallexample
6430
6431@ignore
6432From before GNU Emacs 22
6433@smallexample
6434@group
6435(defun beginning-of-buffer (&optional arg)
6436 "Move point to the beginning of the buffer;
6437leave mark at previous position.
6438With arg N, put point N/10 of the way
6439from the true beginning.
6440@end group
6441@group
6442Don't use this in Lisp programs!
6443\(goto-char (point-min)) is faster
6444and does not set the mark."
6445 (interactive "P")
6446 (push-mark)
6447@end group
6448@group
6449 (goto-char
6450 (if arg
6451 (if (> (buffer-size) 10000)
6452 ;; @r{Avoid overflow for large buffer sizes!}
6453 (* (prefix-numeric-value arg)
6454 (/ (buffer-size) 10))
6455@end group
6456@group
6457 (/ (+ 10 (* (buffer-size)
6458 (prefix-numeric-value arg)))
6459 10))
6460 (point-min)))
6461 (if arg (forward-line 1)))
6462@end group
6463@end smallexample
6464@end ignore
6465
6466@noindent
6467Except for two small points, the previous discussion shows how this
6468function works. The first point deals with a detail in the
6469documentation string, and the second point concerns the last line of
6470the function.
6471
6472@need 800
6473In the documentation string, there is reference to an expression:
6474
6475@smallexample
6476\\[universal-argument]
6477@end smallexample
6478
6479@noindent
6480A @samp{\\} is used before the first square bracket of this
6481expression. This @samp{\\} tells the Lisp interpreter to substitute
6482whatever key is currently bound to the @samp{[@dots{}]}. In the case
6483of @code{universal-argument}, that is usually @kbd{C-u}, but it might
6484be different. (@xref{Documentation Tips, , Tips for Documentation
6485Strings, elisp, The GNU Emacs Lisp Reference Manual}, for more
6486information.)
6487
6488@need 1200
6489Finally, the last line of the @code{beginning-of-buffer} command says
6490to move point to the beginning of the next line if the command is
6491invoked with an argument:
6492
6493@smallexample
6494(if arg (forward-line 1)))
6495@end smallexample
6496
6497@noindent
6498This puts the cursor at the beginning of the first line after the
6499appropriate tenths position in the buffer. This is a flourish that
6500means that the cursor is always located @emph{at least} the requested
6501tenths of the way through the buffer, which is a nicety that is,
6502perhaps, not necessary, but which, if it did not occur, would be sure
6503to draw complaints.
6504
6505On the other hand, it also means that if you specify the command with
6506a @kbd{C-u}, but without a number, that is to say, if the `raw prefix
6507argument' is simply a cons cell, then the command puts you at the
6508beginning of the second line @dots{} I don't know whether this is
6509intended or whether no one has dealt with the code to avoid this
6510happening.
6511
d6adf7e7 6512@node Second Buffer Related Review
8cda6f8f
GM
6513@section Review
6514
6515Here is a brief summary of some of the topics covered in this chapter.
6516
6517@table @code
6518@item or
6519Evaluate each argument in sequence, and return the value of the first
6520argument that is not @code{nil}; if none return a value that is not
6521@code{nil}, return @code{nil}. In brief, return the first true value
6522of the arguments; return a true value if one @emph{or} any of the
6523others are true.
6524
6525@item and
6526Evaluate each argument in sequence, and if any are @code{nil}, return
6527@code{nil}; if none are @code{nil}, return the value of the last
6528argument. In brief, return a true value only if all the arguments are
6529true; return a true value if one @emph{and} each of the others is
6530true.
6531
6532@item &optional
6533A keyword used to indicate that an argument to a function definition
6534is optional; this means that the function can be evaluated without the
6535argument, if desired.
6536
6537@item prefix-numeric-value
6538Convert the `raw prefix argument' produced by @code{(interactive
6539"P")} to a numeric value.
6540
6541@item forward-line
6542Move point forward to the beginning of the next line, or if the argument
6543is greater than one, forward that many lines. If it can't move as far
6544forward as it is supposed to, @code{forward-line} goes forward as far as
6545it can and then returns a count of the number of additional lines it was
6546supposed to move but couldn't.
6547
6548@item erase-buffer
6549Delete the entire contents of the current buffer.
6550
6551@item bufferp
6552Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6553@end table
6554
d6adf7e7 6555@node optional Exercise
8cda6f8f
GM
6556@section @code{optional} Argument Exercise
6557
6558Write an interactive function with an optional argument that tests
6559whether its argument, a number, is greater than or equal to, or else,
6560less than the value of @code{fill-column}, and tells you which, in a
6561message. However, if you do not pass an argument to the function, use
656256 as a default value.
6563
d6adf7e7 6564@node Narrowing & Widening
8cda6f8f
GM
6565@chapter Narrowing and Widening
6566@cindex Focusing attention (narrowing)
6567@cindex Narrowing
6568@cindex Widening
6569
6570Narrowing is a feature of Emacs that makes it possible for you to focus
6571on a specific part of a buffer, and work without accidentally changing
6572other parts. Narrowing is normally disabled since it can confuse
6573novices.
6574
6575@menu
6576* Narrowing advantages:: The advantages of narrowing
6577* save-restriction:: The @code{save-restriction} special form.
6578* what-line:: The number of the line that point is on.
6579* narrow Exercise::
6580@end menu
6581
8cda6f8f 6582@ifnottex
d6adf7e7 6583@node Narrowing advantages
8cda6f8f
GM
6584@unnumberedsec The Advantages of Narrowing
6585@end ifnottex
6586
6587With narrowing, the rest of a buffer is made invisible, as if it weren't
6588there. This is an advantage if, for example, you want to replace a word
6589in one part of a buffer but not in another: you narrow to the part you want
6590and the replacement is carried out only in that section, not in the rest
6591of the buffer. Searches will only work within a narrowed region, not
6592outside of one, so if you are fixing a part of a document, you can keep
6593yourself from accidentally finding parts you do not need to fix by
6594narrowing just to the region you want.
6595(The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6596
6597However, narrowing does make the rest of the buffer invisible, which
6598can scare people who inadvertently invoke narrowing and think they
6599have deleted a part of their file. Moreover, the @code{undo} command
6600(which is usually bound to @kbd{C-x u}) does not turn off narrowing
6601(nor should it), so people can become quite desperate if they do not
6602know that they can return the rest of a buffer to visibility with the
6603@code{widen} command.
6604(The key binding for @code{widen} is @kbd{C-x n w}.)
6605
6606Narrowing is just as useful to the Lisp interpreter as to a human.
6607Often, an Emacs Lisp function is designed to work on just part of a
6608buffer; or conversely, an Emacs Lisp function needs to work on all of a
6609buffer that has been narrowed. The @code{what-line} function, for
6610example, removes the narrowing from a buffer, if it has any narrowing
6611and when it has finished its job, restores the narrowing to what it was.
7001d579
GZ
6612On the other hand, the @code{count-lines} function
6613uses narrowing to restrict itself to just that portion
8cda6f8f
GM
6614of the buffer in which it is interested and then restores the previous
6615situation.
6616
d6adf7e7 6617@node save-restriction
8cda6f8f
GM
6618@section The @code{save-restriction} Special Form
6619@findex save-restriction
6620
6621In Emacs Lisp, you can use the @code{save-restriction} special form to
6622keep track of whatever narrowing is in effect, if any. When the Lisp
6623interpreter meets with @code{save-restriction}, it executes the code
6624in the body of the @code{save-restriction} expression, and then undoes
6625any changes to narrowing that the code caused. If, for example, the
6626buffer is narrowed and the code that follows @code{save-restriction}
6627gets rid of the narrowing, @code{save-restriction} returns the buffer
6628to its narrowed region afterwards. In the @code{what-line} command,
6629any narrowing the buffer may have is undone by the @code{widen}
6630command that immediately follows the @code{save-restriction} command.
6631Any original narrowing is restored just before the completion of the
6632function.
6633
6634@need 1250
6635The template for a @code{save-restriction} expression is simple:
6636
6637@smallexample
6638@group
6639(save-restriction
6640 @var{body}@dots{} )
6641@end group
6642@end smallexample
6643
6644@noindent
6645The body of the @code{save-restriction} is one or more expressions that
6646will be evaluated in sequence by the Lisp interpreter.
6647
6648Finally, a point to note: when you use both @code{save-excursion} and
6649@code{save-restriction}, one right after the other, you should use
6650@code{save-excursion} outermost. If you write them in reverse order,
6651you may fail to record narrowing in the buffer to which Emacs switches
6652after calling @code{save-excursion}. Thus, when written together,
6653@code{save-excursion} and @code{save-restriction} should be written
6654like this:
6655
6656@smallexample
6657@group
6658(save-excursion
6659 (save-restriction
6660 @var{body}@dots{}))
6661@end group
6662@end smallexample
6663
6664In other circumstances, when not written together, the
6665@code{save-excursion} and @code{save-restriction} special forms must
6666be written in the order appropriate to the function.
6667
6668@need 1250
6669For example,
6670
6671@smallexample
6672@group
6673 (save-restriction
6674 (widen)
6675 (save-excursion
6676 @var{body}@dots{}))
6677@end group
6678@end smallexample
6679
6680@ignore
6681Emacs 22
6682/usr/local/src/emacs/lisp/simple.el
6683
6684(defun what-line ()
6685 "Print the current buffer line number and narrowed line number of point."
6686 (interactive)
6687 (let ((start (point-min))
6688 (n (line-number-at-pos)))
6689 (if (= start 1)
6690 (message "Line %d" n)
6691 (save-excursion
6692 (save-restriction
6693 (widen)
6694 (message "line %d (narrowed line %d)"
6695 (+ n (line-number-at-pos start) -1) n))))))
6696
6697(defun line-number-at-pos (&optional pos)
6698 "Return (narrowed) buffer line number at position POS.
6699If POS is nil, use current buffer location.
6700Counting starts at (point-min), so the value refers
6701to the contents of the accessible portion of the buffer."
6702 (let ((opoint (or pos (point))) start)
6703 (save-excursion
6704 (goto-char (point-min))
6705 (setq start (point))
6706 (goto-char opoint)
6707 (forward-line 0)
6708 (1+ (count-lines start (point))))))
6709
6710(defun count-lines (start end)
6711 "Return number of lines between START and END.
6712This is usually the number of newlines between them,
6713but can be one more if START is not equal to END
6714and the greater of them is not at the start of a line."
6715 (save-excursion
6716 (save-restriction
6717 (narrow-to-region start end)
6718 (goto-char (point-min))
6719 (if (eq selective-display t)
6720 (save-match-data
6721 (let ((done 0))
6722 (while (re-search-forward "[\n\C-m]" nil t 40)
6723 (setq done (+ 40 done)))
6724 (while (re-search-forward "[\n\C-m]" nil t 1)
6725 (setq done (+ 1 done)))
6726 (goto-char (point-max))
6727 (if (and (/= start end)
6728 (not (bolp)))
6729 (1+ done)
6730 done)))
6731 (- (buffer-size) (forward-line (buffer-size)))))))
6732@end ignore
6733
d6adf7e7 6734@node what-line
8cda6f8f
GM
6735@section @code{what-line}
6736@findex what-line
6737@cindex Widening, example of
6738
6739The @code{what-line} command tells you the number of the line in which
6740the cursor is located. The function illustrates the use of the
6741@code{save-restriction} and @code{save-excursion} commands. Here is the
6742original text of the function:
6743
6744@smallexample
6745@group
6746(defun what-line ()
6747 "Print the current line number (in the buffer) of point."
6748 (interactive)
6749 (save-restriction
6750 (widen)
6751 (save-excursion
6752 (beginning-of-line)
6753 (message "Line %d"
6754 (1+ (count-lines 1 (point)))))))
6755@end group
6756@end smallexample
6757
6758(In recent versions of GNU Emacs, the @code{what-line} function has
6759been expanded to tell you your line number in a narrowed buffer as
6760well as your line number in a widened buffer. The recent version is
6761more complex than the version shown here. If you feel adventurous,
6762you might want to look at it after figuring out how this version
6763works. You will probably need to use @kbd{C-h f}
6764(@code{describe-function}). The newer version uses a conditional to
6765determine whether the buffer has been narrowed.
6766
6767(Also, it uses @code{line-number-at-pos}, which among other simple
6768expressions, such as @code{(goto-char (point-min))}, moves point to
6769the beginning of the current line with @code{(forward-line 0)} rather
6770than @code{beginning-of-line}.)
6771
6772The @code{what-line} function as shown here has a documentation line
6773and is interactive, as you would expect. The next two lines use the
6774functions @code{save-restriction} and @code{widen}.
6775
6776The @code{save-restriction} special form notes whatever narrowing is in
6777effect, if any, in the current buffer and restores that narrowing after
6778the code in the body of the @code{save-restriction} has been evaluated.
6779
6780The @code{save-restriction} special form is followed by @code{widen}.
6781This function undoes any narrowing the current buffer may have had
6782when @code{what-line} was called. (The narrowing that was there is
6783the narrowing that @code{save-restriction} remembers.) This widening
6784makes it possible for the line counting commands to count from the
6785beginning of the buffer. Otherwise, they would have been limited to
6786counting within the accessible region. Any original narrowing is
6787restored just before the completion of the function by the
6788@code{save-restriction} special form.
6789
6790The call to @code{widen} is followed by @code{save-excursion}, which
6791saves the location of the cursor (i.e., of point) and of the mark, and
6792restores them after the code in the body of the @code{save-excursion}
6793uses the @code{beginning-of-line} function to move point.
6794
6795(Note that the @code{(widen)} expression comes between the
6796@code{save-restriction} and @code{save-excursion} special forms. When
6797you write the two @code{save- @dots{}} expressions in sequence, write
6798@code{save-excursion} outermost.)
6799
6800@need 1200
6801The last two lines of the @code{what-line} function are functions to
6802count the number of lines in the buffer and then print the number in the
6803echo area.
6804
6805@smallexample
6806@group
6807(message "Line %d"
6808 (1+ (count-lines 1 (point)))))))
6809@end group
6810@end smallexample
6811
6812The @code{message} function prints a one-line message at the bottom of
6813the Emacs screen. The first argument is inside of quotation marks and
6814is printed as a string of characters. However, it may contain a
6815@samp{%d} expression to print a following argument. @samp{%d} prints
6816the argument as a decimal, so the message will say something such as
6817@samp{Line 243}.
6818
6819@need 1200
6820The number that is printed in place of the @samp{%d} is computed by the
6821last line of the function:
6822
6823@smallexample
6824(1+ (count-lines 1 (point)))
6825@end smallexample
6826
6827@ignore
6828GNU Emacs 22
6829
6830(defun count-lines (start end)
6831 "Return number of lines between START and END.
6832This is usually the number of newlines between them,
6833but can be one more if START is not equal to END
6834and the greater of them is not at the start of a line."
6835 (save-excursion
6836 (save-restriction
6837 (narrow-to-region start end)
6838 (goto-char (point-min))
6839 (if (eq selective-display t)
6840 (save-match-data
6841 (let ((done 0))
6842 (while (re-search-forward "[\n\C-m]" nil t 40)
6843 (setq done (+ 40 done)))
6844 (while (re-search-forward "[\n\C-m]" nil t 1)
6845 (setq done (+ 1 done)))
6846 (goto-char (point-max))
6847 (if (and (/= start end)
6848 (not (bolp)))
6849 (1+ done)
6850 done)))
6851 (- (buffer-size) (forward-line (buffer-size)))))))
6852@end ignore
6853
6854@noindent
6855What this does is count the lines from the first position of the
6856buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6857one to that number. (The @code{1+} function adds one to its
6858argument.) We add one to it because line 2 has only one line before
6859it, and @code{count-lines} counts only the lines @emph{before} the
6860current line.
6861
6862After @code{count-lines} has done its job, and the message has been
6863printed in the echo area, the @code{save-excursion} restores point and
6864mark to their original positions; and @code{save-restriction} restores
6865the original narrowing, if any.
6866
d6adf7e7 6867@node narrow Exercise
8cda6f8f
GM
6868@section Exercise with Narrowing
6869
6870Write a function that will display the first 60 characters of the
6871current buffer, even if you have narrowed the buffer to its latter
6872half so that the first line is inaccessible. Restore point, mark, and
6873narrowing. For this exercise, you need to use a whole potpourri of
6874functions, including @code{save-restriction}, @code{widen},
6875@code{goto-char}, @code{point-min}, @code{message}, and
6876@code{buffer-substring}.
6877
6878@cindex Properties, mention of @code{buffer-substring-no-properties}
6879(@code{buffer-substring} is a previously unmentioned function you will
6880have to investigate yourself; or perhaps you will have to use
6881@code{buffer-substring-no-properties} or
6882@code{filter-buffer-substring} @dots{}, yet other functions. Text
6883properties are a feature otherwise not discussed here. @xref{Text
6884Properties, , Text Properties, elisp, The GNU Emacs Lisp Reference
6885Manual}.)
6886
6887Additionally, do you really need @code{goto-char} or @code{point-min}?
6888Or can you write the function without them?
6889
d6adf7e7 6890@node car cdr & cons
8cda6f8f
GM
6891@chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6892@findex car, @r{introduced}
6893@findex cdr, @r{introduced}
6894
6895In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6896functions. The @code{cons} function is used to construct lists, and
6897the @code{car} and @code{cdr} functions are used to take them apart.
6898
6899In the walk through of the @code{copy-region-as-kill} function, we
6900will see @code{cons} as well as two variants on @code{cdr},
6901namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6902
6903@menu
6904* Strange Names:: An historical aside: why the strange names?
6905* car & cdr:: Functions for extracting part of a list.
6906* cons:: Constructing a list.
6907* nthcdr:: Calling @code{cdr} repeatedly.
6908* nth::
6909* setcar:: Changing the first element of a list.
6910* setcdr:: Changing the rest of a list.
6911* cons Exercise::
6912@end menu
6913
8cda6f8f 6914@ifnottex
d6adf7e7 6915@node Strange Names
8cda6f8f
GM
6916@unnumberedsec Strange Names
6917@end ifnottex
6918
6919The name of the @code{cons} function is not unreasonable: it is an
6920abbreviation of the word `construct'. The origins of the names for
6921@code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6922is an acronym from the phrase `Contents of the Address part of the
6923Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6924the phrase `Contents of the Decrement part of the Register'. These
6925phrases refer to specific pieces of hardware on the very early
6926computer on which the original Lisp was developed. Besides being
6927obsolete, the phrases have been completely irrelevant for more than 25
6928years to anyone thinking about Lisp. Nonetheless, although a few
6929brave scholars have begun to use more reasonable names for these
6930functions, the old terms are still in use. In particular, since the
6931terms are used in the Emacs Lisp source code, we will use them in this
6932introduction.
6933
d6adf7e7 6934@node car & cdr
8cda6f8f
GM
6935@section @code{car} and @code{cdr}
6936
6937The @sc{car} of a list is, quite simply, the first item in the list.
6938Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6939@code{rose}.
6940
6941@need 1200
6942If you are reading this in Info in GNU Emacs, you can see this by
6943evaluating the following:
6944
6945@smallexample
6946(car '(rose violet daisy buttercup))
6947@end smallexample
6948
6949@noindent
6950After evaluating the expression, @code{rose} will appear in the echo
6951area.
6952
6953Clearly, a more reasonable name for the @code{car} function would be
6954@code{first} and this is often suggested.
6955
6956@code{car} does not remove the first item from the list; it only reports
6957what it is. After @code{car} has been applied to a list, the list is
6958still the same as it was. In the jargon, @code{car} is
6959`non-destructive'. This feature turns out to be important.
6960
6961The @sc{cdr} of a list is the rest of the list, that is, the
6962@code{cdr} function returns the part of the list that follows the
6963first item. Thus, while the @sc{car} of the list @code{'(rose violet
6964daisy buttercup)} is @code{rose}, the rest of the list, the value
6965returned by the @code{cdr} function, is @code{(violet daisy
6966buttercup)}.
6967
6968@need 800
6969You can see this by evaluating the following in the usual way:
6970
6971@smallexample
6972(cdr '(rose violet daisy buttercup))
6973@end smallexample
6974
6975@noindent
6976When you evaluate this, @code{(violet daisy buttercup)} will appear in
6977the echo area.
6978
6979Like @code{car}, @code{cdr} does not remove any elements from the
6980list---it just returns a report of what the second and subsequent
6981elements are.
6982
6983Incidentally, in the example, the list of flowers is quoted. If it were
6984not, the Lisp interpreter would try to evaluate the list by calling
6985@code{rose} as a function. In this example, we do not want to do that.
6986
6987Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6988
6989(There is a lesson here: when you name new functions, consider very
6990carefully what you are doing, since you may be stuck with the names
6991for far longer than you expect. The reason this document perpetuates
6992these names is that the Emacs Lisp source code uses them, and if I did
6993not use them, you would have a hard time reading the code; but do,
6994please, try to avoid using these terms yourself. The people who come
6995after you will be grateful to you.)
6996
6997When @code{car} and @code{cdr} are applied to a list made up of symbols,
6998such as the list @code{(pine fir oak maple)}, the element of the list
6999returned by the function @code{car} is the symbol @code{pine} without
7000any parentheses around it. @code{pine} is the first element in the
7001list. However, the @sc{cdr} of the list is a list itself, @code{(fir
7002oak maple)}, as you can see by evaluating the following expressions in
7003the usual way:
7004
7005@smallexample
7006@group
7007(car '(pine fir oak maple))
7008
7009(cdr '(pine fir oak maple))
7010@end group
7011@end smallexample
7012
7013On the other hand, in a list of lists, the first element is itself a
7014list. @code{car} returns this first element as a list. For example,
7015the following list contains three sub-lists, a list of carnivores, a
7016list of herbivores and a list of sea mammals:
7017
7018@smallexample
7019@group
7020(car '((lion tiger cheetah)
7021 (gazelle antelope zebra)
7022 (whale dolphin seal)))
7023@end group
7024@end smallexample
7025
7026@noindent
7027In this example, the first element or @sc{car} of the list is the list of
7028carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
7029@code{((gazelle antelope zebra) (whale dolphin seal))}.
7030
7031@smallexample
7032@group
7033(cdr '((lion tiger cheetah)
7034 (gazelle antelope zebra)
7035 (whale dolphin seal)))
7036@end group
7037@end smallexample
7038
7039It is worth saying again that @code{car} and @code{cdr} are
7040non-destructive---that is, they do not modify or change lists to which
7041they are applied. This is very important for how they are used.
7042
7043Also, in the first chapter, in the discussion about atoms, I said that
7044in Lisp, ``certain kinds of atom, such as an array, can be separated
7045into parts; but the mechanism for doing this is different from the
7046mechanism for splitting a list. As far as Lisp is concerned, the
7047atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
7048@code{car} and @code{cdr} functions are used for splitting lists and
7049are considered fundamental to Lisp. Since they cannot split or gain
7050access to the parts of an array, an array is considered an atom.
7051Conversely, the other fundamental function, @code{cons}, can put
7052together or construct a list, but not an array. (Arrays are handled
7053by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
7054Emacs Lisp Reference Manual}.)
7055
d6adf7e7 7056@node cons
8cda6f8f
GM
7057@section @code{cons}
7058@findex cons, @r{introduced}
7059
7060The @code{cons} function constructs lists; it is the inverse of
7061@code{car} and @code{cdr}. For example, @code{cons} can be used to make
7062a four element list from the three element list, @code{(fir oak maple)}:
7063
7064@smallexample
7065(cons 'pine '(fir oak maple))
7066@end smallexample
7067
7068@need 800
7069@noindent
7070After evaluating this list, you will see
7071
7072@smallexample
7073(pine fir oak maple)
7074@end smallexample
7075
7076@noindent
7077appear in the echo area. @code{cons} causes the creation of a new
7078list in which the element is followed by the elements of the original
7079list.
7080
7081We often say that `@code{cons} puts a new element at the beginning of
7082a list; it attaches or pushes elements onto the list', but this
7083phrasing can be misleading, since @code{cons} does not change an
7084existing list, but creates a new one.
7085
7086Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
7087
7088@menu
7089* Build a list::
7090* length:: How to find the length of a list.
7091@end menu
7092
8cda6f8f 7093@ifnottex
d6adf7e7 7094@node Build a list
8cda6f8f
GM
7095@unnumberedsubsec Build a list
7096@end ifnottex
7097
7098@code{cons} must have a list to attach to.@footnote{Actually, you can
7099@code{cons} an element to an atom to produce a dotted pair. Dotted
7100pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
7101Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
7102cannot start from absolutely nothing. If you are building a list, you
7103need to provide at least an empty list at the beginning. Here is a
7104series of @code{cons} expressions that build up a list of flowers. If
7105you are reading this in Info in GNU Emacs, you can evaluate each of
7106the expressions in the usual way; the value is printed in this text
7107after @samp{@result{}}, which you may read as `evaluates to'.
7108
7109@smallexample
7110@group
7111(cons 'buttercup ())
7112 @result{} (buttercup)
7113@end group
7114
7115@group
7116(cons 'daisy '(buttercup))
7117 @result{} (daisy buttercup)
7118@end group
7119
7120@group
7121(cons 'violet '(daisy buttercup))
7122 @result{} (violet daisy buttercup)
7123@end group
7124
7125@group
7126(cons 'rose '(violet daisy buttercup))
7127 @result{} (rose violet daisy buttercup)
7128@end group
7129@end smallexample
7130
7131@noindent
7132In the first example, the empty list is shown as @code{()} and a list
7133made up of @code{buttercup} followed by the empty list is constructed.
7134As you can see, the empty list is not shown in the list that was
7135constructed. All that you see is @code{(buttercup)}. The empty list is
7136not counted as an element of a list because there is nothing in an empty
7137list. Generally speaking, an empty list is invisible.
7138
7139The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
7140two element list by putting @code{daisy} in front of @code{buttercup};
7141and the third example constructs a three element list by putting
7142@code{violet} in front of @code{daisy} and @code{buttercup}.
7143
d6adf7e7 7144@node length
8cda6f8f
GM
7145@subsection Find the Length of a List: @code{length}
7146@findex length
7147
7148You can find out how many elements there are in a list by using the Lisp
7149function @code{length}, as in the following examples:
7150
7151@smallexample
7152@group
7153(length '(buttercup))
7154 @result{} 1
7155@end group
7156
7157@group
7158(length '(daisy buttercup))
7159 @result{} 2
7160@end group
7161
7162@group
7163(length (cons 'violet '(daisy buttercup)))
7164 @result{} 3
7165@end group
7166@end smallexample
7167
7168@noindent
7169In the third example, the @code{cons} function is used to construct a
7170three element list which is then passed to the @code{length} function as
7171its argument.
7172
7173@need 1200
7174We can also use @code{length} to count the number of elements in an
7175empty list:
7176
7177@smallexample
7178@group
7179(length ())
7180 @result{} 0
7181@end group
7182@end smallexample
7183
7184@noindent
7185As you would expect, the number of elements in an empty list is zero.
7186
7187An interesting experiment is to find out what happens if you try to find
7188the length of no list at all; that is, if you try to call @code{length}
7189without giving it an argument, not even an empty list:
7190
7191@smallexample
7192(length )
7193@end smallexample
7194
7195@need 800
7196@noindent
7197What you see, if you evaluate this, is the error message
7198
7199@smallexample
7200Lisp error: (wrong-number-of-arguments length 0)
7201@end smallexample
7202
7203@noindent
7204This means that the function receives the wrong number of
7205arguments, zero, when it expects some other number of arguments. In
7206this case, one argument is expected, the argument being a list whose
7207length the function is measuring. (Note that @emph{one} list is
7208@emph{one} argument, even if the list has many elements inside it.)
7209
7210The part of the error message that says @samp{length} is the name of
7211the function.
7212
7213@ignore
7214@code{length} is still a subroutine, but you need C-h f to discover that.
7215
7216In an earlier version:
7217 This is written with a special notation, @samp{#<subr},
7218 that indicates that the function @code{length} is one of the primitive
7219 functions written in C rather than in Emacs Lisp. (@samp{subr} is an
7220 abbreviation for `subroutine'.) @xref{What Is a Function, , What Is a
7221 Function?, elisp , The GNU Emacs Lisp Reference Manual}, for more
7222 about subroutines.
7223@end ignore
7224
d6adf7e7 7225@node nthcdr
8cda6f8f
GM
7226@section @code{nthcdr}
7227@findex nthcdr
7228
7229The @code{nthcdr} function is associated with the @code{cdr} function.
7230What it does is take the @sc{cdr} of a list repeatedly.
7231
7232If you take the @sc{cdr} of the list @code{(pine fir
7233oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
7234repeat this on what was returned, you will be returned the list
7235@code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
7236list will just give you the original @sc{cdr} since the function does
7237not change the list. You need to evaluate the @sc{cdr} of the
7238@sc{cdr} and so on.) If you continue this, eventually you will be
7239returned an empty list, which in this case, instead of being shown as
7240@code{()} is shown as @code{nil}.
7241
7242@need 1200
7243For review, here is a series of repeated @sc{cdr}s, the text following
7244the @samp{@result{}} shows what is returned.
7245
7246@smallexample
7247@group
7248(cdr '(pine fir oak maple))
7249 @result{}(fir oak maple)
7250@end group
7251
7252@group
7253(cdr '(fir oak maple))
7254 @result{} (oak maple)
7255@end group
7256
7257@group
7258(cdr '(oak maple))
7259 @result{}(maple)
7260@end group
7261
7262@group
7263(cdr '(maple))
7264 @result{} nil
7265@end group
7266
7267@group
7268(cdr 'nil)
7269 @result{} nil
7270@end group
7271
7272@group
7273(cdr ())
7274 @result{} nil
7275@end group
7276@end smallexample
7277
7278@need 1200
7279You can also do several @sc{cdr}s without printing the values in
7280between, like this:
7281
7282@smallexample
7283@group
7284(cdr (cdr '(pine fir oak maple)))
7285 @result{} (oak maple)
7286@end group
7287@end smallexample
7288
7289@noindent
7290In this example, the Lisp interpreter evaluates the innermost list first.
7291The innermost list is quoted, so it just passes the list as it is to the
7292innermost @code{cdr}. This @code{cdr} passes a list made up of the
7293second and subsequent elements of the list to the outermost @code{cdr},
7294which produces a list composed of the third and subsequent elements of
7295the original list. In this example, the @code{cdr} function is repeated
7296and returns a list that consists of the original list without its
7297first two elements.
7298
7299The @code{nthcdr} function does the same as repeating the call to
7300@code{cdr}. In the following example, the argument 2 is passed to the
7301function @code{nthcdr}, along with the list, and the value returned is
7302the list without its first two items, which is exactly the same
7303as repeating @code{cdr} twice on the list:
7304
7305@smallexample
7306@group
7307(nthcdr 2 '(pine fir oak maple))
7308 @result{} (oak maple)
7309@end group
7310@end smallexample
7311
7312@need 1200
7313Using the original four element list, we can see what happens when
7314various numeric arguments are passed to @code{nthcdr}, including 0, 1,
7315and 5:
7316
7317@smallexample
7318@group
7319;; @r{Leave the list as it was.}
7320(nthcdr 0 '(pine fir oak maple))
7321 @result{} (pine fir oak maple)
7322@end group
7323
7324@group
7325;; @r{Return a copy without the first element.}
7326(nthcdr 1 '(pine fir oak maple))
7327 @result{} (fir oak maple)
7328@end group
7329
7330@group
7331;; @r{Return a copy of the list without three elements.}
7332(nthcdr 3 '(pine fir oak maple))
7333 @result{} (maple)
7334@end group
7335
7336@group
7337;; @r{Return a copy lacking all four elements.}
7338(nthcdr 4 '(pine fir oak maple))
7339 @result{} nil
7340@end group
7341
7342@group
7343;; @r{Return a copy lacking all elements.}
7344(nthcdr 5 '(pine fir oak maple))
7345 @result{} nil
7346@end group
7347@end smallexample
7348
d6adf7e7 7349@node nth
8cda6f8f
GM
7350@section @code{nth}
7351@findex nth
7352
7353The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
7354The @code{nth} function takes the @sc{car} of the result returned by
7355@code{nthcdr}. It returns the Nth element of the list.
7356
7357@need 1500
7358Thus, if it were not defined in C for speed, the definition of
7359@code{nth} would be:
7360
7361@smallexample
7362@group
7363(defun nth (n list)
7364 "Returns the Nth element of LIST.
7365N counts from zero. If LIST is not that long, nil is returned."
7366 (car (nthcdr n list)))
7367@end group
7368@end smallexample
7369
7370@noindent
7371(Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
7372but its definition was redone in C in the 1980s.)
7373
7374The @code{nth} function returns a single element of a list.
7375This can be very convenient.
7376
7377Note that the elements are numbered from zero, not one. That is to
7378say, the first element of a list, its @sc{car} is the zeroth element.
7379This is called `zero-based' counting and often bothers people who
7380are accustomed to the first element in a list being number one, which
7381is `one-based'.
7382
7383@need 1250
7384For example:
7385
7386@smallexample
7387@group
7388(nth 0 '("one" "two" "three"))
7389 @result{} "one"
7390
7391(nth 1 '("one" "two" "three"))
7392 @result{} "two"
7393@end group
7394@end smallexample
7395
7396It is worth mentioning that @code{nth}, like @code{nthcdr} and
7397@code{cdr}, does not change the original list---the function is
7398non-destructive. This is in sharp contrast to the @code{setcar} and
7399@code{setcdr} functions.
7400
d6adf7e7 7401@node setcar
8cda6f8f
GM
7402@section @code{setcar}
7403@findex setcar
7404
7405As you might guess from their names, the @code{setcar} and @code{setcdr}
7406functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7407They actually change the original list, unlike @code{car} and @code{cdr}
7408which leave the original list as it was. One way to find out how this
7409works is to experiment. We will start with the @code{setcar} function.
7410
7411@need 1200
7412First, we can make a list and then set the value of a variable to the
7413list, using the @code{setq} function. Here is a list of animals:
7414
7415@smallexample
7416(setq animals '(antelope giraffe lion tiger))
7417@end smallexample
7418
7419@noindent
7420If you are reading this in Info inside of GNU Emacs, you can evaluate
7421this expression in the usual fashion, by positioning the cursor after
7422the expression and typing @kbd{C-x C-e}. (I'm doing this right here
7423as I write this. This is one of the advantages of having the
7424interpreter built into the computing environment. Incidentally, when
7425there is nothing on the line after the final parentheses, such as a
7426comment, point can be on the next line. Thus, if your cursor is in
7427the first column of the next line, you do not need to move it.
7428Indeed, Emacs permits any amount of white space after the final
7429parenthesis.)
7430
7431@need 1200
7432When we evaluate the variable @code{animals}, we see that it is bound to
7433the list @code{(antelope giraffe lion tiger)}:
7434
7435@smallexample
7436@group
7437animals
7438 @result{} (antelope giraffe lion tiger)
7439@end group
7440@end smallexample
7441
7442@noindent
7443Put another way, the variable @code{animals} points to the list
7444@code{(antelope giraffe lion tiger)}.
7445
7446Next, evaluate the function @code{setcar} while passing it two
7447arguments, the variable @code{animals} and the quoted symbol
7448@code{hippopotamus}; this is done by writing the three element list
7449@code{(setcar animals 'hippopotamus)} and then evaluating it in the
7450usual fashion:
7451
7452@smallexample
7453(setcar animals 'hippopotamus)
7454@end smallexample
7455
7456@need 1200
7457@noindent
7458After evaluating this expression, evaluate the variable @code{animals}
7459again. You will see that the list of animals has changed:
7460
7461@smallexample
7462@group
7463animals
7464 @result{} (hippopotamus giraffe lion tiger)
7465@end group
7466@end smallexample
7467
7468@noindent
7469The first element on the list, @code{antelope} is replaced by
7470@code{hippopotamus}.
7471
7472So we can see that @code{setcar} did not add a new element to the list
7473as @code{cons} would have; it replaced @code{antelope} with
7474@code{hippopotamus}; it @emph{changed} the list.
7475
d6adf7e7 7476@node setcdr
8cda6f8f
GM
7477@section @code{setcdr}
7478@findex setcdr
7479
7480The @code{setcdr} function is similar to the @code{setcar} function,
7481except that the function replaces the second and subsequent elements of
7482a list rather than the first element.
7483
7484(To see how to change the last element of a list, look ahead to
7485@ref{kill-new function, , The @code{kill-new} function}, which uses
7486the @code{nthcdr} and @code{setcdr} functions.)
7487
7488@need 1200
7489To see how this works, set the value of the variable to a list of
7490domesticated animals by evaluating the following expression:
7491
7492@smallexample
7493(setq domesticated-animals '(horse cow sheep goat))
7494@end smallexample
7495
7496@need 1200
7497@noindent
7498If you now evaluate the list, you will be returned the list
7499@code{(horse cow sheep goat)}:
7500
7501@smallexample
7502@group
7503domesticated-animals
7504 @result{} (horse cow sheep goat)
7505@end group
7506@end smallexample
7507
7508@need 1200
7509Next, evaluate @code{setcdr} with two arguments, the name of the
7510variable which has a list as its value, and the list to which the
7511@sc{cdr} of the first list will be set;
7512
7513@smallexample
7514(setcdr domesticated-animals '(cat dog))
7515@end smallexample
7516
7517@noindent
7518If you evaluate this expression, the list @code{(cat dog)} will appear
7519in the echo area. This is the value returned by the function. The
7520result we are interested in is the ``side effect'', which we can see by
7521evaluating the variable @code{domesticated-animals}:
7522
7523@smallexample
7524@group
7525domesticated-animals
7526 @result{} (horse cat dog)
7527@end group
7528@end smallexample
7529
7530@noindent
7531Indeed, the list is changed from @code{(horse cow sheep goat)} to
7532@code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7533@code{(cow sheep goat)} to @code{(cat dog)}.
7534
d6adf7e7 7535@node cons Exercise
8cda6f8f
GM
7536@section Exercise
7537
7538Construct a list of four birds by evaluating several expressions with
7539@code{cons}. Find out what happens when you @code{cons} a list onto
7540itself. Replace the first element of the list of four birds with a
7541fish. Replace the rest of that list with a list of other fish.
7542
d6adf7e7 7543@node Cutting & Storing Text
8cda6f8f
GM
7544@chapter Cutting and Storing Text
7545@cindex Cutting and storing text
7546@cindex Storing and cutting text
7547@cindex Killing text
7548@cindex Clipping text
7549@cindex Erasing text
7550@cindex Deleting text
7551
7552Whenever you cut or clip text out of a buffer with a `kill' command in
7553GNU Emacs, it is stored in a list and you can bring it back with a
7554`yank' command.
7555
7556(The use of the word `kill' in Emacs for processes which specifically
7557@emph{do not} destroy the values of the entities is an unfortunate
7558historical accident. A much more appropriate word would be `clip' since
7559that is what the kill commands do; they clip text out of a buffer and
7560put it into storage from which it can be brought back. I have often
7561been tempted to replace globally all occurrences of `kill' in the Emacs
7562sources with `clip' and all occurrences of `killed' with `clipped'.)
7563
7564@menu
7565* Storing Text:: Text is stored in a list.
7566* zap-to-char:: Cutting out text up to a character.
7567* kill-region:: Cutting text out of a region.
7568* copy-region-as-kill:: A definition for copying text.
7569* Digression into C:: Minor note on C programming language macros.
7570* defvar:: How to give a variable an initial value.
7571* cons & search-fwd Review::
7572* search Exercises::
7573@end menu
7574
8cda6f8f 7575@ifnottex
d6adf7e7 7576@node Storing Text
8cda6f8f
GM
7577@unnumberedsec Storing Text in a List
7578@end ifnottex
7579
7580When text is cut out of a buffer, it is stored on a list. Successive
7581pieces of text are stored on the list successively, so the list might
7582look like this:
7583
7584@smallexample
7585("a piece of text" "previous piece")
7586@end smallexample
7587
7588@need 1200
7589@noindent
7590The function @code{cons} can be used to create a new list from a piece
7591of text (an `atom', to use the jargon) and an existing list, like
7592this:
7593
7594@smallexample
7595@group
7596(cons "another piece"
7597 '("a piece of text" "previous piece"))
7598@end group
7599@end smallexample
7600
7601@need 1200
7602@noindent
7603If you evaluate this expression, a list of three elements will appear in
7604the echo area:
7605
7606@smallexample
7607("another piece" "a piece of text" "previous piece")
7608@end smallexample
7609
7610With the @code{car} and @code{nthcdr} functions, you can retrieve
7611whichever piece of text you want. For example, in the following code,
7612@code{nthcdr 1 @dots{}} returns the list with the first item removed;
7613and the @code{car} returns the first element of that remainder---the
7614second element of the original list:
7615
7616@smallexample
7617@group
7618(car (nthcdr 1 '("another piece"
7619 "a piece of text"
7620 "previous piece")))
7621 @result{} "a piece of text"
7622@end group
7623@end smallexample
7624
7625The actual functions in Emacs are more complex than this, of course.
7626The code for cutting and retrieving text has to be written so that
7627Emacs can figure out which element in the list you want---the first,
7628second, third, or whatever. In addition, when you get to the end of
7629the list, Emacs should give you the first element of the list, rather
7630than nothing at all.
7631
7632The list that holds the pieces of text is called the @dfn{kill ring}.
7633This chapter leads up to a description of the kill ring and how it is
7634used by first tracing how the @code{zap-to-char} function works. This
7635function uses (or `calls') a function that invokes a function that
7636manipulates the kill ring. Thus, before reaching the mountains, we
7637climb the foothills.
7638
7639A subsequent chapter describes how text that is cut from the buffer is
7640retrieved. @xref{Yanking, , Yanking Text Back}.
7641
d6adf7e7 7642@node zap-to-char
8cda6f8f
GM
7643@section @code{zap-to-char}
7644@findex zap-to-char
7645
8f4ea8e0 7646@c FIXME remove obsolete stuff
8cda6f8f
GM
7647The @code{zap-to-char} function changed little between GNU Emacs
7648version 19 and GNU Emacs version 22. However, @code{zap-to-char}
7649calls another function, @code{kill-region}, which enjoyed a major
7650rewrite.
7651
7652The @code{kill-region} function in Emacs 19 is complex, but does not
7653use code that is important at this time. We will skip it.
7654
7655The @code{kill-region} function in Emacs 22 is easier to read than the
7656same function in Emacs 19 and introduces a very important concept,
7657that of error handling. We will walk through the function.
7658
7659But first, let us look at the interactive @code{zap-to-char} function.
7660
7661@menu
7662* Complete zap-to-char:: The complete implementation.
7663* zap-to-char interactive:: A three part interactive expression.
7664* zap-to-char body:: A short overview.
7665* search-forward:: How to search for a string.
7666* progn:: The @code{progn} special form.
7667* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7668@end menu
7669
8cda6f8f 7670@ifnottex
d6adf7e7 7671@node Complete zap-to-char
8cda6f8f
GM
7672@unnumberedsubsec The Complete @code{zap-to-char} Implementation
7673@end ifnottex
7674
7675The @code{zap-to-char} function removes the text in the region between
7676the location of the cursor (i.e., of point) up to and including the
7677next occurrence of a specified character. The text that
7678@code{zap-to-char} removes is put in the kill ring; and it can be
7679retrieved from the kill ring by typing @kbd{C-y} (@code{yank}). If
7680the command is given an argument, it removes text through that number
7681of occurrences. Thus, if the cursor were at the beginning of this
7682sentence and the character were @samp{s}, @samp{Thus} would be
7683removed. If the argument were two, @samp{Thus, if the curs} would be
7684removed, up to and including the @samp{s} in @samp{cursor}.
7685
7686If the specified character is not found, @code{zap-to-char} will say
7687``Search failed'', tell you the character you typed, and not remove
7688any text.
7689
7690In order to determine how much text to remove, @code{zap-to-char} uses
7691a search function. Searches are used extensively in code that
7692manipulates text, and we will focus attention on them as well as on the
7693deletion command.
7694
7695@ignore
7696@c GNU Emacs version 19
7697(defun zap-to-char (arg char) ; version 19 implementation
7698 "Kill up to and including ARG'th occurrence of CHAR.
7699Goes backward if ARG is negative; error if CHAR not found."
7700 (interactive "*p\ncZap to char: ")
7701 (kill-region (point)
7702 (progn
7703 (search-forward
7704 (char-to-string char) nil nil arg)
7705 (point))))
7706@end ignore
7707
7708@need 1250
7709Here is the complete text of the version 22 implementation of the function:
7710
7711@c GNU Emacs 22
7712@smallexample
7713@group
7714(defun zap-to-char (arg char)
7715 "Kill up to and including ARG'th occurrence of CHAR.
7716Case is ignored if `case-fold-search' is non-nil in the current buffer.
7717Goes backward if ARG is negative; error if CHAR not found."
7718 (interactive "p\ncZap to char: ")
7719 (if (char-table-p translation-table-for-input)
7720 (setq char (or (aref translation-table-for-input char) char)))
7721 (kill-region (point) (progn
a9097c6d
KB
7722 (search-forward (char-to-string char)
7723 nil nil arg)
8cda6f8f
GM
7724 (point))))
7725@end group
7726@end smallexample
7727
7728The documentation is thorough. You do need to know the jargon meaning
7729of the word `kill'.
7730
d6adf7e7 7731@node zap-to-char interactive
8cda6f8f
GM
7732@subsection The @code{interactive} Expression
7733
7734@need 800
7735The interactive expression in the @code{zap-to-char} command looks like
7736this:
7737
7738@smallexample
7739(interactive "p\ncZap to char: ")
7740@end smallexample
7741
7742The part within quotation marks, @code{"p\ncZap to char:@: "}, specifies
7743two different things. First, and most simply, is the @samp{p}.
7744This part is separated from the next part by a newline, @samp{\n}.
7745The @samp{p} means that the first argument to the function will be
7746passed the value of a `processed prefix'. The prefix argument is
7747passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7748the function is called interactively without a prefix, 1 is passed to
7749this argument.
7750
7751The second part of @code{"p\ncZap to char:@: "} is
7752@samp{cZap to char:@: }. In this part, the lower case @samp{c}
7753indicates that @code{interactive} expects a prompt and that the
7754argument will be a character. The prompt follows the @samp{c} and is
7755the string @samp{Zap to char:@: } (with a space after the colon to
7756make it look good).
7757
7758What all this does is prepare the arguments to @code{zap-to-char} so they
7759are of the right type, and give the user a prompt.
7760
7761In a read-only buffer, the @code{zap-to-char} function copies the text
7762to the kill ring, but does not remove it. The echo area displays a
7763message saying that the buffer is read-only. Also, the terminal may
7764beep or blink at you.
7765
d6adf7e7 7766@node zap-to-char body
8cda6f8f
GM
7767@subsection The Body of @code{zap-to-char}
7768
7769The body of the @code{zap-to-char} function contains the code that
7770kills (that is, removes) the text in the region from the current
7771position of the cursor up to and including the specified character.
7772
7773The first part of the code looks like this:
7774
7775@smallexample
7776(if (char-table-p translation-table-for-input)
7777 (setq char (or (aref translation-table-for-input char) char)))
7778(kill-region (point) (progn
7779 (search-forward (char-to-string char) nil nil arg)
7780 (point)))
7781@end smallexample
7782
7783@noindent
7784@code{char-table-p} is an hitherto unseen function. It determines
7785whether its argument is a character table. When it is, it sets the
7786character passed to @code{zap-to-char} to one of them, if that
7787character exists, or to the character itself. (This becomes important
7788for certain characters in non-European languages. The @code{aref}
7789function extracts an element from an array. It is an array-specific
7790function that is not described in this document. @xref{Arrays, ,
7791Arrays, elisp, The GNU Emacs Lisp Reference Manual}.)
7792
7793@noindent
7794@code{(point)} is the current position of the cursor.
7795
7796The next part of the code is an expression using @code{progn}. The body
7797of the @code{progn} consists of calls to @code{search-forward} and
7798@code{point}.
7799
7800It is easier to understand how @code{progn} works after learning about
7801@code{search-forward}, so we will look at @code{search-forward} and
7802then at @code{progn}.
7803
d6adf7e7 7804@node search-forward
8cda6f8f
GM
7805@subsection The @code{search-forward} Function
7806@findex search-forward
7807
7808The @code{search-forward} function is used to locate the
7809zapped-for-character in @code{zap-to-char}. If the search is
7810successful, @code{search-forward} leaves point immediately after the
7811last character in the target string. (In @code{zap-to-char}, the
7812target string is just one character long. @code{zap-to-char} uses the
7813function @code{char-to-string} to ensure that the computer treats that
7814character as a string.) If the search is backwards,
7815@code{search-forward} leaves point just before the first character in
7816the target. Also, @code{search-forward} returns @code{t} for true.
7817(Moving point is therefore a `side effect'.)
7818
7819@need 1250
7820In @code{zap-to-char}, the @code{search-forward} function looks like this:
7821
7822@smallexample
7823(search-forward (char-to-string char) nil nil arg)
7824@end smallexample
7825
7826The @code{search-forward} function takes four arguments:
7827
7828@enumerate
7829@item
7830The first argument is the target, what is searched for. This must be a
7831string, such as @samp{"z"}.
7832
7833As it happens, the argument passed to @code{zap-to-char} is a single
7834character. Because of the way computers are built, the Lisp
7835interpreter may treat a single character as being different from a
7836string of characters. Inside the computer, a single character has a
7837different electronic format than a string of one character. (A single
7838character can often be recorded in the computer using exactly one
7839byte; but a string may be longer, and the computer needs to be ready
7840for this.) Since the @code{search-forward} function searches for a
7841string, the character that the @code{zap-to-char} function receives as
7842its argument must be converted inside the computer from one format to
7843the other; otherwise the @code{search-forward} function will fail.
7844The @code{char-to-string} function is used to make this conversion.
7845
7846@item
7847The second argument bounds the search; it is specified as a position in
7848the buffer. In this case, the search can go to the end of the buffer,
7849so no bound is set and the second argument is @code{nil}.
7850
7851@item
7852The third argument tells the function what it should do if the search
7853fails---it can signal an error (and print a message) or it can return
7854@code{nil}. A @code{nil} as the third argument causes the function to
7855signal an error when the search fails.
7856
7857@item
7858The fourth argument to @code{search-forward} is the repeat count---how
7859many occurrences of the string to look for. This argument is optional
7860and if the function is called without a repeat count, this argument is
7861passed the value 1. If this argument is negative, the search goes
7862backwards.
7863@end enumerate
7864
7865@need 800
7866In template form, a @code{search-forward} expression looks like this:
7867
7868@smallexample
7869@group
7870(search-forward "@var{target-string}"
7871 @var{limit-of-search}
7872 @var{what-to-do-if-search-fails}
7873 @var{repeat-count})
7874@end group
7875@end smallexample
7876
7877We will look at @code{progn} next.
7878
d6adf7e7 7879@node progn
8cda6f8f
GM
7880@subsection The @code{progn} Special Form
7881@findex progn
7882
7883@code{progn} is a special form that causes each of its arguments to be
7884evaluated in sequence and then returns the value of the last one. The
7885preceding expressions are evaluated only for the side effects they
7886perform. The values produced by them are discarded.
7887
7888@need 800
7889The template for a @code{progn} expression is very simple:
7890
7891@smallexample
7892@group
7893(progn
7894 @var{body}@dots{})
7895@end group
7896@end smallexample
7897
7898In @code{zap-to-char}, the @code{progn} expression has to do two things:
7899put point in exactly the right position; and return the location of
7900point so that @code{kill-region} will know how far to kill to.
7901
7902The first argument to the @code{progn} is @code{search-forward}. When
7903@code{search-forward} finds the string, the function leaves point
7904immediately after the last character in the target string. (In this
7905case the target string is just one character long.) If the search is
7906backwards, @code{search-forward} leaves point just before the first
7907character in the target. The movement of point is a side effect.
7908
7909The second and last argument to @code{progn} is the expression
7910@code{(point)}. This expression returns the value of point, which in
7911this case will be the location to which it has been moved by
7912@code{search-forward}. (In the source, a line that tells the function
7913to go to the previous character, if it is going forward, was commented
7914out in 1999; I don't remember whether that feature or mis-feature was
7915ever a part of the distributed source.) The value of @code{point} is
7916returned by the @code{progn} expression and is passed to
7917@code{kill-region} as @code{kill-region}'s second argument.
7918
d6adf7e7 7919@node Summing up zap-to-char
8cda6f8f
GM
7920@subsection Summing up @code{zap-to-char}
7921
7922Now that we have seen how @code{search-forward} and @code{progn} work,
7923we can see how the @code{zap-to-char} function works as a whole.
7924
7925The first argument to @code{kill-region} is the position of the cursor
7926when the @code{zap-to-char} command is given---the value of point at
7927that time. Within the @code{progn}, the search function then moves
7928point to just after the zapped-to-character and @code{point} returns the
7929value of this location. The @code{kill-region} function puts together
7930these two values of point, the first one as the beginning of the region
7931and the second one as the end of the region, and removes the region.
7932
7933The @code{progn} special form is necessary because the
7934@code{kill-region} command takes two arguments; and it would fail if
7935@code{search-forward} and @code{point} expressions were written in
7936sequence as two additional arguments. The @code{progn} expression is
7937a single argument to @code{kill-region} and returns the one value that
7938@code{kill-region} needs for its second argument.
7939
d6adf7e7 7940@node kill-region
8cda6f8f
GM
7941@section @code{kill-region}
7942@findex kill-region
7943
7944The @code{zap-to-char} function uses the @code{kill-region} function.
7945This function clips text from a region and copies that text to
7946the kill ring, from which it may be retrieved.
7947
7948@ignore
7949GNU Emacs 22:
7950
7951(defun kill-region (beg end &optional yank-handler)
7952 "Kill (\"cut\") text between point and mark.
7953This deletes the text from the buffer and saves it in the kill ring.
7954The command \\[yank] can retrieve it from there.
7955\(If you want to kill and then yank immediately, use \\[kill-ring-save].)
7956
7957If you want to append the killed region to the last killed text,
7958use \\[append-next-kill] before \\[kill-region].
7959
7960If the buffer is read-only, Emacs will beep and refrain from deleting
7961the text, but put the text in the kill ring anyway. This means that
7962you can use the killing commands to copy text from a read-only buffer.
7963
7964This is the primitive for programs to kill text (as opposed to deleting it).
7965Supply two arguments, character positions indicating the stretch of text
7966 to be killed.
7967Any command that calls this function is a \"kill command\".
7968If the previous command was also a kill command,
7969the text killed this time appends to the text killed last time
7970to make one entry in the kill ring.
7971
7972In Lisp code, optional third arg YANK-HANDLER, if non-nil,
7973specifies the yank-handler text property to be set on the killed
7974text. See `insert-for-yank'."
7975 ;; Pass point first, then mark, because the order matters
7976 ;; when calling kill-append.
7977 (interactive (list (point) (mark)))
7978 (unless (and beg end)
7979 (error "The mark is not set now, so there is no region"))
7980 (condition-case nil
7981 (let ((string (filter-buffer-substring beg end t)))
7982 (when string ;STRING is nil if BEG = END
7983 ;; Add that string to the kill ring, one way or another.
7984 (if (eq last-command 'kill-region)
7985 (kill-append string (< end beg) yank-handler)
7986 (kill-new string nil yank-handler)))
7987 (when (or string (eq last-command 'kill-region))
7988 (setq this-command 'kill-region))
7989 nil)
7990 ((buffer-read-only text-read-only)
7991 ;; The code above failed because the buffer, or some of the characters
7992 ;; in the region, are read-only.
7993 ;; We should beep, in case the user just isn't aware of this.
7994 ;; However, there's no harm in putting
7995 ;; the region's text in the kill ring, anyway.
7996 (copy-region-as-kill beg end)
7997 ;; Set this-command now, so it will be set even if we get an error.
7998 (setq this-command 'kill-region)
7999 ;; This should barf, if appropriate, and give us the correct error.
8000 (if kill-read-only-ok
8001 (progn (message "Read only text copied to kill ring") nil)
8002 ;; Signal an error if the buffer is read-only.
8003 (barf-if-buffer-read-only)
8004 ;; If the buffer isn't read-only, the text is.
8005 (signal 'text-read-only (list (current-buffer)))))))
8006@end ignore
8007
8008The Emacs 22 version of that function uses @code{condition-case} and
8009@code{copy-region-as-kill}, both of which we will explain.
8010@code{condition-case} is an important special form.
8011
8012In essence, the @code{kill-region} function calls
8013@code{condition-case}, which takes three arguments. In this function,
8014the first argument does nothing. The second argument contains the
8015code that does the work when all goes well. The third argument
8016contains the code that is called in the event of an error.
8017
8018@menu
8019* Complete kill-region:: The function definition.
8020* condition-case:: Dealing with a problem.
8021* Lisp macro::
8022@end menu
8023
8cda6f8f 8024@ifnottex
d6adf7e7 8025@node Complete kill-region
8cda6f8f
GM
8026@unnumberedsubsec The Complete @code{kill-region} Definition
8027@end ifnottex
8028
8029@need 1200
8030We will go through the @code{condition-case} code in a moment. First,
8031let us look at the definition of @code{kill-region}, with comments
8032added:
8033
8034@c GNU Emacs 22:
8035@smallexample
8036@group
8037(defun kill-region (beg end)
8038 "Kill (\"cut\") text between point and mark.
8039This deletes the text from the buffer and saves it in the kill ring.
8040The command \\[yank] can retrieve it from there. @dots{} "
8041@end group
8042
8043@group
8044 ;; @bullet{} Since order matters, pass point first.
8045 (interactive (list (point) (mark)))
8046 ;; @bullet{} And tell us if we cannot cut the text.
8047 ;; `unless' is an `if' without a then-part.
8048 (unless (and beg end)
8049 (error "The mark is not set now, so there is no region"))
8050@end group
8051
8052@group
8053 ;; @bullet{} `condition-case' takes three arguments.
8054 ;; If the first argument is nil, as it is here,
8055 ;; information about the error signal is not
8056 ;; stored for use by another function.
8057 (condition-case nil
8058@end group
8059
8060@group
8061 ;; @bullet{} The second argument to `condition-case' tells the
8062 ;; Lisp interpreter what to do when all goes well.
8063@end group
8064
8065@group
8066 ;; It starts with a `let' function that extracts the string
8067 ;; and tests whether it exists. If so (that is what the
8068 ;; `when' checks), it calls an `if' function that determines
8069 ;; whether the previous command was another call to
8070 ;; `kill-region'; if it was, then the new text is appended to
8071 ;; the previous text; if not, then a different function,
8072 ;; `kill-new', is called.
8073@end group
8074
8075@group
8076 ;; The `kill-append' function concatenates the new string and
8077 ;; the old. The `kill-new' function inserts text into a new
8078 ;; item in the kill ring.
8079@end group
8080
8081@group
8082 ;; `when' is an `if' without an else-part. The second `when'
8083 ;; again checks whether the current string exists; in
8084 ;; addition, it checks whether the previous command was
8085 ;; another call to `kill-region'. If one or the other
8086 ;; condition is true, then it sets the current command to
8087 ;; be `kill-region'.
8088@end group
8089@group
8090 (let ((string (filter-buffer-substring beg end t)))
8091 (when string ;STRING is nil if BEG = END
8092 ;; Add that string to the kill ring, one way or another.
8093 (if (eq last-command 'kill-region)
8094@end group
8095@group
8096 ;; @minus{} `yank-handler' is an optional argument to
8097 ;; `kill-region' that tells the `kill-append' and
8098 ;; `kill-new' functions how deal with properties
8099 ;; added to the text, such as `bold' or `italics'.
8100 (kill-append string (< end beg) yank-handler)
8101 (kill-new string nil yank-handler)))
8102 (when (or string (eq last-command 'kill-region))
8103 (setq this-command 'kill-region))
8104 nil)
8105@end group
8106
8107@group
8108 ;; @bullet{} The third argument to `condition-case' tells the interpreter
8109 ;; what to do with an error.
8110@end group
8111@group
8112 ;; The third argument has a conditions part and a body part.
8113 ;; If the conditions are met (in this case,
8114 ;; if text or buffer are read-only)
8115 ;; then the body is executed.
8116@end group
8117@group
8118 ;; The first part of the third argument is the following:
8119 ((buffer-read-only text-read-only) ;; the if-part
8120 ;; @dots{} the then-part
8121 (copy-region-as-kill beg end)
8122@end group
8123@group
8124 ;; Next, also as part of the then-part, set this-command, so
8125 ;; it will be set in an error
8126 (setq this-command 'kill-region)
8127 ;; Finally, in the then-part, send a message if you may copy
8350f087 8128 ;; the text to the kill ring without signaling an error, but
8cda6f8f
GM
8129 ;; don't if you may not.
8130@end group
8131@group
8132 (if kill-read-only-ok
8133 (progn (message "Read only text copied to kill ring") nil)
8134 (barf-if-buffer-read-only)
8135 ;; If the buffer isn't read-only, the text is.
8136 (signal 'text-read-only (list (current-buffer)))))
8137@end group
8138@end smallexample
8139
8140@ignore
8141@c v 21
8142@smallexample
8143@group
8144(defun kill-region (beg end)
8145 "Kill between point and mark.
8146The text is deleted but saved in the kill ring."
8147 (interactive "r")
8148@end group
8149
8150@group
8151 ;; 1. `condition-case' takes three arguments.
8152 ;; If the first argument is nil, as it is here,
8153 ;; information about the error signal is not
8154 ;; stored for use by another function.
8155 (condition-case nil
8156@end group
8157
8158@group
8159 ;; 2. The second argument to `condition-case'
8160 ;; tells the Lisp interpreter what to do when all goes well.
8161@end group
8162
8163@group
8164 ;; The `delete-and-extract-region' function usually does the
8165 ;; work. If the beginning and ending of the region are both
8166 ;; the same, then the variable `string' will be empty, or nil
8167 (let ((string (delete-and-extract-region beg end)))
8168@end group
8169
8170@group
8171 ;; `when' is an `if' clause that cannot take an `else-part'.
8172 ;; Emacs normally sets the value of `last-command' to the
8173 ;; previous command.
8174@end group
8175@group
8176 ;; `kill-append' concatenates the new string and the old.
8177 ;; `kill-new' inserts text into a new item in the kill ring.
8178 (when string
8179 (if (eq last-command 'kill-region)
8180 ;; if true, prepend string
8181 (kill-append string (< end beg))
8182 (kill-new string)))
8183 (setq this-command 'kill-region))
8184@end group
8185
8186@group
8187 ;; 3. The third argument to `condition-case' tells the interpreter
8188 ;; what to do with an error.
8189@end group
8190@group
8191 ;; The third argument has a conditions part and a body part.
8192 ;; If the conditions are met (in this case,
8193 ;; if text or buffer are read-only)
8194 ;; then the body is executed.
8195@end group
8196@group
8197 ((buffer-read-only text-read-only) ;; this is the if-part
8198 ;; then...
8199 (copy-region-as-kill beg end)
8200@end group
8201@group
8202 (if kill-read-only-ok ;; usually this variable is nil
8203 (message "Read only text copied to kill ring")
8204 ;; or else, signal an error if the buffer is read-only;
8205 (barf-if-buffer-read-only)
8206 ;; and, in any case, signal that the text is read-only.
8207 (signal 'text-read-only (list (current-buffer)))))))
8208@end group
8209@end smallexample
8210@end ignore
8211
d6adf7e7 8212@node condition-case
8cda6f8f
GM
8213@subsection @code{condition-case}
8214@findex condition-case
8215
8216As we have seen earlier (@pxref{Making Errors, , Generate an Error
8217Message}), when the Emacs Lisp interpreter has trouble evaluating an
8218expression, it provides you with help; in the jargon, this is called
8219``signaling an error''. Usually, the computer stops the program and
8220shows you a message.
8221
8222However, some programs undertake complicated actions. They should not
8223simply stop on an error. In the @code{kill-region} function, the most
8224likely error is that you will try to kill text that is read-only and
8225cannot be removed. So the @code{kill-region} function contains code
8226to handle this circumstance. This code, which makes up the body of
8227the @code{kill-region} function, is inside of a @code{condition-case}
8228special form.
8229
8230@need 800
8231The template for @code{condition-case} looks like this:
8232
8233@smallexample
8234@group
8235(condition-case
8236 @var{var}
8237 @var{bodyform}
8238 @var{error-handler}@dots{})
8239@end group
8240@end smallexample
8241
8242The second argument, @var{bodyform}, is straightforward. The
8243@code{condition-case} special form causes the Lisp interpreter to
8244evaluate the code in @var{bodyform}. If no error occurs, the special
8245form returns the code's value and produces the side-effects, if any.
8246
8247In short, the @var{bodyform} part of a @code{condition-case}
8248expression determines what should happen when everything works
8249correctly.
8250
8251However, if an error occurs, among its other actions, the function
8252generating the error signal will define one or more error condition
8253names.
8254
8255An error handler is the third argument to @code{condition case}.
8256An error handler has two parts, a @var{condition-name} and a
8257@var{body}. If the @var{condition-name} part of an error handler
8258matches a condition name generated by an error, then the @var{body}
8259part of the error handler is run.
8260
8261As you will expect, the @var{condition-name} part of an error handler
8262may be either a single condition name or a list of condition names.
8263
8264Also, a complete @code{condition-case} expression may contain more
8265than one error handler. When an error occurs, the first applicable
8266handler is run.
8267
8268Lastly, the first argument to the @code{condition-case} expression,
8269the @var{var} argument, is sometimes bound to a variable that
8270contains information about the error. However, if that argument is
8271nil, as is the case in @code{kill-region}, that information is
8272discarded.
8273
8274@need 1200
8275In brief, in the @code{kill-region} function, the code
8276@code{condition-case} works like this:
8277
8278@smallexample
8279@group
8280@var{If no errors}, @var{run only this code}
8281 @var{but}, @var{if errors}, @var{run this other code}.
8282@end group
8283@end smallexample
8284
8285@ignore
82862006 Oct 24
8287In Emacs 22,
8288copy-region-as-kill is short, 12 lines, and uses
8289filter-buffer-substring, which is longer, 39 lines
8290and has delete-and-extract-region in it.
8291delete-and-extract-region is written in C.
8292
8293see Initializing a Variable with @code{defvar}
8294this is line 8054
8295Initializing a Variable with @code{defvar} includes line 8350
8296@end ignore
8297
d6adf7e7 8298@node Lisp macro
8cda6f8f
GM
8299@subsection Lisp macro
8300@cindex Macro, lisp
8301@cindex Lisp macro
8302
8303The part of the @code{condition-case} expression that is evaluated in
8304the expectation that all goes well has a @code{when}. The code uses
8305@code{when} to determine whether the @code{string} variable points to
8306text that exists.
8307
8308A @code{when} expression is simply a programmers' convenience. It is
8309an @code{if} without the possibility of an else clause. In your mind,
8310you can replace @code{when} with @code{if} and understand what goes
8311on. That is what the Lisp interpreter does.
8312
8313Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
8314enables you to define new control constructs and other language
8315features. It tells the interpreter how to compute another Lisp
8316expression which will in turn compute the value. In this case, the
8317`other expression' is an @code{if} expression.
8318
8319The @code{kill-region} function definition also has an @code{unless}
8320macro; it is the converse of @code{when}. The @code{unless} macro is
8321an @code{if} without a then clause
8322
8323For more about Lisp macros, see @ref{Macros, , Macros, elisp, The GNU
8324Emacs Lisp Reference Manual}. The C programming language also
8325provides macros. These are different, but also useful.
8326
8327@ignore
8328We will briefly look at C macros in
8329@ref{Digression into C}.
8330@end ignore
8331
8332@need 1200
8333Regarding the @code{when} macro, in the @code{condition-case}
8334expression, when the string has content, then another conditional
8335expression is executed. This is an @code{if} with both a then-part
8336and an else-part.
8337
8338@smallexample
8339@group
8340(if (eq last-command 'kill-region)
8341 (kill-append string (< end beg) yank-handler)
8342 (kill-new string nil yank-handler))
8343@end group
8344@end smallexample
8345
8346The then-part is evaluated if the previous command was another call to
8347@code{kill-region}; if not, the else-part is evaluated.
8348
8349@code{yank-handler} is an optional argument to @code{kill-region} that
8350tells the @code{kill-append} and @code{kill-new} functions how deal
8351with properties added to the text, such as `bold' or `italics'.
8352
8353@code{last-command} is a variable that comes with Emacs that we have
8354not seen before. Normally, whenever a function is executed, Emacs
8355sets the value of @code{last-command} to the previous command.
8356
8357@need 1200
8358In this segment of the definition, the @code{if} expression checks
8359whether the previous command was @code{kill-region}. If it was,
8360
8361@smallexample
8362(kill-append string (< end beg) yank-handler)
8363@end smallexample
8364
8365@noindent
8366concatenates a copy of the newly clipped text to the just previously
8367clipped text in the kill ring.
8368
d6adf7e7 8369@node copy-region-as-kill
8cda6f8f
GM
8370@section @code{copy-region-as-kill}
8371@findex copy-region-as-kill
8372@findex nthcdr
8373
8374The @code{copy-region-as-kill} function copies a region of text from a
8375buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8376in the @code{kill-ring}.
8377
8378If you call @code{copy-region-as-kill} immediately after a
8379@code{kill-region} command, Emacs appends the newly copied text to the
8380previously copied text. This means that if you yank back the text, you
8381get it all, from both this and the previous operation. On the other
8382hand, if some other command precedes the @code{copy-region-as-kill},
8383the function copies the text into a separate entry in the kill ring.
8384
8385@menu
8386* Complete copy-region-as-kill:: The complete function definition.
8387* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8388@end menu
8389
8cda6f8f 8390@ifnottex
d6adf7e7 8391@node Complete copy-region-as-kill
8cda6f8f
GM
8392@unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8393@end ifnottex
8394
8395@need 1200
8396Here is the complete text of the version 22 @code{copy-region-as-kill}
8397function:
8398
8399@smallexample
8400@group
8401(defun copy-region-as-kill (beg end)
8402 "Save the region as if killed, but don't kill it.
8403In Transient Mark mode, deactivate the mark.
8404If `interprogram-cut-function' is non-nil, also save the text for a window
8405system cut and paste."
8406 (interactive "r")
8407@end group
8408@group
8409 (if (eq last-command 'kill-region)
8410 (kill-append (filter-buffer-substring beg end) (< end beg))
8411 (kill-new (filter-buffer-substring beg end)))
8412@end group
8413@group
8414 (if transient-mark-mode
8415 (setq deactivate-mark t))
8416 nil)
8417@end group
8418@end smallexample
8419
8420@need 800
8421As usual, this function can be divided into its component parts:
8422
8423@smallexample
8424@group
8425(defun copy-region-as-kill (@var{argument-list})
8426 "@var{documentation}@dots{}"
8427 (interactive "r")
8428 @var{body}@dots{})
8429@end group
8430@end smallexample
8431
8432The arguments are @code{beg} and @code{end} and the function is
8433interactive with @code{"r"}, so the two arguments must refer to the
8434beginning and end of the region. If you have been reading though this
8435document from the beginning, understanding these parts of a function is
8436almost becoming routine.
8437
8438The documentation is somewhat confusing unless you remember that the
8439word `kill' has a meaning different from usual. The `Transient Mark'
8440and @code{interprogram-cut-function} comments explain certain
8441side-effects.
8442
8443After you once set a mark, a buffer always contains a region. If you
8444wish, you can use Transient Mark mode to highlight the region
8445temporarily. (No one wants to highlight the region all the time, so
8446Transient Mark mode highlights it only at appropriate times. Many
8447people turn off Transient Mark mode, so the region is never
8448highlighted.)
8449
8450Also, a windowing system allows you to copy, cut, and paste among
8451different programs. In the X windowing system, for example, the
8452@code{interprogram-cut-function} function is @code{x-select-text},
8453which works with the windowing system's equivalent of the Emacs kill
8454ring.
8455
8456The body of the @code{copy-region-as-kill} function starts with an
8457@code{if} clause. What this clause does is distinguish between two
8458different situations: whether or not this command is executed
8459immediately after a previous @code{kill-region} command. In the first
8460case, the new region is appended to the previously copied text.
8461Otherwise, it is inserted into the beginning of the kill ring as a
8462separate piece of text from the previous piece.
8463
8464The last two lines of the function prevent the region from lighting up
8465if Transient Mark mode is turned on.
8466
8467The body of @code{copy-region-as-kill} merits discussion in detail.
8468
d6adf7e7 8469@node copy-region-as-kill body
8cda6f8f
GM
8470@subsection The Body of @code{copy-region-as-kill}
8471
8472The @code{copy-region-as-kill} function works in much the same way as
8473the @code{kill-region} function. Both are written so that two or more
8474kills in a row combine their text into a single entry. If you yank
8475back the text from the kill ring, you get it all in one piece.
8476Moreover, kills that kill forward from the current position of the
8477cursor are added to the end of the previously copied text and commands
8478that copy text backwards add it to the beginning of the previously
8479copied text. This way, the words in the text stay in the proper
8480order.
8481
8482Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8483use of the @code{last-command} variable that keeps track of the
8484previous Emacs command.
8485
8486@menu
8487* last-command & this-command::
8488* kill-append function::
8489* kill-new function::
8490@end menu
8491
8cda6f8f 8492@ifnottex
d6adf7e7 8493@node last-command & this-command
8cda6f8f
GM
8494@unnumberedsubsubsec @code{last-command} and @code{this-command}
8495@end ifnottex
8496
8497Normally, whenever a function is executed, Emacs sets the value of
8498@code{this-command} to the function being executed (which in this case
8499would be @code{copy-region-as-kill}). At the same time, Emacs sets
8500the value of @code{last-command} to the previous value of
8501@code{this-command}.
8502
8503In the first part of the body of the @code{copy-region-as-kill}
8504function, an @code{if} expression determines whether the value of
8505@code{last-command} is @code{kill-region}. If so, the then-part of
8506the @code{if} expression is evaluated; it uses the @code{kill-append}
8507function to concatenate the text copied at this call to the function
8508with the text already in the first element (the @sc{car}) of the kill
8509ring. On the other hand, if the value of @code{last-command} is not
8510@code{kill-region}, then the @code{copy-region-as-kill} function
8511attaches a new element to the kill ring using the @code{kill-new}
8512function.
8513
8514@need 1250
8515The @code{if} expression reads as follows; it uses @code{eq}:
8516
8517@smallexample
8518@group
8519 (if (eq last-command 'kill-region)
8520 ;; @r{then-part}
8521 (kill-append (filter-buffer-substring beg end) (< end beg))
8522 ;; @r{else-part}
8523 (kill-new (filter-buffer-substring beg end)))
8524@end group
8525@end smallexample
8526
8527@findex filter-buffer-substring
8528(The @code{filter-buffer-substring} function returns a filtered
8529substring of the buffer, if any. Optionally---the arguments are not
8530here, so neither is done---the function may delete the initial text or
8531return the text without its properties; this function is a replacement
8532for the older @code{buffer-substring} function, which came before text
8533properties were implemented.)
8534
8535@findex eq @r{(example of use)}
8536@noindent
8537The @code{eq} function tests whether its first argument is the same Lisp
8538object as its second argument. The @code{eq} function is similar to the
8539@code{equal} function in that it is used to test for equality, but
8540differs in that it determines whether two representations are actually
8541the same object inside the computer, but with different names.
8542@code{equal} determines whether the structure and contents of two
8543expressions are the same.
8544
8545If the previous command was @code{kill-region}, then the Emacs Lisp
8546interpreter calls the @code{kill-append} function
8547
d6adf7e7 8548@node kill-append function
8cda6f8f
GM
8549@unnumberedsubsubsec The @code{kill-append} function
8550@findex kill-append
8551
8552@need 800
8553The @code{kill-append} function looks like this:
8554
8555@c in GNU Emacs 22
8556@smallexample
8557@group
8558(defun kill-append (string before-p &optional yank-handler)
8559 "Append STRING to the end of the latest kill in the kill ring.
8560If BEFORE-P is non-nil, prepend STRING to the kill.
8561@dots{} "
8562 (let* ((cur (car kill-ring)))
8563 (kill-new (if before-p (concat string cur) (concat cur string))
8564 (or (= (length cur) 0)
8565 (equal yank-handler
8566 (get-text-property 0 'yank-handler cur)))
8567 yank-handler)))
8568@end group
8569@end smallexample
8570
8571@ignore
8572was:
8573(defun kill-append (string before-p)
8574 "Append STRING to the end of the latest kill in the kill ring.
8575If BEFORE-P is non-nil, prepend STRING to the kill.
8576If `interprogram-cut-function' is set, pass the resulting kill to
8577it."
8578 (kill-new (if before-p
8579 (concat string (car kill-ring))
8580 (concat (car kill-ring) string))
8581 t))
8582@end ignore
8583
8584@noindent
8585The @code{kill-append} function is fairly straightforward. It uses
8586the @code{kill-new} function, which we will discuss in more detail in
8587a moment.
8588
8589(Also, the function provides an optional argument called
8590@code{yank-handler}; when invoked, this argument tells the function
8591how to deal with properties added to the text, such as `bold' or
8592`italics'.)
8593
8594@c !!! bug in GNU Emacs 22 version of kill-append ?
8595It has a @code{let*} function to set the value of the first element of
8596the kill ring to @code{cur}. (I do not know why the function does not
8597use @code{let} instead; only one value is set in the expression.
8598Perhaps this is a bug that produces no problems?)
8599
8600Consider the conditional that is one of the two arguments to
8601@code{kill-new}. It uses @code{concat} to concatenate the new text to
8602the @sc{car} of the kill ring. Whether it prepends or appends the
8603text depends on the results of an @code{if} expression:
8604
8605@smallexample
8606@group
8607(if before-p ; @r{if-part}
8608 (concat string cur) ; @r{then-part}
8609 (concat cur string)) ; @r{else-part}
8610@end group
8611@end smallexample
8612
8613@noindent
8614If the region being killed is before the region that was killed in the
8615last command, then it should be prepended before the material that was
8616saved in the previous kill; and conversely, if the killed text follows
8617what was just killed, it should be appended after the previous text.
8618The @code{if} expression depends on the predicate @code{before-p} to
8619decide whether the newly saved text should be put before or after the
8620previously saved text.
8621
8622The symbol @code{before-p} is the name of one of the arguments to
8623@code{kill-append}. When the @code{kill-append} function is
8624evaluated, it is bound to the value returned by evaluating the actual
8625argument. In this case, this is the expression @code{(< end beg)}.
8626This expression does not directly determine whether the killed text in
8627this command is located before or after the kill text of the last
8628command; what it does is determine whether the value of the variable
8629@code{end} is less than the value of the variable @code{beg}. If it
8630is, it means that the user is most likely heading towards the
8631beginning of the buffer. Also, the result of evaluating the predicate
8632expression, @code{(< end beg)}, will be true and the text will be
8633prepended before the previous text. On the other hand, if the value of
8634the variable @code{end} is greater than the value of the variable
8635@code{beg}, the text will be appended after the previous text.
8636
8637@need 800
8638When the newly saved text will be prepended, then the string with the new
8639text will be concatenated before the old text:
8640
8641@smallexample
8642(concat string cur)
8643@end smallexample
8644
8645@need 1200
8646@noindent
8647But if the text will be appended, it will be concatenated
8648after the old text:
8649
8650@smallexample
8651(concat cur string))
8652@end smallexample
8653
8654To understand how this works, we first need to review the
8655@code{concat} function. The @code{concat} function links together or
8656unites two strings of text. The result is a string. For example:
8657
8658@smallexample
8659@group
8660(concat "abc" "def")
8661 @result{} "abcdef"
8662@end group
8663
8664@group
8665(concat "new "
8666 (car '("first element" "second element")))
8667 @result{} "new first element"
8668
8669(concat (car
8670 '("first element" "second element")) " modified")
8671 @result{} "first element modified"
8672@end group
8673@end smallexample
8674
8675We can now make sense of @code{kill-append}: it modifies the contents
8676of the kill ring. The kill ring is a list, each element of which is
8677saved text. The @code{kill-append} function uses the @code{kill-new}
8678function which in turn uses the @code{setcar} function.
8679
d6adf7e7 8680@node kill-new function
8cda6f8f
GM
8681@unnumberedsubsubsec The @code{kill-new} function
8682@findex kill-new
8683
8684@c in GNU Emacs 22, additional documentation to kill-new:
8685@ignore
8686Optional third arguments YANK-HANDLER controls how the STRING is later
8687inserted into a buffer; see `insert-for-yank' for details.
8688When a yank handler is specified, STRING must be non-empty (the yank
8689handler, if non-nil, is stored as a `yank-handler' text property on STRING).
8690
8691When the yank handler has a non-nil PARAM element, the original STRING
8692argument is not used by `insert-for-yank'. However, since Lisp code
8693may access and use elements from the kill ring directly, the STRING
8694argument should still be a \"useful\" string for such uses."
8695@end ignore
8696@need 1200
8697The @code{kill-new} function looks like this:
8698
8699@smallexample
8700@group
8701(defun kill-new (string &optional replace yank-handler)
8702 "Make STRING the latest kill in the kill ring.
8703Set `kill-ring-yank-pointer' to point to it.
8704
8705If `interprogram-cut-function' is non-nil, apply it to STRING.
8706Optional second argument REPLACE non-nil means that STRING will replace
8707the front of the kill ring, rather than being added to the list.
8708@dots{}"
8709@end group
8710@group
8711 (if (> (length string) 0)
8712 (if yank-handler
8713 (put-text-property 0 (length string)
8714 'yank-handler yank-handler string))
8715 (if yank-handler
8716 (signal 'args-out-of-range
8717 (list string "yank-handler specified for empty string"))))
8718@end group
8719@group
8720 (if (fboundp 'menu-bar-update-yank-menu)
8721 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8722@end group
8723@group
8724 (if (and replace kill-ring)
8725 (setcar kill-ring string)
8726 (push string kill-ring)
8727 (if (> (length kill-ring) kill-ring-max)
8728 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8729@end group
8730@group
8731 (setq kill-ring-yank-pointer kill-ring)
8732 (if interprogram-cut-function
8733 (funcall interprogram-cut-function string (not replace))))
8734@end group
8735@end smallexample
8736@ignore
8737was:
8738(defun kill-new (string &optional replace)
8739 "Make STRING the latest kill in the kill ring.
8740Set the kill-ring-yank pointer to point to it.
8741If `interprogram-cut-function' is non-nil, apply it to STRING.
8742Optional second argument REPLACE non-nil means that STRING will replace
8743the front of the kill ring, rather than being added to the list."
8744 (and (fboundp 'menu-bar-update-yank-menu)
8745 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8746 (if (and replace kill-ring)
8747 (setcar kill-ring string)
8748 (setq kill-ring (cons string kill-ring))
8749 (if (> (length kill-ring) kill-ring-max)
8750 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8751 (setq kill-ring-yank-pointer kill-ring)
8752 (if interprogram-cut-function
8753 (funcall interprogram-cut-function string (not replace))))
8754@end ignore
8755
8756(Notice that the function is not interactive.)
8757
8758As usual, we can look at this function in parts.
8759
8760The function definition has an optional @code{yank-handler} argument,
8761which when invoked tells the function how to deal with properties
8762added to the text, such as `bold' or `italics'. We will skip that.
8763
8764@need 1200
8765The first line of the documentation makes sense:
8766
8767@smallexample
8768Make STRING the latest kill in the kill ring.
8769@end smallexample
8770
8771@noindent
8772Let's skip over the rest of the documentation for the moment.
8773
8774@noindent
8775Also, let's skip over the initial @code{if} expression and those lines
8776of code involving @code{menu-bar-update-yank-menu}. We will explain
8777them below.
8778
8779@need 1200
8780The critical lines are these:
8781
8782@smallexample
8783@group
8784 (if (and replace kill-ring)
8785 ;; @r{then}
8786 (setcar kill-ring string)
8787@end group
8788@group
8789 ;; @r{else}
8790 (push string kill-ring)
8791@end group
8792@group
8793 (setq kill-ring (cons string kill-ring))
8794 (if (> (length kill-ring) kill-ring-max)
8795 ;; @r{avoid overly long kill ring}
8796 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8797@end group
8798@group
8799 (setq kill-ring-yank-pointer kill-ring)
8800 (if interprogram-cut-function
8801 (funcall interprogram-cut-function string (not replace))))
8802@end group
8803@end smallexample
8804
8805The conditional test is @w{@code{(and replace kill-ring)}}.
8806This will be true when two conditions are met: the kill ring has
8807something in it, and the @code{replace} variable is true.
8808
8809@need 1250
8810When the @code{kill-append} function sets @code{replace} to be true
8811and when the kill ring has at least one item in it, the @code{setcar}
8812expression is executed:
8813
8814@smallexample
8815(setcar kill-ring string)
8816@end smallexample
8817
8818The @code{setcar} function actually changes the first element of the
8819@code{kill-ring} list to the value of @code{string}. It replaces the
8820first element.
8821
8822@need 1250
8823On the other hand, if the kill ring is empty, or replace is false, the
8824else-part of the condition is executed:
8825
8826@smallexample
8827(push string kill-ring)
8828@end smallexample
8829
8830@noindent
8831@need 1250
8832@code{push} puts its first argument onto the second. It is similar to
8833the older
8834
8835@smallexample
8836(setq kill-ring (cons string kill-ring))
8837@end smallexample
8838
8839@noindent
8840@need 1250
8841or the newer
8842
8843@smallexample
8844(add-to-list kill-ring string)
8845@end smallexample
8846
8847@noindent
8848When it is false, the expression first constructs a new version of the
8849kill ring by prepending @code{string} to the existing kill ring as a
8850new element (that is what the @code{push} does). Then it executes a
8851second @code{if} clause. This second @code{if} clause keeps the kill
8852ring from growing too long.
8853
8854Let's look at these two expressions in order.
8855
8856The @code{push} line of the else-part sets the new value of the kill
8857ring to what results from adding the string being killed to the old
8858kill ring.
8859
8860We can see how this works with an example.
8861
8862@need 800
8863First,
8864
8865@smallexample
8866(setq example-list '("here is a clause" "another clause"))
8867@end smallexample
8868
8869@need 1200
8870@noindent
8871After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8872@code{example-list} and see what it returns:
8873
8874@smallexample
8875@group
8876example-list
8877 @result{} ("here is a clause" "another clause")
8878@end group
8879@end smallexample
8880
8881@need 1200
8882@noindent
8883Now, we can add a new element on to this list by evaluating the
8884following expression:
8885@findex push, @r{example}
8886
8887@smallexample
8888(push "a third clause" example-list)
8889@end smallexample
8890
8891@need 800
8892@noindent
8893When we evaluate @code{example-list}, we find its value is:
8894
8895@smallexample
8896@group
8897example-list
8898 @result{} ("a third clause" "here is a clause" "another clause")
8899@end group
8900@end smallexample
8901
8902@noindent
8903Thus, the third clause is added to the list by @code{push}.
8904
8905@need 1200
8906Now for the second part of the @code{if} clause. This expression
8907keeps the kill ring from growing too long. It looks like this:
8908
8909@smallexample
8910@group
8911(if (> (length kill-ring) kill-ring-max)
8912 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8913@end group
8914@end smallexample
8915
8916The code checks whether the length of the kill ring is greater than
8917the maximum permitted length. This is the value of
8918@code{kill-ring-max} (which is 60, by default). If the length of the
8919kill ring is too long, then this code sets the last element of the
8920kill ring to @code{nil}. It does this by using two functions,
8921@code{nthcdr} and @code{setcdr}.
8922
8923We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8924It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8925@sc{car} of a list. In this case, however, @code{setcdr} will not be
8926setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8927function is used to cause it to set the @sc{cdr} of the next to last
8928element of the kill ring---this means that since the @sc{cdr} of the
8929next to last element is the last element of the kill ring, it will set
8930the last element of the kill ring.
8931
8932@findex nthcdr, @r{example}
8933The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8934list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8935@dots{} It does this @var{N} times and returns the results.
8936(@xref{nthcdr, , @code{nthcdr}}.)
8937
8938@findex setcdr, @r{example}
8939Thus, if we had a four element list that was supposed to be three
8940elements long, we could set the @sc{cdr} of the next to last element
8941to @code{nil}, and thereby shorten the list. (If you set the last
8942element to some other value than @code{nil}, which you could do, then
8943you would not have shortened the list. @xref{setcdr, ,
8944@code{setcdr}}.)
8945
8946You can see shortening by evaluating the following three expressions
8947in turn. First set the value of @code{trees} to @code{(maple oak pine
8948birch)}, then set the @sc{cdr} of its second @sc{cdr} to @code{nil}
8949and then find the value of @code{trees}:
8950
8951@smallexample
8952@group
8953(setq trees '(maple oak pine birch))
8954 @result{} (maple oak pine birch)
8955@end group
8956
8957@group
8958(setcdr (nthcdr 2 trees) nil)
8959 @result{} nil
8960
8961trees
8962 @result{} (maple oak pine)
8963@end group
8964@end smallexample
8965
8966@noindent
8967(The value returned by the @code{setcdr} expression is @code{nil} since
8968that is what the @sc{cdr} is set to.)
8969
8970To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8971@sc{cdr} a number of times that is one less than the maximum permitted
8972size of the kill ring and @code{setcdr} sets the @sc{cdr} of that
8973element (which will be the rest of the elements in the kill ring) to
8974@code{nil}. This prevents the kill ring from growing too long.
8975
8976@need 800
8977The next to last expression in the @code{kill-new} function is
8978
8979@smallexample
8980(setq kill-ring-yank-pointer kill-ring)
8981@end smallexample
8982
8983The @code{kill-ring-yank-pointer} is a global variable that is set to be
8984the @code{kill-ring}.
8985
8986Even though the @code{kill-ring-yank-pointer} is called a
8987@samp{pointer}, it is a variable just like the kill ring. However, the
8988name has been chosen to help humans understand how the variable is used.
8989
8990@need 1200
8991Now, to return to an early expression in the body of the function:
8992
8993@smallexample
8994@group
8995 (if (fboundp 'menu-bar-update-yank-menu)
8996 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8997@end group
8998@end smallexample
8999
9000@noindent
9001It starts with an @code{if} expression
9002
9003In this case, the expression tests first to see whether
9004@code{menu-bar-update-yank-menu} exists as a function, and if so,
9005calls it. The @code{fboundp} function returns true if the symbol it
9006is testing has a function definition that `is not void'. If the
9007symbol's function definition were void, we would receive an error
9008message, as we did when we created errors intentionally (@pxref{Making
9009Errors, , Generate an Error Message}).
9010
9011@noindent
9012The then-part contains an expression whose first element is the
9013function @code{and}.
9014
9015@findex and
9016The @code{and} special form evaluates each of its arguments until one
9017of the arguments returns a value of @code{nil}, in which case the
9018@code{and} expression returns @code{nil}; however, if none of the
9019arguments returns a value of @code{nil}, the value resulting from
9020evaluating the last argument is returned. (Since such a value is not
9021@code{nil}, it is considered true in Emacs Lisp.) In other words, an
9022@code{and} expression returns a true value only if all its arguments
9023are true. (@xref{Second Buffer Related Review}.)
9024
9025The expression determines whether the second argument to
9026@code{menu-bar-update-yank-menu} is true or not.
9027@ignore
9028 ;; If we're supposed to be extending an existing string, and that
9029 ;; string really is at the front of the menu, then update it in place.
9030@end ignore
9031
9032@code{menu-bar-update-yank-menu} is one of the functions that make it
9033possible to use the `Select and Paste' menu in the Edit item of a menu
9034bar; using a mouse, you can look at the various pieces of text you
9035have saved and select one piece to paste.
9036
9037The last expression in the @code{kill-new} function adds the newly
9038copied string to whatever facility exists for copying and pasting
9039among different programs running in a windowing system. In the X
9040Windowing system, for example, the @code{x-select-text} function takes
1df7defd 9041the string and stores it in memory operated by X@. You can paste the
8cda6f8f
GM
9042string in another program, such as an Xterm.
9043
9044@need 1200
9045The expression looks like this:
9046
9047@smallexample
9048@group
9049 (if interprogram-cut-function
9050 (funcall interprogram-cut-function string (not replace))))
9051@end group
9052@end smallexample
9053
9054If an @code{interprogram-cut-function} exists, then Emacs executes
9055@code{funcall}, which in turn calls its first argument as a function
9056and passes the remaining arguments to it. (Incidentally, as far as I
9057can see, this @code{if} expression could be replaced by an @code{and}
9058expression similar to the one in the first part of the function.)
9059
9060We are not going to discuss windowing systems and other programs
9061further, but merely note that this is a mechanism that enables GNU
9062Emacs to work easily and well with other programs.
9063
9064This code for placing text in the kill ring, either concatenated with
9065an existing element or as a new element, leads us to the code for
9066bringing back text that has been cut out of the buffer---the yank
9067commands. However, before discussing the yank commands, it is better
9068to learn how lists are implemented in a computer. This will make
9069clear such mysteries as the use of the term `pointer'. But before
9070that, we will digress into C.
9071
9072@ignore
9073@c is this true in Emacs 22? Does not seems to be
9074
9075 (If the @w{@code{(< end beg))}}
9076expression is true, @code{kill-append} prepends the string to the just
9077previously clipped text. For a detailed discussion, see
9078@ref{kill-append function, , The @code{kill-append} function}.)
9079
9080If you then yank back the text, i.e., `paste' it, you get both
9081pieces of text at once. That way, if you delete two words in a row,
9082and then yank them back, you get both words, in their proper order,
9083with one yank. (The @w{@code{(< end beg))}} expression makes sure the
9084order is correct.)
9085
9086On the other hand, if the previous command is not @code{kill-region},
9087then the @code{kill-new} function is called, which adds the text to
9088the kill ring as the latest item, and sets the
9089@code{kill-ring-yank-pointer} variable to point to it.
9090@end ignore
9091@ignore
9092
9093@c Evidently, changed for Emacs 22. The zap-to-char command does not
9094@c use the delete-and-extract-region function
9095
90962006 Oct 26, the Digression into C is now OK but should come after
9097copy-region-as-kill and filter-buffer-substring
9098
90992006 Oct 24
9100In Emacs 22,
9101copy-region-as-kill is short, 12 lines, and uses
9102filter-buffer-substring, which is longer, 39 lines
9103and has delete-and-extract-region in it.
9104delete-and-extract-region is written in C.
9105
9106see Initializing a Variable with @code{defvar}
9107@end ignore
9108
d6adf7e7 9109@node Digression into C
8cda6f8f
GM
9110@section Digression into C
9111@findex delete-and-extract-region
9112@cindex C, a digression into
9113@cindex Digression into C
9114
9115The @code{copy-region-as-kill} function (@pxref{copy-region-as-kill, ,
9116@code{copy-region-as-kill}}) uses the @code{filter-buffer-substring}
9117function, which in turn uses the @code{delete-and-extract-region}
9118function. It removes the contents of a region and you cannot get them
9119back.
9120
9121Unlike the other code discussed here, the
9122@code{delete-and-extract-region} function is not written in Emacs
9123Lisp; it is written in C and is one of the primitives of the GNU Emacs
9124system. Since it is very simple, I will digress briefly from Lisp and
9125describe it here.
9126
2d7d2325
GM
9127@c GNU Emacs 24 in src/editfns.c
9128@c the DEFUN for delete-and-extract-region
8cda6f8f
GM
9129
9130@need 1500
9131Like many of the other Emacs primitives,
9132@code{delete-and-extract-region} is written as an instance of a C
9133macro, a macro being a template for code. The complete macro looks
9134like this:
9135
9136@smallexample
9137@group
2d7d2325
GM
9138DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
9139 Sdelete_and_extract_region, 2, 2, 0,
9140 doc: /* Delete the text between START and END and return it. */)
9141 (Lisp_Object start, Lisp_Object end)
8cda6f8f 9142@{
8cda6f8f 9143 validate_region (&start, &end);
2d7d2325
GM
9144 if (XINT (start) == XINT (end))
9145 return empty_unibyte_string;
9146 return del_range_1 (XINT (start), XINT (end), 1, 1);
8cda6f8f
GM
9147@}
9148@end group
9149@end smallexample
9150
9151Without going into the details of the macro writing process, let me
9152point out that this macro starts with the word @code{DEFUN}. The word
9153@code{DEFUN} was chosen since the code serves the same purpose as
9154@code{defun} does in Lisp. (The @code{DEFUN} C macro is defined in
9155@file{emacs/src/lisp.h}.)
9156
9157The word @code{DEFUN} is followed by seven parts inside of
9158parentheses:
9159
9160@itemize @bullet
9161@item
9162The first part is the name given to the function in Lisp,
9163@code{delete-and-extract-region}.
9164
9165@item
9166The second part is the name of the function in C,
9167@code{Fdelete_and_extract_region}. By convention, it starts with
9168@samp{F}. Since C does not use hyphens in names, underscores are used
9169instead.
9170
9171@item
9172The third part is the name for the C constant structure that records
9173information on this function for internal use. It is the name of the
9174function in C but begins with an @samp{S} instead of an @samp{F}.
9175
9176@item
9177The fourth and fifth parts specify the minimum and maximum number of
9178arguments the function can have. This function demands exactly 2
9179arguments.
9180
9181@item
9182The sixth part is nearly like the argument that follows the
9183@code{interactive} declaration in a function written in Lisp: a letter
9184followed, perhaps, by a prompt. The only difference from the Lisp is
9185when the macro is called with no arguments. Then you write a @code{0}
9186(which is a `null string'), as in this macro.
9187
9188If you were to specify arguments, you would place them between
9189quotation marks. The C macro for @code{goto-char} includes
9190@code{"NGoto char: "} in this position to indicate that the function
9191expects a raw prefix, in this case, a numerical location in a buffer,
9192and provides a prompt.
9193
9194@item
9195The seventh part is a documentation string, just like the one for a
2d7d2325
GM
9196function written in Emacs Lisp. This is written as a C comment. (When
9197you build Emacs, the program @command{lib-src/make-docfile} extracts
9198these comments and uses them to make the ``real'' documentation.)
8cda6f8f
GM
9199@end itemize
9200
9201@need 1200
9202In a C macro, the formal parameters come next, with a statement of
9203what kind of object they are, followed by what might be called the `body'
9204of the macro. For @code{delete-and-extract-region} the `body'
9205consists of the following four lines:
9206
9207@smallexample
9208@group
9209validate_region (&start, &end);
9210if (XINT (start) == XINT (end))
2d7d2325 9211 return empty_unibyte_string;
8cda6f8f
GM
9212return del_range_1 (XINT (start), XINT (end), 1, 1);
9213@end group
9214@end smallexample
9215
2d7d2325 9216The @code{validate_region} function checks whether the values
8cda6f8f
GM
9217passed as the beginning and end of the region are the proper type and
9218are within range. If the beginning and end positions are the same,
2d7d2325 9219then return an empty string.
8cda6f8f
GM
9220
9221The @code{del_range_1} function actually deletes the text. It is a
9222complex function we will not look into. It updates the buffer and
9223does other things. However, it is worth looking at the two arguments
9224passed to @code{del_range}. These are @w{@code{XINT (start)}} and
9225@w{@code{XINT (end)}}.
9226
9227As far as the C language is concerned, @code{start} and @code{end} are
9228two integers that mark the beginning and end of the region to be
9229deleted@footnote{More precisely, and requiring more expert knowledge
9230to understand, the two integers are of type `Lisp_Object', which can
9231also be a C union instead of an integer type.}.
9232
9233In early versions of Emacs, these two numbers were thirty-two bits
9234long, but the code is slowly being generalized to handle other
9235lengths. Three of the available bits are used to specify the type of
9236information; the remaining bits are used as `content'.
9237
9238@samp{XINT} is a C macro that extracts the relevant number from the
9239longer collection of bits; the three other bits are discarded.
9240
9241@need 800
9242The command in @code{delete-and-extract-region} looks like this:
9243
9244@smallexample
9245del_range_1 (XINT (start), XINT (end), 1, 1);
9246@end smallexample
9247
9248@noindent
9249It deletes the region between the beginning position, @code{start},
9250and the ending position, @code{end}.
9251
9252From the point of view of the person writing Lisp, Emacs is all very
9253simple; but hidden underneath is a great deal of complexity to make it
9254all work.
9255
d6adf7e7 9256@node defvar
8cda6f8f
GM
9257@section Initializing a Variable with @code{defvar}
9258@findex defvar
9259@cindex Initializing a variable
9260@cindex Variable initialization
9261
9262@ignore
92632006 Oct 24
9264In Emacs 22,
9265copy-region-as-kill is short, 12 lines, and uses
9266filter-buffer-substring, which is longer, 39 lines
9267and has delete-and-extract-region in it.
9268delete-and-extract-region is written in C.
9269
9270see Initializing a Variable with @code{defvar}
9271
9272@end ignore
9273
9274The @code{copy-region-as-kill} function is written in Emacs Lisp. Two
9275functions within it, @code{kill-append} and @code{kill-new}, copy a
9276region in a buffer and save it in a variable called the
9277@code{kill-ring}. This section describes how the @code{kill-ring}
9278variable is created and initialized using the @code{defvar} special
9279form.
9280
9281(Again we note that the term @code{kill-ring} is a misnomer. The text
9282that is clipped out of the buffer can be brought back; it is not a ring
9283of corpses, but a ring of resurrectable text.)
9284
9285In Emacs Lisp, a variable such as the @code{kill-ring} is created and
9286given an initial value by using the @code{defvar} special form. The
9287name comes from ``define variable''.
9288
9289The @code{defvar} special form is similar to @code{setq} in that it sets
9290the value of a variable. It is unlike @code{setq} in two ways: first,
9291it only sets the value of the variable if the variable does not already
9292have a value. If the variable already has a value, @code{defvar} does
9293not override the existing value. Second, @code{defvar} has a
9294documentation string.
9295
9296(Another special form, @code{defcustom}, is designed for variables
9297that people customize. It has more features than @code{defvar}.
9298(@xref{defcustom, , Setting Variables with @code{defcustom}}.)
9299
9300@menu
9301* See variable current value::
9302* defvar and asterisk::
9303@end menu
9304
8cda6f8f 9305@ifnottex
d6adf7e7 9306@node See variable current value
8cda6f8f
GM
9307@unnumberedsubsec Seeing the Current Value of a Variable
9308@end ifnottex
9309
9310You can see the current value of a variable, any variable, by using
9311the @code{describe-variable} function, which is usually invoked by
9312typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
9313(followed by @key{RET}) when prompted, you will see what is in your
9314current kill ring---this may be quite a lot! Conversely, if you have
9315been doing nothing this Emacs session except read this document, you
9316may have nothing in it. Also, you will see the documentation for
9317@code{kill-ring}:
9318
9319@smallexample
9320@group
9321Documentation:
9322List of killed text sequences.
9323Since the kill ring is supposed to interact nicely with cut-and-paste
9324facilities offered by window systems, use of this variable should
9325@end group
9326@group
9327interact nicely with `interprogram-cut-function' and
9328`interprogram-paste-function'. The functions `kill-new',
9329`kill-append', and `current-kill' are supposed to implement this
9330interaction; you may want to use them instead of manipulating the kill
9331ring directly.
9332@end group
9333@end smallexample
9334
9335@need 800
9336The kill ring is defined by a @code{defvar} in the following way:
9337
9338@smallexample
9339@group
9340(defvar kill-ring nil
9341 "List of killed text sequences.
9342@dots{}")
9343@end group
9344@end smallexample
9345
9346@noindent
9347In this variable definition, the variable is given an initial value of
9348@code{nil}, which makes sense, since if you have saved nothing, you want
9349nothing back if you give a @code{yank} command. The documentation
9350string is written just like the documentation string of a @code{defun}.
9351As with the documentation string of the @code{defun}, the first line of
9352the documentation should be a complete sentence, since some commands,
9353like @code{apropos}, print only the first line of documentation.
9354Succeeding lines should not be indented; otherwise they look odd when
9355you use @kbd{C-h v} (@code{describe-variable}).
9356
d6adf7e7 9357@node defvar and asterisk
8cda6f8f
GM
9358@subsection @code{defvar} and an asterisk
9359@findex defvar @r{for a user customizable variable}
9360@findex defvar @r{with an asterisk}
9361
9362In the past, Emacs used the @code{defvar} special form both for
9363internal variables that you would not expect a user to change and for
9364variables that you do expect a user to change. Although you can still
9365use @code{defvar} for user customizable variables, please use
9366@code{defcustom} instead, since that special form provides a path into
9367the Customization commands. (@xref{defcustom, , Specifying Variables
9368using @code{defcustom}}.)
9369
9370When you specified a variable using the @code{defvar} special form,
943157cf
GM
9371you could distinguish a variable that a user might want to change from
9372others by typing an asterisk, @samp{*}, in the first column of its
9373documentation string. For example:
8cda6f8f
GM
9374
9375@smallexample
9376@group
9377(defvar shell-command-default-error-buffer nil
9378 "*Buffer name for `shell-command' @dots{} error output.
9379@dots{} ")
9380@end group
9381@end smallexample
9382
9383@findex set-variable
9384@noindent
9385You could (and still can) use the @code{set-variable} command to
9386change the value of @code{shell-command-default-error-buffer}
9387temporarily. However, options set using @code{set-variable} are set
9388only for the duration of your editing session. The new values are not
9389saved between sessions. Each time Emacs starts, it reads the original
9390value, unless you change the value within your @file{.emacs} file,
9391either by setting it manually or by using @code{customize}.
9392@xref{Emacs Initialization, , Your @file{.emacs} File}.
9393
9394For me, the major use of the @code{set-variable} command is to suggest
9395variables that I might want to set in my @file{.emacs} file. There
f99f1641 9396are now more than 700 such variables, far too many to remember
8cda6f8f
GM
9397readily. Fortunately, you can press @key{TAB} after calling the
9398@code{M-x set-variable} command to see the list of variables.
9399(@xref{Examining, , Examining and Setting Variables, emacs,
9400The GNU Emacs Manual}.)
9401
9402@need 1250
d6adf7e7 9403@node cons & search-fwd Review
8cda6f8f
GM
9404@section Review
9405
9406Here is a brief summary of some recently introduced functions.
9407
9408@table @code
9409@item car
9410@itemx cdr
9411@code{car} returns the first element of a list; @code{cdr} returns the
9412second and subsequent elements of a list.
9413
9414@need 1250
9415For example:
9416
9417@smallexample
9418@group
9419(car '(1 2 3 4 5 6 7))
9420 @result{} 1
9421(cdr '(1 2 3 4 5 6 7))
9422 @result{} (2 3 4 5 6 7)
9423@end group
9424@end smallexample
9425
9426@item cons
9427@code{cons} constructs a list by prepending its first argument to its
9428second argument.
9429
9430@need 1250
9431For example:
9432
9433@smallexample
9434@group
9435(cons 1 '(2 3 4))
9436 @result{} (1 2 3 4)
9437@end group
9438@end smallexample
9439
9440@item funcall
9441@code{funcall} evaluates its first argument as a function. It passes
9442its remaining arguments to its first argument.
9443
9444@item nthcdr
9445Return the result of taking @sc{cdr} `n' times on a list.
9446@iftex
9447The
9448@tex
9449$n^{th}$
9450@end tex
9451@code{cdr}.
9452@end iftex
9453The `rest of the rest', as it were.
9454
9455@need 1250
9456For example:
9457
9458@smallexample
9459@group
9460(nthcdr 3 '(1 2 3 4 5 6 7))
9461 @result{} (4 5 6 7)
9462@end group
9463@end smallexample
9464
9465@item setcar
9466@itemx setcdr
9467@code{setcar} changes the first element of a list; @code{setcdr}
9468changes the second and subsequent elements of a list.
9469
9470@need 1250
9471For example:
9472
9473@smallexample
9474@group
9475(setq triple '(1 2 3))
9476
9477(setcar triple '37)
9478
9479triple
9480 @result{} (37 2 3)
9481
9482(setcdr triple '("foo" "bar"))
9483
9484triple
9485 @result{} (37 "foo" "bar")
9486@end group
9487@end smallexample
9488
9489@item progn
9490Evaluate each argument in sequence and then return the value of the
9491last.
9492
9493@need 1250
9494For example:
9495
9496@smallexample
9497@group
9498(progn 1 2 3 4)
9499 @result{} 4
9500@end group
9501@end smallexample
9502
9503@item save-restriction
9504Record whatever narrowing is in effect in the current buffer, if any,
9505and restore that narrowing after evaluating the arguments.
9506
9507@item search-forward
9508Search for a string, and if the string is found, move point. With a
9509regular expression, use the similar @code{re-search-forward}.
9510(@xref{Regexp Search, , Regular Expression Searches}, for an
9511explanation of regular expression patterns and searches.)
9512
9513@need 1250
9514@noindent
9515@code{search-forward} and @code{re-search-forward} take four
9516arguments:
9517
9518@enumerate
9519@item
9520The string or regular expression to search for.
9521
9522@item
9523Optionally, the limit of the search.
9524
9525@item
9526Optionally, what to do if the search fails, return @code{nil} or an
9527error message.
9528
9529@item
9530Optionally, how many times to repeat the search; if negative, the
9531search goes backwards.
9532@end enumerate
9533
9534@item kill-region
9535@itemx delete-and-extract-region
9536@itemx copy-region-as-kill
9537
9538@code{kill-region} cuts the text between point and mark from the
9539buffer and stores that text in the kill ring, so you can get it back
9540by yanking.
9541
9542@code{copy-region-as-kill} copies the text between point and mark into
9543the kill ring, from which you can get it by yanking. The function
9544does not cut or remove the text from the buffer.
9545@end table
9546
9547@code{delete-and-extract-region} removes the text between point and
9548mark from the buffer and throws it away. You cannot get it back.
9549(This is not an interactive command.)
9550
9551@need 1500
d6adf7e7 9552@node search Exercises
8cda6f8f
GM
9553@section Searching Exercises
9554
9555@itemize @bullet
9556@item
9557Write an interactive function that searches for a string. If the
9558search finds the string, leave point after it and display a message
9559that says ``Found!''. (Do not use @code{search-forward} for the name
9560of this function; if you do, you will overwrite the existing version of
9561@code{search-forward} that comes with Emacs. Use a name such as
9562@code{test-search} instead.)
9563
9564@item
9565Write a function that prints the third element of the kill ring in the
9566echo area, if any; if the kill ring does not contain a third element,
9567print an appropriate message.
9568@end itemize
9569
d6adf7e7 9570@node List Implementation
8cda6f8f
GM
9571@chapter How Lists are Implemented
9572@cindex Lists in a computer
9573
9574In Lisp, atoms are recorded in a straightforward fashion; if the
9575implementation is not straightforward in practice, it is, nonetheless,
9576straightforward in theory. The atom @samp{rose}, for example, is
9577recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
9578@samp{e}. A list, on the other hand, is kept differently. The mechanism
9579is equally simple, but it takes a moment to get used to the idea. A
9580list is kept using a series of pairs of pointers. In the series, the
9581first pointer in each pair points to an atom or to another list, and the
9582second pointer in each pair points to the next pair, or to the symbol
9583@code{nil}, which marks the end of the list.
9584
9585A pointer itself is quite simply the electronic address of what is
9586pointed to. Hence, a list is kept as a series of electronic addresses.
9587
9588@menu
9589* Lists diagrammed::
9590* Symbols as Chest:: Exploring a powerful metaphor.
9591* List Exercise::
9592@end menu
9593
8cda6f8f 9594@ifnottex
d6adf7e7 9595@node Lists diagrammed
8cda6f8f
GM
9596@unnumberedsec Lists diagrammed
9597@end ifnottex
9598
9599For example, the list @code{(rose violet buttercup)} has three elements,
9600@samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
9601electronic address of @samp{rose} is recorded in a segment of computer
9602memory along with the address that gives the electronic address of where
9603the atom @samp{violet} is located; and that address (the one that tells
9604where @samp{violet} is located) is kept along with an address that tells
9605where the address for the atom @samp{buttercup} is located.
9606
9607@need 1200
9608This sounds more complicated than it is and is easier seen in a diagram:
9609
9610@c clear print-postscript-figures
9611@c !!! cons-cell-diagram #1
9612@ifnottex
9613@smallexample
9614@group
9615 ___ ___ ___ ___ ___ ___
9616 |___|___|--> |___|___|--> |___|___|--> nil
9617 | | |
9618 | | |
9619 --> rose --> violet --> buttercup
9620@end group
9621@end smallexample
9622@end ifnottex
9623@ifset print-postscript-figures
9624@sp 1
9625@tex
9626@center @image{cons-1}
9627%%%% old method of including an image
9628% \input /usr/local/lib/tex/inputs/psfig.tex
9629% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
9630% \catcode`\@=0 %
9631@end tex
9632@sp 1
9633@end ifset
9634@ifclear print-postscript-figures
9635@iftex
9636@smallexample
9637@group
9638 ___ ___ ___ ___ ___ ___
9639 |___|___|--> |___|___|--> |___|___|--> nil
9640 | | |
9641 | | |
9642 --> rose --> violet --> buttercup
9643@end group
9644@end smallexample
9645@end iftex
9646@end ifclear
9647
9648@noindent
9649In the diagram, each box represents a word of computer memory that
9650holds a Lisp object, usually in the form of a memory address. The boxes,
1df7defd 9651i.e., the addresses, are in pairs. Each arrow points to what the address
8cda6f8f
GM
9652is the address of, either an atom or another pair of addresses. The
9653first box is the electronic address of @samp{rose} and the arrow points
9654to @samp{rose}; the second box is the address of the next pair of boxes,
9655the first part of which is the address of @samp{violet} and the second
9656part of which is the address of the next pair. The very last box
9657points to the symbol @code{nil}, which marks the end of the list.
9658
9659@need 1200
9660When a variable is set to a list with a function such as @code{setq},
9661it stores the address of the first box in the variable. Thus,
9662evaluation of the expression
9663
9664@smallexample
9665(setq bouquet '(rose violet buttercup))
9666@end smallexample
9667
9668@need 1250
9669@noindent
9670creates a situation like this:
9671
9672@c cons-cell-diagram #2
9673@ifnottex
9674@smallexample
9675@group
9676bouquet
9677 |
9678 | ___ ___ ___ ___ ___ ___
9679 --> |___|___|--> |___|___|--> |___|___|--> nil
9680 | | |
9681 | | |
9682 --> rose --> violet --> buttercup
9683@end group
9684@end smallexample
9685@end ifnottex
9686@ifset print-postscript-figures
9687@sp 1
9688@tex
9689@center @image{cons-2}
9690%%%% old method of including an image
9691% \input /usr/local/lib/tex/inputs/psfig.tex
9692% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9693% \catcode`\@=0 %
9694@end tex
9695@sp 1
9696@end ifset
9697@ifclear print-postscript-figures
9698@iftex
9699@smallexample
9700@group
9701bouquet
9702 |
9703 | ___ ___ ___ ___ ___ ___
9704 --> |___|___|--> |___|___|--> |___|___|--> nil
9705 | | |
9706 | | |
9707 --> rose --> violet --> buttercup
9708@end group
9709@end smallexample
9710@end iftex
9711@end ifclear
9712
9713@noindent
9714In this example, the symbol @code{bouquet} holds the address of the first
9715pair of boxes.
9716
9717@need 1200
9718This same list can be illustrated in a different sort of box notation
9719like this:
9720
9721@c cons-cell-diagram #2a
9722@ifnottex
9723@smallexample
9724@group
9725bouquet
9726 |
9727 | -------------- --------------- ----------------
9728 | | car | cdr | | car | cdr | | car | cdr |
9729 -->| rose | o------->| violet | o------->| butter- | nil |
9730 | | | | | | | cup | |
9731 -------------- --------------- ----------------
9732@end group
9733@end smallexample
9734@end ifnottex
9735@ifset print-postscript-figures
9736@sp 1
9737@tex
9738@center @image{cons-2a}
9739%%%% old method of including an image
9740% \input /usr/local/lib/tex/inputs/psfig.tex
9741% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9742% \catcode`\@=0 %
9743@end tex
9744@sp 1
9745@end ifset
9746@ifclear print-postscript-figures
9747@iftex
9748@smallexample
9749@group
9750bouquet
9751 |
9752 | -------------- --------------- ----------------
9753 | | car | cdr | | car | cdr | | car | cdr |
9754 -->| rose | o------->| violet | o------->| butter- | nil |
9755 | | | | | | | cup | |
9756 -------------- --------------- ----------------
9757@end group
9758@end smallexample
9759@end iftex
9760@end ifclear
9761
9762(Symbols consist of more than pairs of addresses, but the structure of
9763a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9764consists of a group of address-boxes, one of which is the address of
9765the printed word @samp{bouquet}, a second of which is the address of a
9766function definition attached to the symbol, if any, a third of which
9767is the address of the first pair of address-boxes for the list
9768@code{(rose violet buttercup)}, and so on. Here we are showing that
9769the symbol's third address-box points to the first pair of
9770address-boxes for the list.)
9771
9772If a symbol is set to the @sc{cdr} of a list, the list itself is not
9773changed; the symbol simply has an address further down the list. (In
9774the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9775evaluation of the following expression
9776
9777@smallexample
9778(setq flowers (cdr bouquet))
9779@end smallexample
9780
9781@need 800
9782@noindent
9783produces this:
9784
9785@c cons-cell-diagram #3
9786@ifnottex
9787@sp 1
9788@smallexample
9789@group
9790bouquet flowers
9791 | |
9792 | ___ ___ | ___ ___ ___ ___
9793 --> | | | --> | | | | | |
9794 |___|___|----> |___|___|--> |___|___|--> nil
9795 | | |
9796 | | |
9797 --> rose --> violet --> buttercup
9798@end group
9799@end smallexample
9800@sp 1
9801@end ifnottex
9802@ifset print-postscript-figures
9803@sp 1
9804@tex
9805@center @image{cons-3}
9806%%%% old method of including an image
9807% \input /usr/local/lib/tex/inputs/psfig.tex
9808% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9809% \catcode`\@=0 %
9810@end tex
9811@sp 1
9812@end ifset
9813@ifclear print-postscript-figures
9814@iftex
9815@sp 1
9816@smallexample
9817@group
9818bouquet flowers
9819 | |
9820 | ___ ___ | ___ ___ ___ ___
9821 --> | | | --> | | | | | |
9822 |___|___|----> |___|___|--> |___|___|--> nil
9823 | | |
9824 | | |
9825 --> rose --> violet --> buttercup
9826@end group
9827@end smallexample
9828@sp 1
9829@end iftex
9830@end ifclear
9831
9832@noindent
9833The value of @code{flowers} is @code{(violet buttercup)}, which is
9834to say, the symbol @code{flowers} holds the address of the pair of
9835address-boxes, the first of which holds the address of @code{violet},
9836and the second of which holds the address of @code{buttercup}.
9837
9838A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9839pair}. @xref{Cons Cell Type, , Cons Cell and List Types, elisp, The GNU Emacs Lisp
9840Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9841Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9842information about cons cells and dotted pairs.
9843
9844@need 1200
9845The function @code{cons} adds a new pair of addresses to the front of
9846a series of addresses like that shown above. For example, evaluating
9847the expression
9848
9849@smallexample
9850(setq bouquet (cons 'lily bouquet))
9851@end smallexample
9852
9853@need 1500
9854@noindent
9855produces:
9856
9857@c cons-cell-diagram #4
9858@ifnottex
9859@sp 1
9860@smallexample
9861@group
9862bouquet flowers
9863 | |
9864 | ___ ___ ___ ___ | ___ ___ ___ ___
9865 --> | | | | | | --> | | | | | |
9866 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9867 | | | |
9868 | | | |
9869 --> lily --> rose --> violet --> buttercup
9870@end group
9871@end smallexample
9872@sp 1
9873@end ifnottex
9874@ifset print-postscript-figures
9875@sp 1
9876@tex
9877@center @image{cons-4}
9878%%%% old method of including an image
9879% \input /usr/local/lib/tex/inputs/psfig.tex
9880% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9881% \catcode`\@=0 %
9882@end tex
9883@sp 1
9884@end ifset
9885@ifclear print-postscript-figures
9886@iftex
9887@sp 1
9888@smallexample
9889@group
9890bouquet flowers
9891 | |
9892 | ___ ___ ___ ___ | ___ ___ ___ ___
9893 --> | | | | | | --> | | | | | |
9894 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9895 | | | |
9896 | | | |
9897 --> lily --> rose --> violet --> buttercup
9898@end group
9899@end smallexample
9900@sp 1
9901@end iftex
9902@end ifclear
9903
9904@need 1200
9905@noindent
9906However, this does not change the value of the symbol
9907@code{flowers}, as you can see by evaluating the following,
9908
9909@smallexample
9910(eq (cdr (cdr bouquet)) flowers)
9911@end smallexample
9912
9913@noindent
9914which returns @code{t} for true.
9915
9916Until it is reset, @code{flowers} still has the value
9917@code{(violet buttercup)}; that is, it has the address of the cons
9918cell whose first address is of @code{violet}. Also, this does not
9919alter any of the pre-existing cons cells; they are all still there.
9920
9921Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9922of the next cons cell in the series; to get the @sc{car} of a list,
9923you get the address of the first element of the list; to @code{cons} a
9924new element on a list, you add a new cons cell to the front of the list.
9925That is all there is to it! The underlying structure of Lisp is
9926brilliantly simple!
9927
9928And what does the last address in a series of cons cells refer to? It
9929is the address of the empty list, of @code{nil}.
9930
9931In summary, when a Lisp variable is set to a value, it is provided with
9932the address of the list to which the variable refers.
9933
d6adf7e7 9934@node Symbols as Chest
8cda6f8f
GM
9935@section Symbols as a Chest of Drawers
9936@cindex Symbols as a Chest of Drawers
9937@cindex Chest of Drawers, metaphor for a symbol
9938@cindex Drawers, Chest of, metaphor for a symbol
9939
9940In an earlier section, I suggested that you might imagine a symbol as
9941being a chest of drawers. The function definition is put in one
9942drawer, the value in another, and so on. What is put in the drawer
9943holding the value can be changed without affecting the contents of the
9944drawer holding the function definition, and vice-verse.
9945
9946Actually, what is put in each drawer is the address of the value or
9947function definition. It is as if you found an old chest in the attic,
9948and in one of its drawers you found a map giving you directions to
9949where the buried treasure lies.
9950
9951(In addition to its name, symbol definition, and variable value, a
9952symbol has a `drawer' for a @dfn{property list} which can be used to
9953record other information. Property lists are not discussed here; see
9954@ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9955Reference Manual}.)
9956
9957@need 1500
9958Here is a fanciful representation:
9959
9960@c chest-of-drawers diagram
9961@ifnottex
9962@sp 1
9963@smallexample
9964@group
9965 Chest of Drawers Contents of Drawers
9966
9967 __ o0O0o __
9968 / \
9969 ---------------------
9970 | directions to | [map to]
9971 | symbol name | bouquet
9972 | |
9973 +---------------------+
9974 | directions to |
9975 | symbol definition | [none]
9976 | |
9977 +---------------------+
9978 | directions to | [map to]
9979 | variable value | (rose violet buttercup)
9980 | |
9981 +---------------------+
9982 | directions to |
9983 | property list | [not described here]
9984 | |
9985 +---------------------+
9986 |/ \|
9987@end group
9988@end smallexample
9989@sp 1
9990@end ifnottex
9991@ifset print-postscript-figures
9992@sp 1
9993@tex
9994@center @image{drawers}
9995%%%% old method of including an image
9996% \input /usr/local/lib/tex/inputs/psfig.tex
9997% \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9998% \catcode`\@=0 %
9999@end tex
10000@sp 1
10001@end ifset
10002@ifclear print-postscript-figures
10003@iftex
10004@sp 1
10005@smallexample
10006@group
10007 Chest of Drawers Contents of Drawers
10008
10009 __ o0O0o __
10010 / \
10011 ---------------------
10012 | directions to | [map to]
10013 | symbol name | bouquet
10014 | |
10015 +---------------------+
10016 | directions to |
10017 | symbol definition | [none]
10018 | |
10019 +---------------------+
10020 | directions to | [map to]
10021 | variable value | (rose violet buttercup)
10022 | |
10023 +---------------------+
10024 | directions to |
10025 | property list | [not described here]
10026 | |
10027 +---------------------+
10028 |/ \|
10029@end group
10030@end smallexample
10031@sp 1
10032@end iftex
10033@end ifclear
10034
d6adf7e7 10035@node List Exercise
8cda6f8f
GM
10036@section Exercise
10037
10038Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
10039more flowers on to this list and set this new list to
10040@code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
10041What does the @code{more-flowers} list now contain?
10042
d6adf7e7 10043@node Yanking
8cda6f8f
GM
10044@chapter Yanking Text Back
10045@findex yank
10046@cindex Text retrieval
10047@cindex Retrieving text
10048@cindex Pasting text
10049
10050Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
10051you can bring it back with a `yank' command. The text that is cut out of
10052the buffer is put in the kill ring and the yank commands insert the
10053appropriate contents of the kill ring back into a buffer (not necessarily
10054the original buffer).
10055
10056A simple @kbd{C-y} (@code{yank}) command inserts the first item from
10057the kill ring into the current buffer. If the @kbd{C-y} command is
10058followed immediately by @kbd{M-y}, the first element is replaced by
10059the second element. Successive @kbd{M-y} commands replace the second
10060element with the third, fourth, or fifth element, and so on. When the
10061last element in the kill ring is reached, it is replaced by the first
10062element and the cycle is repeated. (Thus the kill ring is called a
10063`ring' rather than just a `list'. However, the actual data structure
10064that holds the text is a list.
10065@xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
10066list is handled as a ring.)
10067
10068@menu
10069* Kill Ring Overview::
10070* kill-ring-yank-pointer:: The kill ring is a list.
10071* yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
10072@end menu
10073
d6adf7e7 10074@node Kill Ring Overview
8cda6f8f
GM
10075@section Kill Ring Overview
10076@cindex Kill ring overview
10077
10078The kill ring is a list of textual strings. This is what it looks like:
10079
10080@smallexample
10081("some text" "a different piece of text" "yet more text")
10082@end smallexample
10083
10084If this were the contents of my kill ring and I pressed @kbd{C-y}, the
10085string of characters saying @samp{some text} would be inserted in this
10086buffer where my cursor is located.
10087
10088The @code{yank} command is also used for duplicating text by copying it.
10089The copied text is not cut from the buffer, but a copy of it is put on the
10090kill ring and is inserted by yanking it back.
10091
10092Three functions are used for bringing text back from the kill ring:
10093@code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
10094which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
10095which is used by the two other functions.
10096
10097These functions refer to the kill ring through a variable called the
10098@code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
10099@code{yank} and @code{yank-pop} functions is:
10100
10101@smallexample
10102(insert (car kill-ring-yank-pointer))
10103@end smallexample
10104
10105@noindent
10106(Well, no more. In GNU Emacs 22, the function has been replaced by
10107@code{insert-for-yank} which calls @code{insert-for-yank-1}
10108repetitively for each @code{yank-handler} segment. In turn,
10109@code{insert-for-yank-1} strips text properties from the inserted text
10110according to @code{yank-excluded-properties}. Otherwise, it is just
10111like @code{insert}. We will stick with plain @code{insert} since it
10112is easier to understand.)
10113
10114To begin to understand how @code{yank} and @code{yank-pop} work, it is
10115first necessary to look at the @code{kill-ring-yank-pointer} variable.
10116
d6adf7e7 10117@node kill-ring-yank-pointer
8cda6f8f
GM
10118@section The @code{kill-ring-yank-pointer} Variable
10119
10120@code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
10121a variable. It points to something by being bound to the value of what
10122it points to, like any other Lisp variable.
10123
10124@need 1000
10125Thus, if the value of the kill ring is:
10126
10127@smallexample
10128("some text" "a different piece of text" "yet more text")
10129@end smallexample
10130
10131@need 1250
10132@noindent
10133and the @code{kill-ring-yank-pointer} points to the second clause, the
10134value of @code{kill-ring-yank-pointer} is:
10135
10136@smallexample
10137("a different piece of text" "yet more text")
10138@end smallexample
10139
10140As explained in the previous chapter (@pxref{List Implementation}), the
10141computer does not keep two different copies of the text being pointed to
10142by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
10143words ``a different piece of text'' and ``yet more text'' are not
10144duplicated. Instead, the two Lisp variables point to the same pieces of
10145text. Here is a diagram:
10146
10147@c cons-cell-diagram #5
10148@ifnottex
10149@smallexample
10150@group
10151kill-ring kill-ring-yank-pointer
10152 | |
10153 | ___ ___ | ___ ___ ___ ___
10154 ---> | | | --> | | | | | |
10155 |___|___|----> |___|___|--> |___|___|--> nil
10156 | | |
10157 | | |
10158 | | --> "yet more text"
10159 | |
10160 | --> "a different piece of text"
10161 |
10162 --> "some text"
10163@end group
10164@end smallexample
10165@sp 1
10166@end ifnottex
10167@ifset print-postscript-figures
10168@sp 1
10169@tex
10170@center @image{cons-5}
10171%%%% old method of including an image
10172% \input /usr/local/lib/tex/inputs/psfig.tex
10173% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
10174% \catcode`\@=0 %
10175@end tex
10176@sp 1
10177@end ifset
10178@ifclear print-postscript-figures
10179@iftex
10180@smallexample
10181@group
10182kill-ring kill-ring-yank-pointer
10183 | |
10184 | ___ ___ | ___ ___ ___ ___
10185 ---> | | | --> | | | | | |
10186 |___|___|----> |___|___|--> |___|___|--> nil
10187 | | |
10188 | | |
10189 | | --> "yet more text"
10190 | |
10191 | --> "a different piece of text
10192 |
10193 --> "some text"
10194@end group
10195@end smallexample
10196@sp 1
10197@end iftex
10198@end ifclear
10199
10200Both the variable @code{kill-ring} and the variable
10201@code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
10202usually described as if it were actually what it is composed of. The
10203@code{kill-ring} is spoken of as if it were the list rather than that it
10204points to the list. Conversely, the @code{kill-ring-yank-pointer} is
10205spoken of as pointing to a list.
10206
10207These two ways of talking about the same thing sound confusing at first but
10208make sense on reflection. The kill ring is generally thought of as the
10209complete structure of data that holds the information of what has recently
10210been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
10211on the other hand, serves to indicate---that is, to `point to'---that part
10212of the kill ring of which the first element (the @sc{car}) will be
10213inserted.
10214
10215@ignore
10216In GNU Emacs 22, the @code{kill-new} function calls
10217
10218@code{(setq kill-ring-yank-pointer kill-ring)}
10219
10220(defun rotate-yank-pointer (arg)
10221 "Rotate the yanking point in the kill ring.
10222With argument, rotate that many kills forward (or backward, if negative)."
10223 (interactive "p")
10224 (current-kill arg))
10225
10226(defun current-kill (n &optional do-not-move)
10227 "Rotate the yanking point by N places, and then return that kill.
10228If N is zero, `interprogram-paste-function' is set, and calling it
10229returns a string, then that string is added to the front of the
10230kill ring and returned as the latest kill.
10231If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
10232yanking point; just return the Nth kill forward."
10233 (let ((interprogram-paste (and (= n 0)
10234 interprogram-paste-function
10235 (funcall interprogram-paste-function))))
10236 (if interprogram-paste
10237 (progn
10238 ;; Disable the interprogram cut function when we add the new
10239 ;; text to the kill ring, so Emacs doesn't try to own the
10240 ;; selection, with identical text.
10241 (let ((interprogram-cut-function nil))
10242 (kill-new interprogram-paste))
10243 interprogram-paste)
10244 (or kill-ring (error "Kill ring is empty"))
10245 (let ((ARGth-kill-element
10246 (nthcdr (mod (- n (length kill-ring-yank-pointer))
10247 (length kill-ring))
10248 kill-ring)))
10249 (or do-not-move
10250 (setq kill-ring-yank-pointer ARGth-kill-element))
10251 (car ARGth-kill-element)))))
10252
10253@end ignore
10254
10255@need 1500
d6adf7e7 10256@node yank nthcdr Exercises
8cda6f8f
GM
10257@section Exercises with @code{yank} and @code{nthcdr}
10258
10259@itemize @bullet
10260@item
10261Using @kbd{C-h v} (@code{describe-variable}), look at the value of
10262your kill ring. Add several items to your kill ring; look at its
10263value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
10264around the kill ring. How many items were in your kill ring? Find
10265the value of @code{kill-ring-max}. Was your kill ring full, or could
10266you have kept more blocks of text within it?
10267
10268@item
10269Using @code{nthcdr} and @code{car}, construct a series of expressions
10270to return the first, second, third, and fourth elements of a list.
10271@end itemize
10272
d6adf7e7 10273@node Loops & Recursion
8cda6f8f
GM
10274@chapter Loops and Recursion
10275@cindex Loops and recursion
10276@cindex Recursion and loops
10277@cindex Repetition (loops)
10278
10279Emacs Lisp has two primary ways to cause an expression, or a series of
10280expressions, to be evaluated repeatedly: one uses a @code{while}
10281loop, and the other uses @dfn{recursion}.
10282
10283Repetition can be very valuable. For example, to move forward four
10284sentences, you need only write a program that will move forward one
10285sentence and then repeat the process four times. Since a computer does
10286not get bored or tired, such repetitive action does not have the
10287deleterious effects that excessive or the wrong kinds of repetition can
10288have on humans.
10289
10290People mostly write Emacs Lisp functions using @code{while} loops and
10291their kin; but you can use recursion, which provides a very powerful
10292way to think about and then to solve problems@footnote{You can write
10293recursive functions to be frugal or wasteful of mental or computer
10294resources; as it happens, methods that people find easy---that are
10295frugal of `mental resources'---sometimes use considerable computer
10296resources. Emacs was designed to run on machines that we now consider
10297limited and its default settings are conservative. You may want to
10298increase the values of @code{max-specpdl-size} and
10299@code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
1030015 and 30 times their default value.}.
10301
10302@menu
10303* while:: Causing a stretch of code to repeat.
10304* dolist dotimes::
10305* Recursion:: Causing a function to call itself.
10306* Looping exercise::
10307@end menu
10308
d6adf7e7 10309@node while
8cda6f8f
GM
10310@section @code{while}
10311@cindex Loops
10312@findex while
10313
10314The @code{while} special form tests whether the value returned by
10315evaluating its first argument is true or false. This is similar to what
10316the Lisp interpreter does with an @code{if}; what the interpreter does
10317next, however, is different.
10318
10319In a @code{while} expression, if the value returned by evaluating the
10320first argument is false, the Lisp interpreter skips the rest of the
10321expression (the @dfn{body} of the expression) and does not evaluate it.
10322However, if the value is true, the Lisp interpreter evaluates the body
10323of the expression and then again tests whether the first argument to
10324@code{while} is true or false. If the value returned by evaluating the
10325first argument is again true, the Lisp interpreter again evaluates the
10326body of the expression.
10327
10328@need 1200
10329The template for a @code{while} expression looks like this:
10330
10331@smallexample
10332@group
10333(while @var{true-or-false-test}
10334 @var{body}@dots{})
10335@end group
10336@end smallexample
10337
10338@menu
10339* Looping with while:: Repeat so long as test returns true.
10340* Loop Example:: A @code{while} loop that uses a list.
10341* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
10342* Incrementing Loop:: A loop with an incrementing counter.
10343* Incrementing Loop Details::
10344* Decrementing Loop:: A loop with a decrementing counter.
10345@end menu
10346
8cda6f8f 10347@ifnottex
d6adf7e7 10348@node Looping with while
8cda6f8f
GM
10349@unnumberedsubsec Looping with @code{while}
10350@end ifnottex
10351
10352So long as the true-or-false-test of the @code{while} expression
10353returns a true value when it is evaluated, the body is repeatedly
10354evaluated. This process is called a loop since the Lisp interpreter
10355repeats the same thing again and again, like an airplane doing a loop.
10356When the result of evaluating the true-or-false-test is false, the
10357Lisp interpreter does not evaluate the rest of the @code{while}
10358expression and `exits the loop'.
10359
10360Clearly, if the value returned by evaluating the first argument to
10361@code{while} is always true, the body following will be evaluated
10362again and again @dots{} and again @dots{} forever. Conversely, if the
10363value returned is never true, the expressions in the body will never
10364be evaluated. The craft of writing a @code{while} loop consists of
10365choosing a mechanism such that the true-or-false-test returns true
10366just the number of times that you want the subsequent expressions to
10367be evaluated, and then have the test return false.
10368
10369The value returned by evaluating a @code{while} is the value of the
10370true-or-false-test. An interesting consequence of this is that a
10371@code{while} loop that evaluates without error will return @code{nil}
10372or false regardless of whether it has looped 1 or 100 times or none at
10373all. A @code{while} expression that evaluates successfully never
10374returns a true value! What this means is that @code{while} is always
10375evaluated for its side effects, which is to say, the consequences of
10376evaluating the expressions within the body of the @code{while} loop.
10377This makes sense. It is not the mere act of looping that is desired,
10378but the consequences of what happens when the expressions in the loop
10379are repeatedly evaluated.
10380
d6adf7e7 10381@node Loop Example
8cda6f8f
GM
10382@subsection A @code{while} Loop and a List
10383
10384A common way to control a @code{while} loop is to test whether a list
10385has any elements. If it does, the loop is repeated; but if it does not,
10386the repetition is ended. Since this is an important technique, we will
10387create a short example to illustrate it.
10388
10389A simple way to test whether a list has elements is to evaluate the
10390list: if it has no elements, it is an empty list and will return the
10391empty list, @code{()}, which is a synonym for @code{nil} or false. On
10392the other hand, a list with elements will return those elements when it
10393is evaluated. Since Emacs Lisp considers as true any value that is not
10394@code{nil}, a list that returns elements will test true in a
10395@code{while} loop.
10396
10397@need 1200
10398For example, you can set the variable @code{empty-list} to @code{nil} by
10399evaluating the following @code{setq} expression:
10400
10401@smallexample
10402(setq empty-list ())
10403@end smallexample
10404
10405@noindent
10406After evaluating the @code{setq} expression, you can evaluate the
10407variable @code{empty-list} in the usual way, by placing the cursor after
10408the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
10409echo area:
10410
10411@smallexample
10412empty-list
10413@end smallexample
10414
10415On the other hand, if you set a variable to be a list with elements, the
10416list will appear when you evaluate the variable, as you can see by
10417evaluating the following two expressions:
10418
10419@smallexample
10420@group
10421(setq animals '(gazelle giraffe lion tiger))
10422
10423animals
10424@end group
10425@end smallexample
10426
10427Thus, to create a @code{while} loop that tests whether there are any
10428items in the list @code{animals}, the first part of the loop will be
10429written like this:
10430
10431@smallexample
10432@group
10433(while animals
10434 @dots{}
10435@end group
10436@end smallexample
10437
10438@noindent
10439When the @code{while} tests its first argument, the variable
10440@code{animals} is evaluated. It returns a list. So long as the list
10441has elements, the @code{while} considers the results of the test to be
10442true; but when the list is empty, it considers the results of the test
10443to be false.
10444
10445To prevent the @code{while} loop from running forever, some mechanism
10446needs to be provided to empty the list eventually. An oft-used
10447technique is to have one of the subsequent forms in the @code{while}
10448expression set the value of the list to be the @sc{cdr} of the list.
10449Each time the @code{cdr} function is evaluated, the list will be made
10450shorter, until eventually only the empty list will be left. At this
10451point, the test of the @code{while} loop will return false, and the
10452arguments to the @code{while} will no longer be evaluated.
10453
10454For example, the list of animals bound to the variable @code{animals}
10455can be set to be the @sc{cdr} of the original list with the
10456following expression:
10457
10458@smallexample
10459(setq animals (cdr animals))
10460@end smallexample
10461
10462@noindent
10463If you have evaluated the previous expressions and then evaluate this
10464expression, you will see @code{(giraffe lion tiger)} appear in the echo
10465area. If you evaluate the expression again, @code{(lion tiger)} will
10466appear in the echo area. If you evaluate it again and yet again,
10467@code{(tiger)} appears and then the empty list, shown by @code{nil}.
10468
10469A template for a @code{while} loop that uses the @code{cdr} function
10470repeatedly to cause the true-or-false-test eventually to test false
10471looks like this:
10472
10473@smallexample
10474@group
10475(while @var{test-whether-list-is-empty}
10476 @var{body}@dots{}
10477 @var{set-list-to-cdr-of-list})
10478@end group
10479@end smallexample
10480
10481This test and use of @code{cdr} can be put together in a function that
10482goes through a list and prints each element of the list on a line of its
10483own.
10484
d6adf7e7 10485@node print-elements-of-list
8cda6f8f
GM
10486@subsection An Example: @code{print-elements-of-list}
10487@findex print-elements-of-list
10488
10489The @code{print-elements-of-list} function illustrates a @code{while}
10490loop with a list.
10491
10492@cindex @file{*scratch*} buffer
10493The function requires several lines for its output. If you are
10494reading this in a recent instance of GNU Emacs,
10495@c GNU Emacs 21, GNU Emacs 22, or a later version,
10496you can evaluate the following expression inside of Info, as usual.
10497
10498If you are using an earlier version of Emacs, you need to copy the
10499necessary expressions to your @file{*scratch*} buffer and evaluate
10500them there. This is because the echo area had only one line in the
10501earlier versions.
10502
10503You can copy the expressions by marking the beginning of the region
10504with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
10505the end of the region and then copying the region using @kbd{M-w}
10506(@code{kill-ring-save}, which calls @code{copy-region-as-kill} and
10507then provides visual feedback). In the @file{*scratch*}
10508buffer, you can yank the expressions back by typing @kbd{C-y}
10509(@code{yank}).
10510
10511After you have copied the expressions to the @file{*scratch*} buffer,
10512evaluate each expression in turn. Be sure to evaluate the last
10513expression, @code{(print-elements-of-list animals)}, by typing
10514@kbd{C-u C-x C-e}, that is, by giving an argument to
10515@code{eval-last-sexp}. This will cause the result of the evaluation
10516to be printed in the @file{*scratch*} buffer instead of being printed
10517in the echo area. (Otherwise you will see something like this in your
10518echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
10519each @samp{^J} stands for a `newline'.)
10520
10521@need 1500
10522In a recent instance of GNU Emacs, you can evaluate these expressions
10523directly in the Info buffer, and the echo area will grow to show the
10524results.
10525
10526@smallexample
10527@group
10528(setq animals '(gazelle giraffe lion tiger))
10529
10530(defun print-elements-of-list (list)
10531 "Print each element of LIST on a line of its own."
10532 (while list
10533 (print (car list))
10534 (setq list (cdr list))))
10535
10536(print-elements-of-list animals)
10537@end group
10538@end smallexample
10539
10540@need 1200
10541@noindent
10542When you evaluate the three expressions in sequence, you will see
10543this:
10544
10545@smallexample
10546@group
10547gazelle
10548
10549giraffe
10550
10551lion
10552
10553tiger
10554nil
10555@end group
10556@end smallexample
10557
10558Each element of the list is printed on a line of its own (that is what
10559the function @code{print} does) and then the value returned by the
10560function is printed. Since the last expression in the function is the
10561@code{while} loop, and since @code{while} loops always return
10562@code{nil}, a @code{nil} is printed after the last element of the list.
10563
d6adf7e7 10564@node Incrementing Loop
8cda6f8f
GM
10565@subsection A Loop with an Incrementing Counter
10566
10567A loop is not useful unless it stops when it ought. Besides
10568controlling a loop with a list, a common way of stopping a loop is to
10569write the first argument as a test that returns false when the correct
10570number of repetitions are complete. This means that the loop must
10571have a counter---an expression that counts how many times the loop
10572repeats itself.
10573
8cda6f8f 10574@ifnottex
d6adf7e7 10575@node Incrementing Loop Details
8cda6f8f
GM
10576@unnumberedsubsec Details of an Incrementing Loop
10577@end ifnottex
10578
10579The test for a loop with an incrementing counter can be an expression
10580such as @code{(< count desired-number)} which returns @code{t} for
10581true if the value of @code{count} is less than the
10582@code{desired-number} of repetitions and @code{nil} for false if the
10583value of @code{count} is equal to or is greater than the
10584@code{desired-number}. The expression that increments the count can
10585be a simple @code{setq} such as @code{(setq count (1+ count))}, where
10586@code{1+} is a built-in function in Emacs Lisp that adds 1 to its
10587argument. (The expression @w{@code{(1+ count)}} has the same result
10588as @w{@code{(+ count 1)}}, but is easier for a human to read.)
10589
10590@need 1250
10591The template for a @code{while} loop controlled by an incrementing
10592counter looks like this:
10593
10594@smallexample
10595@group
10596@var{set-count-to-initial-value}
10597(while (< count desired-number) ; @r{true-or-false-test}
10598 @var{body}@dots{}
10599 (setq count (1+ count))) ; @r{incrementer}
10600@end group
10601@end smallexample
10602
10603@noindent
10604Note that you need to set the initial value of @code{count}; usually it
10605is set to 1.
10606
10607@menu
10608* Incrementing Example:: Counting pebbles in a triangle.
10609* Inc Example parts:: The parts of the function definition.
10610* Inc Example altogether:: Putting the function definition together.
10611@end menu
10612
d6adf7e7 10613@node Incrementing Example
8cda6f8f
GM
10614@unnumberedsubsubsec Example with incrementing counter
10615
10616Suppose you are playing on the beach and decide to make a triangle of
10617pebbles, putting one pebble in the first row, two in the second row,
10618three in the third row and so on, like this:
10619
10620@sp 1
10621@c pebble diagram
10622@ifnottex
10623@smallexample
10624@group
10625 *
10626 * *
10627 * * *
10628 * * * *
10629@end group
10630@end smallexample
10631@end ifnottex
10632@iftex
10633@smallexample
10634@group
10635 @bullet{}
10636 @bullet{} @bullet{}
10637 @bullet{} @bullet{} @bullet{}
10638 @bullet{} @bullet{} @bullet{} @bullet{}
10639@end group
10640@end smallexample
10641@end iftex
10642@sp 1
10643
10644@noindent
10645(About 2500 years ago, Pythagoras and others developed the beginnings of
10646number theory by considering questions such as this.)
10647
10648Suppose you want to know how many pebbles you will need to make a
10649triangle with 7 rows?
10650
10651Clearly, what you need to do is add up the numbers from 1 to 7. There
10652are two ways to do this; start with the smallest number, one, and add up
10653the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
10654number and add the list going down: 7, 6, 5, 4 and so on. Because both
10655mechanisms illustrate common ways of writing @code{while} loops, we will
10656create two examples, one counting up and the other counting down. In
10657this first example, we will start with 1 and add 2, 3, 4 and so on.
10658
10659If you are just adding up a short list of numbers, the easiest way to do
10660it is to add up all the numbers at once. However, if you do not know
10661ahead of time how many numbers your list will have, or if you want to be
10662prepared for a very long list, then you need to design your addition so
10663that what you do is repeat a simple process many times instead of doing
10664a more complex process once.
10665
10666For example, instead of adding up all the pebbles all at once, what you
10667can do is add the number of pebbles in the first row, 1, to the number
10668in the second row, 2, and then add the total of those two rows to the
10669third row, 3. Then you can add the number in the fourth row, 4, to the
10670total of the first three rows; and so on.
10671
10672The critical characteristic of the process is that each repetitive
10673action is simple. In this case, at each step we add only two numbers,
10674the number of pebbles in the row and the total already found. This
10675process of adding two numbers is repeated again and again until the last
10676row has been added to the total of all the preceding rows. In a more
10677complex loop the repetitive action might not be so simple, but it will
10678be simpler than doing everything all at once.
10679
d6adf7e7 10680@node Inc Example parts
8cda6f8f
GM
10681@unnumberedsubsubsec The parts of the function definition
10682
10683The preceding analysis gives us the bones of our function definition:
10684first, we will need a variable that we can call @code{total} that will
10685be the total number of pebbles. This will be the value returned by
10686the function.
10687
10688Second, we know that the function will require an argument: this
10689argument will be the total number of rows in the triangle. It can be
10690called @code{number-of-rows}.
10691
10692Finally, we need a variable to use as a counter. We could call this
10693variable @code{counter}, but a better name is @code{row-number}. That
10694is because what the counter does in this function is count rows, and a
10695program should be written to be as understandable as possible.
10696
10697When the Lisp interpreter first starts evaluating the expressions in the
10698function, the value of @code{total} should be set to zero, since we have
10699not added anything to it. Then the function should add the number of
10700pebbles in the first row to the total, and then add the number of
10701pebbles in the second to the total, and then add the number of
10702pebbles in the third row to the total, and so on, until there are no
10703more rows left to add.
10704
10705Both @code{total} and @code{row-number} are used only inside the
10706function, so they can be declared as local variables with @code{let}
10707and given initial values. Clearly, the initial value for @code{total}
10708should be 0. The initial value of @code{row-number} should be 1,
10709since we start with the first row. This means that the @code{let}
10710statement will look like this:
10711
10712@smallexample
10713@group
10714 (let ((total 0)
10715 (row-number 1))
10716 @var{body}@dots{})
10717@end group
10718@end smallexample
10719
10720After the internal variables are declared and bound to their initial
10721values, we can begin the @code{while} loop. The expression that serves
10722as the test should return a value of @code{t} for true so long as the
10723@code{row-number} is less than or equal to the @code{number-of-rows}.
10724(If the expression tests true only so long as the row number is less
10725than the number of rows in the triangle, the last row will never be
10726added to the total; hence the row number has to be either less than or
10727equal to the number of rows.)
10728
10729@need 1500
10730@findex <= @r{(less than or equal)}
10731Lisp provides the @code{<=} function that returns true if the value of
10732its first argument is less than or equal to the value of its second
10733argument and false otherwise. So the expression that the @code{while}
10734will evaluate as its test should look like this:
10735
10736@smallexample
10737(<= row-number number-of-rows)
10738@end smallexample
10739
10740The total number of pebbles can be found by repeatedly adding the number
10741of pebbles in a row to the total already found. Since the number of
10742pebbles in the row is equal to the row number, the total can be found by
10743adding the row number to the total. (Clearly, in a more complex
10744situation, the number of pebbles in the row might be related to the row
10745number in a more complicated way; if this were the case, the row number
10746would be replaced by the appropriate expression.)
10747
10748@smallexample
10749(setq total (+ total row-number))
10750@end smallexample
10751
10752@noindent
10753What this does is set the new value of @code{total} to be equal to the
10754sum of adding the number of pebbles in the row to the previous total.
10755
10756After setting the value of @code{total}, the conditions need to be
10757established for the next repetition of the loop, if there is one. This
10758is done by incrementing the value of the @code{row-number} variable,
10759which serves as a counter. After the @code{row-number} variable has
10760been incremented, the true-or-false-test at the beginning of the
10761@code{while} loop tests whether its value is still less than or equal to
10762the value of the @code{number-of-rows} and if it is, adds the new value
10763of the @code{row-number} variable to the @code{total} of the previous
10764repetition of the loop.
10765
10766@need 1200
10767The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10768@code{row-number} variable can be incremented with this expression:
10769
10770@smallexample
10771(setq row-number (1+ row-number))
10772@end smallexample
10773
d6adf7e7 10774@node Inc Example altogether
8cda6f8f
GM
10775@unnumberedsubsubsec Putting the function definition together
10776
10777We have created the parts for the function definition; now we need to
10778put them together.
10779
10780@need 800
10781First, the contents of the @code{while} expression:
10782
10783@smallexample
10784@group
10785(while (<= row-number number-of-rows) ; @r{true-or-false-test}
10786 (setq total (+ total row-number))
10787 (setq row-number (1+ row-number))) ; @r{incrementer}
10788@end group
10789@end smallexample
10790
10791Along with the @code{let} expression varlist, this very nearly
10792completes the body of the function definition. However, it requires
10793one final element, the need for which is somewhat subtle.
10794
10795The final touch is to place the variable @code{total} on a line by
10796itself after the @code{while} expression. Otherwise, the value returned
10797by the whole function is the value of the last expression that is
10798evaluated in the body of the @code{let}, and this is the value
10799returned by the @code{while}, which is always @code{nil}.
10800
10801This may not be evident at first sight. It almost looks as if the
10802incrementing expression is the last expression of the whole function.
10803But that expression is part of the body of the @code{while}; it is the
10804last element of the list that starts with the symbol @code{while}.
10805Moreover, the whole of the @code{while} loop is a list within the body
10806of the @code{let}.
10807
10808@need 1250
10809In outline, the function will look like this:
10810
10811@smallexample
10812@group
10813(defun @var{name-of-function} (@var{argument-list})
10814 "@var{documentation}@dots{}"
10815 (let (@var{varlist})
10816 (while (@var{true-or-false-test})
10817 @var{body-of-while}@dots{} )
10818 @dots{} )) ; @r{Need final expression here.}
10819@end group
10820@end smallexample
10821
10822The result of evaluating the @code{let} is what is going to be returned
10823by the @code{defun} since the @code{let} is not embedded within any
10824containing list, except for the @code{defun} as a whole. However, if
10825the @code{while} is the last element of the @code{let} expression, the
10826function will always return @code{nil}. This is not what we want!
10827Instead, what we want is the value of the variable @code{total}. This
10828is returned by simply placing the symbol as the last element of the list
10829starting with @code{let}. It gets evaluated after the preceding
10830elements of the list are evaluated, which means it gets evaluated after
10831it has been assigned the correct value for the total.
10832
10833It may be easier to see this by printing the list starting with
10834@code{let} all on one line. This format makes it evident that the
10835@var{varlist} and @code{while} expressions are the second and third
10836elements of the list starting with @code{let}, and the @code{total} is
10837the last element:
10838
10839@smallexample
10840@group
10841(let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10842@end group
10843@end smallexample
10844
10845@need 1200
10846Putting everything together, the @code{triangle} function definition
10847looks like this:
10848
10849@smallexample
10850@group
10851(defun triangle (number-of-rows) ; @r{Version with}
10852 ; @r{ incrementing counter.}
10853 "Add up the number of pebbles in a triangle.
10854The first row has one pebble, the second row two pebbles,
10855the third row three pebbles, and so on.
10856The argument is NUMBER-OF-ROWS."
10857@end group
10858@group
10859 (let ((total 0)
10860 (row-number 1))
10861 (while (<= row-number number-of-rows)
10862 (setq total (+ total row-number))
10863 (setq row-number (1+ row-number)))
10864 total))
10865@end group
10866@end smallexample
10867
10868@need 1200
10869After you have installed @code{triangle} by evaluating the function, you
10870can try it out. Here are two examples:
10871
10872@smallexample
10873@group
10874(triangle 4)
10875
10876(triangle 7)
10877@end group
10878@end smallexample
10879
10880@noindent
10881The sum of the first four numbers is 10 and the sum of the first seven
10882numbers is 28.
10883
d6adf7e7 10884@node Decrementing Loop
8cda6f8f
GM
10885@subsection Loop with a Decrementing Counter
10886
10887Another common way to write a @code{while} loop is to write the test
10888so that it determines whether a counter is greater than zero. So long
10889as the counter is greater than zero, the loop is repeated. But when
10890the counter is equal to or less than zero, the loop is stopped. For
10891this to work, the counter has to start out greater than zero and then
10892be made smaller and smaller by a form that is evaluated
10893repeatedly.
10894
10895The test will be an expression such as @code{(> counter 0)} which
10896returns @code{t} for true if the value of @code{counter} is greater
10897than zero, and @code{nil} for false if the value of @code{counter} is
10898equal to or less than zero. The expression that makes the number
10899smaller and smaller can be a simple @code{setq} such as @code{(setq
10900counter (1- counter))}, where @code{1-} is a built-in function in
10901Emacs Lisp that subtracts 1 from its argument.
10902
10903@need 1250
10904The template for a decrementing @code{while} loop looks like this:
10905
10906@smallexample
10907@group
10908(while (> counter 0) ; @r{true-or-false-test}
10909 @var{body}@dots{}
10910 (setq counter (1- counter))) ; @r{decrementer}
10911@end group
10912@end smallexample
10913
10914@menu
10915* Decrementing Example:: More pebbles on the beach.
10916* Dec Example parts:: The parts of the function definition.
10917* Dec Example altogether:: Putting the function definition together.
10918@end menu
10919
d6adf7e7 10920@node Decrementing Example
8cda6f8f
GM
10921@unnumberedsubsubsec Example with decrementing counter
10922
10923To illustrate a loop with a decrementing counter, we will rewrite the
10924@code{triangle} function so the counter decreases to zero.
10925
10926This is the reverse of the earlier version of the function. In this
10927case, to find out how many pebbles are needed to make a triangle with
109283 rows, add the number of pebbles in the third row, 3, to the number
10929in the preceding row, 2, and then add the total of those two rows to
10930the row that precedes them, which is 1.
10931
10932Likewise, to find the number of pebbles in a triangle with 7 rows, add
10933the number of pebbles in the seventh row, 7, to the number in the
10934preceding row, which is 6, and then add the total of those two rows to
10935the row that precedes them, which is 5, and so on. As in the previous
10936example, each addition only involves adding two numbers, the total of
10937the rows already added up and the number of pebbles in the row that is
10938being added to the total. This process of adding two numbers is
10939repeated again and again until there are no more pebbles to add.
10940
10941We know how many pebbles to start with: the number of pebbles in the
10942last row is equal to the number of rows. If the triangle has seven
10943rows, the number of pebbles in the last row is 7. Likewise, we know how
10944many pebbles are in the preceding row: it is one less than the number in
10945the row.
10946
d6adf7e7 10947@node Dec Example parts
8cda6f8f
GM
10948@unnumberedsubsubsec The parts of the function definition
10949
10950We start with three variables: the total number of rows in the
10951triangle; the number of pebbles in a row; and the total number of
10952pebbles, which is what we want to calculate. These variables can be
10953named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10954@code{total}, respectively.
10955
10956Both @code{total} and @code{number-of-pebbles-in-row} are used only
10957inside the function and are declared with @code{let}. The initial
10958value of @code{total} should, of course, be zero. However, the
10959initial value of @code{number-of-pebbles-in-row} should be equal to
10960the number of rows in the triangle, since the addition will start with
10961the longest row.
10962
10963@need 1250
10964This means that the beginning of the @code{let} expression will look
10965like this:
10966
10967@smallexample
10968@group
10969(let ((total 0)
10970 (number-of-pebbles-in-row number-of-rows))
10971 @var{body}@dots{})
10972@end group
10973@end smallexample
10974
10975The total number of pebbles can be found by repeatedly adding the number
10976of pebbles in a row to the total already found, that is, by repeatedly
10977evaluating the following expression:
10978
10979@smallexample
10980(setq total (+ total number-of-pebbles-in-row))
10981@end smallexample
10982
10983@noindent
10984After the @code{number-of-pebbles-in-row} is added to the @code{total},
10985the @code{number-of-pebbles-in-row} should be decremented by one, since
10986the next time the loop repeats, the preceding row will be
10987added to the total.
10988
10989The number of pebbles in a preceding row is one less than the number of
10990pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10991used to compute the number of pebbles in the preceding row. This can be
10992done with the following expression:
10993
10994@smallexample
10995@group
10996(setq number-of-pebbles-in-row
10997 (1- number-of-pebbles-in-row))
10998@end group
10999@end smallexample
11000
11001Finally, we know that the @code{while} loop should stop making repeated
11002additions when there are no pebbles in a row. So the test for
11003the @code{while} loop is simply:
11004
11005@smallexample
11006(while (> number-of-pebbles-in-row 0)
11007@end smallexample
11008
d6adf7e7 11009@node Dec Example altogether
8cda6f8f
GM
11010@unnumberedsubsubsec Putting the function definition together
11011
11012We can put these expressions together to create a function definition
11013that works. However, on examination, we find that one of the local
11014variables is unneeded!
11015
11016@need 1250
11017The function definition looks like this:
11018
11019@smallexample
11020@group
11021;;; @r{First subtractive version.}
11022(defun triangle (number-of-rows)
11023 "Add up the number of pebbles in a triangle."
11024 (let ((total 0)
11025 (number-of-pebbles-in-row number-of-rows))
11026 (while (> number-of-pebbles-in-row 0)
11027 (setq total (+ total number-of-pebbles-in-row))
11028 (setq number-of-pebbles-in-row
11029 (1- number-of-pebbles-in-row)))
11030 total))
11031@end group
11032@end smallexample
11033
11034As written, this function works.
11035
11036However, we do not need @code{number-of-pebbles-in-row}.
11037
11038@cindex Argument as local variable
11039When the @code{triangle} function is evaluated, the symbol
11040@code{number-of-rows} will be bound to a number, giving it an initial
11041value. That number can be changed in the body of the function as if
11042it were a local variable, without any fear that such a change will
11043effect the value of the variable outside of the function. This is a
11044very useful characteristic of Lisp; it means that the variable
11045@code{number-of-rows} can be used anywhere in the function where
11046@code{number-of-pebbles-in-row} is used.
11047
11048@need 800
11049Here is a second version of the function written a bit more cleanly:
11050
11051@smallexample
11052@group
11053(defun triangle (number) ; @r{Second version.}
11054 "Return sum of numbers 1 through NUMBER inclusive."
11055 (let ((total 0))
11056 (while (> number 0)
11057 (setq total (+ total number))
11058 (setq number (1- number)))
11059 total))
11060@end group
11061@end smallexample
11062
11063In brief, a properly written @code{while} loop will consist of three parts:
11064
11065@enumerate
11066@item
11067A test that will return false after the loop has repeated itself the
11068correct number of times.
11069
11070@item
11071An expression the evaluation of which will return the value desired
11072after being repeatedly evaluated.
11073
11074@item
11075An expression to change the value passed to the true-or-false-test so
11076that the test returns false after the loop has repeated itself the right
11077number of times.
11078@end enumerate
11079
d6adf7e7 11080@node dolist dotimes
8cda6f8f
GM
11081@section Save your time: @code{dolist} and @code{dotimes}
11082
11083In addition to @code{while}, both @code{dolist} and @code{dotimes}
11084provide for looping. Sometimes these are quicker to write than the
11085equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
11086Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
11087
11088@code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
11089list': @code{dolist} automatically shortens the list each time it
11090loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
11091each shorter version of the list to the first of its arguments.
11092
11093@code{dotimes} loops a specific number of times: you specify the number.
11094
11095@menu
11096* dolist::
11097* dotimes::
11098@end menu
11099
d6adf7e7
GM
11100@node dolist
11101@unnumberedsubsec The @code{dolist} Macro
8cda6f8f
GM
11102@findex dolist
11103
11104Suppose, for example, you want to reverse a list, so that
11105``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
11106
11107@need 1250
11108In practice, you would use the @code{reverse} function, like this:
11109
11110@smallexample
11111@group
11112(setq animals '(gazelle giraffe lion tiger))
11113
11114(reverse animals)
11115@end group
11116@end smallexample
11117
11118@need 800
11119@noindent
11120Here is how you could reverse the list using a @code{while} loop:
11121
11122@smallexample
11123@group
11124(setq animals '(gazelle giraffe lion tiger))
11125
11126(defun reverse-list-with-while (list)
11127 "Using while, reverse the order of LIST."
11128 (let (value) ; make sure list starts empty
11129 (while list
11130 (setq value (cons (car list) value))
11131 (setq list (cdr list)))
11132 value))
11133
11134(reverse-list-with-while animals)
11135@end group
11136@end smallexample
11137
11138@need 800
11139@noindent
11140And here is how you could use the @code{dolist} macro:
11141
11142@smallexample
11143@group
11144(setq animals '(gazelle giraffe lion tiger))
11145
11146(defun reverse-list-with-dolist (list)
11147 "Using dolist, reverse the order of LIST."
11148 (let (value) ; make sure list starts empty
11149 (dolist (element list value)
11150 (setq value (cons element value)))))
11151
11152(reverse-list-with-dolist animals)
11153@end group
11154@end smallexample
11155
11156@need 1250
11157@noindent
11158In Info, you can place your cursor after the closing parenthesis of
11159each expression and type @kbd{C-x C-e}; in each case, you should see
11160
11161@smallexample
11162(tiger lion giraffe gazelle)
11163@end smallexample
11164
11165@noindent
11166in the echo area.
11167
11168For this example, the existing @code{reverse} function is obviously best.
11169The @code{while} loop is just like our first example (@pxref{Loop
11170Example, , A @code{while} Loop and a List}). The @code{while} first
11171checks whether the list has elements; if so, it constructs a new list
11172by adding the first element of the list to the existing list (which in
11173the first iteration of the loop is @code{nil}). Since the second
11174element is prepended in front of the first element, and the third
11175element is prepended in front of the second element, the list is reversed.
11176
11177In the expression using a @code{while} loop,
11178the @w{@code{(setq list (cdr list))}}
11179expression shortens the list, so the @code{while} loop eventually
11180stops. In addition, it provides the @code{cons} expression with a new
11181first element by creating a new and shorter list at each repetition of
11182the loop.
11183
11184The @code{dolist} expression does very much the same as the
11185@code{while} expression, except that the @code{dolist} macro does some
11186of the work you have to do when writing a @code{while} expression.
11187
11188Like a @code{while} loop, a @code{dolist} loops. What is different is
f99f1641
PE
11189that it automatically shortens the list each time it loops---it
11190`@sc{cdr}s down the list' on its own---and it automatically binds
8cda6f8f
GM
11191the @sc{car} of each shorter version of the list to the first of its
11192arguments.
11193
11194In the example, the @sc{car} of each shorter version of the list is
11195referred to using the symbol @samp{element}, the list itself is called
11196@samp{list}, and the value returned is called @samp{value}. The
11197remainder of the @code{dolist} expression is the body.
11198
11199The @code{dolist} expression binds the @sc{car} of each shorter
11200version of the list to @code{element} and then evaluates the body of
11201the expression; and repeats the loop. The result is returned in
11202@code{value}.
11203
d6adf7e7
GM
11204@node dotimes
11205@unnumberedsubsec The @code{dotimes} Macro
8cda6f8f
GM
11206@findex dotimes
11207
11208The @code{dotimes} macro is similar to @code{dolist}, except that it
11209loops a specific number of times.
11210
11211The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
11212and so forth each time around the loop, and the value of the third
11213argument is returned. You need to provide the value of the second
11214argument, which is how many times the macro loops.
11215
11216@need 1250
11217For example, the following binds the numbers from 0 up to, but not
11218including, the number 3 to the first argument, @var{number}, and then
11219constructs a list of the three numbers. (The first number is 0, the
11220second number is 1, and the third number is 2; this makes a total of
11221three numbers in all, starting with zero as the first number.)
11222
11223@smallexample
11224@group
11225(let (value) ; otherwise a value is a void variable
11226 (dotimes (number 3 value)
11227 (setq value (cons number value))))
11228
11229@result{} (2 1 0)
11230@end group
11231@end smallexample
11232
11233@noindent
11234@code{dotimes} returns @code{value}, so the way to use
11235@code{dotimes} is to operate on some expression @var{number} number of
11236times and then return the result, either as a list or an atom.
11237
11238@need 1250
11239Here is an example of a @code{defun} that uses @code{dotimes} to add
11240up the number of pebbles in a triangle.
11241
11242@smallexample
11243@group
11244(defun triangle-using-dotimes (number-of-rows)
11245 "Using dotimes, add up the number of pebbles in a triangle."
11246(let ((total 0)) ; otherwise a total is a void variable
11247 (dotimes (number number-of-rows total)
11248 (setq total (+ total (1+ number))))))
11249
11250(triangle-using-dotimes 4)
11251@end group
11252@end smallexample
11253
d6adf7e7 11254@node Recursion
8cda6f8f
GM
11255@section Recursion
11256@cindex Recursion
11257
11258A recursive function contains code that tells the Lisp interpreter to
11259call a program that runs exactly like itself, but with slightly
11260different arguments. The code runs exactly the same because it has
11261the same name. However, even though the program has the same name, it
11262is not the same entity. It is different. In the jargon, it is a
11263different `instance'.
11264
11265Eventually, if the program is written correctly, the `slightly
11266different arguments' will become sufficiently different from the first
11267arguments that the final instance will stop.
11268
11269@menu
11270* Building Robots:: Same model, different serial number ...
11271* Recursive Definition Parts:: Walk until you stop ...
11272* Recursion with list:: Using a list as the test whether to recurse.
11273* Recursive triangle function::
11274* Recursion with cond::
11275* Recursive Patterns:: Often used templates.
11276* No Deferment:: Don't store up work ...
11277* No deferment solution::
11278@end menu
11279
d6adf7e7 11280@node Building Robots
8cda6f8f
GM
11281@subsection Building Robots: Extending the Metaphor
11282@cindex Building robots
11283@cindex Robots, building
11284
11285It is sometimes helpful to think of a running program as a robot that
11286does a job. In doing its job, a recursive function calls on a second
11287robot to help it. The second robot is identical to the first in every
11288way, except that the second robot helps the first and has been
11289passed different arguments than the first.
11290
11291In a recursive function, the second robot may call a third; and the
11292third may call a fourth, and so on. Each of these is a different
11293entity; but all are clones.
11294
11295Since each robot has slightly different instructions---the arguments
11296will differ from one robot to the next---the last robot should know
11297when to stop.
11298
11299Let's expand on the metaphor in which a computer program is a robot.
11300
11301A function definition provides the blueprints for a robot. When you
11302install a function definition, that is, when you evaluate a
11303@code{defun} special form, you install the necessary equipment to
11304build robots. It is as if you were in a factory, setting up an
11305assembly line. Robots with the same name are built according to the
11306same blueprints. So they have, as it were, the same `model number',
11307but a different `serial number'.
11308
11309We often say that a recursive function `calls itself'. What we mean
11310is that the instructions in a recursive function cause the Lisp
11311interpreter to run a different function that has the same name and
11312does the same job as the first, but with different arguments.
11313
11314It is important that the arguments differ from one instance to the
11315next; otherwise, the process will never stop.
11316
d6adf7e7 11317@node Recursive Definition Parts
8cda6f8f
GM
11318@subsection The Parts of a Recursive Definition
11319@cindex Parts of a Recursive Definition
11320@cindex Recursive Definition Parts
11321
11322A recursive function typically contains a conditional expression which
11323has three parts:
11324
11325@enumerate
11326@item
11327A true-or-false-test that determines whether the function is called
11328again, here called the @dfn{do-again-test}.
11329
11330@item
11331The name of the function. When this name is called, a new instance of
11332the function---a new robot, as it were---is created and told what to do.
11333
11334@item
11335An expression that returns a different value each time the function is
11336called, here called the @dfn{next-step-expression}. Consequently, the
11337argument (or arguments) passed to the new instance of the function
11338will be different from that passed to the previous instance. This
11339causes the conditional expression, the @dfn{do-again-test}, to test
11340false after the correct number of repetitions.
11341@end enumerate
11342
11343Recursive functions can be much simpler than any other kind of
11344function. Indeed, when people first start to use them, they often look
11345so mysteriously simple as to be incomprehensible. Like riding a
11346bicycle, reading a recursive function definition takes a certain knack
11347which is hard at first but then seems simple.
11348
11349@need 1200
11350There are several different common recursive patterns. A very simple
11351pattern looks like this:
11352
11353@smallexample
11354@group
11355(defun @var{name-of-recursive-function} (@var{argument-list})
11356 "@var{documentation}@dots{}"
11357 (if @var{do-again-test}
11358 @var{body}@dots{}
11359 (@var{name-of-recursive-function}
11360 @var{next-step-expression})))
11361@end group
11362@end smallexample
11363
11364Each time a recursive function is evaluated, a new instance of it is
11365created and told what to do. The arguments tell the instance what to do.
11366
11367An argument is bound to the value of the next-step-expression. Each
11368instance runs with a different value of the next-step-expression.
11369
11370The value in the next-step-expression is used in the do-again-test.
11371
11372The value returned by the next-step-expression is passed to the new
11373instance of the function, which evaluates it (or some
11374transmogrification of it) to determine whether to continue or stop.
11375The next-step-expression is designed so that the do-again-test returns
11376false when the function should no longer be repeated.
11377
11378The do-again-test is sometimes called the @dfn{stop condition},
11379since it stops the repetitions when it tests false.
11380
d6adf7e7 11381@node Recursion with list
8cda6f8f
GM
11382@subsection Recursion with a List
11383
11384The example of a @code{while} loop that printed the elements of a list
11385of numbers can be written recursively. Here is the code, including
11386an expression to set the value of the variable @code{animals} to a list.
11387
8f4ea8e0
GM
11388If you are reading this in Info in Emacs, you can evaluate this
11389expression directly in Info. Otherwise, you must copy the example
11390to the @file{*scratch*} buffer and evaluate each expression there.
11391Use @kbd{C-u C-x C-e} to evaluate the
8cda6f8f
GM
11392@code{(print-elements-recursively animals)} expression so that the
11393results are printed in the buffer; otherwise the Lisp interpreter will
11394try to squeeze the results into the one line of the echo area.
11395
11396Also, place your cursor immediately after the last closing parenthesis
11397of the @code{print-elements-recursively} function, before the comment.
11398Otherwise, the Lisp interpreter will try to evaluate the comment.
11399
8cda6f8f
GM
11400@findex print-elements-recursively
11401@smallexample
11402@group
11403(setq animals '(gazelle giraffe lion tiger))
11404
11405(defun print-elements-recursively (list)
11406 "Print each element of LIST on a line of its own.
11407Uses recursion."
11408 (when list ; @r{do-again-test}
11409 (print (car list)) ; @r{body}
11410 (print-elements-recursively ; @r{recursive call}
11411 (cdr list)))) ; @r{next-step-expression}
11412
11413(print-elements-recursively animals)
11414@end group
11415@end smallexample
11416
11417The @code{print-elements-recursively} function first tests whether
11418there is any content in the list; if there is, the function prints the
11419first element of the list, the @sc{car} of the list. Then the
11420function `invokes itself', but gives itself as its argument, not the
11421whole list, but the second and subsequent elements of the list, the
11422@sc{cdr} of the list.
11423
11424Put another way, if the list is not empty, the function invokes
11425another instance of code that is similar to the initial code, but is a
11426different thread of execution, with different arguments than the first
11427instance.
11428
11429Put in yet another way, if the list is not empty, the first robot
2d7752a0 11430assembles a second robot and tells it what to do; the second robot is
8cda6f8f
GM
11431a different individual from the first, but is the same model.
11432
11433When the second evaluation occurs, the @code{when} expression is
11434evaluated and if true, prints the first element of the list it
11435receives as its argument (which is the second element of the original
11436list). Then the function `calls itself' with the @sc{cdr} of the list
11437it is invoked with, which (the second time around) is the @sc{cdr} of
11438the @sc{cdr} of the original list.
11439
11440Note that although we say that the function `calls itself', what we
11441mean is that the Lisp interpreter assembles and instructs a new
11442instance of the program. The new instance is a clone of the first,
11443but is a separate individual.
11444
11445Each time the function `invokes itself', it invokes itself on a
11446shorter version of the original list. It creates a new instance that
11447works on a shorter list.
11448
11449Eventually, the function invokes itself on an empty list. It creates
11450a new instance whose argument is @code{nil}. The conditional expression
11451tests the value of @code{list}. Since the value of @code{list} is
11452@code{nil}, the @code{when} expression tests false so the then-part is
11453not evaluated. The function as a whole then returns @code{nil}.
11454
11455@need 1200
a9097c6d
KB
11456When you evaluate the expression @code{(print-elements-recursively
11457animals)} in the @file{*scratch*} buffer, you see this result:
8cda6f8f
GM
11458
11459@smallexample
11460@group
11461gazelle
11462
11463giraffe
11464
11465lion
11466
11467tiger
11468nil
11469@end group
11470@end smallexample
11471
11472@need 2000
d6adf7e7 11473@node Recursive triangle function
8cda6f8f
GM
11474@subsection Recursion in Place of a Counter
11475@findex triangle-recursively
11476
11477@need 1200
11478The @code{triangle} function described in a previous section can also
11479be written recursively. It looks like this:
11480
11481@smallexample
11482@group
11483(defun triangle-recursively (number)
11484 "Return the sum of the numbers 1 through NUMBER inclusive.
11485Uses recursion."
11486 (if (= number 1) ; @r{do-again-test}
11487 1 ; @r{then-part}
11488 (+ number ; @r{else-part}
11489 (triangle-recursively ; @r{recursive call}
11490 (1- number))))) ; @r{next-step-expression}
11491
11492(triangle-recursively 7)
11493@end group
11494@end smallexample
11495
11496@noindent
11497You can install this function by evaluating it and then try it by
11498evaluating @code{(triangle-recursively 7)}. (Remember to put your
11499cursor immediately after the last parenthesis of the function
11500definition, before the comment.) The function evaluates to 28.
11501
11502To understand how this function works, let's consider what happens in the
11503various cases when the function is passed 1, 2, 3, or 4 as the value of
11504its argument.
11505
11506@menu
11507* Recursive Example arg of 1 or 2::
11508* Recursive Example arg of 3 or 4::
11509@end menu
11510
8cda6f8f 11511@ifnottex
d6adf7e7 11512@node Recursive Example arg of 1 or 2
8cda6f8f
GM
11513@unnumberedsubsubsec An argument of 1 or 2
11514@end ifnottex
11515
11516First, what happens if the value of the argument is 1?
11517
11518The function has an @code{if} expression after the documentation
11519string. It tests whether the value of @code{number} is equal to 1; if
11520so, Emacs evaluates the then-part of the @code{if} expression, which
11521returns the number 1 as the value of the function. (A triangle with
11522one row has one pebble in it.)
11523
11524Suppose, however, that the value of the argument is 2. In this case,
11525Emacs evaluates the else-part of the @code{if} expression.
11526
11527@need 1200
11528The else-part consists of an addition, the recursive call to
11529@code{triangle-recursively} and a decrementing action; and it looks like
11530this:
11531
11532@smallexample
11533(+ number (triangle-recursively (1- number)))
11534@end smallexample
11535
11536When Emacs evaluates this expression, the innermost expression is
11537evaluated first; then the other parts in sequence. Here are the steps
11538in detail:
11539
11540@table @i
11541@item Step 1 @w{ } Evaluate the innermost expression.
11542
11543The innermost expression is @code{(1- number)} so Emacs decrements the
11544value of @code{number} from 2 to 1.
11545
11546@item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
11547
11548The Lisp interpreter creates an individual instance of
11549@code{triangle-recursively}. It does not matter that this function is
11550contained within itself. Emacs passes the result Step 1 as the
11551argument used by this instance of the @code{triangle-recursively}
11552function
11553
11554In this case, Emacs evaluates @code{triangle-recursively} with an
11555argument of 1. This means that this evaluation of
11556@code{triangle-recursively} returns 1.
11557
11558@item Step 3 @w{ } Evaluate the value of @code{number}.
11559
11560The variable @code{number} is the second element of the list that
11561starts with @code{+}; its value is 2.
11562
11563@item Step 4 @w{ } Evaluate the @code{+} expression.
11564
11565The @code{+} expression receives two arguments, the first
11566from the evaluation of @code{number} (Step 3) and the second from the
11567evaluation of @code{triangle-recursively} (Step 2).
11568
11569The result of the addition is the sum of 2 plus 1, and the number 3 is
11570returned, which is correct. A triangle with two rows has three
11571pebbles in it.
11572@end table
11573
d6adf7e7 11574@node Recursive Example arg of 3 or 4
8cda6f8f
GM
11575@unnumberedsubsubsec An argument of 3 or 4
11576
11577Suppose that @code{triangle-recursively} is called with an argument of
115783.
11579
11580@table @i
11581@item Step 1 @w{ } Evaluate the do-again-test.
11582
11583The @code{if} expression is evaluated first. This is the do-again
11584test and returns false, so the else-part of the @code{if} expression
11585is evaluated. (Note that in this example, the do-again-test causes
11586the function to call itself when it tests false, not when it tests
11587true.)
11588
11589@item Step 2 @w{ } Evaluate the innermost expression of the else-part.
11590
11591The innermost expression of the else-part is evaluated, which decrements
115923 to 2. This is the next-step-expression.
11593
11594@item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
11595
11596The number 2 is passed to the @code{triangle-recursively} function.
11597
a9097c6d 11598We already know what happens when Emacs evaluates @code{triangle-recursively} with
8cda6f8f
GM
11599an argument of 2. After going through the sequence of actions described
11600earlier, it returns a value of 3. So that is what will happen here.
11601
11602@item Step 4 @w{ } Evaluate the addition.
11603
116043 will be passed as an argument to the addition and will be added to the
11605number with which the function was called, which is 3.
11606@end table
11607
11608@noindent
11609The value returned by the function as a whole will be 6.
11610
11611Now that we know what will happen when @code{triangle-recursively} is
11612called with an argument of 3, it is evident what will happen if it is
11613called with an argument of 4:
11614
11615@quotation
11616@need 800
11617In the recursive call, the evaluation of
11618
11619@smallexample
11620(triangle-recursively (1- 4))
11621@end smallexample
11622
11623@need 800
11624@noindent
11625will return the value of evaluating
11626
11627@smallexample
11628(triangle-recursively 3)
11629@end smallexample
11630
11631@noindent
11632which is 6 and this value will be added to 4 by the addition in the
11633third line.
11634@end quotation
11635
11636@noindent
11637The value returned by the function as a whole will be 10.
11638
11639Each time @code{triangle-recursively} is evaluated, it evaluates a
11640version of itself---a different instance of itself---with a smaller
11641argument, until the argument is small enough so that it does not
11642evaluate itself.
11643
11644Note that this particular design for a recursive function
11645requires that operations be deferred.
11646
11647Before @code{(triangle-recursively 7)} can calculate its answer, it
11648must call @code{(triangle-recursively 6)}; and before
11649@code{(triangle-recursively 6)} can calculate its answer, it must call
11650@code{(triangle-recursively 5)}; and so on. That is to say, the
11651calculation that @code{(triangle-recursively 7)} makes must be
11652deferred until @code{(triangle-recursively 6)} makes its calculation;
11653and @code{(triangle-recursively 6)} must defer until
11654@code{(triangle-recursively 5)} completes; and so on.
11655
11656If each of these instances of @code{triangle-recursively} are thought
11657of as different robots, the first robot must wait for the second to
11658complete its job, which must wait until the third completes, and so
11659on.
11660
11661There is a way around this kind of waiting, which we will discuss in
11662@ref{No Deferment, , Recursion without Deferments}.
11663
d6adf7e7 11664@node Recursion with cond
8cda6f8f
GM
11665@subsection Recursion Example Using @code{cond}
11666@findex cond
11667
11668The version of @code{triangle-recursively} described earlier is written
11669with the @code{if} special form. It can also be written using another
11670special form called @code{cond}. The name of the special form
11671@code{cond} is an abbreviation of the word @samp{conditional}.
11672
11673Although the @code{cond} special form is not used as often in the
11674Emacs Lisp sources as @code{if}, it is used often enough to justify
11675explaining it.
11676
11677@need 800
11678The template for a @code{cond} expression looks like this:
11679
11680@smallexample
11681@group
11682(cond
11683 @var{body}@dots{})
11684@end group
11685@end smallexample
11686
11687@noindent
11688where the @var{body} is a series of lists.
11689
11690@need 800
11691Written out more fully, the template looks like this:
11692
11693@smallexample
11694@group
11695(cond
11696 (@var{first-true-or-false-test} @var{first-consequent})
11697 (@var{second-true-or-false-test} @var{second-consequent})
11698 (@var{third-true-or-false-test} @var{third-consequent})
11699 @dots{})
11700@end group
11701@end smallexample
11702
11703When the Lisp interpreter evaluates the @code{cond} expression, it
11704evaluates the first element (the @sc{car} or true-or-false-test) of
11705the first expression in a series of expressions within the body of the
11706@code{cond}.
11707
11708If the true-or-false-test returns @code{nil} the rest of that
11709expression, the consequent, is skipped and the true-or-false-test of the
11710next expression is evaluated. When an expression is found whose
11711true-or-false-test returns a value that is not @code{nil}, the
11712consequent of that expression is evaluated. The consequent can be one
11713or more expressions. If the consequent consists of more than one
11714expression, the expressions are evaluated in sequence and the value of
11715the last one is returned. If the expression does not have a consequent,
11716the value of the true-or-false-test is returned.
11717
11718If none of the true-or-false-tests test true, the @code{cond} expression
11719returns @code{nil}.
11720
11721@need 1250
11722Written using @code{cond}, the @code{triangle} function looks like this:
11723
11724@smallexample
11725@group
11726(defun triangle-using-cond (number)
11727 (cond ((<= number 0) 0)
11728 ((= number 1) 1)
11729 ((> number 1)
11730 (+ number (triangle-using-cond (1- number))))))
11731@end group
11732@end smallexample
11733
11734@noindent
11735In this example, the @code{cond} returns 0 if the number is less than or
11736equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11737number (triangle-using-cond (1- number)))} if the number is greater than
117381.
11739
d6adf7e7 11740@node Recursive Patterns
8cda6f8f
GM
11741@subsection Recursive Patterns
11742@cindex Recursive Patterns
11743
11744Here are three common recursive patterns. Each involves a list.
11745Recursion does not need to involve lists, but Lisp is designed for lists
11746and this provides a sense of its primal capabilities.
11747
11748@menu
11749* Every::
11750* Accumulate::
11751* Keep::
11752@end menu
11753
d6adf7e7 11754@node Every
8cda6f8f
GM
11755@unnumberedsubsubsec Recursive Pattern: @emph{every}
11756@cindex Every, type of recursive pattern
11757@cindex Recursive pattern: every
11758
11759In the @code{every} recursive pattern, an action is performed on every
11760element of a list.
11761
11762@need 1500
11763The basic pattern is:
11764
11765@itemize @bullet
11766@item
11767If a list be empty, return @code{nil}.
11768@item
11769Else, act on the beginning of the list (the @sc{car} of the list)
11770 @itemize @minus
11771 @item
11772 through a recursive call by the function on the rest (the
11773 @sc{cdr}) of the list,
11774 @item
11775 and, optionally, combine the acted-on element, using @code{cons},
11776 with the results of acting on the rest.
11777 @end itemize
11778@end itemize
11779
11780@need 1500
11781Here is example:
11782
11783@smallexample
11784@group
11785(defun square-each (numbers-list)
11786 "Square each of a NUMBERS LIST, recursively."
11787 (if (not numbers-list) ; do-again-test
11788 nil
11789 (cons
11790 (* (car numbers-list) (car numbers-list))
11791 (square-each (cdr numbers-list))))) ; next-step-expression
11792@end group
11793
11794@group
11795(square-each '(1 2 3))
11796 @result{} (1 4 9)
11797@end group
11798@end smallexample
11799
11800@need 1200
11801@noindent
11802If @code{numbers-list} is empty, do nothing. But if it has content,
11803construct a list combining the square of the first number in the list
11804with the result of the recursive call.
11805
11806(The example follows the pattern exactly: @code{nil} is returned if
11807the numbers' list is empty. In practice, you would write the
11808conditional so it carries out the action when the numbers' list is not
11809empty.)
11810
11811The @code{print-elements-recursively} function (@pxref{Recursion with
11812list, , Recursion with a List}) is another example of an @code{every}
11813pattern, except in this case, rather than bring the results together
11814using @code{cons}, we print each element of output.
11815
11816@need 1250
11817The @code{print-elements-recursively} function looks like this:
11818
11819@smallexample
11820@group
11821(setq animals '(gazelle giraffe lion tiger))
11822@end group
11823
11824@group
11825(defun print-elements-recursively (list)
11826 "Print each element of LIST on a line of its own.
11827Uses recursion."
11828 (when list ; @r{do-again-test}
11829 (print (car list)) ; @r{body}
11830 (print-elements-recursively ; @r{recursive call}
11831 (cdr list)))) ; @r{next-step-expression}
11832
11833(print-elements-recursively animals)
11834@end group
11835@end smallexample
11836
11837@need 1500
11838The pattern for @code{print-elements-recursively} is:
11839
11840@itemize @bullet
11841@item
11842When the list is empty, do nothing.
11843@item
11844But when the list has at least one element,
11845 @itemize @minus
11846 @item
11847 act on the beginning of the list (the @sc{car} of the list),
11848 @item
11849 and make a recursive call on the rest (the @sc{cdr}) of the list.
11850 @end itemize
11851@end itemize
11852
d6adf7e7 11853@node Accumulate
8cda6f8f
GM
11854@unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11855@cindex Accumulate, type of recursive pattern
11856@cindex Recursive pattern: accumulate
11857
11858Another recursive pattern is called the @code{accumulate} pattern. In
11859the @code{accumulate} recursive pattern, an action is performed on
11860every element of a list and the result of that action is accumulated
11861with the results of performing the action on the other elements.
11862
11863This is very like the `every' pattern using @code{cons}, except that
11864@code{cons} is not used, but some other combiner.
11865
11866@need 1500
11867The pattern is:
11868
11869@itemize @bullet
11870@item
11871If a list be empty, return zero or some other constant.
11872@item
11873Else, act on the beginning of the list (the @sc{car} of the list),
11874 @itemize @minus
11875 @item
11876 and combine that acted-on element, using @code{+} or
11877 some other combining function, with
11878 @item
11879 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11880 @end itemize
11881@end itemize
11882
11883@need 1500
11884Here is an example:
11885
11886@smallexample
11887@group
11888(defun add-elements (numbers-list)
11889 "Add the elements of NUMBERS-LIST together."
11890 (if (not numbers-list)
11891 0
11892 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11893@end group
11894
11895@group
11896(add-elements '(1 2 3 4))
11897 @result{} 10
11898@end group
11899@end smallexample
11900
11901@xref{Files List, , Making a List of Files}, for an example of the
11902accumulate pattern.
11903
d6adf7e7 11904@node Keep
8cda6f8f
GM
11905@unnumberedsubsubsec Recursive Pattern: @emph{keep}
11906@cindex Keep, type of recursive pattern
11907@cindex Recursive pattern: keep
11908
11909A third recursive pattern is called the @code{keep} pattern.
11910In the @code{keep} recursive pattern, each element of a list is tested;
11911the element is acted on and the results are kept only if the element
11912meets a criterion.
11913
11914Again, this is very like the `every' pattern, except the element is
11915skipped unless it meets a criterion.
11916
11917@need 1500
11918The pattern has three parts:
11919
11920@itemize @bullet
11921@item
11922If a list be empty, return @code{nil}.
11923@item
11924Else, if the beginning of the list (the @sc{car} of the list) passes
11925 a test
11926 @itemize @minus
11927 @item
11928 act on that element and combine it, using @code{cons} with
11929 @item
11930 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11931 @end itemize
11932@item
11933Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11934the test
11935 @itemize @minus
11936 @item
11937 skip on that element,
11938 @item
11939 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11940 @end itemize
11941@end itemize
11942
11943@need 1500
11944Here is an example that uses @code{cond}:
11945
11946@smallexample
11947@group
11948(defun keep-three-letter-words (word-list)
11949 "Keep three letter words in WORD-LIST."
11950 (cond
11951 ;; First do-again-test: stop-condition
11952 ((not word-list) nil)
11953
11954 ;; Second do-again-test: when to act
11955 ((eq 3 (length (symbol-name (car word-list))))
11956 ;; combine acted-on element with recursive call on shorter list
11957 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11958
11959 ;; Third do-again-test: when to skip element;
11960 ;; recursively call shorter list with next-step expression
11961 (t (keep-three-letter-words (cdr word-list)))))
11962@end group
11963
11964@group
11965(keep-three-letter-words '(one two three four five six))
11966 @result{} (one two six)
11967@end group
11968@end smallexample
11969
11970It goes without saying that you need not use @code{nil} as the test for
11971when to stop; and you can, of course, combine these patterns.
11972
d6adf7e7 11973@node No Deferment
8cda6f8f
GM
11974@subsection Recursion without Deferments
11975@cindex Deferment in recursion
11976@cindex Recursion without Deferments
11977
11978Let's consider again what happens with the @code{triangle-recursively}
11979function. We will find that the intermediate calculations are
11980deferred until all can be done.
11981
11982@need 800
11983Here is the function definition:
11984
11985@smallexample
11986@group
11987(defun triangle-recursively (number)
11988 "Return the sum of the numbers 1 through NUMBER inclusive.
11989Uses recursion."
11990 (if (= number 1) ; @r{do-again-test}
11991 1 ; @r{then-part}
11992 (+ number ; @r{else-part}
11993 (triangle-recursively ; @r{recursive call}
11994 (1- number))))) ; @r{next-step-expression}
11995@end group
11996@end smallexample
11997
11998What happens when we call this function with a argument of 7?
11999
12000The first instance of the @code{triangle-recursively} function adds
12001the number 7 to the value returned by a second instance of
12002@code{triangle-recursively}, an instance that has been passed an
12003argument of 6. That is to say, the first calculation is:
12004
12005@smallexample
12006(+ 7 (triangle-recursively 6))
12007@end smallexample
12008
12009@noindent
12010The first instance of @code{triangle-recursively}---you may want to
12011think of it as a little robot---cannot complete its job. It must hand
12012off the calculation for @code{(triangle-recursively 6)} to a second
12013instance of the program, to a second robot. This second individual is
12014completely different from the first one; it is, in the jargon, a
12015`different instantiation'. Or, put another way, it is a different
12016robot. It is the same model as the first; it calculates triangle
12017numbers recursively; but it has a different serial number.
12018
12019And what does @code{(triangle-recursively 6)} return? It returns the
12020number 6 added to the value returned by evaluating
12021@code{triangle-recursively} with an argument of 5. Using the robot
12022metaphor, it asks yet another robot to help it.
12023
12024@need 800
12025Now the total is:
12026
12027@smallexample
12028(+ 7 6 (triangle-recursively 5))
12029@end smallexample
12030
12031@need 800
12032And what happens next?
12033
12034@smallexample
12035(+ 7 6 5 (triangle-recursively 4))
12036@end smallexample
12037
12038Each time @code{triangle-recursively} is called, except for the last
12039time, it creates another instance of the program---another robot---and
12040asks it to make a calculation.
12041
12042@need 800
12043Eventually, the full addition is set up and performed:
12044
12045@smallexample
12046(+ 7 6 5 4 3 2 1)
12047@end smallexample
12048
12049This design for the function defers the calculation of the first step
12050until the second can be done, and defers that until the third can be
12051done, and so on. Each deferment means the computer must remember what
12052is being waited on. This is not a problem when there are only a few
12053steps, as in this example. But it can be a problem when there are
12054more steps.
12055
d6adf7e7 12056@node No deferment solution
8cda6f8f
GM
12057@subsection No Deferment Solution
12058@cindex No deferment solution
12059@cindex Defermentless solution
12060@cindex Solution without deferment
12061
12062The solution to the problem of deferred operations is to write in a
12063manner that does not defer operations@footnote{The phrase @dfn{tail
12064recursive} is used to describe such a process, one that uses
12065`constant space'.}. This requires
12066writing to a different pattern, often one that involves writing two
12067function definitions, an `initialization' function and a `helper'
12068function.
12069
12070The `initialization' function sets up the job; the `helper' function
12071does the work.
12072
12073@need 1200
12074Here are the two function definitions for adding up numbers. They are
12075so simple, I find them hard to understand.
12076
12077@smallexample
12078@group
12079(defun triangle-initialization (number)
12080 "Return the sum of the numbers 1 through NUMBER inclusive.
12081This is the `initialization' component of a two function
12082duo that uses recursion."
12083 (triangle-recursive-helper 0 0 number))
12084@end group
12085@end smallexample
12086
12087@smallexample
12088@group
12089(defun triangle-recursive-helper (sum counter number)
12090 "Return SUM, using COUNTER, through NUMBER inclusive.
12091This is the `helper' component of a two function duo
12092that uses recursion."
12093 (if (> counter number)
12094 sum
12095 (triangle-recursive-helper (+ sum counter) ; @r{sum}
12096 (1+ counter) ; @r{counter}
12097 number))) ; @r{number}
12098@end group
12099@end smallexample
12100
12101@need 1250
12102Install both function definitions by evaluating them, then call
12103@code{triangle-initialization} with 2 rows:
12104
12105@smallexample
12106@group
12107(triangle-initialization 2)
12108 @result{} 3
12109@end group
12110@end smallexample
12111
12112The `initialization' function calls the first instance of the `helper'
12113function with three arguments: zero, zero, and a number which is the
12114number of rows in the triangle.
12115
12116The first two arguments passed to the `helper' function are
12117initialization values. These values are changed when
12118@code{triangle-recursive-helper} invokes new instances.@footnote{The
12119jargon is mildly confusing: @code{triangle-recursive-helper} uses a
12120process that is iterative in a procedure that is recursive. The
12121process is called iterative because the computer need only record the
12122three values, @code{sum}, @code{counter}, and @code{number}; the
12123procedure is recursive because the function `calls itself'. On the
12124other hand, both the process and the procedure used by
12125@code{triangle-recursively} are called recursive. The word
12126`recursive' has different meanings in the two contexts.}
12127
12128Let's see what happens when we have a triangle that has one row. (This
12129triangle will have one pebble in it!)
12130
12131@need 1200
12132@code{triangle-initialization} will call its helper with
12133the arguments @w{@code{0 0 1}}. That function will run the conditional
12134test whether @code{(> counter number)}:
12135
12136@smallexample
12137(> 0 1)
12138@end smallexample
12139
12140@need 1200
12141@noindent
12142and find that the result is false, so it will invoke
12143the else-part of the @code{if} clause:
12144
12145@smallexample
12146@group
12147 (triangle-recursive-helper
12148 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12149 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12150 number) ; @r{number stays the same}
12151@end group
12152@end smallexample
12153
12154@need 800
12155@noindent
12156which will first compute:
12157
12158@smallexample
12159@group
12160(triangle-recursive-helper (+ 0 0) ; @r{sum}
12161 (1+ 0) ; @r{counter}
12162 1) ; @r{number}
12163@exdent which is:
12164
12165(triangle-recursive-helper 0 1 1)
12166@end group
12167@end smallexample
12168
12169Again, @code{(> counter number)} will be false, so again, the Lisp
12170interpreter will evaluate @code{triangle-recursive-helper}, creating a
12171new instance with new arguments.
12172
12173@need 800
12174This new instance will be;
12175
12176@smallexample
12177@group
12178 (triangle-recursive-helper
12179 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12180 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12181 number) ; @r{number stays the same}
12182
12183@exdent which is:
12184
12185(triangle-recursive-helper 1 2 1)
12186@end group
12187@end smallexample
12188
12189In this case, the @code{(> counter number)} test will be true! So the
12190instance will return the value of the sum, which will be 1, as
12191expected.
12192
12193Now, let's pass @code{triangle-initialization} an argument
12194of 2, to find out how many pebbles there are in a triangle with two rows.
12195
12196That function calls @code{(triangle-recursive-helper 0 0 2)}.
12197
12198@need 800
12199In stages, the instances called will be:
12200
12201@smallexample
12202@group
12203 @r{sum counter number}
12204(triangle-recursive-helper 0 1 2)
12205
12206(triangle-recursive-helper 1 2 2)
12207
12208(triangle-recursive-helper 3 3 2)
12209@end group
12210@end smallexample
12211
12212When the last instance is called, the @code{(> counter number)} test
12213will be true, so the instance will return the value of @code{sum},
12214which will be 3.
12215
12216This kind of pattern helps when you are writing functions that can use
12217many resources in a computer.
12218
12219@need 1500
d6adf7e7 12220@node Looping exercise
8cda6f8f
GM
12221@section Looping Exercise
12222
12223@itemize @bullet
12224@item
12225Write a function similar to @code{triangle} in which each row has a
12226value which is the square of the row number. Use a @code{while} loop.
12227
12228@item
12229Write a function similar to @code{triangle} that multiplies instead of
12230adds the values.
12231
12232@item
12233Rewrite these two functions recursively. Rewrite these functions
12234using @code{cond}.
12235
12236@c comma in printed title causes problem in Info cross reference
12237@item
12238Write a function for Texinfo mode that creates an index entry at the
12239beginning of a paragraph for every @samp{@@dfn} within the paragraph.
12240(In a Texinfo file, @samp{@@dfn} marks a definition. This book is
12241written in Texinfo.)
12242
12243Many of the functions you will need are described in two of the
12244previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
12245Text}, and @ref{Yanking, , Yanking Text Back}. If you use
12246@code{forward-paragraph} to put the index entry at the beginning of
12247the paragraph, you will have to use @w{@kbd{C-h f}}
12248(@code{describe-function}) to find out how to make the command go
12249backwards.
12250
12251For more information, see
12252@ifinfo
12253@ref{Indicating, , Indicating Definitions, texinfo}.
12254@end ifinfo
12255@ifhtml
12256@ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
12257a Texinfo manual in the current directory. Or, if you are on the
12258Internet, see
12259@uref{http://www.gnu.org/software/texinfo/manual/texinfo/}
12260@end ifhtml
12261@iftex
12262``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
12263Documentation Format}.
12264@end iftex
12265@end itemize
12266
d6adf7e7 12267@node Regexp Search
8cda6f8f
GM
12268@chapter Regular Expression Searches
12269@cindex Searches, illustrating
12270@cindex Regular expression searches
12271@cindex Patterns, searching for
12272@cindex Motion by sentence and paragraph
12273@cindex Sentences, movement by
12274@cindex Paragraphs, movement by
12275
12276Regular expression searches are used extensively in GNU Emacs. The
12277two functions, @code{forward-sentence} and @code{forward-paragraph},
12278illustrate these searches well. They use regular expressions to find
12279where to move point. The phrase `regular expression' is often written
12280as `regexp'.
12281
12282Regular expression searches are described in @ref{Regexp Search, ,
12283Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
12284@ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
12285Manual}. In writing this chapter, I am presuming that you have at
12286least a mild acquaintance with them. The major point to remember is
12287that regular expressions permit you to search for patterns as well as
12288for literal strings of characters. For example, the code in
12289@code{forward-sentence} searches for the pattern of possible
12290characters that could mark the end of a sentence, and moves point to
12291that spot.
12292
12293Before looking at the code for the @code{forward-sentence} function, it
12294is worth considering what the pattern that marks the end of a sentence
12295must be. The pattern is discussed in the next section; following that
12296is a description of the regular expression search function,
12297@code{re-search-forward}. The @code{forward-sentence} function
12298is described in the section following. Finally, the
12299@code{forward-paragraph} function is described in the last section of
12300this chapter. @code{forward-paragraph} is a complex function that
12301introduces several new features.
12302
12303@menu
12304* sentence-end:: The regular expression for @code{sentence-end}.
12305* re-search-forward:: Very similar to @code{search-forward}.
12306* forward-sentence:: A straightforward example of regexp search.
12307* forward-paragraph:: A somewhat complex example.
12308* etags:: How to create your own @file{TAGS} table.
12309* Regexp Review::
12310* re-search Exercises::
12311@end menu
12312
d6adf7e7 12313@node sentence-end
8cda6f8f
GM
12314@section The Regular Expression for @code{sentence-end}
12315@findex sentence-end
12316
12317The symbol @code{sentence-end} is bound to the pattern that marks the
12318end of a sentence. What should this regular expression be?
12319
12320Clearly, a sentence may be ended by a period, a question mark, or an
12321exclamation mark. Indeed, in English, only clauses that end with one
12322of those three characters should be considered the end of a sentence.
12323This means that the pattern should include the character set:
12324
12325@smallexample
12326[.?!]
12327@end smallexample
12328
12329However, we do not want @code{forward-sentence} merely to jump to a
12330period, a question mark, or an exclamation mark, because such a character
12331might be used in the middle of a sentence. A period, for example, is
12332used after abbreviations. So other information is needed.
12333
12334According to convention, you type two spaces after every sentence, but
12335only one space after a period, a question mark, or an exclamation mark in
12336the body of a sentence. So a period, a question mark, or an exclamation
12337mark followed by two spaces is a good indicator of an end of sentence.
12338However, in a file, the two spaces may instead be a tab or the end of a
12339line. This means that the regular expression should include these three
12340items as alternatives.
12341
12342@need 800
12343This group of alternatives will look like this:
12344
12345@smallexample
12346@group
12347\\($\\| \\| \\)
12348 ^ ^^
12349 TAB SPC
12350@end group
12351@end smallexample
12352
12353@noindent
12354Here, @samp{$} indicates the end of the line, and I have pointed out
12355where the tab and two spaces are inserted in the expression. Both are
12356inserted by putting the actual characters into the expression.
12357
12358Two backslashes, @samp{\\}, are required before the parentheses and
12359vertical bars: the first backslash quotes the following backslash in
12360Emacs; and the second indicates that the following character, the
12361parenthesis or the vertical bar, is special.
12362
12363@need 1000
12364Also, a sentence may be followed by one or more carriage returns, like
12365this:
12366
12367@smallexample
12368@group
12369[
12370]*
12371@end group
12372@end smallexample
12373
12374@noindent
12375Like tabs and spaces, a carriage return is inserted into a regular
12376expression by inserting it literally. The asterisk indicates that the
12377@key{RET} is repeated zero or more times.
12378
12379But a sentence end does not consist only of a period, a question mark or
12380an exclamation mark followed by appropriate space: a closing quotation
12381mark or a closing brace of some kind may precede the space. Indeed more
12382than one such mark or brace may precede the space. These require a
12383expression that looks like this:
12384
12385@smallexample
12386[]\"')@}]*
12387@end smallexample
12388
12389In this expression, the first @samp{]} is the first character in the
12390expression; the second character is @samp{"}, which is preceded by a
12391@samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
12392three characters are @samp{'}, @samp{)}, and @samp{@}}.
12393
12394All this suggests what the regular expression pattern for matching the
12395end of a sentence should be; and, indeed, if we evaluate
12396@code{sentence-end} we find that it returns the following value:
12397
12398@smallexample
12399@group
12400sentence-end
12401 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
12402]*"
12403@end group
12404@end smallexample
12405
12406@noindent
12407(Well, not in GNU Emacs 22; that is because of an effort to make the
12408process simpler and to handle more glyphs and languages. When the
12409value of @code{sentence-end} is @code{nil}, then use the value defined
12410by the function @code{sentence-end}. (Here is a use of the difference
12411between a value and a function in Emacs Lisp.) The function returns a
12412value constructed from the variables @code{sentence-end-base},
12413@code{sentence-end-double-space}, @code{sentence-end-without-period},
12414and @code{sentence-end-without-space}. The critical variable is
12415@code{sentence-end-base}; its global value is similar to the one
12416described above but it also contains two additional quotation marks.
12417These have differing degrees of curliness. The
12418@code{sentence-end-without-period} variable, when true, tells Emacs
12419that a sentence may end without a period, such as text in Thai.)
12420
12421@ignore
12422@noindent
12423(Note that here the @key{TAB}, two spaces, and @key{RET} are shown
12424literally in the pattern.)
12425
12426This regular expression can be deciphered as follows:
12427
12428@table @code
12429@item [.?!]
12430The first part of the pattern is the three characters, a period, a question
12431mark and an exclamation mark, within square brackets. The pattern must
12432begin with one or other of these characters.
12433
12434@item []\"')@}]*
12435The second part of the pattern is the group of closing braces and
12436quotation marks, which can appear zero or more times. These may follow
12437the period, question mark or exclamation mark. In a regular expression,
12438the backslash, @samp{\}, followed by the double quotation mark,
12439@samp{"}, indicates the class of string-quote characters. Usually, the
12440double quotation mark is the only character in this class. The
12441asterisk, @samp{*}, indicates that the items in the previous group (the
12442group surrounded by square brackets, @samp{[]}) may be repeated zero or
12443more times.
12444
12445@item \\($\\| \\| \\)
12446The third part of the pattern is one or other of: either the end of a
12447line, or two blank spaces, or a tab. The double back-slashes are used
12448to prevent Emacs from reading the parentheses and vertical bars as part
12449of the search pattern; the parentheses are used to mark the group and
12450the vertical bars are used to indicated that the patterns to either side
12451of them are alternatives. The dollar sign is used to indicate the end
12452of a line and both the two spaces and the tab are each inserted as is to
12453indicate what they are.
12454
12455@item [@key{RET}]*
12456Finally, the last part of the pattern indicates that the end of the line
12457or the whitespace following the period, question mark or exclamation
12458mark may, but need not, be followed by one or more carriage returns. In
12459the pattern, the carriage return is inserted as an actual carriage
12460return between square brackets but here it is shown as @key{RET}.
12461@end table
12462@end ignore
12463
d6adf7e7 12464@node re-search-forward
8cda6f8f
GM
12465@section The @code{re-search-forward} Function
12466@findex re-search-forward
12467
12468The @code{re-search-forward} function is very like the
12469@code{search-forward} function. (@xref{search-forward, , The
12470@code{search-forward} Function}.)
12471
12472@code{re-search-forward} searches for a regular expression. If the
12473search is successful, it leaves point immediately after the last
12474character in the target. If the search is backwards, it leaves point
12475just before the first character in the target. You may tell
12476@code{re-search-forward} to return @code{t} for true. (Moving point
12477is therefore a `side effect'.)
12478
12479Like @code{search-forward}, the @code{re-search-forward} function takes
12480four arguments:
12481
12482@enumerate
12483@item
12484The first argument is the regular expression that the function searches
7b4b1301 12485for. The regular expression will be a string between quotation marks.
8cda6f8f
GM
12486
12487@item
12488The optional second argument limits how far the function will search; it is a
12489bound, which is specified as a position in the buffer.
12490
12491@item
12492The optional third argument specifies how the function responds to
12493failure: @code{nil} as the third argument causes the function to
12494signal an error (and print a message) when the search fails; any other
12495value causes it to return @code{nil} if the search fails and @code{t}
12496if the search succeeds.
12497
12498@item
12499The optional fourth argument is the repeat count. A negative repeat
12500count causes @code{re-search-forward} to search backwards.
12501@end enumerate
12502
12503@need 800
12504The template for @code{re-search-forward} looks like this:
12505
12506@smallexample
12507@group
12508(re-search-forward "@var{regular-expression}"
12509 @var{limit-of-search}
12510 @var{what-to-do-if-search-fails}
12511 @var{repeat-count})
12512@end group
12513@end smallexample
12514
12515The second, third, and fourth arguments are optional. However, if you
12516want to pass a value to either or both of the last two arguments, you
12517must also pass a value to all the preceding arguments. Otherwise, the
12518Lisp interpreter will mistake which argument you are passing the value
12519to.
12520
12521@need 1200
12522In the @code{forward-sentence} function, the regular expression will be
12523the value of the variable @code{sentence-end}. In simple form, that is:
12524
12525@smallexample
12526@group
12527"[.?!][]\"')@}]*\\($\\| \\| \\)[
12528]*"
12529@end group
12530@end smallexample
12531
12532@noindent
12533The limit of the search will be the end of the paragraph (since a
12534sentence cannot go beyond a paragraph). If the search fails, the
12535function will return @code{nil}; and the repeat count will be provided
12536by the argument to the @code{forward-sentence} function.
12537
d6adf7e7 12538@node forward-sentence
8cda6f8f
GM
12539@section @code{forward-sentence}
12540@findex forward-sentence
12541
12542The command to move the cursor forward a sentence is a straightforward
12543illustration of how to use regular expression searches in Emacs Lisp.
12544Indeed, the function looks longer and more complicated than it is; this
12545is because the function is designed to go backwards as well as forwards;
12546and, optionally, over more than one sentence. The function is usually
12547bound to the key command @kbd{M-e}.
12548
12549@menu
12550* Complete forward-sentence::
12551* fwd-sentence while loops:: Two @code{while} loops.
12552* fwd-sentence re-search:: A regular expression search.
12553@end menu
12554
8cda6f8f 12555@ifnottex
d6adf7e7 12556@node Complete forward-sentence
8cda6f8f
GM
12557@unnumberedsubsec Complete @code{forward-sentence} function definition
12558@end ifnottex
12559
12560@need 1250
12561Here is the code for @code{forward-sentence}:
12562
12563@c in GNU Emacs 22
12564@smallexample
12565@group
12566(defun forward-sentence (&optional arg)
12567 "Move forward to next `sentence-end'. With argument, repeat.
12568With negative argument, move backward repeatedly to `sentence-beginning'.
12569
12570The variable `sentence-end' is a regular expression that matches ends of
12571sentences. Also, every paragraph boundary terminates sentences as well."
12572@end group
12573@group
12574 (interactive "p")
12575 (or arg (setq arg 1))
12576 (let ((opoint (point))
12577 (sentence-end (sentence-end)))
12578 (while (< arg 0)
12579 (let ((pos (point))
12580 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12581 (if (and (re-search-backward sentence-end par-beg t)
12582 (or (< (match-end 0) pos)
12583 (re-search-backward sentence-end par-beg t)))
12584 (goto-char (match-end 0))
12585 (goto-char par-beg)))
12586 (setq arg (1+ arg)))
12587@end group
12588@group
12589 (while (> arg 0)
12590 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12591 (if (re-search-forward sentence-end par-end t)
12592 (skip-chars-backward " \t\n")
12593 (goto-char par-end)))
12594 (setq arg (1- arg)))
12595 (constrain-to-field nil opoint t)))
12596@end group
12597@end smallexample
12598
12599@ignore
12600GNU Emacs 21
12601@smallexample
12602@group
12603(defun forward-sentence (&optional arg)
12604 "Move forward to next sentence-end. With argument, repeat.
12605With negative argument, move backward repeatedly to sentence-beginning.
12606Sentence ends are identified by the value of sentence-end
12607treated as a regular expression. Also, every paragraph boundary
12608terminates sentences as well."
12609@end group
12610@group
12611 (interactive "p")
12612 (or arg (setq arg 1))
12613 (while (< arg 0)
12614 (let ((par-beg
12615 (save-excursion (start-of-paragraph-text) (point))))
12616 (if (re-search-backward
12617 (concat sentence-end "[^ \t\n]") par-beg t)
12618 (goto-char (1- (match-end 0)))
12619 (goto-char par-beg)))
12620 (setq arg (1+ arg)))
12621 (while (> arg 0)
12622 (let ((par-end
12623 (save-excursion (end-of-paragraph-text) (point))))
12624 (if (re-search-forward sentence-end par-end t)
12625 (skip-chars-backward " \t\n")
12626 (goto-char par-end)))
12627 (setq arg (1- arg))))
12628@end group
12629@end smallexample
12630@end ignore
12631
12632The function looks long at first sight and it is best to look at its
12633skeleton first, and then its muscle. The way to see the skeleton is to
12634look at the expressions that start in the left-most columns:
12635
12636@smallexample
12637@group
12638(defun forward-sentence (&optional arg)
12639 "@var{documentation}@dots{}"
12640 (interactive "p")
12641 (or arg (setq arg 1))
12642 (let ((opoint (point)) (sentence-end (sentence-end)))
12643 (while (< arg 0)
12644 (let ((pos (point))
12645 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12646 @var{rest-of-body-of-while-loop-when-going-backwards}
12647 (while (> arg 0)
12648 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12649 @var{rest-of-body-of-while-loop-when-going-forwards}
12650 @var{handle-forms-and-equivalent}
12651@end group
12652@end smallexample
12653
12654This looks much simpler! The function definition consists of
12655documentation, an @code{interactive} expression, an @code{or}
12656expression, a @code{let} expression, and @code{while} loops.
12657
12658Let's look at each of these parts in turn.
12659
12660We note that the documentation is thorough and understandable.
12661
12662The function has an @code{interactive "p"} declaration. This means
12663that the processed prefix argument, if any, is passed to the
12664function as its argument. (This will be a number.) If the function
12665is not passed an argument (it is optional) then the argument
12666@code{arg} will be bound to 1.
12667
12668When @code{forward-sentence} is called non-interactively without an
12669argument, @code{arg} is bound to @code{nil}. The @code{or} expression
12670handles this. What it does is either leave the value of @code{arg} as
12671it is, but only if @code{arg} is bound to a value; or it sets the
12672value of @code{arg} to 1, in the case when @code{arg} is bound to
12673@code{nil}.
12674
12675Next is a @code{let}. That specifies the values of two local
12676variables, @code{point} and @code{sentence-end}. The local value of
12677point, from before the search, is used in the
12678@code{constrain-to-field} function which handles forms and
12679equivalents. The @code{sentence-end} variable is set by the
12680@code{sentence-end} function.
12681
d6adf7e7 12682@node fwd-sentence while loops
8cda6f8f
GM
12683@unnumberedsubsec The @code{while} loops
12684
12685Two @code{while} loops follow. The first @code{while} has a
12686true-or-false-test that tests true if the prefix argument for
12687@code{forward-sentence} is a negative number. This is for going
12688backwards. The body of this loop is similar to the body of the second
12689@code{while} clause, but it is not exactly the same. We will skip
12690this @code{while} loop and concentrate on the second @code{while}
12691loop.
12692
12693@need 1500
12694The second @code{while} loop is for moving point forward. Its skeleton
12695looks like this:
12696
12697@smallexample
12698@group
12699(while (> arg 0) ; @r{true-or-false-test}
12700 (let @var{varlist}
12701 (if (@var{true-or-false-test})
12702 @var{then-part}
12703 @var{else-part}
12704 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
12705@end group
12706@end smallexample
12707
12708The @code{while} loop is of the decrementing kind.
12709(@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
12710has a true-or-false-test that tests true so long as the counter (in
12711this case, the variable @code{arg}) is greater than zero; and it has a
12712decrementer that subtracts 1 from the value of the counter every time
12713the loop repeats.
12714
12715If no prefix argument is given to @code{forward-sentence}, which is
12716the most common way the command is used, this @code{while} loop will
12717run once, since the value of @code{arg} will be 1.
12718
12719The body of the @code{while} loop consists of a @code{let} expression,
12720which creates and binds a local variable, and has, as its body, an
12721@code{if} expression.
12722
12723@need 1250
12724The body of the @code{while} loop looks like this:
12725
12726@smallexample
12727@group
12728(let ((par-end
12729 (save-excursion (end-of-paragraph-text) (point))))
12730 (if (re-search-forward sentence-end par-end t)
12731 (skip-chars-backward " \t\n")
12732 (goto-char par-end)))
12733@end group
12734@end smallexample
12735
12736The @code{let} expression creates and binds the local variable
12737@code{par-end}. As we shall see, this local variable is designed to
12738provide a bound or limit to the regular expression search. If the
12739search fails to find a proper sentence ending in the paragraph, it will
12740stop on reaching the end of the paragraph.
12741
12742But first, let us examine how @code{par-end} is bound to the value of
12743the end of the paragraph. What happens is that the @code{let} sets the
12744value of @code{par-end} to the value returned when the Lisp interpreter
12745evaluates the expression
12746
12747@smallexample
12748@group
12749(save-excursion (end-of-paragraph-text) (point))
12750@end group
12751@end smallexample
12752
12753@noindent
12754In this expression, @code{(end-of-paragraph-text)} moves point to the
12755end of the paragraph, @code{(point)} returns the value of point, and then
12756@code{save-excursion} restores point to its original position. Thus,
12757the @code{let} binds @code{par-end} to the value returned by the
12758@code{save-excursion} expression, which is the position of the end of
12759the paragraph. (The @code{end-of-paragraph-text} function uses
12760@code{forward-paragraph}, which we will discuss shortly.)
12761
12762@need 1200
12763Emacs next evaluates the body of the @code{let}, which is an @code{if}
12764expression that looks like this:
12765
12766@smallexample
12767@group
12768(if (re-search-forward sentence-end par-end t) ; @r{if-part}
12769 (skip-chars-backward " \t\n") ; @r{then-part}
12770 (goto-char par-end))) ; @r{else-part}
12771@end group
12772@end smallexample
12773
12774The @code{if} tests whether its first argument is true and if so,
12775evaluates its then-part; otherwise, the Emacs Lisp interpreter
12776evaluates the else-part. The true-or-false-test of the @code{if}
12777expression is the regular expression search.
12778
12779It may seem odd to have what looks like the `real work' of
12780the @code{forward-sentence} function buried here, but this is a common
12781way this kind of operation is carried out in Lisp.
12782
d6adf7e7 12783@node fwd-sentence re-search
8cda6f8f
GM
12784@unnumberedsubsec The regular expression search
12785
12786The @code{re-search-forward} function searches for the end of the
12787sentence, that is, for the pattern defined by the @code{sentence-end}
12788regular expression. If the pattern is found---if the end of the sentence is
12789found---then the @code{re-search-forward} function does two things:
12790
12791@enumerate
12792@item
12793The @code{re-search-forward} function carries out a side effect, which
12794is to move point to the end of the occurrence found.
12795
12796@item
12797The @code{re-search-forward} function returns a value of true. This is
12798the value received by the @code{if}, and means that the search was
12799successful.
12800@end enumerate
12801
12802@noindent
12803The side effect, the movement of point, is completed before the
12804@code{if} function is handed the value returned by the successful
12805conclusion of the search.
12806
12807When the @code{if} function receives the value of true from a successful
12808call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12809which is the expression @code{(skip-chars-backward " \t\n")}. This
12810expression moves backwards over any blank spaces, tabs or carriage
12811returns until a printed character is found and then leaves point after
12812the character. Since point has already been moved to the end of the
12813pattern that marks the end of the sentence, this action leaves point
12814right after the closing printed character of the sentence, which is
12815usually a period.
12816
12817On the other hand, if the @code{re-search-forward} function fails to
12818find a pattern marking the end of the sentence, the function returns
12819false. The false then causes the @code{if} to evaluate its third
12820argument, which is @code{(goto-char par-end)}: it moves point to the
12821end of the paragraph.
12822
12823(And if the text is in a form or equivalent, and point may not move
12824fully, then the @code{constrain-to-field} function comes into play.)
12825
12826Regular expression searches are exceptionally useful and the pattern
12827illustrated by @code{re-search-forward}, in which the search is the
12828test of an @code{if} expression, is handy. You will see or write code
12829incorporating this pattern often.
12830
d6adf7e7 12831@node forward-paragraph
8cda6f8f
GM
12832@section @code{forward-paragraph}: a Goldmine of Functions
12833@findex forward-paragraph
12834
12835@ignore
12836@c in GNU Emacs 22
12837(defun forward-paragraph (&optional arg)
12838 "Move forward to end of paragraph.
12839With argument ARG, do it ARG times;
12840a negative argument ARG = -N means move backward N paragraphs.
12841
12842A line which `paragraph-start' matches either separates paragraphs
12843\(if `paragraph-separate' matches it also) or is the first line of a paragraph.
12844A paragraph end is the beginning of a line which is not part of the paragraph
12845to which the end of the previous line belongs, or the end of the buffer.
12846Returns the count of paragraphs left to move."
12847 (interactive "p")
12848 (or arg (setq arg 1))
12849 (let* ((opoint (point))
12850 (fill-prefix-regexp
12851 (and fill-prefix (not (equal fill-prefix ""))
12852 (not paragraph-ignore-fill-prefix)
12853 (regexp-quote fill-prefix)))
12854 ;; Remove ^ from paragraph-start and paragraph-sep if they are there.
12855 ;; These regexps shouldn't be anchored, because we look for them
12856 ;; starting at the left-margin. This allows paragraph commands to
12857 ;; work normally with indented text.
12858 ;; This hack will not find problem cases like "whatever\\|^something".
12859 (parstart (if (and (not (equal "" paragraph-start))
12860 (equal ?^ (aref paragraph-start 0)))
12861 (substring paragraph-start 1)
12862 paragraph-start))
12863 (parsep (if (and (not (equal "" paragraph-separate))
12864 (equal ?^ (aref paragraph-separate 0)))
12865 (substring paragraph-separate 1)
12866 paragraph-separate))
12867 (parsep
12868 (if fill-prefix-regexp
12869 (concat parsep "\\|"
12870 fill-prefix-regexp "[ \t]*$")
12871 parsep))
12872 ;; This is used for searching.
12873 (sp-parstart (concat "^[ \t]*\\(?:" parstart "\\|" parsep "\\)"))
12874 start found-start)
12875 (while (and (< arg 0) (not (bobp)))
12876 (if (and (not (looking-at parsep))
12877 (re-search-backward "^\n" (max (1- (point)) (point-min)) t)
12878 (looking-at parsep))
12879 (setq arg (1+ arg))
12880 (setq start (point))
12881 ;; Move back over paragraph-separating lines.
12882 (forward-char -1) (beginning-of-line)
12883 (while (and (not (bobp))
12884 (progn (move-to-left-margin)
12885 (looking-at parsep)))
12886 (forward-line -1))
12887 (if (bobp)
12888 nil
12889 (setq arg (1+ arg))
12890 ;; Go to end of the previous (non-separating) line.
12891 (end-of-line)
12892 ;; Search back for line that starts or separates paragraphs.
12893 (if (if fill-prefix-regexp
12894 ;; There is a fill prefix; it overrides parstart.
12895 (let (multiple-lines)
12896 (while (and (progn (beginning-of-line) (not (bobp)))
12897 (progn (move-to-left-margin)
12898 (not (looking-at parsep)))
12899 (looking-at fill-prefix-regexp))
12900 (unless (= (point) start)
12901 (setq multiple-lines t))
12902 (forward-line -1))
12903 (move-to-left-margin)
12904 ;; This deleted code caused a long hanging-indent line
12905 ;; not to be filled together with the following lines.
12906 ;; ;; Don't move back over a line before the paragraph
12907 ;; ;; which doesn't start with fill-prefix
12908 ;; ;; unless that is the only line we've moved over.
12909 ;; (and (not (looking-at fill-prefix-regexp))
12910 ;; multiple-lines
12911 ;; (forward-line 1))
12912 (not (bobp)))
12913 (while (and (re-search-backward sp-parstart nil 1)
12914 (setq found-start t)
12915 ;; Found a candidate, but need to check if it is a
12916 ;; REAL parstart.
12917 (progn (setq start (point))
12918 (move-to-left-margin)
12919 (not (looking-at parsep)))
12920 (not (and (looking-at parstart)
12921 (or (not use-hard-newlines)
12922 (bobp)
12923 (get-text-property
12924 (1- start) 'hard)))))
12925 (setq found-start nil)
12926 (goto-char start))
12927 found-start)
12928 ;; Found one.
12929 (progn
12930 ;; Move forward over paragraph separators.
12931 ;; We know this cannot reach the place we started
12932 ;; because we know we moved back over a non-separator.
12933 (while (and (not (eobp))
12934 (progn (move-to-left-margin)
12935 (looking-at parsep)))
12936 (forward-line 1))
12937 ;; If line before paragraph is just margin, back up to there.
12938 (end-of-line 0)
12939 (if (> (current-column) (current-left-margin))
12940 (forward-char 1)
12941 (skip-chars-backward " \t")
12942 (if (not (bolp))
12943 (forward-line 1))))
12944 ;; No starter or separator line => use buffer beg.
12945 (goto-char (point-min))))))
12946
12947 (while (and (> arg 0) (not (eobp)))
12948 ;; Move forward over separator lines...
12949 (while (and (not (eobp))
12950 (progn (move-to-left-margin) (not (eobp)))
12951 (looking-at parsep))
12952 (forward-line 1))
12953 (unless (eobp) (setq arg (1- arg)))
12954 ;; ... and one more line.
12955 (forward-line 1)
12956 (if fill-prefix-regexp
12957 ;; There is a fill prefix; it overrides parstart.
12958 (while (and (not (eobp))
12959 (progn (move-to-left-margin) (not (eobp)))
12960 (not (looking-at parsep))
12961 (looking-at fill-prefix-regexp))
12962 (forward-line 1))
12963 (while (and (re-search-forward sp-parstart nil 1)
12964 (progn (setq start (match-beginning 0))
12965 (goto-char start)
12966 (not (eobp)))
12967 (progn (move-to-left-margin)
12968 (not (looking-at parsep)))
12969 (or (not (looking-at parstart))
12970 (and use-hard-newlines
12971 (not (get-text-property (1- start) 'hard)))))
12972 (forward-char 1))
12973 (if (< (point) (point-max))
12974 (goto-char start))))
12975 (constrain-to-field nil opoint t)
12976 ;; Return the number of steps that could not be done.
12977 arg))
12978@end ignore
12979
12980The @code{forward-paragraph} function moves point forward to the end
12981of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12982number of functions that are important in themselves, including
12983@code{let*}, @code{match-beginning}, and @code{looking-at}.
12984
12985The function definition for @code{forward-paragraph} is considerably
12986longer than the function definition for @code{forward-sentence}
12987because it works with a paragraph, each line of which may begin with a
12988fill prefix.
12989
12990A fill prefix consists of a string of characters that are repeated at
12991the beginning of each line. For example, in Lisp code, it is a
12992convention to start each line of a paragraph-long comment with
12993@samp{;;; }. In Text mode, four blank spaces make up another common
12994fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
12995emacs, The GNU Emacs Manual}, for more information about fill
12996prefixes.)
12997
12998The existence of a fill prefix means that in addition to being able to
12999find the end of a paragraph whose lines begin on the left-most
13000column, the @code{forward-paragraph} function must be able to find the
13001end of a paragraph when all or many of the lines in the buffer begin
13002with the fill prefix.
13003
13004Moreover, it is sometimes practical to ignore a fill prefix that
13005exists, especially when blank lines separate paragraphs.
13006This is an added complication.
13007
13008@menu
13009* forward-paragraph in brief:: Key parts of the function definition.
13010* fwd-para let:: The @code{let*} expression.
13011* fwd-para while:: The forward motion @code{while} loop.
13012@end menu
13013
8cda6f8f 13014@ifnottex
d6adf7e7 13015@node forward-paragraph in brief
8cda6f8f
GM
13016@unnumberedsubsec Shortened @code{forward-paragraph} function definition
13017@end ifnottex
13018
13019Rather than print all of the @code{forward-paragraph} function, we
13020will only print parts of it. Read without preparation, the function
13021can be daunting!
13022
13023@need 800
13024In outline, the function looks like this:
13025
13026@smallexample
13027@group
13028(defun forward-paragraph (&optional arg)
13029 "@var{documentation}@dots{}"
13030 (interactive "p")
13031 (or arg (setq arg 1))
13032 (let*
13033 @var{varlist}
13034 (while (and (< arg 0) (not (bobp))) ; @r{backward-moving-code}
13035 @dots{}
13036 (while (and (> arg 0) (not (eobp))) ; @r{forward-moving-code}
13037 @dots{}
13038@end group
13039@end smallexample
13040
13041The first parts of the function are routine: the function's argument
13042list consists of one optional argument. Documentation follows.
13043
13044The lower case @samp{p} in the @code{interactive} declaration means
13045that the processed prefix argument, if any, is passed to the function.
13046This will be a number, and is the repeat count of how many paragraphs
13047point will move. The @code{or} expression in the next line handles
13048the common case when no argument is passed to the function, which occurs
13049if the function is called from other code rather than interactively.
13050This case was described earlier. (@xref{forward-sentence, The
13051@code{forward-sentence} function}.) Now we reach the end of the
13052familiar part of this function.
13053
d6adf7e7 13054@node fwd-para let
8cda6f8f
GM
13055@unnumberedsubsec The @code{let*} expression
13056
13057The next line of the @code{forward-paragraph} function begins a
13058@code{let*} expression. This is a different than @code{let}. The
13059symbol is @code{let*} not @code{let}.
13060
13061The @code{let*} special form is like @code{let} except that Emacs sets
13062each variable in sequence, one after another, and variables in the
13063latter part of the varlist can make use of the values to which Emacs
13064set variables in the earlier part of the varlist.
13065
13066@ignore
13067( refappend save-excursion, , code save-excursion in code append-to-buffer .)
13068@end ignore
13069
13070(@ref{append save-excursion, , @code{save-excursion} in @code{append-to-buffer}}.)
13071
13072In the @code{let*} expression in this function, Emacs binds a total of
13073seven variables: @code{opoint}, @code{fill-prefix-regexp},
13074@code{parstart}, @code{parsep}, @code{sp-parstart}, @code{start}, and
13075@code{found-start}.
13076
13077The variable @code{parsep} appears twice, first, to remove instances
13078of @samp{^}, and second, to handle fill prefixes.
13079
13080The variable @code{opoint} is just the value of @code{point}. As you
13081can guess, it is used in a @code{constrain-to-field} expression, just
13082as in @code{forward-sentence}.
13083
13084The variable @code{fill-prefix-regexp} is set to the value returned by
13085evaluating the following list:
13086
13087@smallexample
13088@group
13089(and fill-prefix
13090 (not (equal fill-prefix ""))
13091 (not paragraph-ignore-fill-prefix)
13092 (regexp-quote fill-prefix))
13093@end group
13094@end smallexample
13095
13096@noindent
13097This is an expression whose first element is the @code{and} special form.
13098
13099As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
13100function}), the @code{and} special form evaluates each of its
13101arguments until one of the arguments returns a value of @code{nil}, in
13102which case the @code{and} expression returns @code{nil}; however, if
13103none of the arguments returns a value of @code{nil}, the value
13104resulting from evaluating the last argument is returned. (Since such
13105a value is not @code{nil}, it is considered true in Lisp.) In other
13106words, an @code{and} expression returns a true value only if all its
13107arguments are true.
13108@findex and
13109
13110In this case, the variable @code{fill-prefix-regexp} is bound to a
13111non-@code{nil} value only if the following four expressions produce a
13112true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
13113@code{fill-prefix-regexp} is bound to @code{nil}.
13114
13115@table @code
13116@item fill-prefix
13117When this variable is evaluated, the value of the fill prefix, if any,
13118is returned. If there is no fill prefix, this variable returns
13119@code{nil}.
13120
13121@item (not (equal fill-prefix "")
13122This expression checks whether an existing fill prefix is an empty
13123string, that is, a string with no characters in it. An empty string is
13124not a useful fill prefix.
13125
13126@item (not paragraph-ignore-fill-prefix)
13127This expression returns @code{nil} if the variable
13128@code{paragraph-ignore-fill-prefix} has been turned on by being set to a
13129true value such as @code{t}.
13130
13131@item (regexp-quote fill-prefix)
13132This is the last argument to the @code{and} special form. If all the
13133arguments to the @code{and} are true, the value resulting from
13134evaluating this expression will be returned by the @code{and} expression
13135and bound to the variable @code{fill-prefix-regexp},
13136@end table
13137
13138@findex regexp-quote
13139@noindent
13140The result of evaluating this @code{and} expression successfully is that
13141@code{fill-prefix-regexp} will be bound to the value of
13142@code{fill-prefix} as modified by the @code{regexp-quote} function.
13143What @code{regexp-quote} does is read a string and return a regular
13144expression that will exactly match the string and match nothing else.
13145This means that @code{fill-prefix-regexp} will be set to a value that
13146will exactly match the fill prefix if the fill prefix exists.
13147Otherwise, the variable will be set to @code{nil}.
13148
13149The next two local variables in the @code{let*} expression are
13150designed to remove instances of @samp{^} from @code{parstart} and
13151@code{parsep}, the local variables which indicate the paragraph start
13152and the paragraph separator. The next expression sets @code{parsep}
13153again. That is to handle fill prefixes.
13154
13155This is the setting that requires the definition call @code{let*}
13156rather than @code{let}. The true-or-false-test for the @code{if}
13157depends on whether the variable @code{fill-prefix-regexp} evaluates to
13158@code{nil} or some other value.
13159
13160If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
13161the else-part of the @code{if} expression and binds @code{parsep} to
13162its local value. (@code{parsep} is a regular expression that matches
13163what separates paragraphs.)
13164
13165But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
13166the then-part of the @code{if} expression and binds @code{parsep} to a
13167regular expression that includes the @code{fill-prefix-regexp} as part
13168of the pattern.
13169
13170Specifically, @code{parsep} is set to the original value of the
13171paragraph separate regular expression concatenated with an alternative
13172expression that consists of the @code{fill-prefix-regexp} followed by
13173optional whitespace to the end of the line. The whitespace is defined
13174by @w{@code{"[ \t]*$"}}.) The @samp{\\|} defines this portion of the
13175regexp as an alternative to @code{parsep}.
13176
13177According to a comment in the code, the next local variable,
13178@code{sp-parstart}, is used for searching, and then the final two,
13179@code{start} and @code{found-start}, are set to @code{nil}.
13180
13181Now we get into the body of the @code{let*}. The first part of the body
13182of the @code{let*} deals with the case when the function is given a
13183negative argument and is therefore moving backwards. We will skip this
13184section.
13185
d6adf7e7 13186@node fwd-para while
8cda6f8f
GM
13187@unnumberedsubsec The forward motion @code{while} loop
13188
13189The second part of the body of the @code{let*} deals with forward
13190motion. It is a @code{while} loop that repeats itself so long as the
13191value of @code{arg} is greater than zero. In the most common use of
13192the function, the value of the argument is 1, so the body of the
13193@code{while} loop is evaluated exactly once, and the cursor moves
13194forward one paragraph.
13195
13196@ignore
13197(while (and (> arg 0) (not (eobp)))
13198
13199 ;; Move forward over separator lines...
13200 (while (and (not (eobp))
13201 (progn (move-to-left-margin) (not (eobp)))
13202 (looking-at parsep))
13203 (forward-line 1))
13204 (unless (eobp) (setq arg (1- arg)))
13205 ;; ... and one more line.
13206 (forward-line 1)
13207
13208 (if fill-prefix-regexp
13209 ;; There is a fill prefix; it overrides parstart.
13210 (while (and (not (eobp))
13211 (progn (move-to-left-margin) (not (eobp)))
13212 (not (looking-at parsep))
13213 (looking-at fill-prefix-regexp))
13214 (forward-line 1))
13215
13216 (while (and (re-search-forward sp-parstart nil 1)
13217 (progn (setq start (match-beginning 0))
13218 (goto-char start)
13219 (not (eobp)))
13220 (progn (move-to-left-margin)
13221 (not (looking-at parsep)))
13222 (or (not (looking-at parstart))
13223 (and use-hard-newlines
13224 (not (get-text-property (1- start) 'hard)))))
13225 (forward-char 1))
13226
13227 (if (< (point) (point-max))
13228 (goto-char start))))
13229@end ignore
13230
13231This part handles three situations: when point is between paragraphs,
13232when there is a fill prefix and when there is no fill prefix.
13233
13234@need 800
13235The @code{while} loop looks like this:
13236
13237@smallexample
13238@group
13239;; @r{going forwards and not at the end of the buffer}
13240(while (and (> arg 0) (not (eobp)))
13241
13242 ;; @r{between paragraphs}
13243 ;; Move forward over separator lines...
13244 (while (and (not (eobp))
13245 (progn (move-to-left-margin) (not (eobp)))
13246 (looking-at parsep))
13247 (forward-line 1))
13248 ;; @r{This decrements the loop}
13249 (unless (eobp) (setq arg (1- arg)))
13250 ;; ... and one more line.
13251 (forward-line 1)
13252@end group
13253
13254@group
13255 (if fill-prefix-regexp
13256 ;; There is a fill prefix; it overrides parstart;
13257 ;; we go forward line by line
13258 (while (and (not (eobp))
13259 (progn (move-to-left-margin) (not (eobp)))
13260 (not (looking-at parsep))
13261 (looking-at fill-prefix-regexp))
13262 (forward-line 1))
13263@end group
13264
13265@group
13266 ;; There is no fill prefix;
13267 ;; we go forward character by character
13268 (while (and (re-search-forward sp-parstart nil 1)
13269 (progn (setq start (match-beginning 0))
13270 (goto-char start)
13271 (not (eobp)))
13272 (progn (move-to-left-margin)
13273 (not (looking-at parsep)))
13274 (or (not (looking-at parstart))
13275 (and use-hard-newlines
13276 (not (get-text-property (1- start) 'hard)))))
13277 (forward-char 1))
13278@end group
13279
13280@group
13281 ;; and if there is no fill prefix and if we are not at the end,
13282 ;; go to whatever was found in the regular expression search
13283 ;; for sp-parstart
13284 (if (< (point) (point-max))
13285 (goto-char start))))
13286@end group
13287@end smallexample
13288
13289@findex eobp
13290We can see that this is a decrementing counter @code{while} loop,
13291using the expression @code{(setq arg (1- arg))} as the decrementer.
13292That expression is not far from the @code{while}, but is hidden in
13293another Lisp macro, an @code{unless} macro. Unless we are at the end
f99f1641
PE
13294of the buffer---that is what the @code{eobp} function determines; it
13295is an abbreviation of @samp{End Of Buffer P}---we decrease the value
8cda6f8f
GM
13296of @code{arg} by one.
13297
13298(If we are at the end of the buffer, we cannot go forward any more and
13299the next loop of the @code{while} expression will test false since the
13300test is an @code{and} with @code{(not (eobp))}. The @code{not}
13301function means exactly as you expect; it is another name for
13302@code{null}, a function that returns true when its argument is false.)
13303
13304Interestingly, the loop count is not decremented until we leave the
13305space between paragraphs, unless we come to the end of buffer or stop
13306seeing the local value of the paragraph separator.
13307
13308That second @code{while} also has a @code{(move-to-left-margin)}
13309expression. The function is self-explanatory. It is inside a
13310@code{progn} expression and not the last element of its body, so it is
13311only invoked for its side effect, which is to move point to the left
13312margin of the current line.
13313
13314@findex looking-at
13315The @code{looking-at} function is also self-explanatory; it returns
13316true if the text after point matches the regular expression given as
13317its argument.
13318
13319The rest of the body of the loop looks difficult at first, but makes
13320sense as you come to understand it.
13321
13322@need 800
13323First consider what happens if there is a fill prefix:
13324
13325@smallexample
13326@group
13327 (if fill-prefix-regexp
13328 ;; There is a fill prefix; it overrides parstart;
13329 ;; we go forward line by line
13330 (while (and (not (eobp))
13331 (progn (move-to-left-margin) (not (eobp)))
13332 (not (looking-at parsep))
13333 (looking-at fill-prefix-regexp))
13334 (forward-line 1))
13335@end group
13336@end smallexample
13337
13338@noindent
13339This expression moves point forward line by line so long
13340as four conditions are true:
13341
13342@enumerate
13343@item
13344Point is not at the end of the buffer.
13345
13346@item
13347We can move to the left margin of the text and are
13348not at the end of the buffer.
13349
13350@item
13351The text following point does not separate paragraphs.
13352
13353@item
13354The pattern following point is the fill prefix regular expression.
13355@end enumerate
13356
13357The last condition may be puzzling, until you remember that point was
13358moved to the beginning of the line early in the @code{forward-paragraph}
13359function. This means that if the text has a fill prefix, the
13360@code{looking-at} function will see it.
13361
13362@need 1250
13363Consider what happens when there is no fill prefix.
13364
13365@smallexample
13366@group
13367 (while (and (re-search-forward sp-parstart nil 1)
13368 (progn (setq start (match-beginning 0))
13369 (goto-char start)
13370 (not (eobp)))
13371 (progn (move-to-left-margin)
13372 (not (looking-at parsep)))
13373 (or (not (looking-at parstart))
13374 (and use-hard-newlines
13375 (not (get-text-property (1- start) 'hard)))))
13376 (forward-char 1))
13377@end group
13378@end smallexample
13379
13380@noindent
13381This @code{while} loop has us searching forward for
13382@code{sp-parstart}, which is the combination of possible whitespace
13383with a the local value of the start of a paragraph or of a paragraph
13384separator. (The latter two are within an expression starting
13385@code{\(?:} so that they are not referenced by the
13386@code{match-beginning} function.)
13387
13388@need 800
13389The two expressions,
13390
13391@smallexample
13392@group
13393(setq start (match-beginning 0))
13394(goto-char start)
13395@end group
13396@end smallexample
13397
13398@noindent
13399mean go to the start of the text matched by the regular expression
13400search.
13401
13402The @code{(match-beginning 0)} expression is new. It returns a number
13403specifying the location of the start of the text that was matched by
13404the last search.
13405
13406The @code{match-beginning} function is used here because of a
13407characteristic of a forward search: a successful forward search,
13408regardless of whether it is a plain search or a regular expression
13409search, moves point to the end of the text that is found. In this
13410case, a successful search moves point to the end of the pattern for
13411@code{sp-parstart}.
13412
13413However, we want to put point at the end of the current paragraph, not
13414somewhere else. Indeed, since the search possibly includes the
13415paragraph separator, point may end up at the beginning of the next one
13416unless we use an expression that includes @code{match-beginning}.
13417
13418@findex match-beginning
13419When given an argument of 0, @code{match-beginning} returns the
13420position that is the start of the text matched by the most recent
13421search. In this case, the most recent search looks for
13422@code{sp-parstart}. The @code{(match-beginning 0)} expression returns
13423the beginning position of that pattern, rather than the end position
13424of that pattern.
13425
13426(Incidentally, when passed a positive number as an argument, the
13427@code{match-beginning} function returns the location of point at that
13428parenthesized expression in the last search unless that parenthesized
13429expression begins with @code{\(?:}. I don't know why @code{\(?:}
13430appears here since the argument is 0.)
13431
13432@need 1250
13433The last expression when there is no fill prefix is
13434
13435@smallexample
13436@group
13437(if (< (point) (point-max))
13438 (goto-char start))))
13439@end group
13440@end smallexample
13441
13442@noindent
13443This says that if there is no fill prefix and if we are not at the
13444end, point should move to the beginning of whatever was found by the
13445regular expression search for @code{sp-parstart}.
13446
13447The full definition for the @code{forward-paragraph} function not only
13448includes code for going forwards, but also code for going backwards.
13449
13450If you are reading this inside of GNU Emacs and you want to see the
13451whole function, you can type @kbd{C-h f} (@code{describe-function})
13452and the name of the function. This gives you the function
13453documentation and the name of the library containing the function's
13454source. Place point over the name of the library and press the RET
13455key; you will be taken directly to the source. (Be sure to install
13456your sources! Without them, you are like a person who tries to drive
13457a car with his eyes shut!)
13458
d6adf7e7 13459@node etags
8cda6f8f
GM
13460@section Create Your Own @file{TAGS} File
13461@findex etags
13462@cindex @file{TAGS} file, create own
13463
13464Besides @kbd{C-h f} (@code{describe-function}), another way to see the
13465source of a function is to type @kbd{M-.} (@code{find-tag}) and the
13466name of the function when prompted for it. This is a good habit to
13467get into. The @kbd{M-.} (@code{find-tag}) command takes you directly
13468to the source for a function, variable, or node. The function depends
13469on tags tables to tell it where to go.
13470
13471If the @code{find-tag} function first asks you for the name of a
13472@file{TAGS} table, give it the name of a @file{TAGS} file such as
13473@file{/usr/local/src/emacs/src/TAGS}. (The exact path to your
13474@file{TAGS} file depends on how your copy of Emacs was installed. I
13475just told you the location that provides both my C and my Emacs Lisp
13476sources.)
13477
13478You can also create your own @file{TAGS} file for directories that
13479lack one.
13480
13481You often need to build and install tags tables yourself. They are
13482not built automatically. A tags table is called a @file{TAGS} file;
13483the name is in upper case letters.
13484
13485You can create a @file{TAGS} file by calling the @code{etags} program
13486that comes as a part of the Emacs distribution. Usually, @code{etags}
13487is compiled and installed when Emacs is built. (@code{etags} is not
13488an Emacs Lisp function or a part of Emacs; it is a C program.)
13489
13490@need 1250
13491To create a @file{TAGS} file, first switch to the directory in which
13492you want to create the file. In Emacs you can do this with the
13493@kbd{M-x cd} command, or by visiting a file in the directory, or by
13494listing the directory with @kbd{C-x d} (@code{dired}). Then run the
13495compile command, with @w{@code{etags *.el}} as the command to execute
13496
13497@smallexample
13498M-x compile RET etags *.el RET
13499@end smallexample
13500
13501@noindent
13502to create a @file{TAGS} file for Emacs Lisp.
13503
13504For example, if you have a large number of files in your
13505@file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
13506of which I load 12---you can create a @file{TAGS} file for the Emacs
13507Lisp files in that directory.
13508
13509@need 1250
13510The @code{etags} program takes all the usual shell `wildcards'. For
13511example, if you have two directories for which you want a single
13512@file{TAGS} file, type @w{@code{etags *.el ../elisp/*.el}}, where
13513@file{../elisp/} is the second directory:
13514
13515@smallexample
13516M-x compile RET etags *.el ../elisp/*.el RET
13517@end smallexample
13518
13519@need 1250
13520Type
13521
13522@smallexample
13523M-x compile RET etags --help RET
13524@end smallexample
13525
13526@noindent
13527to see a list of the options accepted by @code{etags} as well as a
13528list of supported languages.
13529
13530The @code{etags} program handles more than 20 languages, including
13531Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, HTML, Java,
7877f373 13532LaTeX, Pascal, Perl, PostScript, Python, TeX, Texinfo, makefiles, and
8cda6f8f
GM
13533most assemblers. The program has no switches for specifying the
13534language; it recognizes the language in an input file according to its
13535file name and contents.
13536
13537@file{etags} is very helpful when you are writing code yourself and
13538want to refer back to functions you have already written. Just run
13539@code{etags} again at intervals as you write new functions, so they
13540become part of the @file{TAGS} file.
13541
13542If you think an appropriate @file{TAGS} file already exists for what
13543you want, but do not know where it is, you can use the @code{locate}
13544program to attempt to find it.
13545
13546Type @w{@kbd{M-x locate @key{RET} TAGS @key{RET}}} and Emacs will list
13547for you the full path names of all your @file{TAGS} files. On my
13548system, this command lists 34 @file{TAGS} files. On the other hand, a
13549`plain vanilla' system I recently installed did not contain any
13550@file{TAGS} files.
13551
13552If the tags table you want has been created, you can use the @code{M-x
13553visit-tags-table} command to specify it. Otherwise, you will need to
13554create the tag table yourself and then use @code{M-x
13555visit-tags-table}.
13556
13557@subsubheading Building Tags in the Emacs sources
13558@cindex Building Tags in the Emacs sources
13559@cindex Tags in the Emacs sources
13560@findex make tags
13561
13562The GNU Emacs sources come with a @file{Makefile} that contains a
13563sophisticated @code{etags} command that creates, collects, and merges
13564tags tables from all over the Emacs sources and puts the information
13565into one @file{TAGS} file in the @file{src/} directory. (The
13566@file{src/} directory is below the top level of your Emacs directory.)
13567
13568@need 1250
13569To build this @file{TAGS} file, go to the top level of your Emacs
13570source directory and run the compile command @code{make tags}:
13571
13572@smallexample
13573M-x compile RET make tags RET
13574@end smallexample
13575
13576@noindent
13577(The @code{make tags} command works well with the GNU Emacs sources,
13578as well as with some other source packages.)
13579
13580For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
13581Manual}.
13582
d6adf7e7 13583@node Regexp Review
8cda6f8f
GM
13584@section Review
13585
13586Here is a brief summary of some recently introduced functions.
13587
13588@table @code
13589@item while
13590Repeatedly evaluate the body of the expression so long as the first
13591element of the body tests true. Then return @code{nil}. (The
13592expression is evaluated only for its side effects.)
13593
13594@need 1250
13595For example:
13596
13597@smallexample
13598@group
13599(let ((foo 2))
13600 (while (> foo 0)
13601 (insert (format "foo is %d.\n" foo))
13602 (setq foo (1- foo))))
13603
13604 @result{} foo is 2.
13605 foo is 1.
13606 nil
13607@end group
13608@end smallexample
13609
13610@noindent
13611(The @code{insert} function inserts its arguments at point; the
13612@code{format} function returns a string formatted from its arguments
13613the way @code{message} formats its arguments; @code{\n} produces a new
13614line.)
13615
13616@item re-search-forward
13617Search for a pattern, and if the pattern is found, move point to rest
13618just after it.
13619
13620@noindent
13621Takes four arguments, like @code{search-forward}:
13622
13623@enumerate
13624@item
13625A regular expression that specifies the pattern to search for.
13626(Remember to put quotation marks around this argument!)
13627
13628@item
13629Optionally, the limit of the search.
13630
13631@item
13632Optionally, what to do if the search fails, return @code{nil} or an
13633error message.
13634
13635@item
13636Optionally, how many times to repeat the search; if negative, the
13637search goes backwards.
13638@end enumerate
13639
13640@item let*
13641Bind some variables locally to particular values,
13642and then evaluate the remaining arguments, returning the value of the
13643last one. While binding the local variables, use the local values of
13644variables bound earlier, if any.
13645
13646@need 1250
13647For example:
13648
13649@smallexample
13650@group
13651(let* ((foo 7)
13652 (bar (* 3 foo)))
13653 (message "`bar' is %d." bar))
13654 @result{} `bar' is 21.
13655@end group
13656@end smallexample
13657
13658@item match-beginning
13659Return the position of the start of the text found by the last regular
13660expression search.
13661
13662@item looking-at
13663Return @code{t} for true if the text after point matches the argument,
13664which should be a regular expression.
13665
13666@item eobp
13667Return @code{t} for true if point is at the end of the accessible part
13668of a buffer. The end of the accessible part is the end of the buffer
13669if the buffer is not narrowed; it is the end of the narrowed part if
13670the buffer is narrowed.
13671@end table
13672
13673@need 1500
d6adf7e7 13674@node re-search Exercises
8cda6f8f
GM
13675@section Exercises with @code{re-search-forward}
13676
13677@itemize @bullet
13678@item
13679Write a function to search for a regular expression that matches two
13680or more blank lines in sequence.
13681
13682@item
13683Write a function to search for duplicated words, such as `the the'.
13684@xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
13685Manual}, for information on how to write a regexp (a regular
13686expression) to match a string that is composed of two identical
13687halves. You can devise several regexps; some are better than others.
13688The function I use is described in an appendix, along with several
13689regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
13690@end itemize
13691
d6adf7e7 13692@node Counting Words
8cda6f8f
GM
13693@chapter Counting: Repetition and Regexps
13694@cindex Repetition for word counting
13695@cindex Regular expressions for word counting
13696
13697Repetition and regular expression searches are powerful tools that you
13698often use when you write code in Emacs Lisp. This chapter illustrates
13699the use of regular expression searches through the construction of
13700word count commands using @code{while} loops and recursion.
13701
13702@menu
13703* Why Count Words::
ea4f7750 13704* @value{COUNT-WORDS}:: Use a regexp, but find a problem.
8cda6f8f
GM
13705* recursive-count-words:: Start with case of no words in region.
13706* Counting Exercise::
13707@end menu
13708
8cda6f8f 13709@ifnottex
d6adf7e7 13710@node Why Count Words
8cda6f8f
GM
13711@unnumberedsec Counting words
13712@end ifnottex
13713
ea4f7750
GM
13714The standard Emacs distribution contains functions for counting the
13715number of lines and words within a region.
8cda6f8f
GM
13716
13717Certain types of writing ask you to count words. Thus, if you write
13718an essay, you may be limited to 800 words; if you write a novel, you
ea4f7750
GM
13719may discipline yourself to write 1000 words a day. It seems odd, but
13720for a long time, Emacs lacked a word count command. Perhaps people used
13721Emacs mostly for code or types of documentation that did not require
13722word counts; or perhaps they restricted themselves to the operating
13723system word count command, @code{wc}. Alternatively, people may have
13724followed the publishers' convention and computed a word count by
13725dividing the number of characters in a document by five.
13726
13727There are many ways to implement a command to count words. Here are
13728some examples, which you may wish to compare with the standard Emacs
13729command, @code{count-words-region}.
13730
d6adf7e7 13731@node @value{COUNT-WORDS}
ea4f7750
GM
13732@section The @code{@value{COUNT-WORDS}} Function
13733@findex @value{COUNT-WORDS}
8cda6f8f
GM
13734
13735A word count command could count words in a line, paragraph, region,
13736or buffer. What should the command cover? You could design the
13737command to count the number of words in a complete buffer. However,
13738the Emacs tradition encourages flexibility---you may want to count
13739words in just a section, rather than all of a buffer. So it makes
13740more sense to design the command to count the number of words in a
ea4f7750 13741region. Once you have a command to count words in a region, you can,
8cda6f8f
GM
13742if you wish, count words in a whole buffer by marking it with
13743@w{@kbd{C-x h}} (@code{mark-whole-buffer}).
13744
13745Clearly, counting words is a repetitive act: starting from the
13746beginning of the region, you count the first word, then the second
13747word, then the third word, and so on, until you reach the end of the
13748region. This means that word counting is ideally suited to recursion
13749or to a @code{while} loop.
13750
13751@menu
ea4f7750
GM
13752* Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
13753* Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
13754@end menu
13755
8cda6f8f 13756@ifnottex
d6adf7e7 13757@node Design @value{COUNT-WORDS}
ea4f7750 13758@unnumberedsubsec Designing @code{@value{COUNT-WORDS}}
8cda6f8f
GM
13759@end ifnottex
13760
13761First, we will implement the word count command with a @code{while}
13762loop, then with recursion. The command will, of course, be
13763interactive.
13764
13765@need 800
13766The template for an interactive function definition is, as always:
13767
13768@smallexample
13769@group
13770(defun @var{name-of-function} (@var{argument-list})
13771 "@var{documentation}@dots{}"
13772 (@var{interactive-expression}@dots{})
13773 @var{body}@dots{})
13774@end group
13775@end smallexample
13776
13777What we need to do is fill in the slots.
13778
13779The name of the function should be self-explanatory and similar to the
13780existing @code{count-lines-region} name. This makes the name easier
ea4f7750
GM
13781to remember. @code{count-words-region} is the obvious choice. Since
13782that name is now used for the standard Emacs command to count words, we
13783will name our implementation @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
13784
13785The function counts words within a region. This means that the
13786argument list must contain symbols that are bound to the two
13787positions, the beginning and end of the region. These two positions
13788can be called @samp{beginning} and @samp{end} respectively. The first
13789line of the documentation should be a single sentence, since that is
13790all that is printed as documentation by a command such as
13791@code{apropos}. The interactive expression will be of the form
13792@samp{(interactive "r")}, since that will cause Emacs to pass the
13793beginning and end of the region to the function's argument list. All
13794this is routine.
13795
13796The body of the function needs to be written to do three tasks:
13797first, to set up conditions under which the @code{while} loop can
13798count words, second, to run the @code{while} loop, and third, to send
13799a message to the user.
13800
ea4f7750 13801When a user calls @code{@value{COUNT-WORDS}}, point may be at the
8cda6f8f
GM
13802beginning or the end of the region. However, the counting process
13803must start at the beginning of the region. This means we will want
13804to put point there if it is not already there. Executing
13805@code{(goto-char beginning)} ensures this. Of course, we will want to
13806return point to its expected position when the function finishes its
13807work. For this reason, the body must be enclosed in a
13808@code{save-excursion} expression.
13809
13810The central part of the body of the function consists of a
13811@code{while} loop in which one expression jumps point forward word by
13812word, and another expression counts those jumps. The true-or-false-test
13813of the @code{while} loop should test true so long as point should jump
13814forward, and false when point is at the end of the region.
13815
13816We could use @code{(forward-word 1)} as the expression for moving point
13817forward word by word, but it is easier to see what Emacs identifies as a
13818`word' if we use a regular expression search.
13819
13820A regular expression search that finds the pattern for which it is
13821searching leaves point after the last character matched. This means
13822that a succession of successful word searches will move point forward
13823word by word.
13824
13825As a practical matter, we want the regular expression search to jump
13826over whitespace and punctuation between words as well as over the
13827words themselves. A regexp that refuses to jump over interword
13828whitespace would never jump more than one word! This means that
13829the regexp should include the whitespace and punctuation that follows
13830a word, if any, as well as the word itself. (A word may end a buffer
13831and not have any following whitespace or punctuation, so that part of
13832the regexp must be optional.)
13833
13834Thus, what we want for the regexp is a pattern defining one or more
13835word constituent characters followed, optionally, by one or more
13836characters that are not word constituents. The regular expression for
13837this is:
13838
13839@smallexample
13840\w+\W*
13841@end smallexample
13842
13843@noindent
13844The buffer's syntax table determines which characters are and are not
0fd2c9a3
GM
13845word constituents. For more information about syntax,
13846@pxref{Syntax Tables, , Syntax Tables, elisp, The GNU Emacs Lisp
13847Reference Manual}.
8cda6f8f
GM
13848
13849@need 800
13850The search expression looks like this:
13851
13852@smallexample
13853(re-search-forward "\\w+\\W*")
13854@end smallexample
13855
13856@noindent
13857(Note that paired backslashes precede the @samp{w} and @samp{W}. A
13858single backslash has special meaning to the Emacs Lisp interpreter.
13859It indicates that the following character is interpreted differently
13860than usual. For example, the two characters, @samp{\n}, stand for
13861@samp{newline}, rather than for a backslash followed by @samp{n}. Two
13862backslashes in a row stand for an ordinary, `unspecial' backslash, so
13863Emacs Lisp interpreter ends of seeing a single backslash followed by a
13864letter. So it discovers the letter is special.)
13865
13866We need a counter to count how many words there are; this variable
13867must first be set to 0 and then incremented each time Emacs goes
13868around the @code{while} loop. The incrementing expression is simply:
13869
13870@smallexample
13871(setq count (1+ count))
13872@end smallexample
13873
13874Finally, we want to tell the user how many words there are in the
13875region. The @code{message} function is intended for presenting this
13876kind of information to the user. The message has to be phrased so
13877that it reads properly regardless of how many words there are in the
13878region: we don't want to say that ``there are 1 words in the region''.
13879The conflict between singular and plural is ungrammatical. We can
13880solve this problem by using a conditional expression that evaluates
13881different messages depending on the number of words in the region.
13882There are three possibilities: no words in the region, one word in the
13883region, and more than one word. This means that the @code{cond}
13884special form is appropriate.
13885
13886@need 1500
13887All this leads to the following function definition:
13888
13889@smallexample
13890@group
13891;;; @r{First version; has bugs!}
ea4f7750 13892(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
13893 "Print number of words in the region.
13894Words are defined as at least one word-constituent
13895character followed by at least one character that
13896is not a word-constituent. The buffer's syntax
13897table determines which characters these are."
13898 (interactive "r")
13899 (message "Counting words in region ... ")
13900@end group
13901
13902@group
13903;;; @r{1. Set up appropriate conditions.}
13904 (save-excursion
13905 (goto-char beginning)
13906 (let ((count 0))
13907@end group
13908
13909@group
13910;;; @r{2. Run the} while @r{loop.}
13911 (while (< (point) end)
13912 (re-search-forward "\\w+\\W*")
13913 (setq count (1+ count)))
13914@end group
13915
13916@group
13917;;; @r{3. Send a message to the user.}
13918 (cond ((zerop count)
13919 (message
13920 "The region does NOT have any words."))
13921 ((= 1 count)
13922 (message
13923 "The region has 1 word."))
13924 (t
13925 (message
13926 "The region has %d words." count))))))
13927@end group
13928@end smallexample
13929
13930@noindent
13931As written, the function works, but not in all circumstances.
13932
d6adf7e7 13933@node Whitespace Bug
ea4f7750 13934@subsection The Whitespace Bug in @code{@value{COUNT-WORDS}}
8cda6f8f 13935
ea4f7750 13936The @code{@value{COUNT-WORDS}} command described in the preceding
8cda6f8f
GM
13937section has two bugs, or rather, one bug with two manifestations.
13938First, if you mark a region containing only whitespace in the middle
ea4f7750 13939of some text, the @code{@value{COUNT-WORDS}} command tells you that the
8cda6f8f
GM
13940region contains one word! Second, if you mark a region containing
13941only whitespace at the end of the buffer or the accessible portion of
13942a narrowed buffer, the command displays an error message that looks
13943like this:
13944
13945@smallexample
13946Search failed: "\\w+\\W*"
13947@end smallexample
13948
13949If you are reading this in Info in GNU Emacs, you can test for these
13950bugs yourself.
13951
13952First, evaluate the function in the usual manner to install it.
13953@ifinfo
13954Here is a copy of the definition. Place your cursor after the closing
13955parenthesis and type @kbd{C-x C-e} to install it.
13956
13957@smallexample
13958@group
13959;; @r{First version; has bugs!}
ea4f7750 13960(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
13961 "Print number of words in the region.
13962Words are defined as at least one word-constituent character followed
13963by at least one character that is not a word-constituent. The buffer's
13964syntax table determines which characters these are."
13965@end group
13966@group
13967 (interactive "r")
13968 (message "Counting words in region ... ")
13969@end group
13970
13971@group
13972;;; @r{1. Set up appropriate conditions.}
13973 (save-excursion
13974 (goto-char beginning)
13975 (let ((count 0))
13976@end group
13977
13978@group
13979;;; @r{2. Run the} while @r{loop.}
13980 (while (< (point) end)
13981 (re-search-forward "\\w+\\W*")
13982 (setq count (1+ count)))
13983@end group
13984
13985@group
13986;;; @r{3. Send a message to the user.}
13987 (cond ((zerop count)
13988 (message "The region does NOT have any words."))
13989 ((= 1 count) (message "The region has 1 word."))
13990 (t (message "The region has %d words." count))))))
13991@end group
13992@end smallexample
13993@end ifinfo
13994
13995@need 1000
13996If you wish, you can also install this keybinding by evaluating it:
13997
13998@smallexample
ea4f7750 13999(global-set-key "\C-c=" '@value{COUNT-WORDS})
8cda6f8f
GM
14000@end smallexample
14001
14002To conduct the first test, set mark and point to the beginning and end
14003of the following line and then type @kbd{C-c =} (or @kbd{M-x
ea4f7750 14004@value{COUNT-WORDS}} if you have not bound @kbd{C-c =}):
8cda6f8f
GM
14005
14006@smallexample
14007 one two three
14008@end smallexample
14009
14010@noindent
14011Emacs will tell you, correctly, that the region has three words.
14012
14013Repeat the test, but place mark at the beginning of the line and place
14014point just @emph{before} the word @samp{one}. Again type the command
ea4f7750 14015@kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}). Emacs should tell you
8cda6f8f
GM
14016that the region has no words, since it is composed only of the
14017whitespace at the beginning of the line. But instead Emacs tells you
14018that the region has one word!
14019
14020For the third test, copy the sample line to the end of the
14021@file{*scratch*} buffer and then type several spaces at the end of the
14022line. Place mark right after the word @samp{three} and point at the
14023end of line. (The end of the line will be the end of the buffer.)
ea4f7750 14024Type @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}) as you did before.
8cda6f8f
GM
14025Again, Emacs should tell you that the region has no words, since it is
14026composed only of the whitespace at the end of the line. Instead,
14027Emacs displays an error message saying @samp{Search failed}.
14028
14029The two bugs stem from the same problem.
14030
14031Consider the first manifestation of the bug, in which the command
14032tells you that the whitespace at the beginning of the line contains
ea4f7750 14033one word. What happens is this: The @code{M-x @value{COUNT-WORDS}}
8cda6f8f
GM
14034command moves point to the beginning of the region. The @code{while}
14035tests whether the value of point is smaller than the value of
14036@code{end}, which it is. Consequently, the regular expression search
14037looks for and finds the first word. It leaves point after the word.
14038@code{count} is set to one. The @code{while} loop repeats; but this
14039time the value of point is larger than the value of @code{end}, the
14040loop is exited; and the function displays a message saying the number
14041of words in the region is one. In brief, the regular expression
14042search looks for and finds the word even though it is outside
14043the marked region.
14044
14045In the second manifestation of the bug, the region is whitespace at
14046the end of the buffer. Emacs says @samp{Search failed}. What happens
14047is that the true-or-false-test in the @code{while} loop tests true, so
14048the search expression is executed. But since there are no more words
14049in the buffer, the search fails.
14050
14051In both manifestations of the bug, the search extends or attempts to
14052extend outside of the region.
14053
14054The solution is to limit the search to the region---this is a fairly
14055simple action, but as you may have come to expect, it is not quite as
14056simple as you might think.
14057
14058As we have seen, the @code{re-search-forward} function takes a search
14059pattern as its first argument. But in addition to this first,
14060mandatory argument, it accepts three optional arguments. The optional
14061second argument bounds the search. The optional third argument, if
14062@code{t}, causes the function to return @code{nil} rather than signal
14063an error if the search fails. The optional fourth argument is a
14064repeat count. (In Emacs, you can see a function's documentation by
14065typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
14066
ea4f7750 14067In the @code{@value{COUNT-WORDS}} definition, the value of the end of
8cda6f8f
GM
14068the region is held by the variable @code{end} which is passed as an
14069argument to the function. Thus, we can add @code{end} as an argument
14070to the regular expression search expression:
14071
14072@smallexample
14073(re-search-forward "\\w+\\W*" end)
14074@end smallexample
14075
ea4f7750 14076However, if you make only this change to the @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14077definition and then test the new version of the definition on a
14078stretch of whitespace, you will receive an error message saying
14079@samp{Search failed}.
14080
14081What happens is this: the search is limited to the region, and fails
14082as you expect because there are no word-constituent characters in the
14083region. Since it fails, we receive an error message. But we do not
14084want to receive an error message in this case; we want to receive the
14085message that "The region does NOT have any words."
14086
14087The solution to this problem is to provide @code{re-search-forward}
14088with a third argument of @code{t}, which causes the function to return
14089@code{nil} rather than signal an error if the search fails.
14090
14091However, if you make this change and try it, you will see the message
14092``Counting words in region ... '' and @dots{} you will keep on seeing
14093that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
14094
14095Here is what happens: the search is limited to the region, as before,
14096and it fails because there are no word-constituent characters in the
14097region, as expected. Consequently, the @code{re-search-forward}
14098expression returns @code{nil}. It does nothing else. In particular,
14099it does not move point, which it does as a side effect if it finds the
14100search target. After the @code{re-search-forward} expression returns
14101@code{nil}, the next expression in the @code{while} loop is evaluated.
14102This expression increments the count. Then the loop repeats. The
14103true-or-false-test tests true because the value of point is still less
14104than the value of end, since the @code{re-search-forward} expression
14105did not move point. @dots{} and the cycle repeats @dots{}
14106
ea4f7750 14107The @code{@value{COUNT-WORDS}} definition requires yet another
8cda6f8f
GM
14108modification, to cause the true-or-false-test of the @code{while} loop
14109to test false if the search fails. Put another way, there are two
14110conditions that must be satisfied in the true-or-false-test before the
14111word count variable is incremented: point must still be within the
14112region and the search expression must have found a word to count.
14113
14114Since both the first condition and the second condition must be true
14115together, the two expressions, the region test and the search
14116expression, can be joined with an @code{and} special form and embedded in
14117the @code{while} loop as the true-or-false-test, like this:
14118
14119@smallexample
14120(and (< (point) end) (re-search-forward "\\w+\\W*" end t))
14121@end smallexample
14122
14123@c colon in printed section title causes problem in Info cross reference
14124@c also trouble with an overfull hbox
14125@iftex
14126@noindent
14127(For information about @code{and}, see
14128@ref{kill-new function, , The @code{kill-new} function}.)
14129@end iftex
14130@ifinfo
14131@noindent
14132(@xref{kill-new function, , The @code{kill-new} function}, for
14133information about @code{and}.)
14134@end ifinfo
14135
14136The @code{re-search-forward} expression returns @code{t} if the search
14137succeeds and as a side effect moves point. Consequently, as words are
14138found, point is moved through the region. When the search expression
14139fails to find another word, or when point reaches the end of the
14140region, the true-or-false-test tests false, the @code{while} loop
ea4f7750 14141exits, and the @code{@value{COUNT-WORDS}} function displays one or
8cda6f8f
GM
14142other of its messages.
14143
ea4f7750 14144After incorporating these final changes, the @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14145works without bugs (or at least, without bugs that I have found!).
14146Here is what it looks like:
14147
14148@smallexample
14149@group
14150;;; @r{Final version:} @code{while}
ea4f7750 14151(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14152 "Print number of words in the region."
14153 (interactive "r")
14154 (message "Counting words in region ... ")
14155@end group
14156
14157@group
14158;;; @r{1. Set up appropriate conditions.}
14159 (save-excursion
14160 (let ((count 0))
14161 (goto-char beginning)
14162@end group
14163
14164@group
14165;;; @r{2. Run the} while @r{loop.}
14166 (while (and (< (point) end)
14167 (re-search-forward "\\w+\\W*" end t))
14168 (setq count (1+ count)))
14169@end group
14170
14171@group
14172;;; @r{3. Send a message to the user.}
14173 (cond ((zerop count)
14174 (message
14175 "The region does NOT have any words."))
14176 ((= 1 count)
14177 (message
14178 "The region has 1 word."))
14179 (t
14180 (message
14181 "The region has %d words." count))))))
14182@end group
14183@end smallexample
14184
d6adf7e7 14185@node recursive-count-words
8cda6f8f
GM
14186@section Count Words Recursively
14187@cindex Count words recursively
14188@cindex Recursively counting words
14189@cindex Words, counted recursively
14190
14191You can write the function for counting words recursively as well as
14192with a @code{while} loop. Let's see how this is done.
14193
ea4f7750 14194First, we need to recognize that the @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14195function has three jobs: it sets up the appropriate conditions for
14196counting to occur; it counts the words in the region; and it sends a
14197message to the user telling how many words there are.
14198
14199If we write a single recursive function to do everything, we will
14200receive a message for every recursive call. If the region contains 13
14201words, we will receive thirteen messages, one right after the other.
14202We don't want this! Instead, we must write two functions to do the
14203job, one of which (the recursive function) will be used inside of the
14204other. One function will set up the conditions and display the
14205message; the other will return the word count.
14206
14207Let us start with the function that causes the message to be displayed.
ea4f7750 14208We can continue to call this @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
14209
14210This is the function that the user will call. It will be interactive.
14211Indeed, it will be similar to our previous versions of this
14212function, except that it will call @code{recursive-count-words} to
14213determine how many words are in the region.
14214
14215@need 1250
14216We can readily construct a template for this function, based on our
14217previous versions:
14218
14219@smallexample
14220@group
14221;; @r{Recursive version; uses regular expression search}
ea4f7750 14222(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14223 "@var{documentation}@dots{}"
14224 (@var{interactive-expression}@dots{})
14225@end group
14226@group
14227
14228;;; @r{1. Set up appropriate conditions.}
14229 (@var{explanatory message})
14230 (@var{set-up functions}@dots{}
14231@end group
14232@group
14233
14234;;; @r{2. Count the words.}
14235 @var{recursive call}
14236@end group
14237@group
14238
14239;;; @r{3. Send a message to the user.}
14240 @var{message providing word count}))
14241@end group
14242@end smallexample
14243
14244The definition looks straightforward, except that somehow the count
14245returned by the recursive call must be passed to the message
14246displaying the word count. A little thought suggests that this can be
14247done by making use of a @code{let} expression: we can bind a variable
14248in the varlist of a @code{let} expression to the number of words in
14249the region, as returned by the recursive call; and then the
14250@code{cond} expression, using binding, can display the value to the
14251user.
14252
14253Often, one thinks of the binding within a @code{let} expression as
14254somehow secondary to the `primary' work of a function. But in this
14255case, what you might consider the `primary' job of the function,
14256counting words, is done within the @code{let} expression.
14257
14258@need 1250
14259Using @code{let}, the function definition looks like this:
14260
14261@smallexample
14262@group
ea4f7750 14263(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14264 "Print number of words in the region."
14265 (interactive "r")
14266@end group
14267
14268@group
14269;;; @r{1. Set up appropriate conditions.}
14270 (message "Counting words in region ... ")
14271 (save-excursion
14272 (goto-char beginning)
14273@end group
14274
14275@group
14276;;; @r{2. Count the words.}
14277 (let ((count (recursive-count-words end)))
14278@end group
14279
14280@group
14281;;; @r{3. Send a message to the user.}
14282 (cond ((zerop count)
14283 (message
14284 "The region does NOT have any words."))
14285 ((= 1 count)
14286 (message
14287 "The region has 1 word."))
14288 (t
14289 (message
14290 "The region has %d words." count))))))
14291@end group
14292@end smallexample
14293
14294Next, we need to write the recursive counting function.
14295
14296A recursive function has at least three parts: the `do-again-test', the
14297`next-step-expression', and the recursive call.
14298
14299The do-again-test determines whether the function will or will not be
14300called again. Since we are counting words in a region and can use a
14301function that moves point forward for every word, the do-again-test
14302can check whether point is still within the region. The do-again-test
14303should find the value of point and determine whether point is before,
14304at, or after the value of the end of the region. We can use the
14305@code{point} function to locate point. Clearly, we must pass the
14306value of the end of the region to the recursive counting function as an
14307argument.
14308
14309In addition, the do-again-test should also test whether the search finds a
14310word. If it does not, the function should not call itself again.
14311
14312The next-step-expression changes a value so that when the recursive
14313function is supposed to stop calling itself, it stops. More
14314precisely, the next-step-expression changes a value so that at the
14315right time, the do-again-test stops the recursive function from
14316calling itself again. In this case, the next-step-expression can be
14317the expression that moves point forward, word by word.
14318
14319The third part of a recursive function is the recursive call.
14320
14321Somewhere, also, we also need a part that does the `work' of the
14322function, a part that does the counting. A vital part!
14323
14324@need 1250
14325But already, we have an outline of the recursive counting function:
14326
14327@smallexample
14328@group
14329(defun recursive-count-words (region-end)
14330 "@var{documentation}@dots{}"
14331 @var{do-again-test}
14332 @var{next-step-expression}
14333 @var{recursive call})
14334@end group
14335@end smallexample
14336
14337Now we need to fill in the slots. Let's start with the simplest cases
14338first: if point is at or beyond the end of the region, there cannot
14339be any words in the region, so the function should return zero.
14340Likewise, if the search fails, there are no words to count, so the
14341function should return zero.
14342
14343On the other hand, if point is within the region and the search
14344succeeds, the function should call itself again.
14345
14346@need 800
14347Thus, the do-again-test should look like this:
14348
14349@smallexample
14350@group
14351(and (< (point) region-end)
14352 (re-search-forward "\\w+\\W*" region-end t))
14353@end group
14354@end smallexample
14355
14356Note that the search expression is part of the do-again-test---the
14357function returns @code{t} if its search succeeds and @code{nil} if it
14358fails. (@xref{Whitespace Bug, , The Whitespace Bug in
ea4f7750 14359@code{@value{COUNT-WORDS}}}, for an explanation of how
8cda6f8f
GM
14360@code{re-search-forward} works.)
14361
14362The do-again-test is the true-or-false test of an @code{if} clause.
14363Clearly, if the do-again-test succeeds, the then-part of the @code{if}
14364clause should call the function again; but if it fails, the else-part
14365should return zero since either point is outside the region or the
14366search failed because there were no words to find.
14367
14368But before considering the recursive call, we need to consider the
14369next-step-expression. What is it? Interestingly, it is the search
14370part of the do-again-test.
14371
14372In addition to returning @code{t} or @code{nil} for the
14373do-again-test, @code{re-search-forward} moves point forward as a side
14374effect of a successful search. This is the action that changes the
14375value of point so that the recursive function stops calling itself
14376when point completes its movement through the region. Consequently,
14377the @code{re-search-forward} expression is the next-step-expression.
14378
14379@need 1200
14380In outline, then, the body of the @code{recursive-count-words}
14381function looks like this:
14382
14383@smallexample
14384@group
14385(if @var{do-again-test-and-next-step-combined}
14386 ;; @r{then}
14387 @var{recursive-call-returning-count}
14388 ;; @r{else}
14389 @var{return-zero})
14390@end group
14391@end smallexample
14392
14393How to incorporate the mechanism that counts?
14394
14395If you are not used to writing recursive functions, a question like
14396this can be troublesome. But it can and should be approached
14397systematically.
14398
14399We know that the counting mechanism should be associated in some way
14400with the recursive call. Indeed, since the next-step-expression moves
14401point forward by one word, and since a recursive call is made for
14402each word, the counting mechanism must be an expression that adds one
14403to the value returned by a call to @code{recursive-count-words}.
14404
14405@need 800
14406Consider several cases:
14407
14408@itemize @bullet
14409@item
14410If there are two words in the region, the function should return
14411a value resulting from adding one to the value returned when it counts
14412the first word, plus the number returned when it counts the remaining
14413words in the region, which in this case is one.
14414
14415@item
14416If there is one word in the region, the function should return
14417a value resulting from adding one to the value returned when it counts
14418that word, plus the number returned when it counts the remaining
14419words in the region, which in this case is zero.
14420
14421@item
14422If there are no words in the region, the function should return zero.
14423@end itemize
14424
14425From the sketch we can see that the else-part of the @code{if} returns
14426zero for the case of no words. This means that the then-part of the
14427@code{if} must return a value resulting from adding one to the value
14428returned from a count of the remaining words.
14429
14430@need 1200
14431The expression will look like this, where @code{1+} is a function that
14432adds one to its argument.
14433
14434@smallexample
14435(1+ (recursive-count-words region-end))
14436@end smallexample
14437
14438@need 1200
14439The whole @code{recursive-count-words} function will then look like
14440this:
14441
14442@smallexample
14443@group
14444(defun recursive-count-words (region-end)
14445 "@var{documentation}@dots{}"
14446
14447;;; @r{1. do-again-test}
14448 (if (and (< (point) region-end)
14449 (re-search-forward "\\w+\\W*" region-end t))
14450@end group
14451
14452@group
14453;;; @r{2. then-part: the recursive call}
14454 (1+ (recursive-count-words region-end))
14455
14456;;; @r{3. else-part}
14457 0))
14458@end group
14459@end smallexample
14460
14461@need 1250
14462Let's examine how this works:
14463
14464If there are no words in the region, the else part of the @code{if}
14465expression is evaluated and consequently the function returns zero.
14466
14467If there is one word in the region, the value of point is less than
14468the value of @code{region-end} and the search succeeds. In this case,
14469the true-or-false-test of the @code{if} expression tests true, and the
14470then-part of the @code{if} expression is evaluated. The counting
14471expression is evaluated. This expression returns a value (which will
14472be the value returned by the whole function) that is the sum of one
14473added to the value returned by a recursive call.
14474
14475Meanwhile, the next-step-expression has caused point to jump over the
14476first (and in this case only) word in the region. This means that
14477when @code{(recursive-count-words region-end)} is evaluated a second
14478time, as a result of the recursive call, the value of point will be
14479equal to or greater than the value of region end. So this time,
14480@code{recursive-count-words} will return zero. The zero will be added
14481to one, and the original evaluation of @code{recursive-count-words}
14482will return one plus zero, which is one, which is the correct amount.
14483
14484Clearly, if there are two words in the region, the first call to
14485@code{recursive-count-words} returns one added to the value returned
14486by calling @code{recursive-count-words} on a region containing the
14487remaining word---that is, it adds one to one, producing two, which is
14488the correct amount.
14489
14490Similarly, if there are three words in the region, the first call to
14491@code{recursive-count-words} returns one added to the value returned
14492by calling @code{recursive-count-words} on a region containing the
14493remaining two words---and so on and so on.
14494
14495@need 1250
14496@noindent
14497With full documentation the two functions look like this:
14498
14499@need 1250
14500@noindent
14501The recursive function:
14502
14503@findex recursive-count-words
14504@smallexample
14505@group
14506(defun recursive-count-words (region-end)
14507 "Number of words between point and REGION-END."
14508@end group
14509
14510@group
14511;;; @r{1. do-again-test}
14512 (if (and (< (point) region-end)
14513 (re-search-forward "\\w+\\W*" region-end t))
14514@end group
14515
14516@group
14517;;; @r{2. then-part: the recursive call}
14518 (1+ (recursive-count-words region-end))
14519
14520;;; @r{3. else-part}
14521 0))
14522@end group
14523@end smallexample
14524
14525@need 800
14526@noindent
14527The wrapper:
14528
14529@smallexample
14530@group
14531;;; @r{Recursive version}
ea4f7750 14532(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14533 "Print number of words in the region.
14534@end group
14535
14536@group
14537Words are defined as at least one word-constituent
14538character followed by at least one character that is
14539not a word-constituent. The buffer's syntax table
14540determines which characters these are."
14541@end group
14542@group
14543 (interactive "r")
14544 (message "Counting words in region ... ")
14545 (save-excursion
14546 (goto-char beginning)
14547 (let ((count (recursive-count-words end)))
14548@end group
14549@group
14550 (cond ((zerop count)
14551 (message
14552 "The region does NOT have any words."))
14553@end group
14554@group
14555 ((= 1 count)
14556 (message "The region has 1 word."))
14557 (t
14558 (message
14559 "The region has %d words." count))))))
14560@end group
14561@end smallexample
14562
d6adf7e7 14563@node Counting Exercise
8cda6f8f
GM
14564@section Exercise: Counting Punctuation
14565
14566Using a @code{while} loop, write a function to count the number of
14567punctuation marks in a region---period, comma, semicolon, colon,
14568exclamation mark, and question mark. Do the same using recursion.
14569
d6adf7e7 14570@node Words in a defun
8cda6f8f
GM
14571@chapter Counting Words in a @code{defun}
14572@cindex Counting words in a @code{defun}
14573@cindex Word counting in a @code{defun}
14574
14575Our next project is to count the number of words in a function
14576definition. Clearly, this can be done using some variant of
ea4f7750 14577@code{@value{COUNT-WORDS}}. @xref{Counting Words, , Counting Words:
8cda6f8f
GM
14578Repetition and Regexps}. If we are just going to count the words in
14579one definition, it is easy enough to mark the definition with the
14580@kbd{C-M-h} (@code{mark-defun}) command, and then call
ea4f7750 14581@code{@value{COUNT-WORDS}}.
8cda6f8f
GM
14582
14583However, I am more ambitious: I want to count the words and symbols in
14584every definition in the Emacs sources and then print a graph that
14585shows how many functions there are of each length: how many contain 40
14586to 49 words or symbols, how many contain 50 to 59 words or symbols,
14587and so on. I have often been curious how long a typical function is,
14588and this will tell.
14589
14590@menu
14591* Divide and Conquer::
14592* Words and Symbols:: What to count?
14593* Syntax:: What constitutes a word or symbol?
ea4f7750 14594* count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
14595* Several defuns:: Counting several defuns in a file.
14596* Find a File:: Do you want to look at a file?
14597* lengths-list-file:: A list of the lengths of many definitions.
14598* Several files:: Counting in definitions in different files.
14599* Several files recursively:: Recursively counting in different files.
14600* Prepare the data:: Prepare the data for display in a graph.
14601@end menu
14602
8cda6f8f 14603@ifnottex
d6adf7e7 14604@node Divide and Conquer
8cda6f8f
GM
14605@unnumberedsec Divide and Conquer
14606@end ifnottex
14607
14608Described in one phrase, the histogram project is daunting; but
14609divided into numerous small steps, each of which we can take one at a
14610time, the project becomes less fearsome. Let us consider what the
14611steps must be:
14612
14613@itemize @bullet
14614@item
14615First, write a function to count the words in one definition. This
14616includes the problem of handling symbols as well as words.
14617
14618@item
14619Second, write a function to list the numbers of words in each function
14620in a file. This function can use the @code{count-words-in-defun}
14621function.
14622
14623@item
14624Third, write a function to list the numbers of words in each function
14625in each of several files. This entails automatically finding the
14626various files, switching to them, and counting the words in the
14627definitions within them.
14628
14629@item
14630Fourth, write a function to convert the list of numbers that we
14631created in step three to a form that will be suitable for printing as
14632a graph.
14633
14634@item
14635Fifth, write a function to print the results as a graph.
14636@end itemize
14637
14638This is quite a project! But if we take each step slowly, it will not
14639be difficult.
14640
d6adf7e7 14641@node Words and Symbols
8cda6f8f
GM
14642@section What to Count?
14643@cindex Words and symbols in defun
14644
14645When we first start thinking about how to count the words in a
14646function definition, the first question is (or ought to be) what are
14647we going to count? When we speak of `words' with respect to a Lisp
14648function definition, we are actually speaking, in large part, of
14649`symbols'. For example, the following @code{multiply-by-seven}
14650function contains the five symbols @code{defun},
14651@code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
14652addition, in the documentation string, it contains the four words
14653@samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
14654symbol @samp{number} is repeated, so the definition contains a total
14655of ten words and symbols.
14656
14657@smallexample
14658@group
14659(defun multiply-by-seven (number)
14660 "Multiply NUMBER by seven."
14661 (* 7 number))
14662@end group
14663@end smallexample
14664
14665@noindent
14666However, if we mark the @code{multiply-by-seven} definition with
14667@kbd{C-M-h} (@code{mark-defun}), and then call
ea4f7750
GM
14668@code{@value{COUNT-WORDS}} on it, we will find that
14669@code{@value{COUNT-WORDS}} claims the definition has eleven words, not
8cda6f8f
GM
14670ten! Something is wrong!
14671
ea4f7750 14672The problem is twofold: @code{@value{COUNT-WORDS}} does not count the
8cda6f8f
GM
14673@samp{*} as a word, and it counts the single symbol,
14674@code{multiply-by-seven}, as containing three words. The hyphens are
14675treated as if they were interword spaces rather than intraword
14676connectors: @samp{multiply-by-seven} is counted as if it were written
14677@samp{multiply by seven}.
14678
14679The cause of this confusion is the regular expression search within
ea4f7750
GM
14680the @code{@value{COUNT-WORDS}} definition that moves point forward word
14681by word. In the canonical version of @code{@value{COUNT-WORDS}}, the
8cda6f8f
GM
14682regexp is:
14683
14684@smallexample
14685"\\w+\\W*"
14686@end smallexample
14687
14688@noindent
14689This regular expression is a pattern defining one or more word
14690constituent characters possibly followed by one or more characters
14691that are not word constituents. What is meant by `word constituent
14692characters' brings us to the issue of syntax, which is worth a section
14693of its own.
14694
d6adf7e7 14695@node Syntax
8cda6f8f
GM
14696@section What Constitutes a Word or Symbol?
14697@cindex Syntax categories and tables
14698
14699Emacs treats different characters as belonging to different
14700@dfn{syntax categories}. For example, the regular expression,
14701@samp{\\w+}, is a pattern specifying one or more @emph{word
14702constituent} characters. Word constituent characters are members of
14703one syntax category. Other syntax categories include the class of
14704punctuation characters, such as the period and the comma, and the
14705class of whitespace characters, such as the blank space and the tab
0fd2c9a3 14706character. (For more information, @pxref{Syntax Tables, , Syntax
8cda6f8f
GM
14707Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
14708
14709Syntax tables specify which characters belong to which categories.
14710Usually, a hyphen is not specified as a `word constituent character'.
14711Instead, it is specified as being in the `class of characters that are
14712part of symbol names but not words.' This means that the
ea4f7750
GM
14713@code{@value{COUNT-WORDS}} function treats it in the same way it treats
14714an interword white space, which is why @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14715counts @samp{multiply-by-seven} as three words.
14716
14717There are two ways to cause Emacs to count @samp{multiply-by-seven} as
14718one symbol: modify the syntax table or modify the regular expression.
14719
14720We could redefine a hyphen as a word constituent character by
14721modifying the syntax table that Emacs keeps for each mode. This
14722action would serve our purpose, except that a hyphen is merely the
14723most common character within symbols that is not typically a word
14724constituent character; there are others, too.
14725
52af8e0a 14726Alternatively, we can redefine the regexp used in the
ea4f7750 14727@code{@value{COUNT-WORDS}} definition so as to include symbols. This
8cda6f8f
GM
14728procedure has the merit of clarity, but the task is a little tricky.
14729
14730@need 1200
14731The first part is simple enough: the pattern must match ``at least one
14732character that is a word or symbol constituent''. Thus:
14733
14734@smallexample
14735"\\(\\w\\|\\s_\\)+"
14736@end smallexample
14737
14738@noindent
14739The @samp{\\(} is the first part of the grouping construct that
14740includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
14741by the @samp{\\|}. The @samp{\\w} matches any word-constituent
14742character and the @samp{\\s_} matches any character that is part of a
14743symbol name but not a word-constituent character. The @samp{+}
14744following the group indicates that the word or symbol constituent
14745characters must be matched at least once.
14746
14747However, the second part of the regexp is more difficult to design.
14748What we want is to follow the first part with ``optionally one or more
14749characters that are not constituents of a word or symbol''. At first,
14750I thought I could define this with the following:
14751
14752@smallexample
14753"\\(\\W\\|\\S_\\)*"
14754@end smallexample
14755
14756@noindent
14757The upper case @samp{W} and @samp{S} match characters that are
14758@emph{not} word or symbol constituents. Unfortunately, this
14759expression matches any character that is either not a word constituent
14760or not a symbol constituent. This matches any character!
14761
14762I then noticed that every word or symbol in my test region was
14763followed by white space (blank space, tab, or newline). So I tried
14764placing a pattern to match one or more blank spaces after the pattern
14765for one or more word or symbol constituents. This failed, too. Words
14766and symbols are often separated by whitespace, but in actual code
14767parentheses may follow symbols and punctuation may follow words. So
14768finally, I designed a pattern in which the word or symbol constituents
14769are followed optionally by characters that are not white space and
14770then followed optionally by white space.
14771
14772@need 800
14773Here is the full regular expression:
14774
14775@smallexample
14776"\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14777@end smallexample
14778
d6adf7e7 14779@node count-words-in-defun
8cda6f8f
GM
14780@section The @code{count-words-in-defun} Function
14781@cindex Counting words in a @code{defun}
14782
14783We have seen that there are several ways to write a
ea4f7750 14784@code{count-words-region} function. To write a
8cda6f8f
GM
14785@code{count-words-in-defun}, we need merely adapt one of these
14786versions.
14787
14788The version that uses a @code{while} loop is easy to understand, so I
14789am going to adapt that. Because @code{count-words-in-defun} will be
14790part of a more complex program, it need not be interactive and it need
14791not display a message but just return the count. These considerations
14792simplify the definition a little.
14793
14794On the other hand, @code{count-words-in-defun} will be used within a
14795buffer that contains function definitions. Consequently, it is
14796reasonable to ask that the function determine whether it is called
14797when point is within a function definition, and if it is, to return
14798the count for that definition. This adds complexity to the
14799definition, but saves us from needing to pass arguments to the
14800function.
14801
14802@need 1250
14803These considerations lead us to prepare the following template:
14804
14805@smallexample
14806@group
14807(defun count-words-in-defun ()
14808 "@var{documentation}@dots{}"
14809 (@var{set up}@dots{}
14810 (@var{while loop}@dots{})
14811 @var{return count})
14812@end group
14813@end smallexample
14814
14815@noindent
14816As usual, our job is to fill in the slots.
14817
14818First, the set up.
14819
14820We are presuming that this function will be called within a buffer
14821containing function definitions. Point will either be within a
14822function definition or not. For @code{count-words-in-defun} to work,
14823point must move to the beginning of the definition, a counter must
14824start at zero, and the counting loop must stop when point reaches the
14825end of the definition.
14826
14827The @code{beginning-of-defun} function searches backwards for an
14828opening delimiter such as a @samp{(} at the beginning of a line, and
14829moves point to that position, or else to the limit of the search. In
14830practice, this means that @code{beginning-of-defun} moves point to the
14831beginning of an enclosing or preceding function definition, or else to
14832the beginning of the buffer. We can use @code{beginning-of-defun} to
14833place point where we wish to start.
14834
14835The @code{while} loop requires a counter to keep track of the words or
14836symbols being counted. A @code{let} expression can be used to create
14837a local variable for this purpose, and bind it to an initial value of zero.
14838
14839The @code{end-of-defun} function works like @code{beginning-of-defun}
14840except that it moves point to the end of the definition.
14841@code{end-of-defun} can be used as part of an expression that
14842determines the position of the end of the definition.
14843
14844The set up for @code{count-words-in-defun} takes shape rapidly: first
14845we move point to the beginning of the definition, then we create a
14846local variable to hold the count, and finally, we record the position
14847of the end of the definition so the @code{while} loop will know when to stop
14848looping.
14849
14850@need 1250
14851The code looks like this:
14852
14853@smallexample
14854@group
14855(beginning-of-defun)
14856(let ((count 0)
14857 (end (save-excursion (end-of-defun) (point))))
14858@end group
14859@end smallexample
14860
14861@noindent
14862The code is simple. The only slight complication is likely to concern
14863@code{end}: it is bound to the position of the end of the definition
14864by a @code{save-excursion} expression that returns the value of point
14865after @code{end-of-defun} temporarily moves it to the end of the
14866definition.
14867
14868The second part of the @code{count-words-in-defun}, after the set up,
14869is the @code{while} loop.
14870
14871The loop must contain an expression that jumps point forward word by
14872word and symbol by symbol, and another expression that counts the
14873jumps. The true-or-false-test for the @code{while} loop should test
14874true so long as point should jump forward, and false when point is at
14875the end of the definition. We have already redefined the regular
0fd2c9a3 14876expression for this, so the loop is straightforward:
8cda6f8f
GM
14877
14878@smallexample
14879@group
14880(while (and (< (point) end)
14881 (re-search-forward
1ef17681 14882 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t))
8cda6f8f
GM
14883 (setq count (1+ count)))
14884@end group
14885@end smallexample
14886
14887The third part of the function definition returns the count of words
14888and symbols. This part is the last expression within the body of the
14889@code{let} expression, and can be, very simply, the local variable
14890@code{count}, which when evaluated returns the count.
14891
14892@need 1250
14893Put together, the @code{count-words-in-defun} definition looks like this:
14894
14895@findex count-words-in-defun
14896@smallexample
14897@group
14898(defun count-words-in-defun ()
14899 "Return the number of words and symbols in a defun."
14900 (beginning-of-defun)
14901 (let ((count 0)
14902 (end (save-excursion (end-of-defun) (point))))
14903@end group
14904@group
14905 (while
14906 (and (< (point) end)
14907 (re-search-forward
14908 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14909 end t))
14910 (setq count (1+ count)))
14911 count))
14912@end group
14913@end smallexample
14914
14915How to test this? The function is not interactive, but it is easy to
14916put a wrapper around the function to make it interactive; we can use
14917almost the same code as for the recursive version of
ea4f7750 14918@code{@value{COUNT-WORDS}}:
8cda6f8f
GM
14919
14920@smallexample
14921@group
14922;;; @r{Interactive version.}
14923(defun count-words-defun ()
14924 "Number of words and symbols in a function definition."
14925 (interactive)
14926 (message
14927 "Counting words and symbols in function definition ... ")
14928@end group
14929@group
14930 (let ((count (count-words-in-defun)))
14931 (cond
14932 ((zerop count)
14933 (message
14934 "The definition does NOT have any words or symbols."))
14935@end group
14936@group
14937 ((= 1 count)
14938 (message
14939 "The definition has 1 word or symbol."))
14940 (t
14941 (message
14942 "The definition has %d words or symbols." count)))))
14943@end group
14944@end smallexample
14945
14946@need 800
14947@noindent
14948Let's re-use @kbd{C-c =} as a convenient keybinding:
14949
14950@smallexample
14951(global-set-key "\C-c=" 'count-words-defun)
14952@end smallexample
14953
14954Now we can try out @code{count-words-defun}: install both
14955@code{count-words-in-defun} and @code{count-words-defun}, and set the
14956keybinding, and then place the cursor within the following definition:
14957
14958@smallexample
14959@group
14960(defun multiply-by-seven (number)
14961 "Multiply NUMBER by seven."
14962 (* 7 number))
14963 @result{} 10
14964@end group
14965@end smallexample
14966
14967@noindent
14968Success! The definition has 10 words and symbols.
14969
14970The next problem is to count the numbers of words and symbols in
14971several definitions within a single file.
14972
d6adf7e7 14973@node Several defuns
8cda6f8f
GM
14974@section Count Several @code{defuns} Within a File
14975
14976A file such as @file{simple.el} may have a hundred or more function
14977definitions within it. Our long term goal is to collect statistics on
14978many files, but as a first step, our immediate goal is to collect
14979statistics on one file.
14980
14981The information will be a series of numbers, each number being the
14982length of a function definition. We can store the numbers in a list.
14983
14984We know that we will want to incorporate the information regarding one
14985file with information about many other files; this means that the
14986function for counting definition lengths within one file need only
14987return the list of lengths. It need not and should not display any
14988messages.
14989
14990The word count commands contain one expression to jump point forward
14991word by word and another expression to count the jumps. The function
14992to return the lengths of definitions can be designed to work the same
14993way, with one expression to jump point forward definition by
14994definition and another expression to construct the lengths' list.
14995
14996This statement of the problem makes it elementary to write the
14997function definition. Clearly, we will start the count at the
14998beginning of the file, so the first command will be @code{(goto-char
14999(point-min))}. Next, we start the @code{while} loop; and the
15000true-or-false test of the loop can be a regular expression search for
15001the next function definition---so long as the search succeeds, point
15002is moved forward and then the body of the loop is evaluated. The body
15003needs an expression that constructs the lengths' list. @code{cons},
15004the list construction command, can be used to create the list. That
15005is almost all there is to it.
15006
15007@need 800
15008Here is what this fragment of code looks like:
15009
15010@smallexample
15011@group
15012(goto-char (point-min))
15013(while (re-search-forward "^(defun" nil t)
15014 (setq lengths-list
15015 (cons (count-words-in-defun) lengths-list)))
15016@end group
15017@end smallexample
15018
15019What we have left out is the mechanism for finding the file that
15020contains the function definitions.
15021
15022In previous examples, we either used this, the Info file, or we
15023switched back and forth to some other buffer, such as the
15024@file{*scratch*} buffer.
15025
15026Finding a file is a new process that we have not yet discussed.
15027
d6adf7e7 15028@node Find a File
8cda6f8f
GM
15029@section Find a File
15030@cindex Find a File
15031
15032To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
15033command. This command is almost, but not quite right for the lengths
15034problem.
15035
15036@need 1200
15037Let's look at the source for @code{find-file}:
15038
15039@smallexample
15040@group
15041(defun find-file (filename)
15042 "Edit file FILENAME.
15043Switch to a buffer visiting file FILENAME,
15044creating one if none already exists."
15045 (interactive "FFind file: ")
15046 (switch-to-buffer (find-file-noselect filename)))
15047@end group
15048@end smallexample
15049
15050@noindent
15051(The most recent version of the @code{find-file} function definition
15052permits you to specify optional wildcards to visit multiple files; that
15053makes the definition more complex and we will not discuss it here,
15054since it is not relevant. You can see its source using either
15055@kbd{M-.} (@code{find-tag}) or @kbd{C-h f} (@code{describe-function}).)
15056
15057@ignore
15058In Emacs 22
15059(defun find-file (filename &optional wildcards)
15060 "Edit file FILENAME.
15061Switch to a buffer visiting file FILENAME,
15062creating one if none already exists.
15063Interactively, the default if you just type RET is the current directory,
15064but the visited file name is available through the minibuffer history:
15065type M-n to pull it into the minibuffer.
15066
15067Interactively, or if WILDCARDS is non-nil in a call from Lisp,
15068expand wildcards (if any) and visit multiple files. You can
15069suppress wildcard expansion by setting `find-file-wildcards' to nil.
15070
15071To visit a file without any kind of conversion and without
15072automatically choosing a major mode, use \\[find-file-literally]."
15073 (interactive (find-file-read-args "Find file: " nil))
15074 (let ((value (find-file-noselect filename nil nil wildcards)))
15075 (if (listp value)
15076 (mapcar 'switch-to-buffer (nreverse value))
15077 (switch-to-buffer value))))
15078@end ignore
15079
15080The definition I am showing possesses short but complete documentation
15081and an interactive specification that prompts you for a file name when
15082you use the command interactively. The body of the definition
15083contains two functions, @code{find-file-noselect} and
15084@code{switch-to-buffer}.
15085
15086According to its documentation as shown by @kbd{C-h f} (the
15087@code{describe-function} command), the @code{find-file-noselect}
15088function reads the named file into a buffer and returns the buffer.
15089(Its most recent version includes an optional wildcards argument,
15090too, as well as another to read a file literally and an other you
15091suppress warning messages. These optional arguments are irrelevant.)
15092
15093However, the @code{find-file-noselect} function does not select the
15094buffer in which it puts the file. Emacs does not switch its attention
15095(or yours if you are using @code{find-file-noselect}) to the selected
15096buffer. That is what @code{switch-to-buffer} does: it switches the
15097buffer to which Emacs attention is directed; and it switches the
15098buffer displayed in the window to the new buffer. We have discussed
15099buffer switching elsewhere. (@xref{Switching Buffers}.)
15100
15101In this histogram project, we do not need to display each file on the
15102screen as the program determines the length of each definition within
15103it. Instead of employing @code{switch-to-buffer}, we can work with
15104@code{set-buffer}, which redirects the attention of the computer
15105program to a different buffer but does not redisplay it on the screen.
15106So instead of calling on @code{find-file} to do the job, we must write
15107our own expression.
15108
15109The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
15110
d6adf7e7 15111@node lengths-list-file
8cda6f8f
GM
15112@section @code{lengths-list-file} in Detail
15113
15114The core of the @code{lengths-list-file} function is a @code{while}
15115loop containing a function to move point forward `defun by defun' and
15116a function to count the number of words and symbols in each defun.
15117This core must be surrounded by functions that do various other tasks,
15118including finding the file, and ensuring that point starts out at the
15119beginning of the file. The function definition looks like this:
15120@findex lengths-list-file
15121
15122@smallexample
15123@group
15124(defun lengths-list-file (filename)
15125 "Return list of definitions' lengths within FILE.
15126The returned list is a list of numbers.
15127Each number is the number of words or
15128symbols in one function definition."
15129@end group
15130@group
15131 (message "Working on `%s' ... " filename)
15132 (save-excursion
15133 (let ((buffer (find-file-noselect filename))
15134 (lengths-list))
15135 (set-buffer buffer)
15136 (setq buffer-read-only t)
15137 (widen)
15138 (goto-char (point-min))
15139 (while (re-search-forward "^(defun" nil t)
15140 (setq lengths-list
15141 (cons (count-words-in-defun) lengths-list)))
15142 (kill-buffer buffer)
15143 lengths-list)))
15144@end group
15145@end smallexample
15146
15147@noindent
15148The function is passed one argument, the name of the file on which it
15149will work. It has four lines of documentation, but no interactive
15150specification. Since people worry that a computer is broken if they
15151don't see anything going on, the first line of the body is a
15152message.
15153
44e97401 15154The next line contains a @code{save-excursion} that returns Emacs's
8cda6f8f
GM
15155attention to the current buffer when the function completes. This is
15156useful in case you embed this function in another function that
15157presumes point is restored to the original buffer.
15158
15159In the varlist of the @code{let} expression, Emacs finds the file and
15160binds the local variable @code{buffer} to the buffer containing the
15161file. At the same time, Emacs creates @code{lengths-list} as a local
15162variable.
15163
15164Next, Emacs switches its attention to the buffer.
15165
15166In the following line, Emacs makes the buffer read-only. Ideally,
15167this line is not necessary. None of the functions for counting words
15168and symbols in a function definition should change the buffer.
15169Besides, the buffer is not going to be saved, even if it were changed.
15170This line is entirely the consequence of great, perhaps excessive,
15171caution. The reason for the caution is that this function and those
15172it calls work on the sources for Emacs and it is inconvenient if they
15173are inadvertently modified. It goes without saying that I did not
15174realize a need for this line until an experiment went awry and started
15175to modify my Emacs source files @dots{}
15176
15177Next comes a call to widen the buffer if it is narrowed. This
15178function is usually not needed---Emacs creates a fresh buffer if none
15179already exists; but if a buffer visiting the file already exists Emacs
15180returns that one. In this case, the buffer may be narrowed and must
15181be widened. If we wanted to be fully `user-friendly', we would
15182arrange to save the restriction and the location of point, but we
15183won't.
15184
15185The @code{(goto-char (point-min))} expression moves point to the
15186beginning of the buffer.
15187
15188Then comes a @code{while} loop in which the `work' of the function is
15189carried out. In the loop, Emacs determines the length of each
15190definition and constructs a lengths' list containing the information.
15191
15192Emacs kills the buffer after working through it. This is to save
15193space inside of Emacs. My version of GNU Emacs 19 contained over 300
15194source files of interest; GNU Emacs 22 contains over a thousand source
15195files. Another function will apply @code{lengths-list-file} to each
15196of the files.
15197
15198Finally, the last expression within the @code{let} expression is the
15199@code{lengths-list} variable; its value is returned as the value of
15200the whole function.
15201
15202You can try this function by installing it in the usual fashion. Then
15203place your cursor after the following expression and type @kbd{C-x
15204C-e} (@code{eval-last-sexp}).
15205
15206@c !!! 22.1.1 lisp sources location here
15207@smallexample
15208(lengths-list-file
15209 "/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el")
15210@end smallexample
15211
15212@noindent
15213(You may need to change the pathname of the file; the one here is for
15214GNU Emacs version 22.1.1. To change the expression, copy it to
15215the @file{*scratch*} buffer and edit it.
15216
15217@need 1200
15218@noindent
15219(Also, to see the full length of the list, rather than a truncated
15220version, you may have to evaluate the following:
15221
15222@smallexample
15223(custom-set-variables '(eval-expression-print-length nil))
15224@end smallexample
15225
15226@noindent
15227(@xref{defcustom, , Specifying Variables using @code{defcustom}}.
15228Then evaluate the @code{lengths-list-file} expression.)
15229
15230@need 1200
15231The lengths' list for @file{debug.el} takes less than a second to
15232produce and looks like this in GNU Emacs 22:
15233
15234@smallexample
15235(83 113 105 144 289 22 30 97 48 89 25 52 52 88 28 29 77 49 43 290 232 587)
15236@end smallexample
15237
15238@need 1500
15239(Using my old machine, the version 19 lengths' list for @file{debug.el}
15240took seven seconds to produce and looked like this:
15241
15242@smallexample
15243(75 41 80 62 20 45 44 68 45 12 34 235)
15244@end smallexample
15245
15246(The newer version of @file{debug.el} contains more defuns than the
15247earlier one; and my new machine is much faster than the old one.)
15248
15249Note that the length of the last definition in the file is first in
15250the list.
15251
d6adf7e7 15252@node Several files
8cda6f8f
GM
15253@section Count Words in @code{defuns} in Different Files
15254
15255In the previous section, we created a function that returns a list of
15256the lengths of each definition in a file. Now, we want to define a
15257function to return a master list of the lengths of the definitions in
15258a list of files.
15259
15260Working on each of a list of files is a repetitious act, so we can use
15261either a @code{while} loop or recursion.
15262
15263@menu
15264* lengths-list-many-files:: Return a list of the lengths of defuns.
15265* append:: Attach one list to another.
15266@end menu
15267
8cda6f8f 15268@ifnottex
d6adf7e7 15269@node lengths-list-many-files
8cda6f8f
GM
15270@unnumberedsubsec Determine the lengths of @code{defuns}
15271@end ifnottex
15272
15273The design using a @code{while} loop is routine. The argument passed
15274the function is a list of files. As we saw earlier (@pxref{Loop
15275Example}), you can write a @code{while} loop so that the body of the
15276loop is evaluated if such a list contains elements, but to exit the
15277loop if the list is empty. For this design to work, the body of the
15278loop must contain an expression that shortens the list each time the
15279body is evaluated, so that eventually the list is empty. The usual
15280technique is to set the value of the list to the value of the @sc{cdr}
15281of the list each time the body is evaluated.
15282
15283@need 800
15284The template looks like this:
15285
15286@smallexample
15287@group
15288(while @var{test-whether-list-is-empty}
15289 @var{body}@dots{}
15290 @var{set-list-to-cdr-of-list})
15291@end group
15292@end smallexample
15293
15294Also, we remember that a @code{while} loop returns @code{nil} (the
15295result of evaluating the true-or-false-test), not the result of any
15296evaluation within its body. (The evaluations within the body of the
15297loop are done for their side effects.) However, the expression that
15298sets the lengths' list is part of the body---and that is the value
15299that we want returned by the function as a whole. To do this, we
15300enclose the @code{while} loop within a @code{let} expression, and
15301arrange that the last element of the @code{let} expression contains
15302the value of the lengths' list. (@xref{Incrementing Example, , Loop
15303Example with an Incrementing Counter}.)
15304
15305@findex lengths-list-many-files
15306@need 1250
15307These considerations lead us directly to the function itself:
15308
15309@smallexample
15310@group
15311;;; @r{Use @code{while} loop.}
15312(defun lengths-list-many-files (list-of-files)
15313 "Return list of lengths of defuns in LIST-OF-FILES."
15314@end group
15315@group
15316 (let (lengths-list)
15317
15318;;; @r{true-or-false-test}
15319 (while list-of-files
15320 (setq lengths-list
15321 (append
15322 lengths-list
15323
15324;;; @r{Generate a lengths' list.}
15325 (lengths-list-file
15326 (expand-file-name (car list-of-files)))))
15327@end group
15328
15329@group
15330;;; @r{Make files' list shorter.}
15331 (setq list-of-files (cdr list-of-files)))
15332
15333;;; @r{Return final value of lengths' list.}
15334 lengths-list))
15335@end group
15336@end smallexample
15337
15338@code{expand-file-name} is a built-in function that converts a file
15339name to the absolute, long, path name form. The function employs the
15340name of the directory in which the function is called.
15341
15342@c !!! 22.1.1 lisp sources location here
15343@need 1500
15344Thus, if @code{expand-file-name} is called on @code{debug.el} when
15345Emacs is visiting the
15346@file{/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/} directory,
15347
15348@smallexample
15349debug.el
15350@end smallexample
15351
15352@need 800
15353@noindent
15354becomes
15355
15356@c !!! 22.1.1 lisp sources location here
15357@smallexample
15358/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el
15359@end smallexample
15360
15361The only other new element of this function definition is the as yet
15362unstudied function @code{append}, which merits a short section for
15363itself.
15364
d6adf7e7 15365@node append
8cda6f8f
GM
15366@subsection The @code{append} Function
15367
15368@need 800
15369The @code{append} function attaches one list to another. Thus,
15370
15371@smallexample
15372(append '(1 2 3 4) '(5 6 7 8))
15373@end smallexample
15374
15375@need 800
15376@noindent
15377produces the list
15378
15379@smallexample
15380(1 2 3 4 5 6 7 8)
15381@end smallexample
15382
15383This is exactly how we want to attach two lengths' lists produced by
15384@code{lengths-list-file} to each other. The results contrast with
15385@code{cons},
15386
15387@smallexample
15388(cons '(1 2 3 4) '(5 6 7 8))
15389@end smallexample
15390
15391@need 1250
15392@noindent
15393which constructs a new list in which the first argument to @code{cons}
15394becomes the first element of the new list:
15395
15396@smallexample
15397((1 2 3 4) 5 6 7 8)
15398@end smallexample
15399
d6adf7e7 15400@node Several files recursively
8cda6f8f
GM
15401@section Recursively Count Words in Different Files
15402
15403Besides a @code{while} loop, you can work on each of a list of files
15404with recursion. A recursive version of @code{lengths-list-many-files}
15405is short and simple.
15406
15407The recursive function has the usual parts: the `do-again-test', the
15408`next-step-expression', and the recursive call. The `do-again-test'
15409determines whether the function should call itself again, which it
15410will do if the @code{list-of-files} contains any remaining elements;
15411the `next-step-expression' resets the @code{list-of-files} to the
15412@sc{cdr} of itself, so eventually the list will be empty; and the
15413recursive call calls itself on the shorter list. The complete
15414function is shorter than this description!
15415@findex recursive-lengths-list-many-files
15416
15417@smallexample
15418@group
15419(defun recursive-lengths-list-many-files (list-of-files)
15420 "Return list of lengths of each defun in LIST-OF-FILES."
15421 (if list-of-files ; @r{do-again-test}
15422 (append
15423 (lengths-list-file
15424 (expand-file-name (car list-of-files)))
15425 (recursive-lengths-list-many-files
15426 (cdr list-of-files)))))
15427@end group
15428@end smallexample
15429
15430@noindent
15431In a sentence, the function returns the lengths' list for the first of
15432the @code{list-of-files} appended to the result of calling itself on
15433the rest of the @code{list-of-files}.
15434
15435Here is a test of @code{recursive-lengths-list-many-files}, along with
15436the results of running @code{lengths-list-file} on each of the files
15437individually.
15438
15439Install @code{recursive-lengths-list-many-files} and
15440@code{lengths-list-file}, if necessary, and then evaluate the
15441following expressions. You may need to change the files' pathnames;
15442those here work when this Info file and the Emacs sources are located
15443in their customary places. To change the expressions, copy them to
15444the @file{*scratch*} buffer, edit them, and then evaluate them.
15445
15446The results are shown after the @samp{@result{}}. (These results are
15447for files from Emacs version 22.1.1; files from other versions of
15448Emacs may produce different results.)
15449
15450@c !!! 22.1.1 lisp sources location here
15451@smallexample
15452@group
15453(cd "/usr/local/share/emacs/22.1.1/")
15454
15455(lengths-list-file "./lisp/macros.el")
15456 @result{} (283 263 480 90)
15457@end group
15458
15459@group
15460(lengths-list-file "./lisp/mail/mailalias.el")
15461 @result{} (38 32 29 95 178 180 321 218 324)
15462@end group
15463
15464@group
15465(lengths-list-file "./lisp/makesum.el")
15466 @result{} (85 181)
15467@end group
15468
15469@group
15470 (recursive-lengths-list-many-files
15471 '("./lisp/macros.el"
15472 "./lisp/mail/mailalias.el"
15473 "./lisp/makesum.el"))
15474 @result{} (283 263 480 90 38 32 29 95 178 180 321 218 324 85 181)
15475@end group
15476@end smallexample
15477
15478The @code{recursive-lengths-list-many-files} function produces the
15479output we want.
15480
15481The next step is to prepare the data in the list for display in a graph.
15482
d6adf7e7 15483@node Prepare the data
8cda6f8f
GM
15484@section Prepare the Data for Display in a Graph
15485
15486The @code{recursive-lengths-list-many-files} function returns a list
15487of numbers. Each number records the length of a function definition.
15488What we need to do now is transform this data into a list of numbers
15489suitable for generating a graph. The new list will tell how many
15490functions definitions contain less than 10 words and
15491symbols, how many contain between 10 and 19 words and symbols, how
15492many contain between 20 and 29 words and symbols, and so on.
15493
15494In brief, we need to go through the lengths' list produced by the
15495@code{recursive-lengths-list-many-files} function and count the number
15496of defuns within each range of lengths, and produce a list of those
15497numbers.
15498
15499@menu
15500* Data for Display in Detail::
15501* Sorting:: Sorting lists.
15502* Files List:: Making a list of files.
15503* Counting function definitions::
15504@end menu
15505
8cda6f8f 15506@ifnottex
d6adf7e7 15507@node Data for Display in Detail
8cda6f8f
GM
15508@unnumberedsubsec The Data for Display in Detail
15509@end ifnottex
15510
15511Based on what we have done before, we can readily foresee that it
15512should not be too hard to write a function that `@sc{cdr}s' down the
15513lengths' list, looks at each element, determines which length range it
15514is in, and increments a counter for that range.
15515
15516However, before beginning to write such a function, we should consider
15517the advantages of sorting the lengths' list first, so the numbers are
15518ordered from smallest to largest. First, sorting will make it easier
15519to count the numbers in each range, since two adjacent numbers will
15520either be in the same length range or in adjacent ranges. Second, by
15521inspecting a sorted list, we can discover the highest and lowest
15522number, and thereby determine the largest and smallest length range
15523that we will need.
15524
d6adf7e7 15525@node Sorting
8cda6f8f
GM
15526@subsection Sorting Lists
15527@findex sort
15528
15529Emacs contains a function to sort lists, called (as you might guess)
15530@code{sort}. The @code{sort} function takes two arguments, the list
15531to be sorted, and a predicate that determines whether the first of
15532two list elements is ``less'' than the second.
15533
15534As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
15535Type Object as an Argument}), a predicate is a function that
15536determines whether some property is true or false. The @code{sort}
15537function will reorder a list according to whatever property the
15538predicate uses; this means that @code{sort} can be used to sort
15539non-numeric lists by non-numeric criteria---it can, for example,
15540alphabetize a list.
15541
15542@need 1250
15543The @code{<} function is used when sorting a numeric list. For example,
15544
15545@smallexample
15546(sort '(4 8 21 17 33 7 21 7) '<)
15547@end smallexample
15548
15549@need 800
15550@noindent
15551produces this:
15552
15553@smallexample
15554(4 7 7 8 17 21 21 33)
15555@end smallexample
15556
15557@noindent
15558(Note that in this example, both the arguments are quoted so that the
15559symbols are not evaluated before being passed to @code{sort} as
15560arguments.)
15561
15562Sorting the list returned by the
15563@code{recursive-lengths-list-many-files} function is straightforward;
15564it uses the @code{<} function:
15565
15566@ignore
155672006 Oct 29
15568In GNU Emacs 22, eval
15569(progn
15570 (cd "/usr/local/share/emacs/22.0.50/")
15571 (sort
15572 (recursive-lengths-list-many-files
15573 '("./lisp/macros.el"
15574 "./lisp/mail/mailalias.el"
15575 "./lisp/makesum.el"))
15576 '<))
15577
15578@end ignore
15579
15580@smallexample
15581@group
15582(sort
15583 (recursive-lengths-list-many-files
15584 '("./lisp/macros.el"
15585 "./lisp/mailalias.el"
15586 "./lisp/makesum.el"))
15587 '<)
15588@end group
15589@end smallexample
15590
15591@need 800
15592@noindent
15593which produces:
15594
15595@smallexample
15596(29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)
15597@end smallexample
15598
15599@noindent
15600(Note that in this example, the first argument to @code{sort} is not
15601quoted, since the expression must be evaluated so as to produce the
15602list that is passed to @code{sort}.)
15603
d6adf7e7 15604@node Files List
8cda6f8f
GM
15605@subsection Making a List of Files
15606
15607The @code{recursive-lengths-list-many-files} function requires a list
15608of files as its argument. For our test examples, we constructed such
15609a list by hand; but the Emacs Lisp source directory is too large for
15610us to do for that. Instead, we will write a function to do the job
15611for us. In this function, we will use both a @code{while} loop and a
15612recursive call.
15613
15614@findex directory-files
15615We did not have to write a function like this for older versions of
15616GNU Emacs, since they placed all the @samp{.el} files in one
15617directory. Instead, we were able to use the @code{directory-files}
15618function, which lists the names of files that match a specified
15619pattern within a single directory.
15620
15621However, recent versions of Emacs place Emacs Lisp files in
15622sub-directories of the top level @file{lisp} directory. This
15623re-arrangement eases navigation. For example, all the mail related
15624files are in a @file{lisp} sub-directory called @file{mail}. But at
15625the same time, this arrangement forces us to create a file listing
15626function that descends into the sub-directories.
15627
15628@findex files-in-below-directory
15629We can create this function, called @code{files-in-below-directory},
15630using familiar functions such as @code{car}, @code{nthcdr}, and
15631@code{substring} in conjunction with an existing function called
15632@code{directory-files-and-attributes}. This latter function not only
15633lists all the filenames in a directory, including the names
15634of sub-directories, but also their attributes.
15635
15636To restate our goal: to create a function that will enable us
15637to feed filenames to @code{recursive-lengths-list-many-files}
15638as a list that looks like this (but with more elements):
15639
15640@smallexample
15641@group
15642("./lisp/macros.el"
15643 "./lisp/mail/rmail.el"
15644 "./lisp/makesum.el")
15645@end group
15646@end smallexample
15647
15648The @code{directory-files-and-attributes} function returns a list of
15649lists. Each of the lists within the main list consists of 13
15650elements. The first element is a string that contains the name of the
f99f1641 15651file---which, in GNU/Linux, may be a `directory file', that is to
8cda6f8f
GM
15652say, a file with the special attributes of a directory. The second
15653element of the list is @code{t} for a directory, a string
15654for symbolic link (the string is the name linked to), or @code{nil}.
15655
15656For example, the first @samp{.el} file in the @file{lisp/} directory
15657is @file{abbrev.el}. Its name is
15658@file{/usr/local/share/emacs/22.1.1/lisp/abbrev.el} and it is not a
15659directory or a symbolic link.
15660
15661@need 1000
15662This is how @code{directory-files-and-attributes} lists that file and
15663its attributes:
15664
15665@smallexample
15666@group
15667("abbrev.el"
15668nil
156691
156701000
15671100
15672@end group
15673@group
72ec96fb
PE
15674(20615 27034 579989 697000)
15675(17905 55681 0 0)
15676(20615 26327 734791 805000)
1567713188
15678"-rw-r--r--"
8cda6f8f
GM
15679@end group
15680@group
15681nil
156822971624
15683773)
15684@end group
15685@end smallexample
15686
15687@need 1200
15688On the other hand, @file{mail/} is a directory within the @file{lisp/}
15689directory. The beginning of its listing looks like this:
15690
15691@smallexample
15692@group
15693("mail"
15694t
15695@dots{}
15696)
15697@end group
15698@end smallexample
15699
15700(To learn about the different attributes, look at the documentation of
15701@code{file-attributes}. Bear in mind that the @code{file-attributes}
15702function does not list the filename, so its first element is
15703@code{directory-files-and-attributes}'s second element.)
15704
15705We will want our new function, @code{files-in-below-directory}, to
15706list the @samp{.el} files in the directory it is told to check, and in
15707any directories below that directory.
15708
15709This gives us a hint on how to construct
15710@code{files-in-below-directory}: within a directory, the function
15711should add @samp{.el} filenames to a list; and if, within a directory,
15712the function comes upon a sub-directory, it should go into that
15713sub-directory and repeat its actions.
15714
15715However, we should note that every directory contains a name that
15716refers to itself, called @file{.}, (``dot'') and a name that refers to
15717its parent directory, called @file{..} (``double dot''). (In
15718@file{/}, the root directory, @file{..} refers to itself, since
15719@file{/} has no parent.) Clearly, we do not want our
15720@code{files-in-below-directory} function to enter those directories,
15721since they always lead us, directly or indirectly, to the current
15722directory.
15723
15724Consequently, our @code{files-in-below-directory} function must do
15725several tasks:
15726
15727@itemize @bullet
15728@item
15729Check to see whether it is looking at a filename that ends in
15730@samp{.el}; and if so, add its name to a list.
15731
15732@item
15733Check to see whether it is looking at a filename that is the name of a
15734directory; and if so,
15735
15736@itemize @minus
15737@item
15738Check to see whether it is looking at @file{.} or @file{..}; and if
15739so skip it.
15740
15741@item
15742Or else, go into that directory and repeat the process.
15743@end itemize
15744@end itemize
15745
15746Let's write a function definition to do these tasks. We will use a
15747@code{while} loop to move from one filename to another within a
15748directory, checking what needs to be done; and we will use a recursive
15749call to repeat the actions on each sub-directory. The recursive
15750pattern is `accumulate'
15751(@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
15752using @code{append} as the combiner.
15753
15754@ignore
15755(directory-files "/usr/local/src/emacs/lisp/" t "\\.el$")
15756(shell-command "find /usr/local/src/emacs/lisp/ -name '*.el'")
15757
15758(directory-files "/usr/local/share/emacs/22.1.1/lisp/" t "\\.el$")
15759(shell-command "find /usr/local/share/emacs/22.1.1/lisp/ -name '*.el'")
15760@end ignore
15761
15762@c /usr/local/share/emacs/22.1.1/lisp/
15763
15764@need 800
15765Here is the function:
15766
15767@smallexample
15768@group
15769(defun files-in-below-directory (directory)
15770 "List the .el files in DIRECTORY and in its sub-directories."
15771 ;; Although the function will be used non-interactively,
15772 ;; it will be easier to test if we make it interactive.
15773 ;; The directory will have a name such as
15774 ;; "/usr/local/share/emacs/22.1.1/lisp/"
15775 (interactive "DDirectory name: ")
15776@end group
15777@group
15778 (let (el-files-list
15779 (current-directory-list
15780 (directory-files-and-attributes directory t)))
15781 ;; while we are in the current directory
15782 (while current-directory-list
15783@end group
15784@group
15785 (cond
15786 ;; check to see whether filename ends in `.el'
15787 ;; and if so, append its name to a list.
15788 ((equal ".el" (substring (car (car current-directory-list)) -3))
15789 (setq el-files-list
15790 (cons (car (car current-directory-list)) el-files-list)))
15791@end group
15792@group
15793 ;; check whether filename is that of a directory
15794 ((eq t (car (cdr (car current-directory-list))))
15795 ;; decide whether to skip or recurse
15796 (if
15797 (equal "."
15798 (substring (car (car current-directory-list)) -1))
15799 ;; then do nothing since filename is that of
15800 ;; current directory or parent, "." or ".."
15801 ()
15802@end group
15803@group
15804 ;; else descend into the directory and repeat the process
15805 (setq el-files-list
15806 (append
15807 (files-in-below-directory
15808 (car (car current-directory-list)))
15809 el-files-list)))))
15810 ;; move to the next filename in the list; this also
15811 ;; shortens the list so the while loop eventually comes to an end
15812 (setq current-directory-list (cdr current-directory-list)))
15813 ;; return the filenames
15814 el-files-list))
15815@end group
15816@end smallexample
15817
15818@c (files-in-below-directory "/usr/local/src/emacs/lisp/")
15819@c (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15820
15821The @code{files-in-below-directory} @code{directory-files} function
15822takes one argument, the name of a directory.
15823
15824@need 1250
15825Thus, on my system,
15826
15827@c (length (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15828
15829@c !!! 22.1.1 lisp sources location here
15830@smallexample
15831@group
15832(length
15833 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/"))
15834@end group
15835@end smallexample
15836
15837@noindent
15838tells me that in and below my Lisp sources directory are 1031
15839@samp{.el} files.
15840
15841@code{files-in-below-directory} returns a list in reverse alphabetical
15842order. An expression to sort the list in alphabetical order looks
15843like this:
15844
15845@smallexample
15846@group
15847(sort
15848 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15849 'string-lessp)
15850@end group
15851@end smallexample
15852
15853@ignore
15854(defun test ()
15855 "Test how long it takes to find lengths of all sorted elisp defuns."
15856 (insert "\n" (current-time-string) "\n")
15857 (sit-for 0)
15858 (sort
15859 (recursive-lengths-list-many-files
15860 (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15861 '<)
15862 (insert (format "%s" (current-time-string))))
15863@end ignore
15864
d6adf7e7 15865@node Counting function definitions
8cda6f8f
GM
15866@subsection Counting function definitions
15867
15868Our immediate goal is to generate a list that tells us how many
15869function definitions contain fewer than 10 words and symbols, how many
15870contain between 10 and 19 words and symbols, how many contain between
1587120 and 29 words and symbols, and so on.
15872
15873With a sorted list of numbers, this is easy: count how many elements
15874of the list are smaller than 10, then, after moving past the numbers
15875just counted, count how many are smaller than 20, then, after moving
15876past the numbers just counted, count how many are smaller than 30, and
15877so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
15878larger than the top of that range. We can call the list of such
15879numbers the @code{top-of-ranges} list.
15880
15881@need 1200
15882If we wished, we could generate this list automatically, but it is
15883simpler to write a list manually. Here it is:
15884@vindex top-of-ranges
15885
15886@smallexample
15887@group
15888(defvar top-of-ranges
15889 '(10 20 30 40 50
15890 60 70 80 90 100
15891 110 120 130 140 150
15892 160 170 180 190 200
15893 210 220 230 240 250
15894 260 270 280 290 300)
15895 "List specifying ranges for `defuns-per-range'.")
15896@end group
15897@end smallexample
15898
15899To change the ranges, we edit this list.
15900
15901Next, we need to write the function that creates the list of the
15902number of definitions within each range. Clearly, this function must
15903take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15904as arguments.
15905
15906The @code{defuns-per-range} function must do two things again and
15907again: it must count the number of definitions within a range
15908specified by the current top-of-range value; and it must shift to the
15909next higher value in the @code{top-of-ranges} list after counting the
15910number of definitions in the current range. Since each of these
15911actions is repetitive, we can use @code{while} loops for the job.
15912One loop counts the number of definitions in the range defined by the
15913current top-of-range value, and the other loop selects each of the
15914top-of-range values in turn.
15915
15916Several entries of the @code{sorted-lengths} list are counted for each
15917range; this means that the loop for the @code{sorted-lengths} list
15918will be inside the loop for the @code{top-of-ranges} list, like a
15919small gear inside a big gear.
15920
15921The inner loop counts the number of definitions within the range. It
15922is a simple counting loop of the type we have seen before.
15923(@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15924The true-or-false test of the loop tests whether the value from the
15925@code{sorted-lengths} list is smaller than the current value of the
15926top of the range. If it is, the function increments the counter and
15927tests the next value from the @code{sorted-lengths} list.
15928
15929@need 1250
15930The inner loop looks like this:
15931
15932@smallexample
15933@group
15934(while @var{length-element-smaller-than-top-of-range}
15935 (setq number-within-range (1+ number-within-range))
15936 (setq sorted-lengths (cdr sorted-lengths)))
15937@end group
15938@end smallexample
15939
15940The outer loop must start with the lowest value of the
15941@code{top-of-ranges} list, and then be set to each of the succeeding
15942higher values in turn. This can be done with a loop like this:
15943
15944@smallexample
15945@group
15946(while top-of-ranges
15947 @var{body-of-loop}@dots{}
15948 (setq top-of-ranges (cdr top-of-ranges)))
15949@end group
15950@end smallexample
15951
15952@need 1200
15953Put together, the two loops look like this:
15954
15955@smallexample
15956@group
15957(while top-of-ranges
15958
15959 ;; @r{Count the number of elements within the current range.}
15960 (while @var{length-element-smaller-than-top-of-range}
15961 (setq number-within-range (1+ number-within-range))
15962 (setq sorted-lengths (cdr sorted-lengths)))
15963
15964 ;; @r{Move to next range.}
15965 (setq top-of-ranges (cdr top-of-ranges)))
15966@end group
15967@end smallexample
15968
15969In addition, in each circuit of the outer loop, Emacs should record
15970the number of definitions within that range (the value of
15971@code{number-within-range}) in a list. We can use @code{cons} for
15972this purpose. (@xref{cons, , @code{cons}}.)
15973
15974The @code{cons} function works fine, except that the list it
15975constructs will contain the number of definitions for the highest
15976range at its beginning and the number of definitions for the lowest
15977range at its end. This is because @code{cons} attaches new elements
15978of the list to the beginning of the list, and since the two loops are
15979working their way through the lengths' list from the lower end first,
15980the @code{defuns-per-range-list} will end up largest number first.
15981But we will want to print our graph with smallest values first and the
15982larger later. The solution is to reverse the order of the
15983@code{defuns-per-range-list}. We can do this using the
15984@code{nreverse} function, which reverses the order of a list.
15985@findex nreverse
15986
15987@need 800
15988For example,
15989
15990@smallexample
15991(nreverse '(1 2 3 4))
15992@end smallexample
15993
15994@need 800
15995@noindent
15996produces:
15997
15998@smallexample
15999(4 3 2 1)
16000@end smallexample
16001
16002Note that the @code{nreverse} function is ``destructive''---that is,
16003it changes the list to which it is applied; this contrasts with the
16004@code{car} and @code{cdr} functions, which are non-destructive. In
16005this case, we do not want the original @code{defuns-per-range-list},
16006so it does not matter that it is destroyed. (The @code{reverse}
16007function provides a reversed copy of a list, leaving the original list
16008as is.)
16009@findex reverse
16010
16011@need 1250
16012Put all together, the @code{defuns-per-range} looks like this:
16013
16014@smallexample
16015@group
16016(defun defuns-per-range (sorted-lengths top-of-ranges)
16017 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
16018 (let ((top-of-range (car top-of-ranges))
16019 (number-within-range 0)
16020 defuns-per-range-list)
16021@end group
16022
16023@group
16024 ;; @r{Outer loop.}
16025 (while top-of-ranges
16026@end group
16027
16028@group
16029 ;; @r{Inner loop.}
16030 (while (and
16031 ;; @r{Need number for numeric test.}
16032 (car sorted-lengths)
16033 (< (car sorted-lengths) top-of-range))
16034@end group
16035
16036@group
16037 ;; @r{Count number of definitions within current range.}
16038 (setq number-within-range (1+ number-within-range))
16039 (setq sorted-lengths (cdr sorted-lengths)))
16040
16041 ;; @r{Exit inner loop but remain within outer loop.}
16042@end group
16043
16044@group
16045 (setq defuns-per-range-list
16046 (cons number-within-range defuns-per-range-list))
16047 (setq number-within-range 0) ; @r{Reset count to zero.}
16048@end group
16049
16050@group
16051 ;; @r{Move to next range.}
16052 (setq top-of-ranges (cdr top-of-ranges))
16053 ;; @r{Specify next top of range value.}
16054 (setq top-of-range (car top-of-ranges)))
16055@end group
16056
16057@group
16058 ;; @r{Exit outer loop and count the number of defuns larger than}
16059 ;; @r{ the largest top-of-range value.}
16060 (setq defuns-per-range-list
16061 (cons
16062 (length sorted-lengths)
16063 defuns-per-range-list))
16064@end group
16065
16066@group
16067 ;; @r{Return a list of the number of definitions within each range,}
16068 ;; @r{ smallest to largest.}
16069 (nreverse defuns-per-range-list)))
16070@end group
16071@end smallexample
16072
16073@need 1200
16074@noindent
16075The function is straightforward except for one subtle feature. The
16076true-or-false test of the inner loop looks like this:
16077
16078@smallexample
16079@group
16080(and (car sorted-lengths)
16081 (< (car sorted-lengths) top-of-range))
16082@end group
16083@end smallexample
16084
16085@need 800
16086@noindent
16087instead of like this:
16088
16089@smallexample
16090(< (car sorted-lengths) top-of-range)
16091@end smallexample
16092
16093The purpose of the test is to determine whether the first item in the
16094@code{sorted-lengths} list is less than the value of the top of the
16095range.
16096
16097The simple version of the test works fine unless the
16098@code{sorted-lengths} list has a @code{nil} value. In that case, the
16099@code{(car sorted-lengths)} expression function returns
16100@code{nil}. The @code{<} function cannot compare a number to
16101@code{nil}, which is an empty list, so Emacs signals an error and
16102stops the function from attempting to continue to execute.
16103
16104The @code{sorted-lengths} list always becomes @code{nil} when the
16105counter reaches the end of the list. This means that any attempt to
16106use the @code{defuns-per-range} function with the simple version of
16107the test will fail.
16108
16109We solve the problem by using the @code{(car sorted-lengths)}
16110expression in conjunction with the @code{and} expression. The
16111@code{(car sorted-lengths)} expression returns a non-@code{nil}
16112value so long as the list has at least one number within it, but
16113returns @code{nil} if the list is empty. The @code{and} expression
16114first evaluates the @code{(car sorted-lengths)} expression, and
16115if it is @code{nil}, returns false @emph{without} evaluating the
16116@code{<} expression. But if the @code{(car sorted-lengths)}
16117expression returns a non-@code{nil} value, the @code{and} expression
16118evaluates the @code{<} expression, and returns that value as the value
16119of the @code{and} expression.
16120
16121@c colon in printed section title causes problem in Info cross reference
16122This way, we avoid an error.
16123@iftex
16124@noindent
16125(For information about @code{and}, see
16126@ref{kill-new function, , The @code{kill-new} function}.)
16127@end iftex
16128@ifinfo
16129@noindent
16130(@xref{kill-new function, , The @code{kill-new} function}, for
16131information about @code{and}.)
16132@end ifinfo
16133
16134Here is a short test of the @code{defuns-per-range} function. First,
16135evaluate the expression that binds (a shortened)
16136@code{top-of-ranges} list to the list of values, then evaluate the
16137expression for binding the @code{sorted-lengths} list, and then
16138evaluate the @code{defuns-per-range} function.
16139
16140@smallexample
16141@group
16142;; @r{(Shorter list than we will use later.)}
16143(setq top-of-ranges
16144 '(110 120 130 140 150
16145 160 170 180 190 200))
16146
16147(setq sorted-lengths
16148 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
16149
16150(defuns-per-range sorted-lengths top-of-ranges)
16151@end group
16152@end smallexample
16153
16154@need 800
16155@noindent
16156The list returned looks like this:
16157
16158@smallexample
16159(2 2 2 0 0 1 0 2 0 0 4)
16160@end smallexample
16161
16162@noindent
16163Indeed, there are two elements of the @code{sorted-lengths} list
16164smaller than 110, two elements between 110 and 119, two elements
16165between 120 and 129, and so on. There are four elements with a value
16166of 200 or larger.
16167
16168@c The next step is to turn this numbers' list into a graph.
d6adf7e7 16169@node Readying a Graph
8cda6f8f
GM
16170@chapter Readying a Graph
16171@cindex Readying a graph
16172@cindex Graph prototype
16173@cindex Prototype graph
16174@cindex Body of graph
16175
16176Our goal is to construct a graph showing the numbers of function
16177definitions of various lengths in the Emacs lisp sources.
16178
16179As a practical matter, if you were creating a graph, you would
16180probably use a program such as @code{gnuplot} to do the job.
16181(@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
16182however, we create one from scratch, and in the process we will
16183re-acquaint ourselves with some of what we learned before and learn
16184more.
16185
16186In this chapter, we will first write a simple graph printing function.
16187This first definition will be a @dfn{prototype}, a rapidly written
16188function that enables us to reconnoiter this unknown graph-making
16189territory. We will discover dragons, or find that they are myth.
16190After scouting the terrain, we will feel more confident and enhance
16191the function to label the axes automatically.
16192
16193@menu
16194* Columns of a graph::
16195* graph-body-print:: How to print the body of a graph.
16196* recursive-graph-body-print::
16197* Printed Axes::
16198* Line Graph Exercise::
16199@end menu
16200
8cda6f8f 16201@ifnottex
d6adf7e7 16202@node Columns of a graph
8cda6f8f
GM
16203@unnumberedsec Printing the Columns of a Graph
16204@end ifnottex
16205
16206Since Emacs is designed to be flexible and work with all kinds of
16207terminals, including character-only terminals, the graph will need to
16208be made from one of the `typewriter' symbols. An asterisk will do; as
16209we enhance the graph-printing function, we can make the choice of
16210symbol a user option.
16211
16212We can call this function @code{graph-body-print}; it will take a
16213@code{numbers-list} as its only argument. At this stage, we will not
16214label the graph, but only print its body.
16215
16216The @code{graph-body-print} function inserts a vertical column of
16217asterisks for each element in the @code{numbers-list}. The height of
16218each line is determined by the value of that element of the
16219@code{numbers-list}.
16220
16221Inserting columns is a repetitive act; that means that this function can
16222be written either with a @code{while} loop or recursively.
16223
16224Our first challenge is to discover how to print a column of asterisks.
16225Usually, in Emacs, we print characters onto a screen horizontally,
16226line by line, by typing. We have two routes we can follow: write our
16227own column-insertion function or discover whether one exists in Emacs.
16228
16229To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
16230command. This command is like the @kbd{C-h a} (@code{command-apropos})
16231command, except that the latter finds only those functions that are
16232commands. The @kbd{M-x apropos} command lists all symbols that match
16233a regular expression, including functions that are not interactive.
16234@findex apropos
16235
16236What we want to look for is some command that prints or inserts
16237columns. Very likely, the name of the function will contain either
16238the word `print' or the word `insert' or the word `column'.
16239Therefore, we can simply type @kbd{M-x apropos RET
16240print\|insert\|column RET} and look at the result. On my system, this
16241command once too takes quite some time, and then produced a list of 79
16242functions and variables. Now it does not take much time at all and
16243produces a list of 211 functions and variables. Scanning down the
16244list, the only function that looks as if it might do the job is
16245@code{insert-rectangle}.
16246
16247@need 1200
16248Indeed, this is the function we want; its documentation says:
16249
16250@smallexample
16251@group
16252insert-rectangle:
16253Insert text of RECTANGLE with upper left corner at point.
16254RECTANGLE's first line is inserted at point,
16255its second line is inserted at a point vertically under point, etc.
16256RECTANGLE should be a list of strings.
16257After this command, the mark is at the upper left corner
16258and point is at the lower right corner.
16259@end group
16260@end smallexample
16261
16262We can run a quick test, to make sure it does what we expect of it.
16263
16264Here is the result of placing the cursor after the
16265@code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
16266(@code{eval-last-sexp}). The function inserts the strings
16267@samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
16268point. Also the function returns @code{nil}.
16269
16270@smallexample
16271@group
16272(insert-rectangle '("first" "second" "third"))first
16273 second
16274 thirdnil
16275@end group
16276@end smallexample
16277
16278@noindent
16279Of course, we won't be inserting the text of the
16280@code{insert-rectangle} expression itself into the buffer in which we
16281are making the graph, but will call the function from our program. We
16282shall, however, have to make sure that point is in the buffer at the
16283place where the @code{insert-rectangle} function will insert its
16284column of strings.
16285
16286If you are reading this in Info, you can see how this works by
16287switching to another buffer, such as the @file{*scratch*} buffer,
16288placing point somewhere in the buffer, typing @kbd{M-:}, typing the
16289@code{insert-rectangle} expression into the minibuffer at the prompt,
16290and then typing @key{RET}. This causes Emacs to evaluate the
16291expression in the minibuffer, but to use as the value of point the
16292position of point in the @file{*scratch*} buffer. (@kbd{M-:} is the
16293keybinding for @code{eval-expression}. Also, @code{nil} does not
16294appear in the @file{*scratch*} buffer since the expression is
16295evaluated in the minibuffer.)
16296
16297We find when we do this that point ends up at the end of the last
16298inserted line---that is to say, this function moves point as a
16299side-effect. If we were to repeat the command, with point at this
16300position, the next insertion would be below and to the right of the
16301previous insertion. We don't want this! If we are going to make a
16302bar graph, the columns need to be beside each other.
16303
16304So we discover that each cycle of the column-inserting @code{while}
16305loop must reposition point to the place we want it, and that place
16306will be at the top, not the bottom, of the column. Moreover, we
16307remember that when we print a graph, we do not expect all the columns
16308to be the same height. This means that the top of each column may be
16309at a different height from the previous one. We cannot simply
16310reposition point to the same line each time, but moved over to the
16311right---or perhaps we can@dots{}
16312
16313We are planning to make the columns of the bar graph out of asterisks.
16314The number of asterisks in the column is the number specified by the
16315current element of the @code{numbers-list}. We need to construct a
16316list of asterisks of the right length for each call to
16317@code{insert-rectangle}. If this list consists solely of the requisite
16318number of asterisks, then we will have position point the right number
16319of lines above the base for the graph to print correctly. This could
16320be difficult.
16321
16322Alternatively, if we can figure out some way to pass
16323@code{insert-rectangle} a list of the same length each time, then we
16324can place point on the same line each time, but move it over one
16325column to the right for each new column. If we do this, however, some
16326of the entries in the list passed to @code{insert-rectangle} must be
16327blanks rather than asterisks. For example, if the maximum height of
16328the graph is 5, but the height of the column is 3, then
16329@code{insert-rectangle} requires an argument that looks like this:
16330
16331@smallexample
16332(" " " " "*" "*" "*")
16333@end smallexample
16334
16335This last proposal is not so difficult, so long as we can determine
16336the column height. There are two ways for us to specify the column
16337height: we can arbitrarily state what it will be, which would work
16338fine for graphs of that height; or we can search through the list of
16339numbers and use the maximum height of the list as the maximum height
16340of the graph. If the latter operation were difficult, then the former
16341procedure would be easiest, but there is a function built into Emacs
16342that determines the maximum of its arguments. We can use that
16343function. The function is called @code{max} and it returns the
16344largest of all its arguments, which must be numbers. Thus, for
16345example,
16346
16347@smallexample
16348(max 3 4 6 5 7 3)
16349@end smallexample
16350
16351@noindent
16352returns 7. (A corresponding function called @code{min} returns the
16353smallest of all its arguments.)
16354@findex max
16355@findex min
16356
16357However, we cannot simply call @code{max} on the @code{numbers-list};
16358the @code{max} function expects numbers as its argument, not a list of
16359numbers. Thus, the following expression,
16360
16361@smallexample
16362(max '(3 4 6 5 7 3))
16363@end smallexample
16364
16365@need 800
16366@noindent
16367produces the following error message;
16368
16369@smallexample
16370Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
16371@end smallexample
16372
16373@findex apply
16374We need a function that passes a list of arguments to a function.
16375This function is @code{apply}. This function `applies' its first
16376argument (a function) to its remaining arguments, the last of which
16377may be a list.
16378
16379@need 1250
16380For example,
16381
16382@smallexample
16383(apply 'max 3 4 7 3 '(4 8 5))
16384@end smallexample
16385
16386@noindent
16387returns 8.
16388
16389(Incidentally, I don't know how you would learn of this function
16390without a book such as this. It is possible to discover other
16391functions, like @code{search-forward} or @code{insert-rectangle}, by
16392guessing at a part of their names and then using @code{apropos}. Even
16393though its base in metaphor is clear---`apply' its first argument to
16394the rest---I doubt a novice would come up with that particular word
16395when using @code{apropos} or other aid. Of course, I could be wrong;
16396after all, the function was first named by someone who had to invent
16397it.)
16398
16399The second and subsequent arguments to @code{apply} are optional, so
16400we can use @code{apply} to call a function and pass the elements of a
16401list to it, like this, which also returns 8:
16402
16403@smallexample
16404(apply 'max '(4 8 5))
16405@end smallexample
16406
16407This latter way is how we will use @code{apply}. The
16408@code{recursive-lengths-list-many-files} function returns a numbers'
16409list to which we can apply @code{max} (we could also apply @code{max} to
16410the sorted numbers' list; it does not matter whether the list is
16411sorted or not.)
16412
16413@need 800
16414Hence, the operation for finding the maximum height of the graph is this:
16415
16416@smallexample
16417(setq max-graph-height (apply 'max numbers-list))
16418@end smallexample
16419
16420Now we can return to the question of how to create a list of strings
16421for a column of the graph. Told the maximum height of the graph
16422and the number of asterisks that should appear in the column, the
16423function should return a list of strings for the
16424@code{insert-rectangle} command to insert.
16425
16426Each column is made up of asterisks or blanks. Since the function is
16427passed the value of the height of the column and the number of
16428asterisks in the column, the number of blanks can be found by
16429subtracting the number of asterisks from the height of the column.
16430Given the number of blanks and the number of asterisks, two
16431@code{while} loops can be used to construct the list:
16432
16433@smallexample
16434@group
16435;;; @r{First version.}
16436(defun column-of-graph (max-graph-height actual-height)
16437 "Return list of strings that is one column of a graph."
16438 (let ((insert-list nil)
16439 (number-of-top-blanks
16440 (- max-graph-height actual-height)))
16441@end group
16442
16443@group
16444 ;; @r{Fill in asterisks.}
16445 (while (> actual-height 0)
16446 (setq insert-list (cons "*" insert-list))
16447 (setq actual-height (1- actual-height)))
16448@end group
16449
16450@group
16451 ;; @r{Fill in blanks.}
16452 (while (> number-of-top-blanks 0)
16453 (setq insert-list (cons " " insert-list))
16454 (setq number-of-top-blanks
16455 (1- number-of-top-blanks)))
16456@end group
16457
16458@group
16459 ;; @r{Return whole list.}
16460 insert-list))
16461@end group
16462@end smallexample
16463
16464If you install this function and then evaluate the following
16465expression you will see that it returns the list as desired:
16466
16467@smallexample
16468(column-of-graph 5 3)
16469@end smallexample
16470
16471@need 800
16472@noindent
16473returns
16474
16475@smallexample
16476(" " " " "*" "*" "*")
16477@end smallexample
16478
16479As written, @code{column-of-graph} contains a major flaw: the symbols
16480used for the blank and for the marked entries in the column are
16481`hard-coded' as a space and asterisk. This is fine for a prototype,
16482but you, or another user, may wish to use other symbols. For example,
16483in testing the graph function, you many want to use a period in place
16484of the space, to make sure the point is being repositioned properly
16485each time the @code{insert-rectangle} function is called; or you might
16486want to substitute a @samp{+} sign or other symbol for the asterisk.
16487You might even want to make a graph-column that is more than one
16488display column wide. The program should be more flexible. The way to
16489do that is to replace the blank and the asterisk with two variables
16490that we can call @code{graph-blank} and @code{graph-symbol} and define
16491those variables separately.
16492
16493Also, the documentation is not well written. These considerations
16494lead us to the second version of the function:
16495
16496@smallexample
16497@group
16498(defvar graph-symbol "*"
16499 "String used as symbol in graph, usually an asterisk.")
16500@end group
16501
16502@group
16503(defvar graph-blank " "
16504 "String used as blank in graph, usually a blank space.
16505graph-blank must be the same number of columns wide
16506as graph-symbol.")
16507@end group
16508@end smallexample
16509
16510@noindent
16511(For an explanation of @code{defvar}, see
16512@ref{defvar, , Initializing a Variable with @code{defvar}}.)
16513
16514@smallexample
16515@group
16516;;; @r{Second version.}
16517(defun column-of-graph (max-graph-height actual-height)
16518 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
16519
16520@end group
16521@group
16522The graph-symbols are contiguous entries at the end
16523of the list.
16524The list will be inserted as one column of a graph.
16525The strings are either graph-blank or graph-symbol."
16526@end group
16527
16528@group
16529 (let ((insert-list nil)
16530 (number-of-top-blanks
16531 (- max-graph-height actual-height)))
16532@end group
16533
16534@group
16535 ;; @r{Fill in @code{graph-symbols}.}
16536 (while (> actual-height 0)
16537 (setq insert-list (cons graph-symbol insert-list))
16538 (setq actual-height (1- actual-height)))
16539@end group
16540
16541@group
16542 ;; @r{Fill in @code{graph-blanks}.}
16543 (while (> number-of-top-blanks 0)
16544 (setq insert-list (cons graph-blank insert-list))
16545 (setq number-of-top-blanks
16546 (1- number-of-top-blanks)))
16547
16548 ;; @r{Return whole list.}
16549 insert-list))
16550@end group
16551@end smallexample
16552
16553If we wished, we could rewrite @code{column-of-graph} a third time to
16554provide optionally for a line graph as well as for a bar graph. This
16555would not be hard to do. One way to think of a line graph is that it
16556is no more than a bar graph in which the part of each bar that is
16557below the top is blank. To construct a column for a line graph, the
16558function first constructs a list of blanks that is one shorter than
16559the value, then it uses @code{cons} to attach a graph symbol to the
16560list; then it uses @code{cons} again to attach the `top blanks' to
16561the list.
16562
16563It is easy to see how to write such a function, but since we don't
16564need it, we will not do it. But the job could be done, and if it were
16565done, it would be done with @code{column-of-graph}. Even more
16566important, it is worth noting that few changes would have to be made
16567anywhere else. The enhancement, if we ever wish to make it, is
16568simple.
16569
16570Now, finally, we come to our first actual graph printing function.
16571This prints the body of a graph, not the labels for the vertical and
16572horizontal axes, so we can call this @code{graph-body-print}.
16573
d6adf7e7 16574@node graph-body-print
8cda6f8f
GM
16575@section The @code{graph-body-print} Function
16576@findex graph-body-print
16577
16578After our preparation in the preceding section, the
16579@code{graph-body-print} function is straightforward. The function
16580will print column after column of asterisks and blanks, using the
16581elements of a numbers' list to specify the number of asterisks in each
16582column. This is a repetitive act, which means we can use a
16583decrementing @code{while} loop or recursive function for the job. In
16584this section, we will write the definition using a @code{while} loop.
16585
16586The @code{column-of-graph} function requires the height of the graph
16587as an argument, so we should determine and record that as a local variable.
16588
16589This leads us to the following template for the @code{while} loop
16590version of this function:
16591
16592@smallexample
16593@group
16594(defun graph-body-print (numbers-list)
16595 "@var{documentation}@dots{}"
16596 (let ((height @dots{}
16597 @dots{}))
16598@end group
16599
16600@group
16601 (while numbers-list
16602 @var{insert-columns-and-reposition-point}
16603 (setq numbers-list (cdr numbers-list)))))
16604@end group
16605@end smallexample
16606
16607@noindent
16608We need to fill in the slots of the template.
16609
16610Clearly, we can use the @code{(apply 'max numbers-list)} expression to
16611determine the height of the graph.
16612
16613The @code{while} loop will cycle through the @code{numbers-list} one
16614element at a time. As it is shortened by the @code{(setq numbers-list
16615(cdr numbers-list))} expression, the @sc{car} of each instance of the
16616list is the value of the argument for @code{column-of-graph}.
16617
16618At each cycle of the @code{while} loop, the @code{insert-rectangle}
16619function inserts the list returned by @code{column-of-graph}. Since
16620the @code{insert-rectangle} function moves point to the lower right of
16621the inserted rectangle, we need to save the location of point at the
16622time the rectangle is inserted, move back to that position after the
16623rectangle is inserted, and then move horizontally to the next place
16624from which @code{insert-rectangle} is called.
16625
16626If the inserted columns are one character wide, as they will be if
16627single blanks and asterisks are used, the repositioning command is
16628simply @code{(forward-char 1)}; however, the width of a column may be
16629greater than one. This means that the repositioning command should be
16630written @code{(forward-char symbol-width)}. The @code{symbol-width}
16631itself is the length of a @code{graph-blank} and can be found using
16632the expression @code{(length graph-blank)}. The best place to bind
16633the @code{symbol-width} variable to the value of the width of graph
16634column is in the varlist of the @code{let} expression.
16635
16636@need 1250
16637These considerations lead to the following function definition:
16638
16639@smallexample
16640@group
16641(defun graph-body-print (numbers-list)
16642 "Print a bar graph of the NUMBERS-LIST.
16643The numbers-list consists of the Y-axis values."
16644
16645 (let ((height (apply 'max numbers-list))
16646 (symbol-width (length graph-blank))
16647 from-position)
16648@end group
16649
16650@group
16651 (while numbers-list
16652 (setq from-position (point))
16653 (insert-rectangle
16654 (column-of-graph height (car numbers-list)))
16655 (goto-char from-position)
16656 (forward-char symbol-width)
16657@end group
16658@group
16659 ;; @r{Draw graph column by column.}
16660 (sit-for 0)
16661 (setq numbers-list (cdr numbers-list)))
16662@end group
16663@group
16664 ;; @r{Place point for X axis labels.}
16665 (forward-line height)
16666 (insert "\n")
16667))
16668@end group
16669@end smallexample
16670
16671@noindent
16672The one unexpected expression in this function is the
16673@w{@code{(sit-for 0)}} expression in the @code{while} loop. This
16674expression makes the graph printing operation more interesting to
16675watch than it would be otherwise. The expression causes Emacs to
16676`sit' or do nothing for a zero length of time and then redraw the
16677screen. Placed here, it causes Emacs to redraw the screen column by
16678column. Without it, Emacs would not redraw the screen until the
16679function exits.
16680
16681We can test @code{graph-body-print} with a short list of numbers.
16682
16683@enumerate
16684@item
16685Install @code{graph-symbol}, @code{graph-blank},
16686@code{column-of-graph}, which are in
16687@iftex
16688@ref{Readying a Graph, , Readying a Graph},
16689@end iftex
16690@ifinfo
16691@ref{Columns of a graph},
16692@end ifinfo
16693and @code{graph-body-print}.
16694
16695@need 800
16696@item
16697Copy the following expression:
16698
16699@smallexample
16700(graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
16701@end smallexample
16702
16703@item
16704Switch to the @file{*scratch*} buffer and place the cursor where you
16705want the graph to start.
16706
16707@item
16708Type @kbd{M-:} (@code{eval-expression}).
16709
16710@item
16711Yank the @code{graph-body-print} expression into the minibuffer
16712with @kbd{C-y} (@code{yank)}.
16713
16714@item
16715Press @key{RET} to evaluate the @code{graph-body-print} expression.
16716@end enumerate
16717
16718@need 800
16719Emacs will print a graph like this:
16720
16721@smallexample
16722@group
16723 *
16724 * **
16725 * ****
16726 *** ****
16727 ********* *
16728 ************
16729 *************
16730@end group
16731@end smallexample
16732
d6adf7e7 16733@node recursive-graph-body-print
8cda6f8f
GM
16734@section The @code{recursive-graph-body-print} Function
16735@findex recursive-graph-body-print
16736
16737The @code{graph-body-print} function may also be written recursively.
16738The recursive solution is divided into two parts: an outside `wrapper'
16739that uses a @code{let} expression to determine the values of several
16740variables that need only be found once, such as the maximum height of
16741the graph, and an inside function that is called recursively to print
16742the graph.
16743
16744@need 1250
16745The `wrapper' is uncomplicated:
16746
16747@smallexample
16748@group
16749(defun recursive-graph-body-print (numbers-list)
16750 "Print a bar graph of the NUMBERS-LIST.
16751The numbers-list consists of the Y-axis values."
16752 (let ((height (apply 'max numbers-list))
16753 (symbol-width (length graph-blank))
16754 from-position)
16755 (recursive-graph-body-print-internal
16756 numbers-list
16757 height
16758 symbol-width)))
16759@end group
16760@end smallexample
16761
16762The recursive function is a little more difficult. It has four parts:
16763the `do-again-test', the printing code, the recursive call, and the
16764`next-step-expression'. The `do-again-test' is a @code{when}
16765expression that determines whether the @code{numbers-list} contains
16766any remaining elements; if it does, the function prints one column of
16767the graph using the printing code and calls itself again. The
16768function calls itself again according to the value produced by the
16769`next-step-expression' which causes the call to act on a shorter
16770version of the @code{numbers-list}.
16771
16772@smallexample
16773@group
16774(defun recursive-graph-body-print-internal
16775 (numbers-list height symbol-width)
16776 "Print a bar graph.
16777Used within recursive-graph-body-print function."
16778@end group
16779
16780@group
16781 (when numbers-list
16782 (setq from-position (point))
16783 (insert-rectangle
16784 (column-of-graph height (car numbers-list)))
16785@end group
16786@group
16787 (goto-char from-position)
16788 (forward-char symbol-width)
16789 (sit-for 0) ; @r{Draw graph column by column.}
16790 (recursive-graph-body-print-internal
16791 (cdr numbers-list) height symbol-width)))
16792@end group
16793@end smallexample
16794
16795@need 1250
16796After installation, this expression can be tested; here is a sample:
16797
16798@smallexample
16799(recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
16800@end smallexample
16801
16802@need 800
16803Here is what @code{recursive-graph-body-print} produces:
16804
16805@smallexample
16806@group
16807 *
16808 ** *
16809 **** *
16810 **** ***
16811 * *********
16812 ************
16813 *************
16814@end group
16815@end smallexample
16816
16817Either of these two functions, @code{graph-body-print} or
16818@code{recursive-graph-body-print}, create the body of a graph.
16819
d6adf7e7 16820@node Printed Axes
8cda6f8f
GM
16821@section Need for Printed Axes
16822
16823A graph needs printed axes, so you can orient yourself. For a do-once
44e97401 16824project, it may be reasonable to draw the axes by hand using Emacs's
8cda6f8f
GM
16825Picture mode; but a graph drawing function may be used more than once.
16826
16827For this reason, I have written enhancements to the basic
16828@code{print-graph-body} function that automatically print labels for
16829the horizontal and vertical axes. Since the label printing functions
16830do not contain much new material, I have placed their description in
09e80d9f 16831an appendix. @xref{Full Graph, , A Graph with Labeled Axes}.
8cda6f8f 16832
d6adf7e7 16833@node Line Graph Exercise
8cda6f8f
GM
16834@section Exercise
16835
16836Write a line graph version of the graph printing functions.
16837
d6adf7e7 16838@node Emacs Initialization
8cda6f8f
GM
16839@chapter Your @file{.emacs} File
16840@cindex @file{.emacs} file
16841@cindex Customizing your @file{.emacs} file
16842@cindex Initialization file
16843
f99f1641 16844``You don't have to like Emacs to like it''---this seemingly
8cda6f8f
GM
16845paradoxical statement is the secret of GNU Emacs. The plain, `out of
16846the box' Emacs is a generic tool. Most people who use it, customize
16847it to suit themselves.
16848
16849GNU Emacs is mostly written in Emacs Lisp; this means that by writing
16850expressions in Emacs Lisp you can change or extend Emacs.
16851
16852@menu
16853* Default Configuration::
16854* Site-wide Init:: You can write site-wide init files.
16855* defcustom:: Emacs will write code for you.
16856* Beginning a .emacs File:: How to write a @code{.emacs file}.
16857* Text and Auto-fill:: Automatically wrap lines.
16858* Mail Aliases:: Use abbreviations for email addresses.
16859* Indent Tabs Mode:: Don't use tabs with @TeX{}
16860* Keybindings:: Create some personal keybindings.
16861* Keymaps:: More about key binding.
16862* Loading Files:: Load (i.e., evaluate) files automatically.
16863* Autoload:: Make functions available.
16864* Simple Extension:: Define a function; bind it to a key.
16865* X11 Colors:: Colors in X.
16866* Miscellaneous::
16867* Mode Line:: How to customize your mode line.
16868@end menu
16869
8cda6f8f 16870@ifnottex
d6adf7e7 16871@node Default Configuration
44e97401 16872@unnumberedsec Emacs's Default Configuration
8cda6f8f
GM
16873@end ifnottex
16874
44e97401 16875There are those who appreciate Emacs's default configuration. After
8cda6f8f
GM
16876all, Emacs starts you in C mode when you edit a C file, starts you in
16877Fortran mode when you edit a Fortran file, and starts you in
16878Fundamental mode when you edit an unadorned file. This all makes
16879sense, if you do not know who is going to use Emacs. Who knows what a
16880person hopes to do with an unadorned file? Fundamental mode is the
16881right default for such a file, just as C mode is the right default for
16882editing C code. (Enough programming languages have syntaxes
16883that enable them to share or nearly share features, so C mode is
6bd6c2fa 16884now provided by CC mode, the `C Collection'.)
8cda6f8f
GM
16885
16886But when you do know who is going to use Emacs---you,
16887yourself---then it makes sense to customize Emacs.
16888
16889For example, I seldom want Fundamental mode when I edit an
16890otherwise undistinguished file; I want Text mode. This is why I
16891customize Emacs: so it suits me.
16892
16893You can customize and extend Emacs by writing or adapting a
16894@file{~/.emacs} file. This is your personal initialization file; its
16895contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16896may also add @file{.el} to @file{~/.emacs} and call it a
16897@file{~/.emacs.el} file. In the past, you were forbidden to type the
16898extra keystrokes that the name @file{~/.emacs.el} requires, but now
16899you may. The new format is consistent with the Emacs Lisp file
16900naming conventions; the old format saves typing.}
16901
16902A @file{~/.emacs} file contains Emacs Lisp code. You can write this
44e97401 16903code yourself; or you can use Emacs's @code{customize} feature to write
8cda6f8f
GM
16904the code for you. You can combine your own expressions and
16905auto-written Customize expressions in your @file{.emacs} file.
16906
16907(I myself prefer to write my own expressions, except for those,
16908particularly fonts, that I find easier to manipulate using the
16909@code{customize} command. I combine the two methods.)
16910
16911Most of this chapter is about writing expressions yourself. It
16912describes a simple @file{.emacs} file; for more information, see
16913@ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16914@ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16915Manual}.
16916
d6adf7e7 16917@node Site-wide Init
8cda6f8f
GM
16918@section Site-wide Initialization Files
16919
16920@cindex @file{default.el} init file
16921@cindex @file{site-init.el} init file
16922@cindex @file{site-load.el} init file
16923In addition to your personal initialization file, Emacs automatically
16924loads various site-wide initialization files, if they exist. These
16925have the same form as your @file{.emacs} file, but are loaded by
16926everyone.
16927
16928Two site-wide initialization files, @file{site-load.el} and
16929@file{site-init.el}, are loaded into Emacs and then `dumped' if a
16930`dumped' version of Emacs is created, as is most common. (Dumped
16931copies of Emacs load more quickly. However, once a file is loaded and
16932dumped, a change to it does not lead to a change in Emacs unless you
16933load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16934Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16935@file{INSTALL} file.)
16936
16937Three other site-wide initialization files are loaded automatically
16938each time you start Emacs, if they exist. These are
16939@file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16940file, and @file{default.el}, and the terminal type file, which are both
16941loaded @emph{after} your @file{.emacs} file.
16942
16943Settings and definitions in your @file{.emacs} file will overwrite
16944conflicting settings and definitions in a @file{site-start.el} file,
16945if it exists; but the settings and definitions in a @file{default.el}
16946or terminal type file will overwrite those in your @file{.emacs} file.
16947(You can prevent interference from a terminal type file by setting
16948@code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16949Simple Extension}.)
16950
16951@c Rewritten to avoid overfull hbox.
16952The @file{INSTALL} file that comes in the distribution contains
16953descriptions of the @file{site-init.el} and @file{site-load.el} files.
16954
16955The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16956control loading. These files are in the @file{lisp} directory of the
16957Emacs distribution and are worth perusing.
16958
16959The @file{loaddefs.el} file contains a good many suggestions as to
16960what to put into your own @file{.emacs} file, or into a site-wide
16961initialization file.
16962
d6adf7e7 16963@node defcustom
8cda6f8f
GM
16964@section Specifying Variables using @code{defcustom}
16965@findex defcustom
16966
16967You can specify variables using @code{defcustom} so that you and
44e97401 16968others can then use Emacs's @code{customize} feature to set their
8cda6f8f
GM
16969values. (You cannot use @code{customize} to write function
16970definitions; but you can write @code{defuns} in your @file{.emacs}
16971file. Indeed, you can write any Lisp expression in your @file{.emacs}
16972file.)
16973
16974The @code{customize} feature depends on the @code{defcustom} special
16975form. Although you can use @code{defvar} or @code{setq} for variables
16976that users set, the @code{defcustom} special form is designed for the
16977job.
16978
16979You can use your knowledge of @code{defvar} for writing the
16980first three arguments for @code{defcustom}. The first argument to
16981@code{defcustom} is the name of the variable. The second argument is
16982the variable's initial value, if any; and this value is set only if
16983the value has not already been set. The third argument is the
16984documentation.
16985
16986The fourth and subsequent arguments to @code{defcustom} specify types
16987and options; these are not featured in @code{defvar}. (These
16988arguments are optional.)
16989
16990Each of these arguments consists of a keyword followed by a value.
16991Each keyword starts with the colon character @samp{:}.
16992
16993@need 1250
16994For example, the customizable user option variable
16995@code{text-mode-hook} looks like this:
16996
16997@smallexample
16998@group
16999(defcustom text-mode-hook nil
17000 "Normal hook run when entering Text mode and many related modes."
17001 :type 'hook
17002 :options '(turn-on-auto-fill flyspell-mode)
cfe1c0af 17003 :group 'wp)
8cda6f8f
GM
17004@end group
17005@end smallexample
17006
17007@noindent
17008The name of the variable is @code{text-mode-hook}; it has no default
17009value; and its documentation string tells you what it does.
17010
17011The @code{:type} keyword tells Emacs the kind of data to which
17012@code{text-mode-hook} should be set and how to display the value in a
17013Customization buffer.
17014
17015The @code{:options} keyword specifies a suggested list of values for
17016the variable. Usually, @code{:options} applies to a hook.
17017The list is only a suggestion; it is not exclusive; a person who sets
17018the variable may set it to other values; the list shown following the
17019@code{:options} keyword is intended to offer convenient choices to a
17020user.
17021
17022Finally, the @code{:group} keyword tells the Emacs Customization
17023command in which group the variable is located. This tells where to
17024find it.
17025
17026The @code{defcustom} function recognizes more than a dozen keywords.
17027For more information, see @ref{Customization, , Writing Customization
17028Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
17029
17030Consider @code{text-mode-hook} as an example.
17031
17032There are two ways to customize this variable. You can use the
17033customization command or write the appropriate expressions yourself.
17034
17035@need 800
17036Using the customization command, you can type:
17037
17038@smallexample
17039M-x customize
17040@end smallexample
17041
17042@noindent
17043and find that the group for editing files of data is called `data'.
17044Enter that group. Text Mode Hook is the first member. You can click
17045on its various options, such as @code{turn-on-auto-fill}, to set the
17046values. After you click on the button to
17047
17048@smallexample
17049Save for Future Sessions
17050@end smallexample
17051
17052@noindent
17053Emacs will write an expression into your @file{.emacs} file.
17054It will look like this:
17055
17056@smallexample
17057@group
17058(custom-set-variables
17059 ;; custom-set-variables was added by Custom.
17060 ;; If you edit it by hand, you could mess it up, so be careful.
17061 ;; Your init file should contain only one such instance.
17062 ;; If there is more than one, they won't work right.
17063 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
17064@end group
17065@end smallexample
17066
17067@noindent
17068(The @code{text-mode-hook-identify} function tells
17069@code{toggle-text-mode-auto-fill} which buffers are in Text mode.
17070It comes on automatically.)
17071
17072The @code{custom-set-variables} function works somewhat differently
17073than a @code{setq}. While I have never learned the differences, I
17074modify the @code{custom-set-variables} expressions in my @file{.emacs}
17075file by hand: I make the changes in what appears to me to be a
17076reasonable manner and have not had any problems. Others prefer to use
17077the Customization command and let Emacs do the work for them.
17078
17079Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
17080This function sets the various font faces. Over time, I have set a
17081considerable number of faces. Some of the time, I re-set them using
17082@code{customize}; other times, I simply edit the
17083@code{custom-set-faces} expression in my @file{.emacs} file itself.
17084
17085The second way to customize your @code{text-mode-hook} is to set it
17086yourself in your @file{.emacs} file using code that has nothing to do
17087with the @code{custom-set-@dots{}} functions.
17088
17089@need 800
17090When you do this, and later use @code{customize}, you will see a
17091message that says
17092
17093@smallexample
17094CHANGED outside Customize; operating on it here may be unreliable.
17095@end smallexample
17096
17097@need 800
17098This message is only a warning. If you click on the button to
17099
17100@smallexample
17101Save for Future Sessions
17102@end smallexample
17103
17104@noindent
17105Emacs will write a @code{custom-set-@dots{}} expression near the end
17106of your @file{.emacs} file that will be evaluated after your
17107hand-written expression. It will, therefore, overrule your
17108hand-written expression. No harm will be done. When you do this,
17109however, be careful to remember which expression is active; if you
17110forget, you may confuse yourself.
17111
17112So long as you remember where the values are set, you will have no
17113trouble. In any event, the values are always set in your
17114initialization file, which is usually called @file{.emacs}.
17115
17116I myself use @code{customize} for hardly anything. Mostly, I write
17117expressions myself.
17118
17119@findex defsubst
17120@findex defconst
17121Incidentally, to be more complete concerning defines: @code{defsubst}
17122defines an inline function. The syntax is just like that of
17123@code{defun}. @code{defconst} defines a symbol as a constant. The
17124intent is that neither programs nor users should ever change a value
17125set by @code{defconst}. (You can change it; the value set is a
17126variable; but please do not.)
17127
d6adf7e7 17128@node Beginning a .emacs File
8cda6f8f
GM
17129@section Beginning a @file{.emacs} File
17130@cindex @file{.emacs} file, beginning of
17131
17132When you start Emacs, it loads your @file{.emacs} file unless you tell
17133it not to by specifying @samp{-q} on the command line. (The
17134@code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
17135
17136A @file{.emacs} file contains Lisp expressions. Often, these are no
17137more than expressions to set values; sometimes they are function
17138definitions.
17139
17140@xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
17141Manual}, for a short description of initialization files.
17142
17143This chapter goes over some of the same ground, but is a walk among
17144extracts from a complete, long-used @file{.emacs} file---my own.
17145
17146The first part of the file consists of comments: reminders to myself.
17147By now, of course, I remember these things, but when I started, I did
17148not.
17149
17150@need 1200
17151@smallexample
17152@group
17153;;;; Bob's .emacs file
17154; Robert J. Chassell
17155; 26 September 1985
17156@end group
17157@end smallexample
17158
17159@noindent
17160Look at that date! I started this file a long time ago. I have been
17161adding to it ever since.
17162
17163@smallexample
17164@group
17165; Each section in this file is introduced by a
17166; line beginning with four semicolons; and each
17167; entry is introduced by a line beginning with
17168; three semicolons.
17169@end group
17170@end smallexample
17171
17172@noindent
17173This describes the usual conventions for comments in Emacs Lisp.
17174Everything on a line that follows a semicolon is a comment. Two,
17175three, and four semicolons are used as subsection and section markers.
17176(@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference Manual}, for
17177more about comments.)
17178
17179@smallexample
17180@group
17181;;;; The Help Key
17182; Control-h is the help key;
17183; after typing control-h, type a letter to
17184; indicate the subject about which you want help.
17185; For an explanation of the help facility,
17186; type control-h two times in a row.
17187@end group
17188@end smallexample
17189
17190@noindent
17191Just remember: type @kbd{C-h} two times for help.
17192
17193@smallexample
17194@group
17195; To find out about any mode, type control-h m
17196; while in that mode. For example, to find out
17197; about mail mode, enter mail mode and then type
17198; control-h m.
17199@end group
17200@end smallexample
17201
17202@noindent
17203`Mode help', as I call this, is very helpful. Usually, it tells you
17204all you need to know.
17205
17206Of course, you don't need to include comments like these in your
17207@file{.emacs} file. I included them in mine because I kept forgetting
17208about Mode help or the conventions for comments---but I was able to
17209remember to look here to remind myself.
17210
d6adf7e7 17211@node Text and Auto-fill
8cda6f8f
GM
17212@section Text and Auto Fill Mode
17213
17214Now we come to the part that `turns on' Text mode and
17215Auto Fill mode.
17216
17217@smallexample
17218@group
17219;;; Text mode and Auto Fill mode
cd61af01
SM
17220;; The next two lines put Emacs into Text mode
17221;; and Auto Fill mode, and are for writers who
17222;; want to start writing prose rather than code.
17223(setq-default major-mode 'text-mode)
8cda6f8f
GM
17224(add-hook 'text-mode-hook 'turn-on-auto-fill)
17225@end group
17226@end smallexample
17227
17228Here is the first part of this @file{.emacs} file that does something
17229besides remind a forgetful human!
17230
17231The first of the two lines in parentheses tells Emacs to turn on Text
17232mode when you find a file, @emph{unless} that file should go into some
17233other mode, such as C mode.
17234
17235@cindex Per-buffer, local variables list
17236@cindex Local variables list, per-buffer,
17237@cindex Automatic mode selection
17238@cindex Mode selection, automatic
17239When Emacs reads a file, it looks at the extension to the file name,
17240if any. (The extension is the part that comes after a @samp{.}.) If
17241the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
17242on C mode. Also, Emacs looks at first nonblank line of the file; if
17243the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
17244possesses a list of extensions and specifications that it uses
17245automatically. In addition, Emacs looks near the last page for a
17246per-buffer, ``local variables list'', if any.
17247
17248@ifinfo
17249@xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
17250Emacs Manual}.
17251
17252@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17253Manual}.
17254@end ifinfo
17255@iftex
17256See sections ``How Major Modes are Chosen'' and ``Local Variables in
17257Files'' in @cite{The GNU Emacs Manual}.
17258@end iftex
17259
17260Now, back to the @file{.emacs} file.
17261
17262@need 800
17263Here is the line again; how does it work?
17264
17265@cindex Text Mode turned on
17266@smallexample
4e3b4528 17267(setq major-mode 'text-mode)
8cda6f8f
GM
17268@end smallexample
17269
17270@noindent
17271This line is a short, but complete Emacs Lisp expression.
17272
17273We are already familiar with @code{setq}. It sets the following variable,
4e3b4528
SM
17274@code{major-mode}, to the subsequent value, which is @code{text-mode}.
17275The single quote mark before @code{text-mode} tells Emacs to deal directly
17276with the @code{text-mode} symbol, not with whatever it might stand for.
17277@xref{set & setq, , Setting the Value of a Variable},
17278for a reminder of how @code{setq} works.
17279The main point is that there is no difference between the procedure you
17280use to set a value in your @file{.emacs} file and the procedure you use
17281anywhere else in Emacs.
8cda6f8f
GM
17282
17283@need 800
17284Here is the next line:
17285
17286@cindex Auto Fill mode turned on
17287@findex add-hook
17288@smallexample
17289(add-hook 'text-mode-hook 'turn-on-auto-fill)
17290@end smallexample
17291
17292@noindent
17293In this line, the @code{add-hook} command adds
17294@code{turn-on-auto-fill} to the variable.
17295
17296@code{turn-on-auto-fill} is the name of a program, that, you guessed
17297it!, turns on Auto Fill mode.
17298
17299Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
17300onto Text mode. So every time Emacs turns on Text mode, Emacs also
17301turns on Auto Fill mode.
17302
17303In brief, the first line causes Emacs to enter Text mode when you edit a
17304file, unless the file name extension, a first non-blank line, or local
17305variables to tell Emacs otherwise.
17306
17307Text mode among other actions, sets the syntax table to work
17308conveniently for writers. In Text mode, Emacs considers an apostrophe
17309as part of a word like a letter; but Emacs does not consider a period
17310or a space as part of a word. Thus, @kbd{M-f} moves you over
17311@samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
17312the @samp{t} of @samp{it's}.
17313
17314The second line causes Emacs to turn on Auto Fill mode when it turns
17315on Text mode. In Auto Fill mode, Emacs automatically breaks a line
17316that is too wide and brings the excessively wide part of the line down
17317to the next line. Emacs breaks lines between words, not within them.
17318
17319When Auto Fill mode is turned off, lines continue to the right as you
17320type them. Depending on how you set the value of
17321@code{truncate-lines}, the words you type either disappear off the
17322right side of the screen, or else are shown, in a rather ugly and
17323unreadable manner, as a continuation line on the screen.
17324
17325@need 1250
17326In addition, in this part of my @file{.emacs} file, I tell the Emacs
17327fill commands to insert two spaces after a colon:
17328
17329@smallexample
17330(setq colon-double-space t)
17331@end smallexample
17332
d6adf7e7 17333@node Mail Aliases
8cda6f8f
GM
17334@section Mail Aliases
17335
17336Here is a @code{setq} that `turns on' mail aliases, along with more
17337reminders.
17338
17339@smallexample
17340@group
17341;;; Mail mode
17342; To enter mail mode, type `C-x m'
17343; To enter RMAIL (for reading mail),
17344; type `M-x rmail'
17345(setq mail-aliases t)
17346@end group
17347@end smallexample
17348
17349@cindex Mail aliases
17350@noindent
17351This @code{setq} command sets the value of the variable
17352@code{mail-aliases} to @code{t}. Since @code{t} means true, the line
17353says, in effect, ``Yes, use mail aliases.''
17354
17355Mail aliases are convenient short names for long email addresses or
17356for lists of email addresses. The file where you keep your `aliases'
17357is @file{~/.mailrc}. You write an alias like this:
17358
17359@smallexample
17360alias geo george@@foobar.wiz.edu
17361@end smallexample
17362
17363@noindent
17364When you write a message to George, address it to @samp{geo}; the
17365mailer will automatically expand @samp{geo} to the full address.
17366
d6adf7e7 17367@node Indent Tabs Mode
8cda6f8f
GM
17368@section Indent Tabs Mode
17369@cindex Tabs, preventing
17370@findex indent-tabs-mode
17371
17372By default, Emacs inserts tabs in place of multiple spaces when it
17373formats a region. (For example, you might indent many lines of text
17374all at once with the @code{indent-region} command.) Tabs look fine on
17375a terminal or with ordinary printing, but they produce badly indented
17376output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
17377
17378@need 1250
17379The following turns off Indent Tabs mode:
17380
17381@smallexample
17382@group
17383;;; Prevent Extraneous Tabs
17384(setq-default indent-tabs-mode nil)
17385@end group
17386@end smallexample
17387
17388Note that this line uses @code{setq-default} rather than the
17389@code{setq} command that we have seen before. The @code{setq-default}
17390command sets values only in buffers that do not have their own local
17391values for the variable.
17392
17393@ifinfo
17394@xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
17395
17396@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17397Manual}.
17398@end ifinfo
17399@iftex
17400See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
17401Files'' in @cite{The GNU Emacs Manual}.
17402@end iftex
17403
17404@need 1700
d6adf7e7 17405@node Keybindings
8cda6f8f
GM
17406@section Some Keybindings
17407
17408Now for some personal keybindings:
17409
17410@smallexample
17411@group
17412;;; Compare windows
17413(global-set-key "\C-cw" 'compare-windows)
17414@end group
17415@end smallexample
17416
17417@findex compare-windows
17418@code{compare-windows} is a nifty command that compares the text in
17419your current window with text in the next window. It makes the
17420comparison by starting at point in each window, moving over text in
17421each window as far as they match. I use this command all the time.
17422
17423This also shows how to set a key globally, for all modes.
17424
17425@cindex Setting a key globally
17426@cindex Global set key
17427@cindex Key setting globally
17428@findex global-set-key
17429The command is @code{global-set-key}. It is followed by the
17430keybinding. In a @file{.emacs} file, the keybinding is written as
17431shown: @code{\C-c} stands for `control-c', which means `press the
17432control key and the @key{c} key at the same time'. The @code{w} means
17433`press the @key{w} key'. The keybinding is surrounded by double
17434quotation marks. In documentation, you would write this as
17435@w{@kbd{C-c w}}. (If you were binding a @key{META} key, such as
17436@kbd{M-c}, rather than a @key{CTRL} key, you would write
17437@w{@code{\M-c}} in your @file{.emacs} file. @xref{Init Rebinding, ,
17438Rebinding Keys in Your Init File, emacs, The GNU Emacs Manual}, for
17439details.)
17440
17441The command invoked by the keys is @code{compare-windows}. Note that
17442@code{compare-windows} is preceded by a single quote; otherwise, Emacs
17443would first try to evaluate the symbol to determine its value.
17444
17445These three things, the double quotation marks, the backslash before
17446the @samp{C}, and the single quote mark are necessary parts of
17447keybinding that I tend to forget. Fortunately, I have come to
17448remember that I should look at my existing @file{.emacs} file, and
17449adapt what is there.
17450
17451As for the keybinding itself: @kbd{C-c w}. This combines the prefix
17452key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
17453set of keys, @kbd{C-c} followed by a single character, is strictly
17454reserved for individuals' own use. (I call these `own' keys, since
17455these are for my own use.) You should always be able to create such a
17456keybinding for your own use without stomping on someone else's
17457keybinding. If you ever write an extension to Emacs, please avoid
17458taking any of these keys for public use. Create a key like @kbd{C-c
17459C-w} instead. Otherwise, we will run out of `own' keys.
17460
17461@need 1250
17462Here is another keybinding, with a comment:
17463
17464@smallexample
17465@group
17466;;; Keybinding for `occur'
17467; I use occur a lot, so let's bind it to a key:
17468(global-set-key "\C-co" 'occur)
17469@end group
17470@end smallexample
17471
17472@findex occur
17473The @code{occur} command shows all the lines in the current buffer
17474that contain a match for a regular expression. Matching lines are
17475shown in a buffer called @file{*Occur*}. That buffer serves as a menu
17476to jump to occurrences.
17477
17478@findex global-unset-key
17479@cindex Unbinding key
17480@cindex Key unbinding
17481@need 1250
17482Here is how to unbind a key, so it does not
17483work:
17484
17485@smallexample
17486@group
17487;;; Unbind `C-x f'
17488(global-unset-key "\C-xf")
17489@end group
17490@end smallexample
17491
17492There is a reason for this unbinding: I found I inadvertently typed
17493@w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
17494file, as I intended, I accidentally set the width for filled text,
17495almost always to a width I did not want. Since I hardly ever reset my
17496default width, I simply unbound the key.
17497
17498@findex list-buffers, @r{rebound}
17499@findex buffer-menu, @r{bound to key}
17500@need 1250
17501The following rebinds an existing key:
17502
17503@smallexample
17504@group
17505;;; Rebind `C-x C-b' for `buffer-menu'
17506(global-set-key "\C-x\C-b" 'buffer-menu)
17507@end group
17508@end smallexample
17509
17510By default, @kbd{C-x C-b} runs the
17511@code{list-buffers} command. This command lists
17512your buffers in @emph{another} window. Since I
17513almost always want to do something in that
17514window, I prefer the @code{buffer-menu}
17515command, which not only lists the buffers,
17516but moves point into that window.
17517
d6adf7e7 17518@node Keymaps
8cda6f8f
GM
17519@section Keymaps
17520@cindex Keymaps
17521@cindex Rebinding keys
17522
17523Emacs uses @dfn{keymaps} to record which keys call which commands.
17524When you use @code{global-set-key} to set the keybinding for a single
17525command in all parts of Emacs, you are specifying the keybinding in
17526@code{current-global-map}.
17527
17528Specific modes, such as C mode or Text mode, have their own keymaps;
17529the mode-specific keymaps override the global map that is shared by
17530all buffers.
17531
17532The @code{global-set-key} function binds, or rebinds, the global
17533keymap. For example, the following binds the key @kbd{C-x C-b} to the
17534function @code{buffer-menu}:
17535
17536@smallexample
17537(global-set-key "\C-x\C-b" 'buffer-menu)
17538@end smallexample
17539
17540Mode-specific keymaps are bound using the @code{define-key} function,
17541which takes a specific keymap as an argument, as well as the key and
17542the command. For example, my @file{.emacs} file contains the
17543following expression to bind the @code{texinfo-insert-@@group} command
17544to @kbd{C-c C-c g}:
17545
17546@smallexample
17547@group
17548(define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
17549@end group
17550@end smallexample
17551
17552@noindent
17553The @code{texinfo-insert-@@group} function itself is a little extension
17554to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
17555use this command all the time and prefer to type the three strokes
17556@kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
17557(@samp{@@group} and its matching @samp{@@end group} are commands that
17558keep all enclosed text together on one page; many multi-line examples
17559in this book are surrounded by @samp{@@group @dots{} @@end group}.)
17560
17561@need 1250
17562Here is the @code{texinfo-insert-@@group} function definition:
17563
17564@smallexample
17565@group
17566(defun texinfo-insert-@@group ()
17567 "Insert the string @@group in a Texinfo buffer."
17568 (interactive)
17569 (beginning-of-line)
17570 (insert "@@group\n"))
17571@end group
17572@end smallexample
17573
17574(Of course, I could have used Abbrev mode to save typing, rather than
17575write a function to insert a word; but I prefer key strokes consistent
17576with other Texinfo mode key bindings.)
17577
17578You will see numerous @code{define-key} expressions in
17579@file{loaddefs.el} as well as in the various mode libraries, such as
17580@file{cc-mode.el} and @file{lisp-mode.el}.
17581
17582@xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
17583Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
17584Reference Manual}, for more information about keymaps.
17585
d6adf7e7 17586@node Loading Files
8cda6f8f
GM
17587@section Loading Files
17588@cindex Loading files
17589@c findex load
17590
17591Many people in the GNU Emacs community have written extensions to
17592Emacs. As time goes by, these extensions are often included in new
17593releases. For example, the Calendar and Diary packages are now part
17594of the standard GNU Emacs, as is Calc.
17595
17596You can use a @code{load} command to evaluate a complete file and
17597thereby install all the functions and variables in the file into Emacs.
17598For example:
17599
17600@c (auto-compression-mode t)
17601
17602@smallexample
17603(load "~/emacs/slowsplit")
17604@end smallexample
17605
1df7defd 17606This evaluates, i.e., loads, the @file{slowsplit.el} file or if it
8cda6f8f
GM
17607exists, the faster, byte compiled @file{slowsplit.elc} file from the
17608@file{emacs} sub-directory of your home directory. The file contains
17609the function @code{split-window-quietly}, which John Robinson wrote in
176101989.
17611
17612The @code{split-window-quietly} function splits a window with the
17613minimum of redisplay. I installed it in 1989 because it worked well
17614with the slow 1200 baud terminals I was then using. Nowadays, I only
17615occasionally come across such a slow connection, but I continue to use
17616the function because I like the way it leaves the bottom half of a
17617buffer in the lower of the new windows and the top half in the upper
17618window.
17619
17620@need 1250
17621To replace the key binding for the default
17622@code{split-window-vertically}, you must also unset that key and bind
17623the keys to @code{split-window-quietly}, like this:
17624
17625@smallexample
17626@group
17627(global-unset-key "\C-x2")
17628(global-set-key "\C-x2" 'split-window-quietly)
17629@end group
17630@end smallexample
17631
17632@vindex load-path
17633If you load many extensions, as I do, then instead of specifying the
17634exact location of the extension file, as shown above, you can specify
44e97401 17635that directory as part of Emacs's @code{load-path}. Then, when Emacs
8cda6f8f
GM
17636loads a file, it will search that directory as well as its default
17637list of directories. (The default list is specified in @file{paths.h}
17638when Emacs is built.)
17639
17640@need 1250
17641The following command adds your @file{~/emacs} directory to the
17642existing load path:
17643
17644@smallexample
17645@group
17646;;; Emacs Load Path
17647(setq load-path (cons "~/emacs" load-path))
17648@end group
17649@end smallexample
17650
17651Incidentally, @code{load-library} is an interactive interface to the
17652@code{load} function. The complete function looks like this:
17653
17654@findex load-library
17655@smallexample
17656@group
17657(defun load-library (library)
17658 "Load the library named LIBRARY.
17659This is an interface to the function `load'."
17660 (interactive
17661 (list (completing-read "Load library: "
e0e10d9d 17662 (apply-partially 'locate-file-completion-table
f51f97dd
SM
17663 load-path
17664 (get-load-suffixes)))))
8cda6f8f
GM
17665 (load library))
17666@end group
17667@end smallexample
17668
17669The name of the function, @code{load-library}, comes from the use of
17670`library' as a conventional synonym for `file'. The source for the
17671@code{load-library} command is in the @file{files.el} library.
17672
17673Another interactive command that does a slightly different job is
17674@code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
17675Emacs, emacs, The GNU Emacs Manual}, for information on the
17676distinction between @code{load-library} and this command.
17677
d6adf7e7 17678@node Autoload
8cda6f8f
GM
17679@section Autoloading
17680@findex autoload
17681
17682Instead of installing a function by loading the file that contains it,
17683or by evaluating the function definition, you can make the function
17684available but not actually install it until it is first called. This
17685is called @dfn{autoloading}.
17686
17687When you execute an autoloaded function, Emacs automatically evaluates
17688the file that contains the definition, and then calls the function.
17689
17690Emacs starts quicker with autoloaded functions, since their libraries
17691are not loaded right away; but you need to wait a moment when you
17692first use such a function, while its containing file is evaluated.
17693
17694Rarely used functions are frequently autoloaded. The
17695@file{loaddefs.el} library contains hundreds of autoloaded functions,
17696from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
17697come to use a `rare' function frequently. When you do, you should
17698load that function's file with a @code{load} expression in your
17699@file{.emacs} file.
17700
17701In my @file{.emacs} file, I load 14 libraries that contain functions
17702that would otherwise be autoloaded. (Actually, it would have been
17703better to include these files in my `dumped' Emacs, but I forgot.
17704@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17705Reference Manual}, and the @file{INSTALL} file for more about
17706dumping.)
17707
17708You may also want to include autoloaded expressions in your @file{.emacs}
17709file. @code{autoload} is a built-in function that takes up to five
17710arguments, the final three of which are optional. The first argument
17711is the name of the function to be autoloaded; the second is the name
17712of the file to be loaded. The third argument is documentation for the
17713function, and the fourth tells whether the function can be called
17714interactively. The fifth argument tells what type of
17715object---@code{autoload} can handle a keymap or macro as well as a
17716function (the default is a function).
17717
17718@need 800
17719Here is a typical example:
17720
17721@smallexample
17722@group
17723(autoload 'html-helper-mode
17724 "html-helper-mode" "Edit HTML documents" t)
17725@end group
17726@end smallexample
17727
17728@noindent
17729(@code{html-helper-mode} is an older alternative to @code{html-mode},
17730which is a standard part of the distribution.)
17731
17732@noindent
17733This expression autoloads the @code{html-helper-mode} function. It
17734takes it from the @file{html-helper-mode.el} file (or from the byte
a9097c6d
KB
17735compiled version @file{html-helper-mode.elc}, if that exists.) The
17736file must be located in a directory specified by @code{load-path}.
17737The documentation says that this is a mode to help you edit documents
8cda6f8f
GM
17738written in the HyperText Markup Language. You can call this mode
17739interactively by typing @kbd{M-x html-helper-mode}. (You need to
17740duplicate the function's regular documentation in the autoload
17741expression because the regular function is not yet loaded, so its
17742documentation is not available.)
17743
17744@xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
17745Manual}, for more information.
17746
d6adf7e7 17747@node Simple Extension
8cda6f8f
GM
17748@section A Simple Extension: @code{line-to-top-of-window}
17749@findex line-to-top-of-window
17750@cindex Simple extension in @file{.emacs} file
17751
17752Here is a simple extension to Emacs that moves the line point is on to
17753the top of the window. I use this all the time, to make text easier
17754to read.
17755
17756You can put the following code into a separate file and then load it
17757from your @file{.emacs} file, or you can include it within your
17758@file{.emacs} file.
17759
17760@need 1250
17761Here is the definition:
17762
17763@smallexample
17764@group
17765;;; Line to top of window;
17766;;; replace three keystroke sequence C-u 0 C-l
17767(defun line-to-top-of-window ()
17768 "Move the line point is on to top of window."
17769 (interactive)
17770 (recenter 0))
17771@end group
17772@end smallexample
17773
17774@need 1250
17775Now for the keybinding.
17776
17777Nowadays, function keys as well as mouse button events and
17778non-@sc{ascii} characters are written within square brackets, without
17779quotation marks. (In Emacs version 18 and before, you had to write
17780different function key bindings for each different make of terminal.)
17781
17782I bind @code{line-to-top-of-window} to my @key{F6} function key like
17783this:
17784
17785@smallexample
17786(global-set-key [f6] 'line-to-top-of-window)
17787@end smallexample
17788
17789For more information, see @ref{Init Rebinding, , Rebinding Keys in
17790Your Init File, emacs, The GNU Emacs Manual}.
17791
17792@cindex Conditional 'twixt two versions of Emacs
17793@cindex Version of Emacs, choosing
17794@cindex Emacs version, choosing
6dd28193 17795If you run two versions of GNU Emacs, such as versions 22 and 23, and
8cda6f8f
GM
17796use one @file{.emacs} file, you can select which code to evaluate with
17797the following conditional:
17798
17799@smallexample
17800@group
17801(cond
6dd28193 17802 ((= 22 emacs-major-version)
8cda6f8f 17803 ;; evaluate version 22 code
6dd28193
CY
17804 ( @dots{} ))
17805 ((= 23 emacs-major-version)
17806 ;; evaluate version 23 code
8cda6f8f
GM
17807 ( @dots{} )))
17808@end group
17809@end smallexample
17810
8f4ea8e0 17811For example, recent versions blink
8cda6f8f
GM
17812their cursors by default. I hate such blinking, as well as other
17813features, so I placed the following in my @file{.emacs}
17814file@footnote{When I start instances of Emacs that do not load my
17815@file{.emacs} file or any site file, I also turn off blinking:
17816
17817@smallexample
17818emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
17819
17820@exdent Or nowadays, using an even more sophisticated set of options,
17821
9450ac06 17822emacs -Q -D
8cda6f8f
GM
17823@end smallexample
17824}:
17825
17826@smallexample
17827@group
6dd28193
CY
17828(when (>= emacs-major-version 21)
17829 (blink-cursor-mode 0)
17830 ;; Insert newline when you press `C-n' (next-line)
17831 ;; at the end of the buffer
17832 (setq next-line-add-newlines t)
8cda6f8f
GM
17833@end group
17834@group
6dd28193
CY
17835 ;; Turn on image viewing
17836 (auto-image-file-mode t)
8cda6f8f
GM
17837@end group
17838@group
6dd28193
CY
17839 ;; Turn on menu bar (this bar has text)
17840 ;; (Use numeric argument to turn on)
17841 (menu-bar-mode 1)
8cda6f8f
GM
17842@end group
17843@group
6dd28193
CY
17844 ;; Turn off tool bar (this bar has icons)
17845 ;; (Use numeric argument to turn on)
17846 (tool-bar-mode nil)
8cda6f8f 17847@end group
8cda6f8f 17848@group
6dd28193
CY
17849 ;; Turn off tooltip mode for tool bar
17850 ;; (This mode causes icon explanations to pop up)
17851 ;; (Use numeric argument to turn on)
17852 (tooltip-mode nil)
17853 ;; If tooltips turned on, make tips appear promptly
17854 (setq tooltip-delay 0.1) ; default is 0.7 second
17855 )
8cda6f8f
GM
17856@end group
17857@end smallexample
17858
d6adf7e7 17859@node X11 Colors
8cda6f8f
GM
17860@section X11 Colors
17861
17862You can specify colors when you use Emacs with the MIT X Windowing
17863system.
17864
17865I dislike the default colors and specify my own.
17866
17867@need 1250
17868Here are the expressions in my @file{.emacs}
17869file that set values:
17870
17871@smallexample
17872@group
17873;; Set cursor color
17874(set-cursor-color "white")
17875
17876;; Set mouse color
17877(set-mouse-color "white")
17878
17879;; Set foreground and background
17880(set-foreground-color "white")
17881(set-background-color "darkblue")
17882@end group
17883
17884@group
17885;;; Set highlighting colors for isearch and drag
17886(set-face-foreground 'highlight "white")
17887(set-face-background 'highlight "blue")
17888@end group
17889
17890@group
17891(set-face-foreground 'region "cyan")
17892(set-face-background 'region "blue")
17893@end group
17894
17895@group
17896(set-face-foreground 'secondary-selection "skyblue")
17897(set-face-background 'secondary-selection "darkblue")
17898@end group
17899
17900@group
17901;; Set calendar highlighting colors
17902(setq calendar-load-hook
d1069532
SM
17903 (lambda ()
17904 (set-face-foreground 'diary-face "skyblue")
17905 (set-face-background 'holiday-face "slate blue")
17906 (set-face-foreground 'holiday-face "white")))
8cda6f8f
GM
17907@end group
17908@end smallexample
17909
17910The various shades of blue soothe my eye and prevent me from seeing
17911the screen flicker.
17912
17913Alternatively, I could have set my specifications in various X
17914initialization files. For example, I could set the foreground,
17915background, cursor, and pointer (i.e., mouse) colors in my
17916@file{~/.Xresources} file like this:
17917
17918@smallexample
17919@group
17920Emacs*foreground: white
17921Emacs*background: darkblue
17922Emacs*cursorColor: white
17923Emacs*pointerColor: white
17924@end group
17925@end smallexample
17926
17927In any event, since it is not part of Emacs, I set the root color of
17928my X window in my @file{~/.xinitrc} file, like this@footnote{I also
17929run more modern window managers, such as Enlightenment, Gnome, or KDE;
17930in those cases, I often specify an image rather than a plain color.}:
17931
17932@smallexample
17933xsetroot -solid Navy -fg white &
17934@end smallexample
17935
17936@need 1700
d6adf7e7 17937@node Miscellaneous
8cda6f8f
GM
17938@section Miscellaneous Settings for a @file{.emacs} File
17939
17940@need 1250
17941Here are a few miscellaneous settings:
17942@sp 1
17943
17944@itemize @minus
17945@item
17946Set the shape and color of the mouse cursor:
17947
17948@smallexample
17949@group
17950; Cursor shapes are defined in
17951; `/usr/include/X11/cursorfont.h';
17952; for example, the `target' cursor is number 128;
17953; the `top_left_arrow' cursor is number 132.
17954@end group
17955
17956@group
17957(let ((mpointer (x-get-resource "*mpointer"
17958 "*emacs*mpointer")))
17959 ;; If you have not set your mouse pointer
17960 ;; then set it, otherwise leave as is:
17961 (if (eq mpointer nil)
17962 (setq mpointer "132")) ; top_left_arrow
17963@end group
17964@group
17965 (setq x-pointer-shape (string-to-int mpointer))
17966 (set-mouse-color "white"))
17967@end group
17968@end smallexample
17969
17970@item
17971Or you can set the values of a variety of features in an alist, like
17972this:
17973
17974@smallexample
17975@group
17976(setq-default
17977 default-frame-alist
17978 '((cursor-color . "white")
17979 (mouse-color . "white")
17980 (foreground-color . "white")
17981 (background-color . "DodgerBlue4")
17982 ;; (cursor-type . bar)
17983 (cursor-type . box)
17984@end group
17985@group
17986 (tool-bar-lines . 0)
17987 (menu-bar-lines . 1)
17988 (width . 80)
17989 (height . 58)
17990 (font .
17991 "-Misc-Fixed-Medium-R-Normal--20-200-75-75-C-100-ISO8859-1")
17992 ))
17993@end group
17994@end smallexample
17995
17996@item
17997Convert @kbd{@key{CTRL}-h} into @key{DEL} and @key{DEL}
17998into @kbd{@key{CTRL}-h}.@*
17999(Some older keyboards needed this, although I have not seen the
18000problem recently.)
18001
18002@smallexample
18003@group
18004;; Translate `C-h' to <DEL>.
18005; (keyboard-translate ?\C-h ?\C-?)
18006
18007;; Translate <DEL> to `C-h'.
18008(keyboard-translate ?\C-? ?\C-h)
18009@end group
18010@end smallexample
18011
18012@item Turn off a blinking cursor!
18013
18014@smallexample
18015@group
18016(if (fboundp 'blink-cursor-mode)
18017 (blink-cursor-mode -1))
18018@end group
18019@end smallexample
18020
18021@noindent
18022or start GNU Emacs with the command @code{emacs -nbc}.
18023
18024@need 1250
18025@item When using `grep'@*
18026@samp{-i}@w{ } Ignore case distinctions@*
18027@samp{-n}@w{ } Prefix each line of output with line number@*
18028@samp{-H}@w{ } Print the filename for each match.@*
18029@samp{-e}@w{ } Protect patterns beginning with a hyphen character, @samp{-}
18030
18031@smallexample
18032(setq grep-command "grep -i -nH -e ")
18033@end smallexample
18034
18035@ignore
18036@c Evidently, no longer needed in GNU Emacs 22
18037
18038item Automatically uncompress compressed files when visiting them
18039
18040smallexample
18041(load "uncompress")
18042end smallexample
18043
18044@end ignore
18045
18046@item Find an existing buffer, even if it has a different name@*
18047This avoids problems with symbolic links.
18048
18049@smallexample
18050(setq find-file-existing-other-name t)
18051@end smallexample
18052
18053@item Set your language environment and default input method
18054
18055@smallexample
18056@group
18057(set-language-environment "latin-1")
18058;; Remember you can enable or disable multilingual text input
18059;; with the @code{toggle-input-method'} (@kbd{C-\}) command
18060(setq default-input-method "latin-1-prefix")
18061@end group
18062@end smallexample
18063
18064If you want to write with Chinese `GB' characters, set this instead:
18065
18066@smallexample
18067@group
18068(set-language-environment "Chinese-GB")
18069(setq default-input-method "chinese-tonepy")
18070@end group
18071@end smallexample
18072@end itemize
18073
18074@subsubheading Fixing Unpleasant Key Bindings
18075@cindex Key bindings, fixing
18076@cindex Bindings, key, fixing unpleasant
18077
18078Some systems bind keys unpleasantly. Sometimes, for example, the
18079@key{CTRL} key appears in an awkward spot rather than at the far left
18080of the home row.
18081
18082Usually, when people fix these sorts of keybindings, they do not
18083change their @file{~/.emacs} file. Instead, they bind the proper keys
18084on their consoles with the @code{loadkeys} or @code{install-keymap}
18085commands in their boot script and then include @code{xmodmap} commands
18086in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
18087
18088@need 1250
18089@noindent
18090For a boot script:
18091
18092@smallexample
18093@group
18094loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
18095@exdent or
18096install-keymap emacs2
18097@end group
18098@end smallexample
18099
18100@need 1250
18101@noindent
18102For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
18103Lock} key is at the far left of the home row:
18104
18105@smallexample
18106@group
18107# Bind the key labeled `Caps Lock' to `Control'
18108# (Such a broken user interface suggests that keyboard manufacturers
18109# think that computers are typewriters from 1885.)
18110
18111xmodmap -e "clear Lock"
18112xmodmap -e "add Control = Caps_Lock"
18113@end group
18114@end smallexample
18115
18116@need 1250
18117@noindent
18118In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
18119key to a @key{META} key:
18120
18121@smallexample
18122@group
18123# Some ill designed keyboards have a key labeled ALT and no Meta
18124xmodmap -e "keysym Alt_L = Meta_L Alt_L"
18125@end group
18126@end smallexample
18127
18128@need 1700
d6adf7e7 18129@node Mode Line
8cda6f8f 18130@section A Modified Mode Line
cd61af01 18131@vindex mode-line-format
8cda6f8f
GM
18132@cindex Mode line format
18133
18134Finally, a feature I really like: a modified mode line.
18135
18136When I work over a network, I forget which machine I am using. Also,
18137I tend to I lose track of where I am, and which line point is on.
18138
18139So I reset my mode line to look like this:
18140
18141@smallexample
18142-:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
18143@end smallexample
18144
18145I am visiting a file called @file{foo.texi}, on my machine
18146@file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
18147Texinfo mode, and am at the top of the buffer.
18148
18149@need 1200
18150My @file{.emacs} file has a section that looks like this:
18151
18152@smallexample
18153@group
18154;; Set a Mode Line that tells me which machine, which directory,
18155;; and which line I am on, plus the other customary information.
cd61af01 18156(setq-default mode-line-format
8cda6f8f
GM
18157 (quote
18158 (#("-" 0 1
18159 (help-echo
18160 "mouse-1: select window, mouse-2: delete others ..."))
18161 mode-line-mule-info
18162 mode-line-modified
18163 mode-line-frame-identification
18164 " "
18165@end group
18166@group
18167 mode-line-buffer-identification
18168 " "
18169 (:eval (substring
18170 (system-name) 0 (string-match "\\..+" (system-name))))
18171 ":"
18172 default-directory
18173 #(" " 0 1
18174 (help-echo
18175 "mouse-1: select window, mouse-2: delete others ..."))
18176 (line-number-mode " Line %l ")
18177 global-mode-string
18178@end group
18179@group
18180 #(" %[(" 0 6
18181 (help-echo
18182 "mouse-1: select window, mouse-2: delete others ..."))
18183 (:eval (mode-line-mode-name))
18184 mode-line-process
18185 minor-mode-alist
18186 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
18187 ")%] "
18188 (-3 . "%P")
18189 ;; "-%-"
18190 )))
18191@end group
18192@end smallexample
18193
18194@noindent
18195Here, I redefine the default mode line. Most of the parts are from
18196the original; but I make a few changes. I set the @emph{default} mode
18197line format so as to permit various modes, such as Info, to override
18198it.
18199
18200Many elements in the list are self-explanatory:
18201@code{mode-line-modified} is a variable that tells whether the buffer
18202has been modified, @code{mode-name} tells the name of the mode, and so
18203on. However, the format looks complicated because of two features we
18204have not discussed.
18205
18206@cindex Properties, in mode line example
18207The first string in the mode line is a dash or hyphen, @samp{-}. In
18208the old days, it would have been specified simply as @code{"-"}. But
18209nowadays, Emacs can add properties to a string, such as highlighting
18210or, as in this case, a help feature. If you place your mouse cursor
18211over the hyphen, some help information appears (By default, you must
18212wait seven-tenths of a second before the information appears. You can
18213change that timing by changing the value of @code{tooltip-delay}.)
18214
18215@need 1000
18216The new string format has a special syntax:
18217
18218@smallexample
18219#("-" 0 1 (help-echo "mouse-1: select window, ..."))
18220@end smallexample
18221
18222@noindent
18223The @code{#(} begins a list. The first element of the list is the
18224string itself, just one @samp{-}. The second and third
18225elements specify the range over which the fourth element applies. A
18226range starts @emph{after} a character, so a zero means the range
18227starts just before the first character; a 1 means that the range ends
18228just after the first character. The third element is the property for
18229the range. It consists of a property list, a
18230property name, in this case, @samp{help-echo}, followed by a value, in this
18231case, a string. The second, third, and fourth elements of this new
18232string format can be repeated.
18233
18234@xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
18235Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
18236elisp, The GNU Emacs Lisp Reference Manual}, for more information.
18237
18238@code{mode-line-buffer-identification}
18239displays the current buffer name. It is a list
18240beginning @code{(#("%12b" 0 4 @dots{}}.
18241The @code{#(} begins the list.
18242
18243The @samp{"%12b"} displays the current buffer name, using the
18244@code{buffer-name} function with which we are familiar; the `12'
18245specifies the maximum number of characters that will be displayed.
18246When a name has fewer characters, whitespace is added to fill out to
18247this number. (Buffer names can and often should be longer than 12
18248characters; this length works well in a typical 80 column wide
18249window.)
18250
18251@code{:eval} says to evaluate the following form and use the result as
18252a string to display. In this case, the expression displays the first
18253component of the full system name. The end of the first component is
18254a @samp{.} (`period'), so I use the @code{string-match} function to
18255tell me the length of the first component. The substring from the
18256zeroth character to that length is the name of the machine.
18257
18258@need 1250
18259This is the expression:
18260
18261@smallexample
18262@group
18263(:eval (substring
18264 (system-name) 0 (string-match "\\..+" (system-name))))
18265@end group
18266@end smallexample
18267
18268@samp{%[} and @samp{%]} cause a pair of square brackets
18269to appear for each recursive editing level. @samp{%n} says `Narrow'
18270when narrowing is in effect. @samp{%P} tells you the percentage of
18271the buffer that is above the bottom of the window, or `Top', `Bottom',
18272or `All'. (A lower case @samp{p} tell you the percentage above the
18273@emph{top} of the window.) @samp{%-} inserts enough dashes to fill
18274out the line.
18275
f99f1641 18276Remember, ``You don't have to like Emacs to like it''---your own
8cda6f8f
GM
18277Emacs can have different colors, different commands, and different
18278keys than a default Emacs.
18279
18280On the other hand, if you want to bring up a plain `out of the box'
18281Emacs, with no customization, type:
18282
18283@smallexample
18284emacs -q
18285@end smallexample
18286
18287@noindent
18288This will start an Emacs that does @emph{not} load your
18289@file{~/.emacs} initialization file. A plain, default Emacs. Nothing
18290more.
18291
d6adf7e7 18292@node Debugging
8cda6f8f
GM
18293@chapter Debugging
18294@cindex debugging
18295
18296GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
18297first is built into the internals of Emacs and is always with you;
18298the second requires that you instrument a function before you can use it.
18299
18300Both debuggers are described extensively in @ref{Debugging, ,
18301Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
18302In this chapter, I will walk through a short example of each.
18303
18304@menu
18305* debug:: How to use the built-in debugger.
18306* debug-on-entry:: Start debugging when you call a function.
18307* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
18308* edebug:: How to use Edebug, a source level debugger.
18309* Debugging Exercises::
18310@end menu
18311
d6adf7e7 18312@node debug
8cda6f8f
GM
18313@section @code{debug}
18314@findex debug
18315
18316Suppose you have written a function definition that is intended to
18317return the sum of the numbers 1 through a given number. (This is the
18318@code{triangle} function discussed earlier. @xref{Decrementing
18319Example, , Example with Decrementing Counter}, for a discussion.)
18320@c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
18321
18322However, your function definition has a bug. You have mistyped
18323@samp{1=} for @samp{1-}. Here is the broken definition:
18324
18325@findex triangle-bugged
18326@smallexample
18327@group
18328(defun triangle-bugged (number)
18329 "Return sum of numbers 1 through NUMBER inclusive."
18330 (let ((total 0))
18331 (while (> number 0)
18332 (setq total (+ total number))
18333 (setq number (1= number))) ; @r{Error here.}
18334 total))
18335@end group
18336@end smallexample
18337
18338If you are reading this in Info, you can evaluate this definition in
18339the normal fashion. You will see @code{triangle-bugged} appear in the
18340echo area.
18341
18342@need 1250
18343Now evaluate the @code{triangle-bugged} function with an
18344argument of 4:
18345
18346@smallexample
18347(triangle-bugged 4)
18348@end smallexample
18349
18350@noindent
18351In a recent GNU Emacs, you will create and enter a @file{*Backtrace*}
18352buffer that says:
18353
18354@noindent
18355@smallexample
18356@group
18357---------- Buffer: *Backtrace* ----------
18358Debugger entered--Lisp error: (void-function 1=)
18359 (1= number)
18360 (setq number (1= number))
18361 (while (> number 0) (setq total (+ total number))
18362 (setq number (1= number)))
18363 (let ((total 0)) (while (> number 0) (setq total ...)
18364 (setq number ...)) total)
18365 triangle-bugged(4)
18366@end group
18367@group
18368 eval((triangle-bugged 4))
18369 eval-last-sexp-1(nil)
18370 eval-last-sexp(nil)
18371 call-interactively(eval-last-sexp)
18372---------- Buffer: *Backtrace* ----------
18373@end group
18374@end smallexample
18375
18376@noindent
18377(I have reformatted this example slightly; the debugger does not fold
18378long lines. As usual, you can quit the debugger by typing @kbd{q} in
18379the @file{*Backtrace*} buffer.)
18380
18381In practice, for a bug as simple as this, the `Lisp error' line will
18382tell you what you need to know to correct the definition. The
18383function @code{1=} is `void'.
18384
18385@ignore
18386@need 800
18387In GNU Emacs 20 and before, you will see:
18388
18389@smallexample
18390Symbol's function definition is void:@: 1=
18391@end smallexample
18392
18393@noindent
18394which has the same meaning as the @file{*Backtrace*} buffer line in
18395version 21.
18396@end ignore
18397
18398However, suppose you are not quite certain what is going on?
18399You can read the complete backtrace.
18400
18401In this case, you need to run a recent GNU Emacs, which automatically
18402starts the debugger that puts you in the @file{*Backtrace*} buffer; or
18403else, you need to start the debugger manually as described below.
18404
18405Read the @file{*Backtrace*} buffer from the bottom up; it tells you
18406what Emacs did that led to the error. Emacs made an interactive call
18407to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
18408of the @code{triangle-bugged} expression. Each line above tells you
18409what the Lisp interpreter evaluated next.
18410
18411@need 1250
18412The third line from the top of the buffer is
18413
18414@smallexample
18415(setq number (1= number))
18416@end smallexample
18417
18418@noindent
18419Emacs tried to evaluate this expression; in order to do so, it tried
18420to evaluate the inner expression shown on the second line from the
18421top:
18422
18423@smallexample
18424(1= number)
18425@end smallexample
18426
18427@need 1250
18428@noindent
18429This is where the error occurred; as the top line says:
18430
18431@smallexample
18432Debugger entered--Lisp error: (void-function 1=)
18433@end smallexample
18434
18435@noindent
18436You can correct the mistake, re-evaluate the function definition, and
18437then run your test again.
18438
d6adf7e7 18439@node debug-on-entry
8cda6f8f
GM
18440@section @code{debug-on-entry}
18441@findex debug-on-entry
18442
18443A recent GNU Emacs starts the debugger automatically when your
18444function has an error.
18445
18446@ignore
18447GNU Emacs version 20 and before did not; it simply
18448presented you with an error message. You had to start the debugger
18449manually.
18450@end ignore
18451
18452Incidentally, you can start the debugger manually for all versions of
18453Emacs; the advantage is that the debugger runs even if you do not have
18454a bug in your code. Sometimes your code will be free of bugs!
18455
18456You can enter the debugger when you call the function by calling
18457@code{debug-on-entry}.
18458
18459@need 1250
18460@noindent
18461Type:
18462
18463@smallexample
18464M-x debug-on-entry RET triangle-bugged RET
18465@end smallexample
18466
18467@need 1250
18468@noindent
18469Now, evaluate the following:
18470
18471@smallexample
18472(triangle-bugged 5)
18473@end smallexample
18474
18475@noindent
18476All versions of Emacs will create a @file{*Backtrace*} buffer and tell
18477you that it is beginning to evaluate the @code{triangle-bugged}
18478function:
18479
18480@smallexample
18481@group
18482---------- Buffer: *Backtrace* ----------
18483Debugger entered--entering a function:
18484* triangle-bugged(5)
18485 eval((triangle-bugged 5))
18486@end group
18487@group
18488 eval-last-sexp-1(nil)
18489 eval-last-sexp(nil)
18490 call-interactively(eval-last-sexp)
18491---------- Buffer: *Backtrace* ----------
18492@end group
18493@end smallexample
18494
18495In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
18496the first expression in @code{triangle-bugged}; the buffer will look
18497like this:
18498
18499@smallexample
18500@group
18501---------- Buffer: *Backtrace* ----------
18502Debugger entered--beginning evaluation of function call form:
18503* (let ((total 0)) (while (> number 0) (setq total ...)
18504 (setq number ...)) total)
18505* triangle-bugged(5)
18506 eval((triangle-bugged 5))
18507@end group
18508@group
18509 eval-last-sexp-1(nil)
18510 eval-last-sexp(nil)
18511 call-interactively(eval-last-sexp)
18512---------- Buffer: *Backtrace* ----------
18513@end group
18514@end smallexample
18515
18516@noindent
18517Now, type @kbd{d} again, eight times, slowly. Each time you type
18518@kbd{d}, Emacs will evaluate another expression in the function
18519definition.
18520
18521@need 1750
18522Eventually, the buffer will look like this:
18523
18524@smallexample
18525@group
18526---------- Buffer: *Backtrace* ----------
18527Debugger entered--beginning evaluation of function call form:
18528* (setq number (1= number))
18529* (while (> number 0) (setq total (+ total number))
18530 (setq number (1= number)))
18531@group
18532@end group
18533* (let ((total 0)) (while (> number 0) (setq total ...)
18534 (setq number ...)) total)
18535* triangle-bugged(5)
18536 eval((triangle-bugged 5))
18537@group
18538@end group
18539 eval-last-sexp-1(nil)
18540 eval-last-sexp(nil)
18541 call-interactively(eval-last-sexp)
18542---------- Buffer: *Backtrace* ----------
18543@end group
18544@end smallexample
18545
18546@need 1500
18547@noindent
18548Finally, after you type @kbd{d} two more times, Emacs will reach the
18549error, and the top two lines of the @file{*Backtrace*} buffer will look
18550like this:
18551
18552@smallexample
18553@group
18554---------- Buffer: *Backtrace* ----------
18555Debugger entered--Lisp error: (void-function 1=)
18556* (1= number)
18557@dots{}
18558---------- Buffer: *Backtrace* ----------
18559@end group
18560@end smallexample
18561
18562By typing @kbd{d}, you were able to step through the function.
18563
18564You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
18565quits the trace, but does not cancel @code{debug-on-entry}.
18566
18567@findex cancel-debug-on-entry
18568To cancel the effect of @code{debug-on-entry}, call
18569@code{cancel-debug-on-entry} and the name of the function, like this:
18570
18571@smallexample
18572M-x cancel-debug-on-entry RET triangle-bugged RET
18573@end smallexample
18574
18575@noindent
18576(If you are reading this in Info, cancel @code{debug-on-entry} now.)
18577
d6adf7e7 18578@node debug-on-quit
8cda6f8f
GM
18579@section @code{debug-on-quit} and @code{(debug)}
18580
18581In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
18582there are two other ways to start @code{debug}.
18583
18584@findex debug-on-quit
18585You can start @code{debug} whenever you type @kbd{C-g}
18586(@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
18587@code{t}. This is useful for debugging infinite loops.
18588
18589@need 1500
18590@cindex @code{(debug)} in code
18591Or, you can insert a line that says @code{(debug)} into your code
18592where you want the debugger to start, like this:
18593
18594@smallexample
18595@group
18596(defun triangle-bugged (number)
18597 "Return sum of numbers 1 through NUMBER inclusive."
18598 (let ((total 0))
18599 (while (> number 0)
18600 (setq total (+ total number))
18601 (debug) ; @r{Start debugger.}
18602 (setq number (1= number))) ; @r{Error here.}
18603 total))
18604@end group
18605@end smallexample
18606
18607The @code{debug} function is described in detail in @ref{Debugger, ,
18608The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
18609
d6adf7e7 18610@node edebug
8cda6f8f
GM
18611@section The @code{edebug} Source Level Debugger
18612@cindex Source level debugger
18613@findex edebug
18614
18615Edebug is a source level debugger. Edebug normally displays the
18616source of the code you are debugging, with an arrow at the left that
18617shows which line you are currently executing.
18618
18619You can walk through the execution of a function, line by line, or run
18620quickly until reaching a @dfn{breakpoint} where execution stops.
18621
18622Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18623Lisp Reference Manual}.
18624
18625@need 1250
18626Here is a bugged function definition for @code{triangle-recursively}.
18627@xref{Recursive triangle function, , Recursion in place of a counter},
18628for a review of it.
18629
18630@smallexample
18631@group
18632(defun triangle-recursively-bugged (number)
18633 "Return sum of numbers 1 through NUMBER inclusive.
18634Uses recursion."
18635 (if (= number 1)
18636 1
18637 (+ number
18638 (triangle-recursively-bugged
18639 (1= number))))) ; @r{Error here.}
18640@end group
18641@end smallexample
18642
18643@noindent
18644Normally, you would install this definition by positioning your cursor
18645after the function's closing parenthesis and typing @kbd{C-x C-e}
18646(@code{eval-last-sexp}) or else by positioning your cursor within the
18647definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
18648the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
a1539cd7 18649Interaction mode.)
8cda6f8f
GM
18650
18651@need 1500
18652However, to prepare this function definition for Edebug, you must
18653first @dfn{instrument} the code using a different command. You can do
18654this by positioning your cursor within or just after the definition
18655and typing
18656
18657@smallexample
18658M-x edebug-defun RET
18659@end smallexample
18660
18661@noindent
18662This will cause Emacs to load Edebug automatically if it is not
18663already loaded, and properly instrument the function.
18664
18665After instrumenting the function, place your cursor after the
18666following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
18667
18668@smallexample
18669(triangle-recursively-bugged 3)
18670@end smallexample
18671
18672@noindent
18673You will be jumped back to the source for
18674@code{triangle-recursively-bugged} and the cursor positioned at the
18675beginning of the @code{if} line of the function. Also, you will see
18676an arrowhead at the left hand side of that line. The arrowhead marks
18677the line where the function is executing. (In the following examples,
18678we show the arrowhead with @samp{=>}; in a windowing system, you may
18679see the arrowhead as a solid triangle in the window `fringe'.)
18680
18681@smallexample
18682=>@point{}(if (= number 1)
18683@end smallexample
18684
18685@noindent
18686@iftex
18687In the example, the location of point is displayed with a star,
18688@samp{@point{}} (in Info, it is displayed as @samp{-!-}).
18689@end iftex
18690@ifnottex
18691In the example, the location of point is displayed as @samp{@point{}}
18692(in a printed book, it is displayed with a five pointed star).
18693@end ifnottex
18694
18695If you now press @key{SPC}, point will move to the next expression to
18696be executed; the line will look like this:
18697
18698@smallexample
18699=>(if @point{}(= number 1)
18700@end smallexample
18701
18702@noindent
18703As you continue to press @key{SPC}, point will move from expression to
18704expression. At the same time, whenever an expression returns a value,
18705that value will be displayed in the echo area. For example, after you
18706move point past @code{number}, you will see the following:
18707
18708@smallexample
18709Result: 3 (#o3, #x3, ?\C-c)
18710@end smallexample
18711
18712@noindent
18713This means the value of @code{number} is 3, which is octal three,
18714hexadecimal three, and @sc{ascii} `control-c' (the third letter of the
18715alphabet, in case you need to know this information).
18716
18717You can continue moving through the code until you reach the line with
18718the error. Before evaluation, that line looks like this:
18719
18720@smallexample
18721=> @point{}(1= number))))) ; @r{Error here.}
18722@end smallexample
18723
18724@need 1250
18725@noindent
18726When you press @key{SPC} once again, you will produce an error message
18727that says:
18728
18729@smallexample
18730Symbol's function definition is void:@: 1=
18731@end smallexample
18732
18733@noindent
18734This is the bug.
18735
18736Press @kbd{q} to quit Edebug.
18737
18738To remove instrumentation from a function definition, simply
18739re-evaluate it with a command that does not instrument it.
18740For example, you could place your cursor after the definition's
18741closing parenthesis and type @kbd{C-x C-e}.
18742
18743Edebug does a great deal more than walk with you through a function.
18744You can set it so it races through on its own, stopping only at an
18745error or at specified stopping points; you can cause it to display the
18746changing values of various expressions; you can find out how many
18747times a function is called, and more.
18748
18749Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18750Lisp Reference Manual}.
18751
18752@need 1500
d6adf7e7 18753@node Debugging Exercises
8cda6f8f
GM
18754@section Debugging Exercises
18755
18756@itemize @bullet
18757@item
ea4f7750 18758Install the @code{@value{COUNT-WORDS}} function and then cause it to
8cda6f8f
GM
18759enter the built-in debugger when you call it. Run the command on a
18760region containing two words. You will need to press @kbd{d} a
18761remarkable number of times. On your system, is a `hook' called after
18762the command finishes? (For information on hooks, see @ref{Command
18763Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
18764Manual}.)
18765
18766@item
ea4f7750 18767Copy @code{@value{COUNT-WORDS}} into the @file{*scratch*} buffer,
8cda6f8f
GM
18768instrument the function for Edebug, and walk through its execution.
18769The function does not need to have a bug, although you can introduce
18770one if you wish. If the function lacks a bug, the walk-through
18771completes without problems.
18772
18773@item
18774While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
1df7defd 18775(The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.,
8cda6f8f
GM
18776@kbd{@key{CTRL}-x} followed by an upper case @kbd{X}; use this prefix
18777for commands made outside of the Edebug debugging buffer.)
18778
18779@item
18780In the Edebug debugging buffer, use the @kbd{p}
18781(@code{edebug-bounce-point}) command to see where in the region the
ea4f7750 18782@code{@value{COUNT-WORDS}} is working.
8cda6f8f
GM
18783
18784@item
18785Move point to some spot further down the function and then type the
18786@kbd{h} (@code{edebug-goto-here}) command to jump to that location.
18787
18788@item
18789Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
18790walk through the function on its own; use an upper case @kbd{T} for
18791@code{edebug-Trace-fast-mode}.
18792
18793@item
18794Set a breakpoint, then run Edebug in Trace mode until it reaches the
18795stopping point.
18796@end itemize
18797
d6adf7e7 18798@node Conclusion
8cda6f8f
GM
18799@chapter Conclusion
18800
18801We have now reached the end of this Introduction. You have now
18802learned enough about programming in Emacs Lisp to set values, to write
18803simple @file{.emacs} files for yourself and your friends, and write
18804simple customizations and extensions to Emacs.
18805
18806This is a place to stop. Or, if you wish, you can now go onward, and
18807teach yourself.
18808
18809You have learned some of the basic nuts and bolts of programming. But
18810only some. There are a great many more brackets and hinges that are
18811easy to use that we have not touched.
18812
18813A path you can follow right now lies among the sources to GNU Emacs
18814and in
18815@ifnotinfo
18816@cite{The GNU Emacs Lisp Reference Manual}.
18817@end ifnotinfo
18818@ifinfo
18819@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
18820Emacs Lisp Reference Manual}.
18821@end ifinfo
18822
18823The Emacs Lisp sources are an adventure. When you read the sources and
18824come across a function or expression that is unfamiliar, you need to
18825figure out or find out what it does.
18826
18827Go to the Reference Manual. It is a thorough, complete, and fairly
18828easy-to-read description of Emacs Lisp. It is written not only for
18829experts, but for people who know what you know. (The @cite{Reference
18830Manual} comes with the standard GNU Emacs distribution. Like this
18831introduction, it comes as a Texinfo source file, so you can read it
18832on-line and as a typeset, printed book.)
18833
18834Go to the other on-line help that is part of GNU Emacs: the on-line
88c26f5c 18835documentation for all functions and variables, and @code{find-tag},
8cda6f8f
GM
18836the program that takes you to sources.
18837
18838Here is an example of how I explore the sources. Because of its name,
18839@file{simple.el} is the file I looked at first, a long time ago. As
18840it happens some of the functions in @file{simple.el} are complicated,
18841or at least look complicated at first sight. The @code{open-line}
18842function, for example, looks complicated.
18843
18844You may want to walk through this function slowly, as we did with the
18845@code{forward-sentence} function. (@xref{forward-sentence, The
18846@code{forward-sentence} function}.) Or you may want to skip that
18847function and look at another, such as @code{split-line}. You don't
18848need to read all the functions. According to
18849@code{count-words-in-defun}, the @code{split-line} function contains
18850102 words and symbols.
18851
18852Even though it is short, @code{split-line} contains expressions
18853we have not studied: @code{skip-chars-forward}, @code{indent-to},
18854@code{current-column} and @code{insert-and-inherit}.
18855
18856Consider the @code{skip-chars-forward} function. (It is part of the
18857function definition for @code{back-to-indentation}, which is shown in
18858@ref{Review, , Review}.)
18859
18860In GNU Emacs, you can find out more about @code{skip-chars-forward} by
18861typing @kbd{C-h f} (@code{describe-function}) and the name of the
18862function. This gives you the function documentation.
18863
18864You may be able to guess what is done by a well named function such as
18865@code{indent-to}; or you can look it up, too. Incidentally, the
18866@code{describe-function} function itself is in @file{help.el}; it is
18867one of those long, but decipherable functions. You can look up
18868@code{describe-function} using the @kbd{C-h f} command!
18869
18870In this instance, since the code is Lisp, the @file{*Help*} buffer
18871contains the name of the library containing the function's source.
18872You can put point over the name of the library and press the RET key,
18873which in this situation is bound to @code{help-follow}, and be taken
18874directly to the source, in the same way as @kbd{M-.}
18875(@code{find-tag}).
18876
18877The definition for @code{describe-function} illustrates how to
18878customize the @code{interactive} expression without using the standard
18879character codes; and it shows how to create a temporary buffer.
18880
18881(The @code{indent-to} function is written in C rather than Emacs Lisp;
18882it is a `built-in' function. @code{help-follow} takes you to its
18883source as does @code{find-tag}, when properly set up.)
18884
18885You can look at a function's source using @code{find-tag}, which is
18886bound to @kbd{M-.} Finally, you can find out what the Reference
18887Manual has to say by visiting the manual in Info, and typing @kbd{i}
18888(@code{Info-index}) and the name of the function, or by looking up the
18889function in the index to a printed copy of the manual.
18890
18891Similarly, you can find out what is meant by
18892@code{insert-and-inherit}.
18893
18894Other interesting source files include @file{paragraphs.el},
18895@file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
18896file includes short, easily understood functions as well as longer
18897ones. The @file{loaddefs.el} file contains the many standard
18898autoloads and many keymaps. I have never looked at it all; only at
18899parts. @file{loadup.el} is the file that loads the standard parts of
18900Emacs; it tells you a great deal about how Emacs is built.
18901(@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
18902Reference Manual}, for more about building.)
18903
18904As I said, you have learned some nuts and bolts; however, and very
18905importantly, we have hardly touched major aspects of programming; I
18906have said nothing about how to sort information, except to use the
18907predefined @code{sort} function; I have said nothing about how to store
18908information, except to use variables and lists; I have said nothing
18909about how to write programs that write programs. These are topics for
18910another, and different kind of book, a different kind of learning.
18911
18912What you have done is learn enough for much practical work with GNU
18913Emacs. What you have done is get started. This is the end of a
18914beginning.
18915
18916@c ================ Appendix ================
18917
d6adf7e7 18918@node the-the
8cda6f8f
GM
18919@appendix The @code{the-the} Function
18920@findex the-the
18921@cindex Duplicated words function
18922@cindex Words, duplicated
18923
18924Sometimes when you you write text, you duplicate words---as with ``you
18925you'' near the beginning of this sentence. I find that most
18926frequently, I duplicate ``the''; hence, I call the function for
18927detecting duplicated words, @code{the-the}.
18928
18929@need 1250
18930As a first step, you could use the following regular expression to
18931search for duplicates:
18932
18933@smallexample
18934\\(\\w+[ \t\n]+\\)\\1
18935@end smallexample
18936
18937@noindent
18938This regexp matches one or more word-constituent characters followed
18939by one or more spaces, tabs, or newlines. However, it does not detect
18940duplicated words on different lines, since the ending of the first
18941word, the end of the line, is different from the ending of the second
18942word, a space. (For more information about regular expressions, see
18943@ref{Regexp Search, , Regular Expression Searches}, as well as
18944@ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18945Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18946The GNU Emacs Lisp Reference Manual}.)
18947
18948You might try searching just for duplicated word-constituent
18949characters but that does not work since the pattern detects doubles
18950such as the two occurrences of `th' in `with the'.
18951
18952Another possible regexp searches for word-constituent characters
18953followed by non-word-constituent characters, reduplicated. Here,
18954@w{@samp{\\w+}} matches one or more word-constituent characters and
18955@w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18956
18957@smallexample
18958\\(\\(\\w+\\)\\W*\\)\\1
18959@end smallexample
18960
18961@noindent
18962Again, not useful.
18963
18964Here is the pattern that I use. It is not perfect, but good enough.
18965@w{@samp{\\b}} matches the empty string, provided it is at the beginning
18966or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18967any characters that are @emph{not} an @@-sign, space, newline, or tab.
18968
18969@smallexample
18970\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18971@end smallexample
18972
18973One can write more complicated expressions, but I found that this
18974expression is good enough, so I use it.
18975
18976Here is the @code{the-the} function, as I include it in my
18977@file{.emacs} file, along with a handy global key binding:
18978
18979@smallexample
18980@group
18981(defun the-the ()
18982 "Search forward for for a duplicated word."
18983 (interactive)
18984 (message "Searching for for duplicated words ...")
18985 (push-mark)
18986@end group
18987@group
18988 ;; This regexp is not perfect
18989 ;; but is fairly good over all:
18990 (if (re-search-forward
18991 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
18992 (message "Found duplicated word.")
18993 (message "End of buffer")))
18994@end group
18995
18996@group
18997;; Bind `the-the' to C-c \
18998(global-set-key "\C-c\\" 'the-the)
18999@end group
19000@end smallexample
19001
19002@sp 1
19003Here is test text:
19004
19005@smallexample
19006@group
19007one two two three four five
19008five six seven
19009@end group
19010@end smallexample
19011
19012You can substitute the other regular expressions shown above in the
19013function definition and try each of them on this list.
19014
d6adf7e7 19015@node Kill Ring
8cda6f8f
GM
19016@appendix Handling the Kill Ring
19017@cindex Kill ring handling
19018@cindex Handling the kill ring
19019@cindex Ring, making a list like a
19020
19021The kill ring is a list that is transformed into a ring by the
19022workings of the @code{current-kill} function. The @code{yank} and
19023@code{yank-pop} commands use the @code{current-kill} function.
19024
19025This appendix describes the @code{current-kill} function as well as
19026both the @code{yank} and the @code{yank-pop} commands, but first,
19027consider the workings of the kill ring.
19028
19029@menu
19030* What the Kill Ring Does::
19031* current-kill::
19032* yank:: Paste a copy of a clipped element.
19033* yank-pop:: Insert element pointed to.
19034* ring file::
19035@end menu
19036
8cda6f8f 19037@ifnottex
d6adf7e7 19038@node What the Kill Ring Does
8cda6f8f
GM
19039@unnumberedsec What the Kill Ring Does
19040@end ifnottex
19041
19042@need 1250
19043The kill ring has a default maximum length of sixty items; this number
19044is too large for an explanation. Instead, set it to four. Please
19045evaluate the following:
19046
19047@smallexample
19048@group
19049(setq old-kill-ring-max kill-ring-max)
19050(setq kill-ring-max 4)
19051@end group
19052@end smallexample
19053
19054@noindent
19055Then, please copy each line of the following indented example into the
19056kill ring. You may kill each line with @kbd{C-k} or mark it and copy
19057it with @kbd{M-w}.
19058
19059@noindent
19060(In a read-only buffer, such as the @file{*info*} buffer, the kill
19061command, @kbd{C-k} (@code{kill-line}), will not remove the text,
19062merely copy it to the kill ring. However, your machine may beep at
19063you. Alternatively, for silence, you may copy the region of each line
19064with the @kbd{M-w} (@code{kill-ring-save}) command. You must mark
19065each line for this command to succeed, but it does not matter at which
19066end you put point or mark.)
19067
19068@need 1250
19069@noindent
19070Please invoke the calls in order, so that five elements attempt to
19071fill the kill ring:
19072
19073@smallexample
19074@group
19075first some text
19076second piece of text
19077third line
19078fourth line of text
19079fifth bit of text
19080@end group
19081@end smallexample
19082
19083@need 1250
19084@noindent
19085Then find the value of @code{kill-ring} by evaluating
19086
19087@smallexample
19088kill-ring
19089@end smallexample
19090
19091@need 800
19092@noindent
19093It is:
19094
19095@smallexample
19096@group
19097("fifth bit of text" "fourth line of text"
19098"third line" "second piece of text")
19099@end group
19100@end smallexample
19101
19102@noindent
19103The first element, @samp{first some text}, was dropped.
19104
19105@need 1250
19106To return to the old value for the length of the kill ring, evaluate:
19107
19108@smallexample
19109(setq kill-ring-max old-kill-ring-max)
19110@end smallexample
19111
d6adf7e7 19112@node current-kill
8cda6f8f
GM
19113@appendixsec The @code{current-kill} Function
19114@findex current-kill
19115
19116The @code{current-kill} function changes the element in the kill ring
19117to which @code{kill-ring-yank-pointer} points. (Also, the
19118@code{kill-new} function sets @code{kill-ring-yank-pointer} to point
867d4bb3 19119to the latest element of the kill ring. The @code{kill-new}
8cda6f8f
GM
19120function is used directly or indirectly by @code{kill-append},
19121@code{copy-region-as-kill}, @code{kill-ring-save}, @code{kill-line},
19122and @code{kill-region}.)
19123
19124@menu
19125* Code for current-kill::
19126* Understanding current-kill::
19127@end menu
19128
8cda6f8f 19129@ifnottex
d6adf7e7 19130@node Code for current-kill
8cda6f8f
GM
19131@unnumberedsubsec The code for @code{current-kill}
19132@end ifnottex
19133
19134
19135@need 1500
19136The @code{current-kill} function is used by @code{yank} and by
19137@code{yank-pop}. Here is the code for @code{current-kill}:
19138
19139@smallexample
19140@group
19141(defun current-kill (n &optional do-not-move)
19142 "Rotate the yanking point by N places, and then return that kill.
19143If N is zero, `interprogram-paste-function' is set, and calling it
19144returns a string, then that string is added to the front of the
19145kill ring and returned as the latest kill.
19146@end group
19147@group
19148If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
19149yanking point; just return the Nth kill forward."
19150 (let ((interprogram-paste (and (= n 0)
19151 interprogram-paste-function
19152 (funcall interprogram-paste-function))))
19153@end group
19154@group
19155 (if interprogram-paste
19156 (progn
19157 ;; Disable the interprogram cut function when we add the new
19158 ;; text to the kill ring, so Emacs doesn't try to own the
19159 ;; selection, with identical text.
19160 (let ((interprogram-cut-function nil))
19161 (kill-new interprogram-paste))
19162 interprogram-paste)
19163@end group
19164@group
19165 (or kill-ring (error "Kill ring is empty"))
19166 (let ((ARGth-kill-element
19167 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19168 (length kill-ring))
19169 kill-ring)))
19170 (or do-not-move
19171 (setq kill-ring-yank-pointer ARGth-kill-element))
19172 (car ARGth-kill-element)))))
19173@end group
19174@end smallexample
19175
19176Remember also that the @code{kill-new} function sets
867d4bb3 19177@code{kill-ring-yank-pointer} to the latest element of the kill
8cda6f8f
GM
19178ring, which means that all the functions that call it set the value
19179indirectly: @code{kill-append}, @code{copy-region-as-kill},
19180@code{kill-ring-save}, @code{kill-line}, and @code{kill-region}.
19181
19182@need 1500
19183Here is the line in @code{kill-new}, which is explained in
19184@ref{kill-new function, , The @code{kill-new} function}.
19185
19186@smallexample
19187(setq kill-ring-yank-pointer kill-ring)
19188@end smallexample
19189
8cda6f8f 19190@ifnottex
d6adf7e7 19191@node Understanding current-kill
8cda6f8f
GM
19192@unnumberedsubsec @code{current-kill} in Outline
19193@end ifnottex
19194
19195The @code{current-kill} function looks complex, but as usual, it can
19196be understood by taking it apart piece by piece. First look at it in
19197skeletal form:
19198
19199@smallexample
19200@group
19201(defun current-kill (n &optional do-not-move)
19202 "Rotate the yanking point by N places, and then return that kill."
19203 (let @var{varlist}
19204 @var{body}@dots{})
19205@end group
19206@end smallexample
19207
19208This function takes two arguments, one of which is optional. It has a
19209documentation string. It is @emph{not} interactive.
19210
19211@menu
19212* Body of current-kill::
19213* Digression concerning error:: How to mislead humans, but not computers.
19214* Determining the Element::
19215@end menu
19216
8cda6f8f 19217@ifnottex
d6adf7e7 19218@node Body of current-kill
8cda6f8f
GM
19219@unnumberedsubsubsec The Body of @code{current-kill}
19220@end ifnottex
19221
19222The body of the function definition is a @code{let} expression, which
19223itself has a body as well as a @var{varlist}.
19224
19225The @code{let} expression declares a variable that will be only usable
19226within the bounds of this function. This variable is called
19227@code{interprogram-paste} and is for copying to another program. It
19228is not for copying within this instance of GNU Emacs. Most window
19229systems provide a facility for interprogram pasting. Sadly, that
19230facility usually provides only for the last element. Most windowing
19231systems have not adopted a ring of many possibilities, even though
19232Emacs has provided it for decades.
19233
19234The @code{if} expression has two parts, one if there exists
19235@code{interprogram-paste} and one if not.
19236
19237@need 2000
19238Let us consider the `if not' or else-part of the @code{current-kill}
867d4bb3 19239function. (The then-part uses the @code{kill-new} function, which
8cda6f8f
GM
19240we have already described. @xref{kill-new function, , The
19241@code{kill-new} function}.)
19242
19243@smallexample
19244@group
19245(or kill-ring (error "Kill ring is empty"))
19246(let ((ARGth-kill-element
19247 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19248 (length kill-ring))
19249 kill-ring)))
19250 (or do-not-move
19251 (setq kill-ring-yank-pointer ARGth-kill-element))
19252 (car ARGth-kill-element))
19253@end group
19254@end smallexample
19255
19256@noindent
19257The code first checks whether the kill ring has content; otherwise it
19258signals an error.
19259
19260@need 1000
19261Note that the @code{or} expression is very similar to testing length
19262with an @code{if}:
19263
19264@findex zerop
19265@findex error
19266@smallexample
19267@group
19268(if (zerop (length kill-ring)) ; @r{if-part}
19269 (error "Kill ring is empty")) ; @r{then-part}
19270 ;; No else-part
19271@end group
19272@end smallexample
19273
19274@noindent
19275If there is not anything in the kill ring, its length must be zero and
19276an error message sent to the user: @samp{Kill ring is empty}. The
19277@code{current-kill} function uses an @code{or} expression which is
19278simpler. But an @code{if} expression reminds us what goes on.
19279
19280This @code{if} expression uses the function @code{zerop} which returns
19281true if the value it is testing is zero. When @code{zerop} tests
19282true, the then-part of the @code{if} is evaluated. The then-part is a
19283list starting with the function @code{error}, which is a function that
19284is similar to the @code{message} function
19285(@pxref{message, , The @code{message} Function}) in that
19286it prints a one-line message in the echo area. However, in addition
19287to printing a message, @code{error} also stops evaluation of the
19288function within which it is embedded. This means that the rest of the
19289function will not be evaluated if the length of the kill ring is zero.
19290
19291Then the @code{current-kill} function selects the element to return.
19292The selection depends on the number of places that @code{current-kill}
19293rotates and on where @code{kill-ring-yank-pointer} points.
19294
19295Next, either the optional @code{do-not-move} argument is true or the
19296current value of @code{kill-ring-yank-pointer} is set to point to the
19297list. Finally, another expression returns the first element of the
19298list even if the @code{do-not-move} argument is true.
19299
8cda6f8f 19300@ifnottex
d6adf7e7 19301@node Digression concerning error
8cda6f8f
GM
19302@unnumberedsubsubsec Digression about the word `error'
19303@end ifnottex
19304
19305In my opinion, it is slightly misleading, at least to humans, to use
19306the term `error' as the name of the @code{error} function. A better
19307term would be `cancel'. Strictly speaking, of course, you cannot
19308point to, much less rotate a pointer to a list that has no length, so
19309from the point of view of the computer, the word `error' is correct.
19310But a human expects to attempt this sort of thing, if only to find out
19311whether the kill ring is full or empty. This is an act of
19312exploration.
19313
19314From the human point of view, the act of exploration and discovery is
09e80d9f 19315not necessarily an error, and therefore should not be labeled as one,
8cda6f8f
GM
19316even in the bowels of a computer. As it is, the code in Emacs implies
19317that a human who is acting virtuously, by exploring his or her
19318environment, is making an error. This is bad. Even though the computer
19319takes the same steps as it does when there is an `error', a term such as
19320`cancel' would have a clearer connotation.
19321
8cda6f8f 19322@ifnottex
d6adf7e7 19323@node Determining the Element
8cda6f8f
GM
19324@unnumberedsubsubsec Determining the Element
19325@end ifnottex
19326
19327Among other actions, the else-part of the @code{if} expression sets
19328the value of @code{kill-ring-yank-pointer} to
19329@code{ARGth-kill-element} when the kill ring has something in it and
19330the value of @code{do-not-move} is @code{nil}.
19331
19332@need 800
19333The code looks like this:
19334
19335@smallexample
19336@group
19337(nthcdr (mod (- n (length kill-ring-yank-pointer))
19338 (length kill-ring))
19339 kill-ring)))
19340@end group
19341@end smallexample
19342
19343This needs some examination. Unless it is not supposed to move the
19344pointer, the @code{current-kill} function changes where
19345@code{kill-ring-yank-pointer} points.
19346That is what the
19347@w{@code{(setq kill-ring-yank-pointer ARGth-kill-element))}}
19348expression does. Also, clearly, @code{ARGth-kill-element} is being
19349set to be equal to some @sc{cdr} of the kill ring, using the
19350@code{nthcdr} function that is described in an earlier section.
19351(@xref{copy-region-as-kill}.) How does it do this?
19352
19353As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
19354works by repeatedly taking the @sc{cdr} of a list---it takes the
19355@sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
19356
19357@need 800
19358The two following expressions produce the same result:
19359
19360@smallexample
19361@group
19362(setq kill-ring-yank-pointer (cdr kill-ring))
19363
19364(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
19365@end group
19366@end smallexample
19367
19368However, the @code{nthcdr} expression is more complicated. It uses
19369the @code{mod} function to determine which @sc{cdr} to select.
19370
19371(You will remember to look at inner functions first; indeed, we will
19372have to go inside the @code{mod}.)
19373
19374The @code{mod} function returns the value of its first argument modulo
19375the second; that is to say, it returns the remainder after dividing
19376the first argument by the second. The value returned has the same
19377sign as the second argument.
19378
19379@need 800
19380Thus,
19381
19382@smallexample
19383@group
19384(mod 12 4)
19385 @result{} 0 ;; @r{because there is no remainder}
19386(mod 13 4)
19387 @result{} 1
19388@end group
19389@end smallexample
19390
19391@need 1250
19392In this case, the first argument is often smaller than the second.
19393That is fine.
19394
19395@smallexample
19396@group
19397(mod 0 4)
19398 @result{} 0
19399(mod 1 4)
19400 @result{} 1
19401@end group
19402@end smallexample
19403
19404We can guess what the @code{-} function does. It is like @code{+} but
19405subtracts instead of adds; the @code{-} function subtracts its second
19406argument from its first. Also, we already know what the @code{length}
19407function does (@pxref{length}). It returns the length of a list.
19408
19409And @code{n} is the name of the required argument to the
19410@code{current-kill} function.
19411
19412@need 1250
19413So when the first argument to @code{nthcdr} is zero, the @code{nthcdr}
19414expression returns the whole list, as you can see by evaluating the
19415following:
19416
19417@smallexample
19418@group
19419;; kill-ring-yank-pointer @r{and} kill-ring @r{have a length of four}
19420;; @r{and} (mod (- 0 4) 4) @result{} 0
19421(nthcdr (mod (- 0 4) 4)
19422 '("fourth line of text"
19423 "third line"
19424 "second piece of text"
19425 "first some text"))
19426@end group
19427@end smallexample
19428
19429@need 1250
19430When the first argument to the @code{current-kill} function is one,
19431the @code{nthcdr} expression returns the list without its first
19432element.
19433
19434@smallexample
19435@group
19436(nthcdr (mod (- 1 4) 4)
19437 '("fourth line of text"
19438 "third line"
19439 "second piece of text"
19440 "first some text"))
19441@end group
19442@end smallexample
19443
19444@cindex @samp{global variable} defined
19445@cindex @samp{variable, global}, defined
19446Incidentally, both @code{kill-ring} and @code{kill-ring-yank-pointer}
19447are @dfn{global variables}. That means that any expression in Emacs
19448Lisp can access them. They are not like the local variables set by
19449@code{let} or like the symbols in an argument list.
19450Local variables can only be accessed
19451within the @code{let} that defines them or the function that specifies
19452them in an argument list (and within expressions called by them).
19453
19454@ignore
19455@c texi2dvi fails when the name of the section is within ifnottex ...
19456(@xref{Prevent confusion, , @code{let} Prevents Confusion}, and
19457@ref{defun, , The @code{defun} Special Form}.)
19458@end ignore
19459
d6adf7e7 19460@node yank
8cda6f8f
GM
19461@appendixsec @code{yank}
19462@findex yank
19463
19464After learning about @code{current-kill}, the code for the
19465@code{yank} function is almost easy.
19466
19467The @code{yank} function does not use the
19468@code{kill-ring-yank-pointer} variable directly. It calls
19469@code{insert-for-yank} which calls @code{current-kill} which sets the
19470@code{kill-ring-yank-pointer} variable.
19471
19472@need 1250
19473The code looks like this:
19474
19475@c in GNU Emacs 22
19476@smallexample
19477@group
19478(defun yank (&optional arg)
19479 "Reinsert (\"paste\") the last stretch of killed text.
19480More precisely, reinsert the stretch of killed text most recently
19481killed OR yanked. Put point at end, and set mark at beginning.
19482With just \\[universal-argument] as argument, same but put point at
19483beginning (and mark at end). With argument N, reinsert the Nth most
19484recently killed stretch of killed text.
19485
19486When this command inserts killed text into the buffer, it honors
19487`yank-excluded-properties' and `yank-handler' as described in the
19488doc string for `insert-for-yank-1', which see.
19489
19490See also the command \\[yank-pop]."
19491@end group
19492@group
19493 (interactive "*P")
19494 (setq yank-window-start (window-start))
19495 ;; If we don't get all the way thru, make last-command indicate that
19496 ;; for the following command.
19497 (setq this-command t)
19498 (push-mark (point))
19499@end group
19500@group
19501 (insert-for-yank (current-kill (cond
19502 ((listp arg) 0)
19503 ((eq arg '-) -2)
19504 (t (1- arg)))))
19505 (if (consp arg)
19506 ;; This is like exchange-point-and-mark,
19507 ;; but doesn't activate the mark.
19508 ;; It is cleaner to avoid activation, even though the command
19509 ;; loop would deactivate the mark because we inserted text.
19510 (goto-char (prog1 (mark t)
19511 (set-marker (mark-marker) (point) (current-buffer)))))
19512@end group
19513@group
19514 ;; If we do get all the way thru, make this-command indicate that.
19515 (if (eq this-command t)
19516 (setq this-command 'yank))
19517 nil)
19518@end group
19519@end smallexample
19520
19521The key expression is @code{insert-for-yank}, which inserts the string
19522returned by @code{current-kill}, but removes some text properties from
19523it.
19524
19525However, before getting to that expression, the function sets the value
19526of @code{yank-window-start} to the position returned by the
19527@code{(window-start)} expression, the position at which the display
19528currently starts. The @code{yank} function also sets
19529@code{this-command} and pushes the mark.
19530
19531After it yanks the appropriate element, if the optional argument is a
19532@sc{cons} rather than a number or nothing, it puts point at beginning
19533of the yanked text and mark at its end.
19534
19535(The @code{prog1} function is like @code{progn} but returns the value
19536of its first argument rather than the value of its last argument. Its
19537first argument is forced to return the buffer's mark as an integer.
19538You can see the documentation for these functions by placing point
19539over them in this buffer and then typing @kbd{C-h f}
19540(@code{describe-function}) followed by a @kbd{RET}; the default is the
19541function.)
19542
19543The last part of the function tells what to do when it succeeds.
19544
d6adf7e7 19545@node yank-pop
8cda6f8f
GM
19546@appendixsec @code{yank-pop}
19547@findex yank-pop
19548
19549After understanding @code{yank} and @code{current-kill}, you know how
19550to approach the @code{yank-pop} function. Leaving out the
19551documentation to save space, it looks like this:
19552
19553@c GNU Emacs 22
19554@smallexample
19555@group
19556(defun yank-pop (&optional arg)
19557 "@dots{}"
19558 (interactive "*p")
19559 (if (not (eq last-command 'yank))
19560 (error "Previous command was not a yank"))
19561@end group
19562@group
19563 (setq this-command 'yank)
19564 (unless arg (setq arg 1))
19565 (let ((inhibit-read-only t)
19566 (before (< (point) (mark t))))
19567@end group
19568@group
19569 (if before
19570 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
19571 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
19572 (setq yank-undo-function nil)
19573@end group
19574@group
19575 (set-marker (mark-marker) (point) (current-buffer))
19576 (insert-for-yank (current-kill arg))
19577 ;; Set the window start back where it was in the yank command,
19578 ;; if possible.
19579 (set-window-start (selected-window) yank-window-start t)
19580@end group
19581@group
19582 (if before
19583 ;; This is like exchange-point-and-mark,
19584 ;; but doesn't activate the mark.
19585 ;; It is cleaner to avoid activation, even though the command
19586 ;; loop would deactivate the mark because we inserted text.
19587 (goto-char (prog1 (mark t)
19588 (set-marker (mark-marker)
19589 (point)
19590 (current-buffer))))))
19591 nil)
19592@end group
19593@end smallexample
19594
19595The function is interactive with a small @samp{p} so the prefix
19596argument is processed and passed to the function. The command can
19597only be used after a previous yank; otherwise an error message is
19598sent. This check uses the variable @code{last-command} which is set
19599by @code{yank} and is discussed elsewhere.
19600(@xref{copy-region-as-kill}.)
19601
19602The @code{let} clause sets the variable @code{before} to true or false
19603depending whether point is before or after mark and then the region
19604between point and mark is deleted. This is the region that was just
19605inserted by the previous yank and it is this text that will be
19606replaced.
19607
19608@code{funcall} calls its first argument as a function, passing
19609remaining arguments to it. The first argument is whatever the
19610@code{or} expression returns. The two remaining arguments are the
19611positions of point and mark set by the preceding @code{yank} command.
19612
19613There is more, but that is the hardest part.
19614
d6adf7e7 19615@node ring file
8cda6f8f
GM
19616@appendixsec The @file{ring.el} File
19617@cindex @file{ring.el} file
19618
19619Interestingly, GNU Emacs posses a file called @file{ring.el} that
19620provides many of the features we just discussed. But functions such
19621as @code{kill-ring-yank-pointer} do not use this library, possibly
19622because they were written earlier.
19623
d6adf7e7 19624@node Full Graph
09e80d9f 19625@appendix A Graph with Labeled Axes
8cda6f8f
GM
19626
19627Printed axes help you understand a graph. They convey scale. In an
19628earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
19629wrote the code to print the body of a graph. Here we write the code
09e80d9f 19630for printing and labeling vertical and horizontal axes, along with the
8cda6f8f
GM
19631body itself.
19632
19633@menu
09e80d9f 19634* Labeled Example::
8cda6f8f
GM
19635* print-graph Varlist:: @code{let} expression in @code{print-graph}.
19636* print-Y-axis:: Print a label for the vertical axis.
19637* print-X-axis:: Print a horizontal label.
19638* Print Whole Graph:: The function to print a complete graph.
19639@end menu
19640
8cda6f8f 19641@ifnottex
d6adf7e7 19642@node Labeled Example
09e80d9f 19643@unnumberedsec Labeled Example Graph
8cda6f8f
GM
19644@end ifnottex
19645
19646Since insertions fill a buffer to the right and below point, the new
19647graph printing function should first print the Y or vertical axis,
19648then the body of the graph, and finally the X or horizontal axis.
19649This sequence lays out for us the contents of the function:
19650
19651@enumerate
19652@item
19653Set up code.
19654
19655@item
19656Print Y axis.
19657
19658@item
19659Print body of graph.
19660
19661@item
19662Print X axis.
19663@end enumerate
19664
19665@need 800
19666Here is an example of how a finished graph should look:
19667
19668@smallexample
19669@group
19670 10 -
19671 *
19672 * *
19673 * **
19674 * ***
19675 5 - * *******
19676 * *** *******
19677 *************
19678 ***************
19679 1 - ****************
19680 | | | |
19681 1 5 10 15
19682@end group
19683@end smallexample
19684
19685@noindent
09e80d9f 19686In this graph, both the vertical and the horizontal axes are labeled
8cda6f8f 19687with numbers. However, in some graphs, the horizontal axis is time
09e80d9f 19688and would be better labeled with months, like this:
8cda6f8f
GM
19689
19690@smallexample
19691@group
19692 5 - *
19693 * ** *
19694 *******
19695 ********** **
19696 1 - **************
19697 | ^ |
19698 Jan June Jan
19699@end group
19700@end smallexample
19701
19702Indeed, with a little thought, we can easily come up with a variety of
09e80d9f 19703vertical and horizontal labeling schemes. Our task could become
8cda6f8f 19704complicated. But complications breed confusion. Rather than permit
09e80d9f 19705this, it is better choose a simple labeling scheme for our first
8cda6f8f
GM
19706effort, and to modify or replace it later.
19707
19708@need 1200
19709These considerations suggest the following outline for the
19710@code{print-graph} function:
19711
19712@smallexample
19713@group
19714(defun print-graph (numbers-list)
19715 "@var{documentation}@dots{}"
19716 (let ((height @dots{}
19717 @dots{}))
19718@end group
19719@group
19720 (print-Y-axis height @dots{} )
19721 (graph-body-print numbers-list)
19722 (print-X-axis @dots{} )))
19723@end group
19724@end smallexample
19725
19726We can work on each part of the @code{print-graph} function definition
19727in turn.
19728
d6adf7e7 19729@node print-graph Varlist
8cda6f8f
GM
19730@appendixsec The @code{print-graph} Varlist
19731@cindex @code{print-graph} varlist
19732
19733In writing the @code{print-graph} function, the first task is to write
19734the varlist in the @code{let} expression. (We will leave aside for the
19735moment any thoughts about making the function interactive or about the
19736contents of its documentation string.)
19737
19738The varlist should set several values. Clearly, the top of the label
19739for the vertical axis must be at least the height of the graph, which
19740means that we must obtain this information here. Note that the
19741@code{print-graph-body} function also requires this information. There
19742is no reason to calculate the height of the graph in two different
19743places, so we should change @code{print-graph-body} from the way we
19744defined it earlier to take advantage of the calculation.
19745
19746Similarly, both the function for printing the X axis labels and the
19747@code{print-graph-body} function need to learn the value of the width of
19748each symbol. We can perform the calculation here and change the
19749definition for @code{print-graph-body} from the way we defined it in the
19750previous chapter.
19751
19752The length of the label for the horizontal axis must be at least as long
19753as the graph. However, this information is used only in the function
19754that prints the horizontal axis, so it does not need to be calculated here.
19755
19756These thoughts lead us directly to the following form for the varlist
19757in the @code{let} for @code{print-graph}:
19758
19759@smallexample
19760@group
19761(let ((height (apply 'max numbers-list)) ; @r{First version.}
19762 (symbol-width (length graph-blank)))
19763@end group
19764@end smallexample
19765
19766@noindent
19767As we shall see, this expression is not quite right.
19768
19769@need 2000
d6adf7e7 19770@node print-Y-axis
8cda6f8f
GM
19771@appendixsec The @code{print-Y-axis} Function
19772@cindex Axis, print vertical
19773@cindex Y axis printing
19774@cindex Vertical axis printing
19775@cindex Print vertical axis
19776
19777The job of the @code{print-Y-axis} function is to print a label for
19778the vertical axis that looks like this:
19779
19780@smallexample
19781@group
19782 10 -
19783
19784
19785
19786
19787 5 -
19788
19789
19790
19791 1 -
19792@end group
19793@end smallexample
19794
19795@noindent
19796The function should be passed the height of the graph, and then should
19797construct and insert the appropriate numbers and marks.
19798
19799@menu
19800* print-Y-axis in Detail::
19801* Height of label:: What height for the Y axis?
19802* Compute a Remainder:: How to compute the remainder of a division.
19803* Y Axis Element:: Construct a line for the Y axis.
19804* Y-axis-column:: Generate a list of Y axis labels.
19805* print-Y-axis Penultimate:: A not quite final version.
19806@end menu
19807
8cda6f8f 19808@ifnottex
d6adf7e7 19809@node print-Y-axis in Detail
8cda6f8f
GM
19810@unnumberedsubsec The @code{print-Y-axis} Function in Detail
19811@end ifnottex
19812
19813It is easy enough to see in the figure what the Y axis label should
19814look like; but to say in words, and then to write a function
19815definition to do the job is another matter. It is not quite true to
19816say that we want a number and a tic every five lines: there are only
19817three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19818but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19819and 9). It is better to say that we want a number and a tic mark on
19820the base line (number 1) and then that we want a number and a tic on
19821the fifth line from the bottom and on every line that is a multiple of
19822five.
19823
8cda6f8f 19824@ifnottex
d6adf7e7 19825@node Height of label
8cda6f8f
GM
19826@unnumberedsubsec What height should the label be?
19827@end ifnottex
19828
19829The next issue is what height the label should be? Suppose the maximum
19830height of tallest column of the graph is seven. Should the highest
19831label on the Y axis be @samp{5 -}, and should the graph stick up above
19832the label? Or should the highest label be @samp{7 -}, and mark the peak
19833of the graph? Or should the highest label be @code{10 -}, which is a
19834multiple of five, and be higher than the topmost value of the graph?
19835
19836The latter form is preferred. Most graphs are drawn within rectangles
19837whose sides are an integral number of steps long---5, 10, 15, and so
19838on for a step distance of five. But as soon as we decide to use a
19839step height for the vertical axis, we discover that the simple
19840expression in the varlist for computing the height is wrong. The
19841expression is @code{(apply 'max numbers-list)}. This returns the
19842precise height, not the maximum height plus whatever is necessary to
19843round up to the nearest multiple of five. A more complex expression
19844is required.
19845
19846As usual in cases like this, a complex problem becomes simpler if it is
19847divided into several smaller problems.
19848
19849First, consider the case when the highest value of the graph is an
19850integral multiple of five---when it is 5, 10, 15, or some higher
19851multiple of five. We can use this value as the Y axis height.
19852
19853A fairly simply way to determine whether a number is a multiple of
19854five is to divide it by five and see if the division results in a
19855remainder. If there is no remainder, the number is a multiple of
19856five. Thus, seven divided by five has a remainder of two, and seven
19857is not an integral multiple of five. Put in slightly different
19858language, more reminiscent of the classroom, five goes into seven
19859once, with a remainder of two. However, five goes into ten twice,
19860with no remainder: ten is an integral multiple of five.
19861
d6adf7e7 19862@node Compute a Remainder
8cda6f8f
GM
19863@appendixsubsec Side Trip: Compute a Remainder
19864
19865@findex % @r{(remainder function)}
19866@cindex Remainder function, @code{%}
19867In Lisp, the function for computing a remainder is @code{%}. The
19868function returns the remainder of its first argument divided by its
19869second argument. As it happens, @code{%} is a function in Emacs Lisp
19870that you cannot discover using @code{apropos}: you find nothing if you
19871type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
19872learn of the existence of @code{%} is to read about it in a book such
19873as this or in the Emacs Lisp sources.
19874
19875You can try the @code{%} function by evaluating the following two
19876expressions:
19877
19878@smallexample
19879@group
19880(% 7 5)
19881
19882(% 10 5)
19883@end group
19884@end smallexample
19885
19886@noindent
19887The first expression returns 2 and the second expression returns 0.
19888
19889To test whether the returned value is zero or some other number, we
19890can use the @code{zerop} function. This function returns @code{t} if
19891its argument, which must be a number, is zero.
19892
19893@smallexample
19894@group
19895(zerop (% 7 5))
19896 @result{} nil
19897
19898(zerop (% 10 5))
19899 @result{} t
19900@end group
19901@end smallexample
19902
19903Thus, the following expression will return @code{t} if the height
19904of the graph is evenly divisible by five:
19905
19906@smallexample
19907(zerop (% height 5))
19908@end smallexample
19909
19910@noindent
19911(The value of @code{height}, of course, can be found from @code{(apply
19912'max numbers-list)}.)
19913
19914On the other hand, if the value of @code{height} is not a multiple of
19915five, we want to reset the value to the next higher multiple of five.
19916This is straightforward arithmetic using functions with which we are
19917already familiar. First, we divide the value of @code{height} by five
19918to determine how many times five goes into the number. Thus, five
19919goes into twelve twice. If we add one to this quotient and multiply by
19920five, we will obtain the value of the next multiple of five that is
19921larger than the height. Five goes into twelve twice. Add one to two,
19922and multiply by five; the result is fifteen, which is the next multiple
19923of five that is higher than twelve. The Lisp expression for this is:
19924
19925@smallexample
19926(* (1+ (/ height 5)) 5)
19927@end smallexample
19928
19929@noindent
19930For example, if you evaluate the following, the result is 15:
19931
19932@smallexample
19933(* (1+ (/ 12 5)) 5)
19934@end smallexample
19935
19936All through this discussion, we have been using `five' as the value
19937for spacing labels on the Y axis; but we may want to use some other
19938value. For generality, we should replace `five' with a variable to
19939which we can assign a value. The best name I can think of for this
19940variable is @code{Y-axis-label-spacing}.
19941
19942@need 1250
19943Using this term, and an @code{if} expression, we produce the
19944following:
19945
19946@smallexample
19947@group
19948(if (zerop (% height Y-axis-label-spacing))
19949 height
19950 ;; @r{else}
19951 (* (1+ (/ height Y-axis-label-spacing))
19952 Y-axis-label-spacing))
19953@end group
19954@end smallexample
19955
19956@noindent
19957This expression returns the value of @code{height} itself if the height
19958is an even multiple of the value of the @code{Y-axis-label-spacing} or
19959else it computes and returns a value of @code{height} that is equal to
19960the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19961
19962We can now include this expression in the @code{let} expression of the
19963@code{print-graph} function (after first setting the value of
19964@code{Y-axis-label-spacing}):
19965@vindex Y-axis-label-spacing
19966
19967@smallexample
19968@group
19969(defvar Y-axis-label-spacing 5
19970 "Number of lines from one Y axis label to next.")
19971@end group
19972
19973@group
19974@dots{}
19975(let* ((height (apply 'max numbers-list))
19976 (height-of-top-line
19977 (if (zerop (% height Y-axis-label-spacing))
19978 height
19979@end group
19980@group
19981 ;; @r{else}
19982 (* (1+ (/ height Y-axis-label-spacing))
19983 Y-axis-label-spacing)))
19984 (symbol-width (length graph-blank))))
19985@dots{}
19986@end group
19987@end smallexample
19988
19989@noindent
19990(Note use of the @code{let*} function: the initial value of height is
19991computed once by the @code{(apply 'max numbers-list)} expression and
19992then the resulting value of @code{height} is used to compute its
19993final value. @xref{fwd-para let, , The @code{let*} expression}, for
19994more about @code{let*}.)
19995
d6adf7e7 19996@node Y Axis Element
8cda6f8f
GM
19997@appendixsubsec Construct a Y Axis Element
19998
19999When we print the vertical axis, we want to insert strings such as
20000@w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
20001Moreover, we want the numbers and dashes to line up, so shorter
20002numbers must be padded with leading spaces. If some of the strings
20003use two digit numbers, the strings with single digit numbers must
20004include a leading blank space before the number.
20005
20006@findex number-to-string
20007To figure out the length of the number, the @code{length} function is
20008used. But the @code{length} function works only with a string, not with
20009a number. So the number has to be converted from being a number to
20010being a string. This is done with the @code{number-to-string} function.
20011For example,
20012
20013@smallexample
20014@group
20015(length (number-to-string 35))
20016 @result{} 2
20017
20018(length (number-to-string 100))
20019 @result{} 3
20020@end group
20021@end smallexample
20022
20023@noindent
20024(@code{number-to-string} is also called @code{int-to-string}; you will
20025see this alternative name in various sources.)
20026
20027In addition, in each label, each number is followed by a string such
20028as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
20029This variable is defined with @code{defvar}:
20030
20031@vindex Y-axis-tic
20032@smallexample
20033@group
20034(defvar Y-axis-tic " - "
20035 "String that follows number in a Y axis label.")
20036@end group
20037@end smallexample
20038
20039The length of the Y label is the sum of the length of the Y axis tic
20040mark and the length of the number of the top of the graph.
20041
20042@smallexample
20043(length (concat (number-to-string height) Y-axis-tic)))
20044@end smallexample
20045
20046This value will be calculated by the @code{print-graph} function in
20047its varlist as @code{full-Y-label-width} and passed on. (Note that we
20048did not think to include this in the varlist when we first proposed it.)
20049
20050To make a complete vertical axis label, a tic mark is concatenated
20051with a number; and the two together may be preceded by one or more
20052spaces depending on how long the number is. The label consists of
20053three parts: the (optional) leading spaces, the number, and the tic
20054mark. The function is passed the value of the number for the specific
20055row, and the value of the width of the top line, which is calculated
20056(just once) by @code{print-graph}.
20057
20058@smallexample
20059@group
20060(defun Y-axis-element (number full-Y-label-width)
20061 "Construct a NUMBERed label element.
20062A numbered element looks like this ` 5 - ',
20063and is padded as needed so all line up with
20064the element for the largest number."
20065@end group
20066@group
20067 (let* ((leading-spaces
20068 (- full-Y-label-width
20069 (length
20070 (concat (number-to-string number)
20071 Y-axis-tic)))))
20072@end group
20073@group
20074 (concat
20075 (make-string leading-spaces ? )
20076 (number-to-string number)
20077 Y-axis-tic)))
20078@end group
20079@end smallexample
20080
20081The @code{Y-axis-element} function concatenates together the leading
20082spaces, if any; the number, as a string; and the tic mark.
20083
20084To figure out how many leading spaces the label will need, the
20085function subtracts the actual length of the label---the length of the
20086number plus the length of the tic mark---from the desired label width.
20087
20088@findex make-string
20089Blank spaces are inserted using the @code{make-string} function. This
20090function takes two arguments: the first tells it how long the string
20091will be and the second is a symbol for the character to insert, in a
20092special format. The format is a question mark followed by a blank
20093space, like this, @samp{? }. @xref{Character Type, , Character Type,
20094elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
20095syntax for characters. (Of course, you might want to replace the
20096blank space by some other character @dots{} You know what to do.)
20097
20098The @code{number-to-string} function is used in the concatenation
20099expression, to convert the number to a string that is concatenated
20100with the leading spaces and the tic mark.
20101
d6adf7e7 20102@node Y-axis-column
8cda6f8f
GM
20103@appendixsubsec Create a Y Axis Column
20104
20105The preceding functions provide all the tools needed to construct a
20106function that generates a list of numbered and blank strings to insert
20107as the label for the vertical axis:
20108
20109@findex Y-axis-column
20110@smallexample
20111@group
20112(defun Y-axis-column (height width-of-label)
20113 "Construct list of Y axis labels and blank strings.
20114For HEIGHT of line above base and WIDTH-OF-LABEL."
20115 (let (Y-axis)
20116@group
20117@end group
20118 (while (> height 1)
20119 (if (zerop (% height Y-axis-label-spacing))
20120 ;; @r{Insert label.}
20121 (setq Y-axis
20122 (cons
20123 (Y-axis-element height width-of-label)
20124 Y-axis))
20125@group
20126@end group
20127 ;; @r{Else, insert blanks.}
20128 (setq Y-axis
20129 (cons
20130 (make-string width-of-label ? )
20131 Y-axis)))
20132 (setq height (1- height)))
20133 ;; @r{Insert base line.}
20134 (setq Y-axis
20135 (cons (Y-axis-element 1 width-of-label) Y-axis))
20136 (nreverse Y-axis)))
20137@end group
20138@end smallexample
20139
20140In this function, we start with the value of @code{height} and
20141repetitively subtract one from its value. After each subtraction, we
20142test to see whether the value is an integral multiple of the
20143@code{Y-axis-label-spacing}. If it is, we construct a numbered label
20144using the @code{Y-axis-element} function; if not, we construct a
20145blank label using the @code{make-string} function. The base line
20146consists of the number one followed by a tic mark.
20147
20148@need 2000
d6adf7e7 20149@node print-Y-axis Penultimate
8cda6f8f
GM
20150@appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
20151
20152The list constructed by the @code{Y-axis-column} function is passed to
20153the @code{print-Y-axis} function, which inserts the list as a column.
20154
20155@findex print-Y-axis
20156@smallexample
20157@group
20158(defun print-Y-axis (height full-Y-label-width)
20159 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
20160Height must be the maximum height of the graph.
20161Full width is the width of the highest label element."
20162;; Value of height and full-Y-label-width
20163;; are passed by `print-graph'.
20164@end group
20165@group
20166 (let ((start (point)))
20167 (insert-rectangle
20168 (Y-axis-column height full-Y-label-width))
20169 ;; @r{Place point ready for inserting graph.}
20170 (goto-char start)
20171 ;; @r{Move point forward by value of} full-Y-label-width
20172 (forward-char full-Y-label-width)))
20173@end group
20174@end smallexample
20175
20176The @code{print-Y-axis} uses the @code{insert-rectangle} function to
20177insert the Y axis labels created by the @code{Y-axis-column} function.
20178In addition, it places point at the correct position for printing the body of
20179the graph.
20180
20181You can test @code{print-Y-axis}:
20182
20183@enumerate
20184@item
20185Install
20186
20187@smallexample
20188@group
20189Y-axis-label-spacing
20190Y-axis-tic
20191Y-axis-element
20192Y-axis-column
20193print-Y-axis
20194@end group
20195@end smallexample
20196
20197@item
20198Copy the following expression:
20199
20200@smallexample
20201(print-Y-axis 12 5)
20202@end smallexample
20203
20204@item
20205Switch to the @file{*scratch*} buffer and place the cursor where you
20206want the axis labels to start.
20207
20208@item
20209Type @kbd{M-:} (@code{eval-expression}).
20210
20211@item
20212Yank the @code{graph-body-print} expression into the minibuffer
20213with @kbd{C-y} (@code{yank)}.
20214
20215@item
20216Press @key{RET} to evaluate the expression.
20217@end enumerate
20218
20219Emacs will print labels vertically, the top one being @w{@samp{10 -@w{
20220}}}. (The @code{print-graph} function will pass the value of
20221@code{height-of-top-line}, which in this case will end up as 15,
20222thereby getting rid of what might appear as a bug.)
20223
20224@need 2000
d6adf7e7 20225@node print-X-axis
8cda6f8f
GM
20226@appendixsec The @code{print-X-axis} Function
20227@cindex Axis, print horizontal
20228@cindex X axis printing
20229@cindex Print horizontal axis
20230@cindex Horizontal axis printing
20231
20232X axis labels are much like Y axis labels, except that the ticks are on a
20233line above the numbers. Labels should look like this:
20234
20235@smallexample
20236@group
20237 | | | |
20238 1 5 10 15
20239@end group
20240@end smallexample
20241
20242The first tic is under the first column of the graph and is preceded by
20243several blank spaces. These spaces provide room in rows above for the Y
20244axis labels. The second, third, fourth, and subsequent ticks are all
20245spaced equally, according to the value of @code{X-axis-label-spacing}.
20246
20247The second row of the X axis consists of numbers, preceded by several
20248blank spaces and also separated according to the value of the variable
20249@code{X-axis-label-spacing}.
20250
20251The value of the variable @code{X-axis-label-spacing} should itself be
20252measured in units of @code{symbol-width}, since you may want to change
20253the width of the symbols that you are using to print the body of the
09e80d9f 20254graph without changing the ways the graph is labeled.
8cda6f8f
GM
20255
20256@menu
20257* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
20258* X Axis Tic Marks:: Create tic marks for the horizontal axis.
20259@end menu
20260
8cda6f8f 20261@ifnottex
d6adf7e7 20262@node Similarities differences
8cda6f8f
GM
20263@unnumberedsubsec Similarities and differences
20264@end ifnottex
20265
20266The @code{print-X-axis} function is constructed in more or less the
20267same fashion as the @code{print-Y-axis} function except that it has
20268two lines: the line of tic marks and the numbers. We will write a
20269separate function to print each line and then combine them within the
20270@code{print-X-axis} function.
20271
20272This is a three step process:
20273
20274@enumerate
20275@item
20276Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
20277
20278@item
20279Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
20280
20281@item
20282Write a function to print both lines, the @code{print-X-axis} function,
20283using @code{print-X-axis-tic-line} and
20284@code{print-X-axis-numbered-line}.
20285@end enumerate
20286
d6adf7e7 20287@node X Axis Tic Marks
8cda6f8f
GM
20288@appendixsubsec X Axis Tic Marks
20289
20290The first function should print the X axis tic marks. We must specify
20291the tic marks themselves and their spacing:
20292
20293@smallexample
20294@group
20295(defvar X-axis-label-spacing
20296 (if (boundp 'graph-blank)
20297 (* 5 (length graph-blank)) 5)
20298 "Number of units from one X axis label to next.")
20299@end group
20300@end smallexample
20301
20302@noindent
20303(Note that the value of @code{graph-blank} is set by another
20304@code{defvar}. The @code{boundp} predicate checks whether it has
20305already been set; @code{boundp} returns @code{nil} if it has not. If
20306@code{graph-blank} were unbound and we did not use this conditional
20307construction, in a recent GNU Emacs, we would enter the debugger and
20308see an error message saying @samp{@w{Debugger entered--Lisp error:}
20309@w{(void-variable graph-blank)}}.)
20310
20311@need 1200
20312Here is the @code{defvar} for @code{X-axis-tic-symbol}:
20313
20314@smallexample
20315@group
20316(defvar X-axis-tic-symbol "|"
20317 "String to insert to point to a column in X axis.")
20318@end group
20319@end smallexample
20320
20321@need 1250
20322The goal is to make a line that looks like this:
20323
20324@smallexample
20325 | | | |
20326@end smallexample
20327
20328The first tic is indented so that it is under the first column, which is
20329indented to provide space for the Y axis labels.
20330
20331A tic element consists of the blank spaces that stretch from one tic to
20332the next plus a tic symbol. The number of blanks is determined by the
20333width of the tic symbol and the @code{X-axis-label-spacing}.
20334
20335@need 1250
20336The code looks like this:
20337
20338@smallexample
20339@group
20340;;; X-axis-tic-element
20341@dots{}
20342(concat
20343 (make-string
20344 ;; @r{Make a string of blanks.}
20345 (- (* symbol-width X-axis-label-spacing)
20346 (length X-axis-tic-symbol))
20347 ? )
20348 ;; @r{Concatenate blanks with tic symbol.}
20349 X-axis-tic-symbol)
20350@dots{}
20351@end group
20352@end smallexample
20353
20354Next, we determine how many blanks are needed to indent the first tic
20355mark to the first column of the graph. This uses the value of
20356@code{full-Y-label-width} passed it by the @code{print-graph} function.
20357
20358@need 1250
20359The code to make @code{X-axis-leading-spaces}
20360looks like this:
20361
20362@smallexample
20363@group
20364;; X-axis-leading-spaces
20365@dots{}
20366(make-string full-Y-label-width ? )
20367@dots{}
20368@end group
20369@end smallexample
20370
20371We also need to determine the length of the horizontal axis, which is
20372the length of the numbers list, and the number of ticks in the horizontal
20373axis:
20374
20375@smallexample
20376@group
20377;; X-length
20378@dots{}
20379(length numbers-list)
20380@end group
20381
20382@group
20383;; tic-width
20384@dots{}
20385(* symbol-width X-axis-label-spacing)
20386@end group
20387
20388@group
20389;; number-of-X-ticks
20390(if (zerop (% (X-length tic-width)))
20391 (/ (X-length tic-width))
20392 (1+ (/ (X-length tic-width))))
20393@end group
20394@end smallexample
20395
20396@need 1250
20397All this leads us directly to the function for printing the X axis tic line:
20398
20399@findex print-X-axis-tic-line
20400@smallexample
20401@group
20402(defun print-X-axis-tic-line
20403 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20404 "Print ticks for X axis."
20405 (insert X-axis-leading-spaces)
20406 (insert X-axis-tic-symbol) ; @r{Under first column.}
20407@end group
20408@group
20409 ;; @r{Insert second tic in the right spot.}
20410 (insert (concat
20411 (make-string
20412 (- (* symbol-width X-axis-label-spacing)
20413 ;; @r{Insert white space up to second tic symbol.}
20414 (* 2 (length X-axis-tic-symbol)))
20415 ? )
20416 X-axis-tic-symbol))
20417@end group
20418@group
20419 ;; @r{Insert remaining ticks.}
20420 (while (> number-of-X-tics 1)
20421 (insert X-axis-tic-element)
20422 (setq number-of-X-tics (1- number-of-X-tics))))
20423@end group
20424@end smallexample
20425
20426The line of numbers is equally straightforward:
20427
20428@need 1250
20429First, we create a numbered element with blank spaces before each number:
20430
20431@findex X-axis-element
20432@smallexample
20433@group
20434(defun X-axis-element (number)
20435 "Construct a numbered X axis element."
20436 (let ((leading-spaces
20437 (- (* symbol-width X-axis-label-spacing)
20438 (length (number-to-string number)))))
20439 (concat (make-string leading-spaces ? )
20440 (number-to-string number))))
20441@end group
20442@end smallexample
20443
20444Next, we create the function to print the numbered line, starting with
20445the number ``1'' under the first column:
20446
20447@findex print-X-axis-numbered-line
20448@smallexample
20449@group
20450(defun print-X-axis-numbered-line
20451 (number-of-X-tics X-axis-leading-spaces)
20452 "Print line of X-axis numbers"
20453 (let ((number X-axis-label-spacing))
20454 (insert X-axis-leading-spaces)
20455 (insert "1")
20456@end group
20457@group
20458 (insert (concat
20459 (make-string
20460 ;; @r{Insert white space up to next number.}
20461 (- (* symbol-width X-axis-label-spacing) 2)
20462 ? )
20463 (number-to-string number)))
20464@end group
20465@group
20466 ;; @r{Insert remaining numbers.}
20467 (setq number (+ number X-axis-label-spacing))
20468 (while (> number-of-X-tics 1)
20469 (insert (X-axis-element number))
20470 (setq number (+ number X-axis-label-spacing))
20471 (setq number-of-X-tics (1- number-of-X-tics)))))
20472@end group
20473@end smallexample
20474
20475Finally, we need to write the @code{print-X-axis} that uses
20476@code{print-X-axis-tic-line} and
20477@code{print-X-axis-numbered-line}.
20478
20479The function must determine the local values of the variables used by both
20480@code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
20481then it must call them. Also, it must print the carriage return that
20482separates the two lines.
20483
20484The function consists of a varlist that specifies five local variables,
20485and calls to each of the two line printing functions:
20486
20487@findex print-X-axis
20488@smallexample
20489@group
20490(defun print-X-axis (numbers-list)
20491 "Print X axis labels to length of NUMBERS-LIST."
20492 (let* ((leading-spaces
20493 (make-string full-Y-label-width ? ))
20494@end group
20495@group
20496 ;; symbol-width @r{is provided by} graph-body-print
20497 (tic-width (* symbol-width X-axis-label-spacing))
20498 (X-length (length numbers-list))
20499@end group
20500@group
20501 (X-tic
20502 (concat
20503 (make-string
20504@end group
20505@group
20506 ;; @r{Make a string of blanks.}
20507 (- (* symbol-width X-axis-label-spacing)
20508 (length X-axis-tic-symbol))
20509 ? )
20510@end group
20511@group
20512 ;; @r{Concatenate blanks with tic symbol.}
20513 X-axis-tic-symbol))
20514@end group
20515@group
20516 (tic-number
20517 (if (zerop (% X-length tic-width))
20518 (/ X-length tic-width)
20519 (1+ (/ X-length tic-width)))))
20520@end group
20521@group
20522 (print-X-axis-tic-line tic-number leading-spaces X-tic)
20523 (insert "\n")
20524 (print-X-axis-numbered-line tic-number leading-spaces)))
20525@end group
20526@end smallexample
20527
20528@need 1250
20529You can test @code{print-X-axis}:
20530
20531@enumerate
20532@item
20533Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
20534@code{print-X-axis-tic-line}, as well as @code{X-axis-element},
20535@code{print-X-axis-numbered-line}, and @code{print-X-axis}.
20536
20537@item
20538Copy the following expression:
20539
20540@smallexample
20541@group
20542(progn
20543 (let ((full-Y-label-width 5)
20544 (symbol-width 1))
20545 (print-X-axis
20546 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
20547@end group
20548@end smallexample
20549
20550@item
20551Switch to the @file{*scratch*} buffer and place the cursor where you
20552want the axis labels to start.
20553
20554@item
20555Type @kbd{M-:} (@code{eval-expression}).
20556
20557@item
20558Yank the test expression into the minibuffer
20559with @kbd{C-y} (@code{yank)}.
20560
20561@item
20562Press @key{RET} to evaluate the expression.
20563@end enumerate
20564
20565@need 1250
20566Emacs will print the horizontal axis like this:
20567@sp 1
20568
20569@smallexample
20570@group
20571 | | | | |
20572 1 5 10 15 20
20573@end group
20574@end smallexample
20575
d6adf7e7 20576@node Print Whole Graph
8cda6f8f
GM
20577@appendixsec Printing the Whole Graph
20578@cindex Printing the whole graph
20579@cindex Whole graph printing
20580@cindex Graph, printing all
20581
20582Now we are nearly ready to print the whole graph.
20583
20584The function to print the graph with the proper labels follows the
09e80d9f 20585outline we created earlier (@pxref{Full Graph, , A Graph with Labeled
8cda6f8f
GM
20586Axes}), but with additions.
20587
20588@need 1250
20589Here is the outline:
20590
20591@smallexample
20592@group
20593(defun print-graph (numbers-list)
20594 "@var{documentation}@dots{}"
20595 (let ((height @dots{}
20596 @dots{}))
20597@end group
20598@group
20599 (print-Y-axis height @dots{} )
20600 (graph-body-print numbers-list)
20601 (print-X-axis @dots{} )))
20602@end group
20603@end smallexample
20604
20605@menu
20606* The final version:: A few changes.
20607* Test print-graph:: Run a short test.
20608* Graphing words in defuns:: Executing the final code.
20609* lambda:: How to write an anonymous function.
20610* mapcar:: Apply a function to elements of a list.
20611* Another Bug:: Yet another bug @dots{} most insidious.
20612* Final printed graph:: The graph itself!
20613@end menu
20614
8cda6f8f 20615@ifnottex
d6adf7e7 20616@node The final version
8cda6f8f
GM
20617@unnumberedsubsec Changes for the Final Version
20618@end ifnottex
20619
20620The final version is different from what we planned in two ways:
20621first, it contains additional values calculated once in the varlist;
20622second, it carries an option to specify the labels' increment per row.
20623This latter feature turns out to be essential; otherwise, a graph may
20624have more rows than fit on a display or on a sheet of paper.
20625
20626@need 1500
20627This new feature requires a change to the @code{Y-axis-column}
20628function, to add @code{vertical-step} to it. The function looks like
20629this:
20630
20631@findex Y-axis-column @r{Final version.}
20632@smallexample
20633@group
20634;;; @r{Final version.}
20635(defun Y-axis-column
20636 (height width-of-label &optional vertical-step)
20637 "Construct list of labels for Y axis.
20638HEIGHT is maximum height of graph.
20639WIDTH-OF-LABEL is maximum width of label.
20640VERTICAL-STEP, an option, is a positive integer
20641that specifies how much a Y axis label increments
20642for each line. For example, a step of 5 means
20643that each line is five units of the graph."
20644@end group
20645@group
20646 (let (Y-axis
20647 (number-per-line (or vertical-step 1)))
20648 (while (> height 1)
20649 (if (zerop (% height Y-axis-label-spacing))
20650@end group
20651@group
20652 ;; @r{Insert label.}
20653 (setq Y-axis
20654 (cons
20655 (Y-axis-element
20656 (* height number-per-line)
20657 width-of-label)
20658 Y-axis))
20659@end group
20660@group
20661 ;; @r{Else, insert blanks.}
20662 (setq Y-axis
20663 (cons
20664 (make-string width-of-label ? )
20665 Y-axis)))
20666 (setq height (1- height)))
20667@end group
20668@group
20669 ;; @r{Insert base line.}
20670 (setq Y-axis (cons (Y-axis-element
20671 (or vertical-step 1)
20672 width-of-label)
20673 Y-axis))
20674 (nreverse Y-axis)))
20675@end group
20676@end smallexample
20677
20678The values for the maximum height of graph and the width of a symbol
20679are computed by @code{print-graph} in its @code{let} expression; so
20680@code{graph-body-print} must be changed to accept them.
20681
20682@findex graph-body-print @r{Final version.}
20683@smallexample
20684@group
20685;;; @r{Final version.}
20686(defun graph-body-print (numbers-list height symbol-width)
20687 "Print a bar graph of the NUMBERS-LIST.
20688The numbers-list consists of the Y-axis values.
20689HEIGHT is maximum height of graph.
20690SYMBOL-WIDTH is number of each column."
20691@end group
20692@group
20693 (let (from-position)
20694 (while numbers-list
20695 (setq from-position (point))
20696 (insert-rectangle
20697 (column-of-graph height (car numbers-list)))
20698 (goto-char from-position)
20699 (forward-char symbol-width)
20700@end group
20701@group
20702 ;; @r{Draw graph column by column.}
20703 (sit-for 0)
20704 (setq numbers-list (cdr numbers-list)))
20705 ;; @r{Place point for X axis labels.}
20706 (forward-line height)
20707 (insert "\n")))
20708@end group
20709@end smallexample
20710
20711@need 1250
20712Finally, the code for the @code{print-graph} function:
20713
20714@findex print-graph @r{Final version.}
20715@smallexample
20716@group
20717;;; @r{Final version.}
20718(defun print-graph
20719 (numbers-list &optional vertical-step)
09e80d9f 20720 "Print labeled bar graph of the NUMBERS-LIST.
8cda6f8f
GM
20721The numbers-list consists of the Y-axis values.
20722@end group
20723
20724@group
20725Optionally, VERTICAL-STEP, a positive integer,
20726specifies how much a Y axis label increments for
20727each line. For example, a step of 5 means that
20728each row is five units."
20729@end group
20730@group
20731 (let* ((symbol-width (length graph-blank))
20732 ;; @code{height} @r{is both the largest number}
20733 ;; @r{and the number with the most digits.}
20734 (height (apply 'max numbers-list))
20735@end group
20736@group
20737 (height-of-top-line
20738 (if (zerop (% height Y-axis-label-spacing))
20739 height
20740 ;; @r{else}
20741 (* (1+ (/ height Y-axis-label-spacing))
20742 Y-axis-label-spacing)))
20743@end group
20744@group
20745 (vertical-step (or vertical-step 1))
20746 (full-Y-label-width
20747 (length
20748@end group
20749@group
20750 (concat
20751 (number-to-string
20752 (* height-of-top-line vertical-step))
20753 Y-axis-tic))))
20754@end group
20755
20756@group
20757 (print-Y-axis
20758 height-of-top-line full-Y-label-width vertical-step)
20759@end group
20760@group
20761 (graph-body-print
20762 numbers-list height-of-top-line symbol-width)
20763 (print-X-axis numbers-list)))
20764@end group
20765@end smallexample
20766
d6adf7e7 20767@node Test print-graph
8cda6f8f
GM
20768@appendixsubsec Testing @code{print-graph}
20769
20770@need 1250
20771We can test the @code{print-graph} function with a short list of numbers:
20772
20773@enumerate
20774@item
20775Install the final versions of @code{Y-axis-column},
20776@code{graph-body-print}, and @code{print-graph} (in addition to the
20777rest of the code.)
20778
20779@item
20780Copy the following expression:
20781
20782@smallexample
20783(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20784@end smallexample
20785
20786@item
20787Switch to the @file{*scratch*} buffer and place the cursor where you
20788want the axis labels to start.
20789
20790@item
20791Type @kbd{M-:} (@code{eval-expression}).
20792
20793@item
20794Yank the test expression into the minibuffer
20795with @kbd{C-y} (@code{yank)}.
20796
20797@item
20798Press @key{RET} to evaluate the expression.
20799@end enumerate
20800
20801@need 1250
20802Emacs will print a graph that looks like this:
20803
20804@smallexample
20805@group
2080610 -
20807
20808
20809 *
20810 ** *
20811 5 - **** *
20812 **** ***
20813 * *********
20814 ************
20815 1 - *************
20816
20817 | | | |
20818 1 5 10 15
20819@end group
20820@end smallexample
20821
20822@need 1200
20823On the other hand, if you pass @code{print-graph} a
20824@code{vertical-step} value of 2, by evaluating this expression:
20825
20826@smallexample
20827(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20828@end smallexample
20829
20830@need 1250
20831@noindent
20832The graph looks like this:
20833
20834@smallexample
20835@group
2083620 -
20837
20838
20839 *
20840 ** *
2084110 - **** *
20842 **** ***
20843 * *********
20844 ************
20845 2 - *************
20846
20847 | | | |
20848 1 5 10 15
20849@end group
20850@end smallexample
20851
20852@noindent
20853(A question: is the `2' on the bottom of the vertical axis a bug or a
20854feature? If you think it is a bug, and should be a `1' instead, (or
20855even a `0'), you can modify the sources.)
20856
d6adf7e7 20857@node Graphing words in defuns
8cda6f8f
GM
20858@appendixsubsec Graphing Numbers of Words and Symbols
20859
20860Now for the graph for which all this code was written: a graph that
20861shows how many function definitions contain fewer than 10 words and
20862symbols, how many contain between 10 and 19 words and symbols, how
20863many contain between 20 and 29 words and symbols, and so on.
20864
20865This is a multi-step process. First make sure you have loaded all the
20866requisite code.
20867
20868@need 1500
20869It is a good idea to reset the value of @code{top-of-ranges} in case
20870you have set it to some different value. You can evaluate the
20871following:
20872
20873@smallexample
20874@group
20875(setq top-of-ranges
20876 '(10 20 30 40 50
20877 60 70 80 90 100
20878 110 120 130 140 150
20879 160 170 180 190 200
20880 210 220 230 240 250
20881 260 270 280 290 300)
20882@end group
20883@end smallexample
20884
20885@noindent
20886Next create a list of the number of words and symbols in each range.
20887
20888@need 1500
20889@noindent
20890Evaluate the following:
20891
20892@smallexample
20893@group
20894(setq list-for-graph
20895 (defuns-per-range
20896 (sort
20897 (recursive-lengths-list-many-files
20898 (directory-files "/usr/local/emacs/lisp"
20899 t ".+el$"))
20900 '<)
20901 top-of-ranges))
20902@end group
20903@end smallexample
20904
20905@noindent
20906On my old machine, this took about an hour. It looked though 303 Lisp
20907files in my copy of Emacs version 19.23. After all that computing,
20908the @code{list-for-graph} had this value:
20909
20910@smallexample
20911@group
20912(537 1027 955 785 594 483 349 292 224 199 166 120 116 99
2091390 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20914@end group
20915@end smallexample
20916
20917@noindent
20918This means that my copy of Emacs had 537 function definitions with
20919fewer than 10 words or symbols in them, 1,027 function definitions
20920with 10 to 19 words or symbols in them, 955 function definitions with
2092120 to 29 words or symbols in them, and so on.
20922
20923Clearly, just by looking at this list we can see that most function
20924definitions contain ten to thirty words and symbols.
20925
20926Now for printing. We do @emph{not} want to print a graph that is
209271,030 lines high @dots{} Instead, we should print a graph that is
20928fewer than twenty-five lines high. A graph that height can be
20929displayed on almost any monitor, and easily printed on a sheet of paper.
20930
20931This means that each value in @code{list-for-graph} must be reduced to
20932one-fiftieth its present value.
20933
20934Here is a short function to do just that, using two functions we have
20935not yet seen, @code{mapcar} and @code{lambda}.
20936
20937@smallexample
20938@group
20939(defun one-fiftieth (full-range)
20940 "Return list, each number one-fiftieth of previous."
d1069532 20941 (mapcar (lambda (arg) (/ arg 50)) full-range))
8cda6f8f
GM
20942@end group
20943@end smallexample
20944
d6adf7e7 20945@node lambda
8cda6f8f
GM
20946@appendixsubsec A @code{lambda} Expression: Useful Anonymity
20947@cindex Anonymous function
20948@findex lambda
20949
20950@code{lambda} is the symbol for an anonymous function, a function
20951without a name. Every time you use an anonymous function, you need to
20952include its whole body.
20953
20954@need 1250
20955@noindent
20956Thus,
20957
20958@smallexample
20959(lambda (arg) (/ arg 50))
20960@end smallexample
20961
20962@noindent
20963is a function definition that says `return the value resulting from
20964dividing whatever is passed to me as @code{arg} by 50'.
20965
20966@need 1200
20967Earlier, for example, we had a function @code{multiply-by-seven}; it
20968multiplied its argument by 7. This function is similar, except it
20969divides its argument by 50; and, it has no name. The anonymous
20970equivalent of @code{multiply-by-seven} is:
20971
20972@smallexample
20973(lambda (number) (* 7 number))
20974@end smallexample
20975
20976@noindent
20977(@xref{defun, , The @code{defun} Special Form}.)
20978
20979@need 1250
20980@noindent
20981If we want to multiply 3 by 7, we can write:
20982
20983@c !!! Clear print-postscript-figures if the computer formatting this
20984@c document is too small and cannot handle all the diagrams and figures.
20985@c clear print-postscript-figures
20986@c set print-postscript-figures
20987@c lambda example diagram #1
20988@ifnottex
20989@smallexample
20990@group
20991(multiply-by-seven 3)
20992 \_______________/ ^
20993 | |
20994 function argument
20995@end group
20996@end smallexample
20997@end ifnottex
20998@ifset print-postscript-figures
20999@sp 1
21000@tex
21001@center @image{lambda-1}
21002%%%% old method of including an image
21003% \input /usr/local/lib/tex/inputs/psfig.tex
21004% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
21005% \catcode`\@=0 %
21006@end tex
21007@sp 1
21008@end ifset
21009@ifclear print-postscript-figures
21010@iftex
21011@smallexample
21012@group
21013(multiply-by-seven 3)
21014 \_______________/ ^
21015 | |
21016 function argument
21017@end group
21018@end smallexample
21019@end iftex
21020@end ifclear
21021
21022@noindent
21023This expression returns 21.
21024
21025@need 1250
21026@noindent
21027Similarly, we can write:
21028
21029@c lambda example diagram #2
21030@ifnottex
21031@smallexample
21032@group
21033((lambda (number) (* 7 number)) 3)
21034 \____________________________/ ^
21035 | |
21036 anonymous function argument
21037@end group
21038@end smallexample
21039@end ifnottex
21040@ifset print-postscript-figures
21041@sp 1
21042@tex
21043@center @image{lambda-2}
21044%%%% old method of including an image
21045% \input /usr/local/lib/tex/inputs/psfig.tex
21046% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
21047% \catcode`\@=0 %
21048@end tex
21049@sp 1
21050@end ifset
21051@ifclear print-postscript-figures
21052@iftex
21053@smallexample
21054@group
21055((lambda (number) (* 7 number)) 3)
21056 \____________________________/ ^
21057 | |
21058 anonymous function argument
21059@end group
21060@end smallexample
21061@end iftex
21062@end ifclear
21063
21064@need 1250
21065@noindent
21066If we want to divide 100 by 50, we can write:
21067
21068@c lambda example diagram #3
21069@ifnottex
21070@smallexample
21071@group
21072((lambda (arg) (/ arg 50)) 100)
21073 \______________________/ \_/
21074 | |
21075 anonymous function argument
21076@end group
21077@end smallexample
21078@end ifnottex
21079@ifset print-postscript-figures
21080@sp 1
21081@tex
21082@center @image{lambda-3}
21083%%%% old method of including an image
21084% \input /usr/local/lib/tex/inputs/psfig.tex
21085% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
21086% \catcode`\@=0 %
21087@end tex
21088@sp 1
21089@end ifset
21090@ifclear print-postscript-figures
21091@iftex
21092@smallexample
21093@group
21094((lambda (arg) (/ arg 50)) 100)
21095 \______________________/ \_/
21096 | |
21097 anonymous function argument
21098@end group
21099@end smallexample
21100@end iftex
21101@end ifclear
21102
21103@noindent
21104This expression returns 2. The 100 is passed to the function, which
21105divides that number by 50.
21106
21107@xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
21108Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
21109expressions derive from the Lambda Calculus.
21110
d6adf7e7 21111@node mapcar
8cda6f8f
GM
21112@appendixsubsec The @code{mapcar} Function
21113@findex mapcar
21114
21115@code{mapcar} is a function that calls its first argument with each
21116element of its second argument, in turn. The second argument must be
21117a sequence.
21118
21119The @samp{map} part of the name comes from the mathematical phrase,
21120`mapping over a domain', meaning to apply a function to each of the
21121elements in a domain. The mathematical phrase is based on the
21122metaphor of a surveyor walking, one step at a time, over an area he is
21123mapping. And @samp{car}, of course, comes from the Lisp notion of the
21124first of a list.
21125
21126@need 1250
21127@noindent
21128For example,
21129
21130@smallexample
21131@group
21132(mapcar '1+ '(2 4 6))
21133 @result{} (3 5 7)
21134@end group
21135@end smallexample
21136
21137@noindent
21138The function @code{1+} which adds one to its argument, is executed on
21139@emph{each} element of the list, and a new list is returned.
21140
21141Contrast this with @code{apply}, which applies its first argument to
21142all the remaining.
21143(@xref{Readying a Graph, , Readying a Graph}, for a explanation of
21144@code{apply}.)
21145
21146@need 1250
21147In the definition of @code{one-fiftieth}, the first argument is the
21148anonymous function:
21149
21150@smallexample
21151(lambda (arg) (/ arg 50))
21152@end smallexample
21153
21154@noindent
21155and the second argument is @code{full-range}, which will be bound to
21156@code{list-for-graph}.
21157
21158@need 1250
21159The whole expression looks like this:
21160
21161@smallexample
d1069532 21162(mapcar (lambda (arg) (/ arg 50)) full-range))
8cda6f8f
GM
21163@end smallexample
21164
21165@xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
21166Lisp Reference Manual}, for more about @code{mapcar}.
21167
21168Using the @code{one-fiftieth} function, we can generate a list in
21169which each element is one-fiftieth the size of the corresponding
21170element in @code{list-for-graph}.
21171
21172@smallexample
21173@group
21174(setq fiftieth-list-for-graph
21175 (one-fiftieth list-for-graph))
21176@end group
21177@end smallexample
21178
21179@need 1250
21180The resulting list looks like this:
21181
21182@smallexample
21183@group
21184(10 20 19 15 11 9 6 5 4 3 3 2 2
211851 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
21186@end group
21187@end smallexample
21188
21189@noindent
21190This, we are almost ready to print! (We also notice the loss of
21191information: many of the higher ranges are 0, meaning that fewer than
2119250 defuns had that many words or symbols---but not necessarily meaning
21193that none had that many words or symbols.)
21194
d6adf7e7 21195@node Another Bug
8cda6f8f
GM
21196@appendixsubsec Another Bug @dots{} Most Insidious
21197@cindex Bug, most insidious type
21198@cindex Insidious type of bug
21199
21200I said `almost ready to print'! Of course, there is a bug in the
21201@code{print-graph} function @dots{} It has a @code{vertical-step}
21202option, but not a @code{horizontal-step} option. The
21203@code{top-of-range} scale goes from 10 to 300 by tens. But the
21204@code{print-graph} function will print only by ones.
21205
21206This is a classic example of what some consider the most insidious
21207type of bug, the bug of omission. This is not the kind of bug you can
21208find by studying the code, for it is not in the code; it is an omitted
21209feature. Your best actions are to try your program early and often;
21210and try to arrange, as much as you can, to write code that is easy to
21211understand and easy to change. Try to be aware, whenever you can,
21212that whatever you have written, @emph{will} be rewritten, if not soon,
21213eventually. A hard maxim to follow.
21214
21215It is the @code{print-X-axis-numbered-line} function that needs the
21216work; and then the @code{print-X-axis} and the @code{print-graph}
21217functions need to be adapted. Not much needs to be done; there is one
21218nicety: the numbers ought to line up under the tic marks. This takes
21219a little thought.
21220
21221@need 1250
21222Here is the corrected @code{print-X-axis-numbered-line}:
21223
21224@smallexample
21225@group
21226(defun print-X-axis-numbered-line
21227 (number-of-X-tics X-axis-leading-spaces
21228 &optional horizontal-step)
21229 "Print line of X-axis numbers"
21230 (let ((number X-axis-label-spacing)
21231 (horizontal-step (or horizontal-step 1)))
21232@end group
21233@group
21234 (insert X-axis-leading-spaces)
21235 ;; @r{Delete extra leading spaces.}
21236 (delete-char
21237 (- (1-
21238 (length (number-to-string horizontal-step)))))
21239 (insert (concat
21240 (make-string
21241@end group
21242@group
21243 ;; @r{Insert white space.}
21244 (- (* symbol-width
21245 X-axis-label-spacing)
21246 (1-
21247 (length
21248 (number-to-string horizontal-step)))
21249 2)
21250 ? )
21251 (number-to-string
21252 (* number horizontal-step))))
21253@end group
21254@group
21255 ;; @r{Insert remaining numbers.}
21256 (setq number (+ number X-axis-label-spacing))
21257 (while (> number-of-X-tics 1)
21258 (insert (X-axis-element
21259 (* number horizontal-step)))
21260 (setq number (+ number X-axis-label-spacing))
21261 (setq number-of-X-tics (1- number-of-X-tics)))))
21262@end group
21263@end smallexample
21264
21265@need 1500
21266If you are reading this in Info, you can see the new versions of
21267@code{print-X-axis} @code{print-graph} and evaluate them. If you are
21268reading this in a printed book, you can see the changed lines here
21269(the full text is too much to print).
21270
21271@iftex
21272@smallexample
21273@group
21274(defun print-X-axis (numbers-list horizontal-step)
21275 @dots{}
21276 (print-X-axis-numbered-line
21277 tic-number leading-spaces horizontal-step))
21278@end group
21279@end smallexample
21280
21281@smallexample
21282@group
21283(defun print-graph
21284 (numbers-list
21285 &optional vertical-step horizontal-step)
21286 @dots{}
21287 (print-X-axis numbers-list horizontal-step))
21288@end group
21289@end smallexample
21290@end iftex
21291
21292@ifnottex
21293@smallexample
21294@group
21295(defun print-X-axis (numbers-list horizontal-step)
21296 "Print X axis labels to length of NUMBERS-LIST.
21297Optionally, HORIZONTAL-STEP, a positive integer,
21298specifies how much an X axis label increments for
21299each column."
21300@end group
21301@group
21302;; Value of symbol-width and full-Y-label-width
21303;; are passed by `print-graph'.
21304 (let* ((leading-spaces
21305 (make-string full-Y-label-width ? ))
21306 ;; symbol-width @r{is provided by} graph-body-print
21307 (tic-width (* symbol-width X-axis-label-spacing))
21308 (X-length (length numbers-list))
21309@end group
21310@group
21311 (X-tic
21312 (concat
21313 (make-string
21314 ;; @r{Make a string of blanks.}
21315 (- (* symbol-width X-axis-label-spacing)
21316 (length X-axis-tic-symbol))
21317 ? )
21318@end group
21319@group
21320 ;; @r{Concatenate blanks with tic symbol.}
21321 X-axis-tic-symbol))
21322 (tic-number
21323 (if (zerop (% X-length tic-width))
21324 (/ X-length tic-width)
21325 (1+ (/ X-length tic-width)))))
21326@end group
21327
21328@group
21329 (print-X-axis-tic-line
21330 tic-number leading-spaces X-tic)
21331 (insert "\n")
21332 (print-X-axis-numbered-line
21333 tic-number leading-spaces horizontal-step)))
21334@end group
21335@end smallexample
21336
21337@smallexample
21338@group
21339(defun print-graph
21340 (numbers-list &optional vertical-step horizontal-step)
09e80d9f 21341 "Print labeled bar graph of the NUMBERS-LIST.
8cda6f8f
GM
21342The numbers-list consists of the Y-axis values.
21343@end group
21344
21345@group
21346Optionally, VERTICAL-STEP, a positive integer,
21347specifies how much a Y axis label increments for
21348each line. For example, a step of 5 means that
21349each row is five units.
21350@end group
21351
21352@group
21353Optionally, HORIZONTAL-STEP, a positive integer,
21354specifies how much an X axis label increments for
21355each column."
21356 (let* ((symbol-width (length graph-blank))
21357 ;; @code{height} @r{is both the largest number}
21358 ;; @r{and the number with the most digits.}
21359 (height (apply 'max numbers-list))
21360@end group
21361@group
21362 (height-of-top-line
21363 (if (zerop (% height Y-axis-label-spacing))
21364 height
21365 ;; @r{else}
21366 (* (1+ (/ height Y-axis-label-spacing))
21367 Y-axis-label-spacing)))
21368@end group
21369@group
21370 (vertical-step (or vertical-step 1))
21371 (full-Y-label-width
21372 (length
21373 (concat
21374 (number-to-string
21375 (* height-of-top-line vertical-step))
21376 Y-axis-tic))))
21377@end group
21378@group
21379 (print-Y-axis
21380 height-of-top-line full-Y-label-width vertical-step)
21381 (graph-body-print
21382 numbers-list height-of-top-line symbol-width)
21383 (print-X-axis numbers-list horizontal-step)))
21384@end group
21385@end smallexample
21386@end ifnottex
21387
21388@c qqq
21389@ignore
21390Graphing Definitions Re-listed
21391
21392@need 1250
21393Here are all the graphing definitions in their final form:
21394
21395@smallexample
21396@group
21397(defvar top-of-ranges
21398 '(10 20 30 40 50
21399 60 70 80 90 100
21400 110 120 130 140 150
21401 160 170 180 190 200
21402 210 220 230 240 250)
21403 "List specifying ranges for `defuns-per-range'.")
21404@end group
21405
21406@group
21407(defvar graph-symbol "*"
21408 "String used as symbol in graph, usually an asterisk.")
21409@end group
21410
21411@group
21412(defvar graph-blank " "
21413 "String used as blank in graph, usually a blank space.
21414graph-blank must be the same number of columns wide
21415as graph-symbol.")
21416@end group
21417
21418@group
21419(defvar Y-axis-tic " - "
21420 "String that follows number in a Y axis label.")
21421@end group
21422
21423@group
21424(defvar Y-axis-label-spacing 5
21425 "Number of lines from one Y axis label to next.")
21426@end group
21427
21428@group
21429(defvar X-axis-tic-symbol "|"
21430 "String to insert to point to a column in X axis.")
21431@end group
21432
21433@group
21434(defvar X-axis-label-spacing
21435 (if (boundp 'graph-blank)
21436 (* 5 (length graph-blank)) 5)
21437 "Number of units from one X axis label to next.")
21438@end group
21439@end smallexample
21440
21441@smallexample
21442@group
21443(defun count-words-in-defun ()
21444 "Return the number of words and symbols in a defun."
21445 (beginning-of-defun)
21446 (let ((count 0)
21447 (end (save-excursion (end-of-defun) (point))))
21448@end group
21449
21450@group
21451 (while
21452 (and (< (point) end)
21453 (re-search-forward
21454 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
21455 end t))
21456 (setq count (1+ count)))
21457 count))
21458@end group
21459@end smallexample
21460
21461@smallexample
21462@group
21463(defun lengths-list-file (filename)
21464 "Return list of definitions' lengths within FILE.
21465The returned list is a list of numbers.
21466Each number is the number of words or
21467symbols in one function definition."
21468@end group
21469
21470@group
21471 (message "Working on `%s' ... " filename)
21472 (save-excursion
21473 (let ((buffer (find-file-noselect filename))
21474 (lengths-list))
21475 (set-buffer buffer)
21476 (setq buffer-read-only t)
21477 (widen)
21478 (goto-char (point-min))
21479@end group
21480
21481@group
21482 (while (re-search-forward "^(defun" nil t)
21483 (setq lengths-list
21484 (cons (count-words-in-defun) lengths-list)))
21485 (kill-buffer buffer)
21486 lengths-list)))
21487@end group
21488@end smallexample
21489
21490@smallexample
21491@group
21492(defun lengths-list-many-files (list-of-files)
21493 "Return list of lengths of defuns in LIST-OF-FILES."
21494 (let (lengths-list)
21495;;; @r{true-or-false-test}
21496 (while list-of-files
21497 (setq lengths-list
21498 (append
21499 lengths-list
21500@end group
21501@group
21502;;; @r{Generate a lengths' list.}
21503 (lengths-list-file
21504 (expand-file-name (car list-of-files)))))
21505;;; @r{Make files' list shorter.}
21506 (setq list-of-files (cdr list-of-files)))
21507;;; @r{Return final value of lengths' list.}
21508 lengths-list))
21509@end group
21510@end smallexample
21511
21512@smallexample
21513@group
21514(defun defuns-per-range (sorted-lengths top-of-ranges)
21515 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
21516 (let ((top-of-range (car top-of-ranges))
21517 (number-within-range 0)
21518 defuns-per-range-list)
21519@end group
21520
21521@group
21522 ;; @r{Outer loop.}
21523 (while top-of-ranges
21524
21525 ;; @r{Inner loop.}
21526 (while (and
21527 ;; @r{Need number for numeric test.}
21528 (car sorted-lengths)
21529 (< (car sorted-lengths) top-of-range))
21530
21531 ;; @r{Count number of definitions within current range.}
21532 (setq number-within-range (1+ number-within-range))
21533 (setq sorted-lengths (cdr sorted-lengths)))
21534@end group
21535
21536@group
21537 ;; @r{Exit inner loop but remain within outer loop.}
21538
21539 (setq defuns-per-range-list
21540 (cons number-within-range defuns-per-range-list))
21541 (setq number-within-range 0) ; @r{Reset count to zero.}
21542
21543 ;; @r{Move to next range.}
21544 (setq top-of-ranges (cdr top-of-ranges))
21545 ;; @r{Specify next top of range value.}
21546 (setq top-of-range (car top-of-ranges)))
21547@end group
21548
21549@group
21550 ;; @r{Exit outer loop and count the number of defuns larger than}
21551 ;; @r{ the largest top-of-range value.}
21552 (setq defuns-per-range-list
21553 (cons
21554 (length sorted-lengths)
21555 defuns-per-range-list))
21556
21557 ;; @r{Return a list of the number of definitions within each range,}
21558 ;; @r{ smallest to largest.}
21559 (nreverse defuns-per-range-list)))
21560@end group
21561@end smallexample
21562
21563@smallexample
21564@group
21565(defun column-of-graph (max-graph-height actual-height)
21566 "Return list of MAX-GRAPH-HEIGHT strings;
21567ACTUAL-HEIGHT are graph-symbols.
21568The graph-symbols are contiguous entries at the end
21569of the list.
21570The list will be inserted as one column of a graph.
21571The strings are either graph-blank or graph-symbol."
21572@end group
21573
21574@group
21575 (let ((insert-list nil)
21576 (number-of-top-blanks
21577 (- max-graph-height actual-height)))
21578
21579 ;; @r{Fill in @code{graph-symbols}.}
21580 (while (> actual-height 0)
21581 (setq insert-list (cons graph-symbol insert-list))
21582 (setq actual-height (1- actual-height)))
21583@end group
21584
21585@group
21586 ;; @r{Fill in @code{graph-blanks}.}
21587 (while (> number-of-top-blanks 0)
21588 (setq insert-list (cons graph-blank insert-list))
21589 (setq number-of-top-blanks
21590 (1- number-of-top-blanks)))
21591
21592 ;; @r{Return whole list.}
21593 insert-list))
21594@end group
21595@end smallexample
21596
21597@smallexample
21598@group
21599(defun Y-axis-element (number full-Y-label-width)
21600 "Construct a NUMBERed label element.
21601A numbered element looks like this ` 5 - ',
21602and is padded as needed so all line up with
21603the element for the largest number."
21604@end group
21605@group
21606 (let* ((leading-spaces
21607 (- full-Y-label-width
21608 (length
21609 (concat (number-to-string number)
21610 Y-axis-tic)))))
21611@end group
21612@group
21613 (concat
21614 (make-string leading-spaces ? )
21615 (number-to-string number)
21616 Y-axis-tic)))
21617@end group
21618@end smallexample
21619
21620@smallexample
21621@group
21622(defun print-Y-axis
21623 (height full-Y-label-width &optional vertical-step)
21624 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
21625Height must be the maximum height of the graph.
21626Full width is the width of the highest label element.
21627Optionally, print according to VERTICAL-STEP."
21628@end group
21629@group
21630;; Value of height and full-Y-label-width
21631;; are passed by `print-graph'.
21632 (let ((start (point)))
21633 (insert-rectangle
21634 (Y-axis-column height full-Y-label-width vertical-step))
21635@end group
21636@group
21637 ;; @r{Place point ready for inserting graph.}
21638 (goto-char start)
21639 ;; @r{Move point forward by value of} full-Y-label-width
21640 (forward-char full-Y-label-width)))
21641@end group
21642@end smallexample
21643
21644@smallexample
21645@group
21646(defun print-X-axis-tic-line
21647 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
21648 "Print ticks for X axis."
21649 (insert X-axis-leading-spaces)
21650 (insert X-axis-tic-symbol) ; @r{Under first column.}
21651@end group
21652@group
21653 ;; @r{Insert second tic in the right spot.}
21654 (insert (concat
21655 (make-string
21656 (- (* symbol-width X-axis-label-spacing)
21657 ;; @r{Insert white space up to second tic symbol.}
21658 (* 2 (length X-axis-tic-symbol)))
21659 ? )
21660 X-axis-tic-symbol))
21661@end group
21662@group
21663 ;; @r{Insert remaining ticks.}
21664 (while (> number-of-X-tics 1)
21665 (insert X-axis-tic-element)
21666 (setq number-of-X-tics (1- number-of-X-tics))))
21667@end group
21668@end smallexample
21669
21670@smallexample
21671@group
21672(defun X-axis-element (number)
21673 "Construct a numbered X axis element."
21674 (let ((leading-spaces
21675 (- (* symbol-width X-axis-label-spacing)
21676 (length (number-to-string number)))))
21677 (concat (make-string leading-spaces ? )
21678 (number-to-string number))))
21679@end group
21680@end smallexample
21681
21682@smallexample
21683@group
21684(defun graph-body-print (numbers-list height symbol-width)
21685 "Print a bar graph of the NUMBERS-LIST.
21686The numbers-list consists of the Y-axis values.
21687HEIGHT is maximum height of graph.
21688SYMBOL-WIDTH is number of each column."
21689@end group
21690@group
21691 (let (from-position)
21692 (while numbers-list
21693 (setq from-position (point))
21694 (insert-rectangle
21695 (column-of-graph height (car numbers-list)))
21696 (goto-char from-position)
21697 (forward-char symbol-width)
21698@end group
21699@group
21700 ;; @r{Draw graph column by column.}
21701 (sit-for 0)
21702 (setq numbers-list (cdr numbers-list)))
21703 ;; @r{Place point for X axis labels.}
21704 (forward-line height)
21705 (insert "\n")))
21706@end group
21707@end smallexample
21708
21709@smallexample
21710@group
21711(defun Y-axis-column
21712 (height width-of-label &optional vertical-step)
21713 "Construct list of labels for Y axis.
21714HEIGHT is maximum height of graph.
21715WIDTH-OF-LABEL is maximum width of label.
21716@end group
21717@group
21718VERTICAL-STEP, an option, is a positive integer
21719that specifies how much a Y axis label increments
21720for each line. For example, a step of 5 means
21721that each line is five units of the graph."
21722 (let (Y-axis
21723 (number-per-line (or vertical-step 1)))
21724@end group
21725@group
21726 (while (> height 1)
21727 (if (zerop (% height Y-axis-label-spacing))
21728 ;; @r{Insert label.}
21729 (setq Y-axis
21730 (cons
21731 (Y-axis-element
21732 (* height number-per-line)
21733 width-of-label)
21734 Y-axis))
21735@end group
21736@group
21737 ;; @r{Else, insert blanks.}
21738 (setq Y-axis
21739 (cons
21740 (make-string width-of-label ? )
21741 Y-axis)))
21742 (setq height (1- height)))
21743@end group
21744@group
21745 ;; @r{Insert base line.}
21746 (setq Y-axis (cons (Y-axis-element
21747 (or vertical-step 1)
21748 width-of-label)
21749 Y-axis))
21750 (nreverse Y-axis)))
21751@end group
21752@end smallexample
21753
21754@smallexample
21755@group
21756(defun print-X-axis-numbered-line
21757 (number-of-X-tics X-axis-leading-spaces
21758 &optional horizontal-step)
21759 "Print line of X-axis numbers"
21760 (let ((number X-axis-label-spacing)
21761 (horizontal-step (or horizontal-step 1)))
21762@end group
21763@group
21764 (insert X-axis-leading-spaces)
21765 ;; line up number
21766 (delete-char (- (1- (length (number-to-string horizontal-step)))))
21767 (insert (concat
21768 (make-string
21769 ;; @r{Insert white space up to next number.}
21770 (- (* symbol-width X-axis-label-spacing)
21771 (1- (length (number-to-string horizontal-step)))
21772 2)
21773 ? )
21774 (number-to-string (* number horizontal-step))))
21775@end group
21776@group
21777 ;; @r{Insert remaining numbers.}
21778 (setq number (+ number X-axis-label-spacing))
21779 (while (> number-of-X-tics 1)
21780 (insert (X-axis-element (* number horizontal-step)))
21781 (setq number (+ number X-axis-label-spacing))
21782 (setq number-of-X-tics (1- number-of-X-tics)))))
21783@end group
21784@end smallexample
21785
21786@smallexample
21787@group
21788(defun print-X-axis (numbers-list horizontal-step)
21789 "Print X axis labels to length of NUMBERS-LIST.
21790Optionally, HORIZONTAL-STEP, a positive integer,
21791specifies how much an X axis label increments for
21792each column."
21793@end group
21794@group
21795;; Value of symbol-width and full-Y-label-width
21796;; are passed by `print-graph'.
21797 (let* ((leading-spaces
21798 (make-string full-Y-label-width ? ))
21799 ;; symbol-width @r{is provided by} graph-body-print
21800 (tic-width (* symbol-width X-axis-label-spacing))
21801 (X-length (length numbers-list))
21802@end group
21803@group
21804 (X-tic
21805 (concat
21806 (make-string
21807 ;; @r{Make a string of blanks.}
21808 (- (* symbol-width X-axis-label-spacing)
21809 (length X-axis-tic-symbol))
21810 ? )
21811@end group
21812@group
21813 ;; @r{Concatenate blanks with tic symbol.}
21814 X-axis-tic-symbol))
21815 (tic-number
21816 (if (zerop (% X-length tic-width))
21817 (/ X-length tic-width)
21818 (1+ (/ X-length tic-width)))))
21819@end group
21820
21821@group
21822 (print-X-axis-tic-line
21823 tic-number leading-spaces X-tic)
21824 (insert "\n")
21825 (print-X-axis-numbered-line
21826 tic-number leading-spaces horizontal-step)))
21827@end group
21828@end smallexample
21829
21830@smallexample
21831@group
21832(defun one-fiftieth (full-range)
21833 "Return list, each number of which is 1/50th previous."
d1069532 21834 (mapcar (lambda (arg) (/ arg 50)) full-range))
8cda6f8f
GM
21835@end group
21836@end smallexample
21837
21838@smallexample
21839@group
21840(defun print-graph
21841 (numbers-list &optional vertical-step horizontal-step)
09e80d9f 21842 "Print labeled bar graph of the NUMBERS-LIST.
8cda6f8f
GM
21843The numbers-list consists of the Y-axis values.
21844@end group
21845
21846@group
21847Optionally, VERTICAL-STEP, a positive integer,
21848specifies how much a Y axis label increments for
21849each line. For example, a step of 5 means that
21850each row is five units.
21851@end group
21852
21853@group
21854Optionally, HORIZONTAL-STEP, a positive integer,
21855specifies how much an X axis label increments for
21856each column."
21857 (let* ((symbol-width (length graph-blank))
21858 ;; @code{height} @r{is both the largest number}
21859 ;; @r{and the number with the most digits.}
21860 (height (apply 'max numbers-list))
21861@end group
21862@group
21863 (height-of-top-line
21864 (if (zerop (% height Y-axis-label-spacing))
21865 height
21866 ;; @r{else}
21867 (* (1+ (/ height Y-axis-label-spacing))
21868 Y-axis-label-spacing)))
21869@end group
21870@group
21871 (vertical-step (or vertical-step 1))
21872 (full-Y-label-width
21873 (length
21874 (concat
21875 (number-to-string
21876 (* height-of-top-line vertical-step))
21877 Y-axis-tic))))
21878@end group
21879@group
21880
21881 (print-Y-axis
21882 height-of-top-line full-Y-label-width vertical-step)
21883 (graph-body-print
21884 numbers-list height-of-top-line symbol-width)
21885 (print-X-axis numbers-list horizontal-step)))
21886@end group
21887@end smallexample
21888@c qqq
21889@end ignore
21890
21891@page
d6adf7e7 21892@node Final printed graph
8cda6f8f
GM
21893@appendixsubsec The Printed Graph
21894
21895When made and installed, you can call the @code{print-graph} command
21896like this:
21897@sp 1
21898
21899@smallexample
21900@group
21901(print-graph fiftieth-list-for-graph 50 10)
21902@end group
21903@end smallexample
21904@sp 1
21905
21906@noindent
21907Here is the graph:
21908@sp 2
21909
21910@smallexample
21911@group
219121000 - *
21913 **
21914 **
21915 **
21916 **
21917 750 - ***
21918 ***
21919 ***
21920 ***
21921 ****
21922 500 - *****
21923 ******
21924 ******
21925 ******
21926 *******
21927 250 - ********
21928 ********* *
21929 *********** *
21930 ************* *
21931 50 - ***************** * *
21932 | | | | | | | |
21933 10 50 100 150 200 250 300 350
21934@end group
21935@end smallexample
21936
21937@sp 2
21938
21939@noindent
f99f1641 21940The largest group of functions contain 10--19 words and symbols each.
8cda6f8f 21941
d6adf7e7 21942@node Free Software and Free Manuals
8cda6f8f
GM
21943@appendix Free Software and Free Manuals
21944
21945@strong{by Richard M. Stallman}
21946@sp 1
21947
21948The biggest deficiency in free operating systems is not in the
21949software---it is the lack of good free manuals that we can include in
21950these systems. Many of our most important programs do not come with
21951full manuals. Documentation is an essential part of any software
21952package; when an important free software package does not come with a
21953free manual, that is a major gap. We have many such gaps today.
21954
21955Once upon a time, many years ago, I thought I would learn Perl. I got
21956a copy of a free manual, but I found it hard to read. When I asked
21957Perl users about alternatives, they told me that there were better
21958introductory manuals---but those were not free.
21959
21960Why was this? The authors of the good manuals had written them for
21961O'Reilly Associates, which published them with restrictive terms---no
21962copying, no modification, source files not available---which exclude
21963them from the free software community.
21964
21965That wasn't the first time this sort of thing has happened, and (to
21966our community's great loss) it was far from the last. Proprietary
21967manual publishers have enticed a great many authors to restrict their
21968manuals since then. Many times I have heard a GNU user eagerly tell me
21969about a manual that he is writing, with which he expects to help the
21970GNU project---and then had my hopes dashed, as he proceeded to explain
21971that he had signed a contract with a publisher that would restrict it
21972so that we cannot use it.
21973
21974Given that writing good English is a rare skill among programmers, we
21975can ill afford to lose manuals this way.
21976
8cda6f8f
GM
21977Free documentation, like free software, is a matter of freedom, not
21978price. The problem with these manuals was not that O'Reilly Associates
31b62755
GM
21979charged a price for printed copies---that in itself is fine. The Free
21980Software Foundation @uref{http://shop.fsf.org, sells printed copies} of
21981free @uref{http://www.gnu.org/doc/doc.html, GNU manuals}, too.
8cda6f8f
GM
21982But GNU manuals are available in source code form, while these manuals
21983are available only on paper. GNU manuals come with permission to copy
21984and modify; the Perl manuals do not. These restrictions are the
21985problems.
21986
21987The criterion for a free manual is pretty much the same as for free
21988software: it is a matter of giving all users certain
21989freedoms. Redistribution (including commercial redistribution) must be
21990permitted, so that the manual can accompany every copy of the program,
21991on-line or on paper. Permission for modification is crucial too.
21992
21993As a general rule, I don't believe that it is essential for people to
21994have permission to modify all sorts of articles and books. The issues
21995for writings are not necessarily the same as those for software. For
21996example, I don't think you or I are obliged to give permission to
21997modify articles like this one, which describe our actions and our
21998views.
21999
22000But there is a particular reason why the freedom to modify is crucial
22001for documentation for free software. When people exercise their right
22002to modify the software, and add or change its features, if they are
22003conscientious they will change the manual too---so they can provide
22004accurate and usable documentation with the modified program. A manual
22005which forbids programmers to be conscientious and finish the job, or
22006more precisely requires them to write a new manual from scratch if
22007they change the program, does not fill our community's needs.
22008
22009While a blanket prohibition on modification is unacceptable, some
22010kinds of limits on the method of modification pose no problem. For
22011example, requirements to preserve the original author's copyright
22012notice, the distribution terms, or the list of authors, are ok. It is
22013also no problem to require modified versions to include notice that
22014they were modified, even to have entire sections that may not be
22015deleted or changed, as long as these sections deal with nontechnical
22016topics. (Some GNU manuals have them.)
22017
22018These kinds of restrictions are not a problem because, as a practical
22019matter, they don't stop the conscientious programmer from adapting the
22020manual to fit the modified program. In other words, they don't block
22021the free software community from making full use of the manual.
22022
22023However, it must be possible to modify all the technical content of
22024the manual, and then distribute the result in all the usual media,
22025through all the usual channels; otherwise, the restrictions do block
22026the community, the manual is not free, and so we need another manual.
22027
22028Unfortunately, it is often hard to find someone to write another
22029manual when a proprietary manual exists. The obstacle is that many
22030users think that a proprietary manual is good enough---so they don't
22031see the need to write a free manual. They do not see that the free
22032operating system has a gap that needs filling.
22033
22034Why do users think that proprietary manuals are good enough? Some have
22035not considered the issue. I hope this article will do something to
22036change that.
22037
22038Other users consider proprietary manuals acceptable for the same
22039reason so many people consider proprietary software acceptable: they
22040judge in purely practical terms, not using freedom as a
22041criterion. These people are entitled to their opinions, but since
22042those opinions spring from values which do not include freedom, they
22043are no guide for those of us who do value freedom.
22044
22045Please spread the word about this issue. We continue to lose manuals
22046to proprietary publishing. If we spread the word that proprietary
22047manuals are not sufficient, perhaps the next person who wants to help
22048GNU by writing documentation will realize, before it is too late, that
22049he must above all make it free.
22050
22051We can also encourage commercial publishers to sell free, copylefted
22052manuals instead of proprietary ones. One way you can help this is to
22053check the distribution terms of a manual before you buy it, and prefer
22054copylefted manuals to non-copylefted ones.
22055
22056@sp 2
22057@noindent
22058Note: The Free Software Foundation maintains a page on its Web site
22059that lists free books available from other publishers:@*
22060@uref{http://www.gnu.org/doc/other-free-books.html}
22061
d6adf7e7 22062@node GNU Free Documentation License
8cda6f8f
GM
22063@appendix GNU Free Documentation License
22064
22065@cindex FDL, GNU Free Documentation License
e41dfb1e 22066@include doclicense.texi
8cda6f8f 22067
d6adf7e7 22068@node Index
8cda6f8f
GM
22069@unnumbered Index
22070
22071@ignore
22072MENU ENTRY: NODE NAME.
22073@end ignore
22074
22075@printindex cp
22076
22077@iftex
22078@c Place biographical information on right-hand (verso) page
22079
22080@tex
a9097c6d 22081\par\vfill\supereject
8cda6f8f 22082\ifodd\pageno
8cda6f8f
GM
22083 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22084 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
a9097c6d 22085 %\page\hbox{}\page
8cda6f8f 22086\else
a9097c6d 22087% \par\vfill\supereject
8cda6f8f
GM
22088 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22089 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
a9097c6d
KB
22090 %\page\hbox{}%\page
22091 %\page\hbox{}%\page
8cda6f8f
GM
22092\fi
22093@end tex
22094
a9097c6d 22095@c page
8cda6f8f
GM
22096@w{ }
22097
22098@c ================ Biographical information ================
22099
22100@w{ }
22101@sp 8
22102@center About the Author
22103@sp 1
22104@end iftex
22105
22106@ifnottex
d6adf7e7 22107@node About the Author
8cda6f8f
GM
22108@unnumbered About the Author
22109@end ifnottex
22110
22111@quotation
22112Robert J. Chassell has worked with GNU Emacs since 1985. He writes
22113and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
22114world on software freedom. Chassell was a founding Director and
22115Treasurer of the Free Software Foundation, Inc. He is co-author of
22116the @cite{Texinfo} manual, and has edited more than a dozen other
22117books. He graduated from Cambridge University, in England. He has an
22118abiding interest in social and economic history and flies his own
22119airplane.
22120@end quotation
22121
a9097c6d
KB
22122@c @page
22123@c @w{ }
22124@c
22125@c @c Prevent page number on blank verso, so eject it first.
22126@c @tex
22127@c \par\vfill\supereject
22128@c @end tex
22129
22130@c @iftex
22131@c @headings off
22132@c @evenheading @thispage @| @| @thistitle
22133@c @oddheading @| @| @thispage
22134@c @end iftex
8cda6f8f
GM
22135
22136@bye