Fix permissions bugs with setgid directories etc.
[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}
230@sp 1
acaf905b 231Copyright @copyright{} 1990-1995, 1997, 2001-2012 Free Software Foundation, Inc.
8cda6f8f
GM
232@sp 1
233
234@iftex
235Published by the:@*
236
aa89a0ef
GM
237GNU Press, @hfill @uref{http://www.fsf.org/campaigns/gnu-press/}@*
238a division of the @hfill email: @email{sales@@fsf.org}@*
239Free Software Foundation, Inc. @hfill Tel: +1 (617) 542-5942@*
24051 Franklin Street, Fifth Floor @hfill Fax: +1 (617) 542-2652@*
72ec96fb 241Boston, MA 02110-1301 USA
8cda6f8f
GM
242@end iftex
243
244@ifnottex
245Published by the:
246
247@example
aa89a0ef
GM
248GNU Press, http://www.fsf.org/campaigns/gnu-press/
249a division of the email: sales@@fsf.org
250Free Software Foundation, Inc. Tel: +1 (617) 542-5942
25151 Franklin Street, Fifth Floor Fax: +1 (617) 542-2652
72ec96fb 252Boston, MA 02110-1301 USA
8cda6f8f
GM
253@end example
254@end ifnottex
255
256@sp 1
aa89a0ef 257@c Printed copies are available from @uref{http://shop.fsf.org/} for $35 each.@*
8cda6f8f
GM
258ISBN 1-882114-43-4
259
260Permission is granted to copy, distribute and/or modify this document
e41dfb1e 261under the terms of the GNU Free Documentation License, Version 1.3 or
8cda6f8f
GM
262any later version published by the Free Software Foundation; there
263being no Invariant Section, with the Front-Cover Texts being ``A GNU
264Manual'', and with the Back-Cover Texts as in (a) below. A copy of
265the license is included in the section entitled ``GNU Free
266Documentation License''.
267
868a6b71
RC
268(a) The FSF's Back-Cover Text is: ``You have the freedom to
269copy and modify this GNU manual. Buying copies from the FSF
270supports it in developing GNU and promoting software freedom.''
8cda6f8f
GM
271@end copying
272
273@c half title; two lines here, so do not use `shorttitlepage'
274@tex
275{\begingroup%
276 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
277 \endgroup}%
278{\begingroup\hbox{}\vskip 0.25in \chaprm%
279 \centerline{Programming in Emacs Lisp}%
280 \endgroup\page\hbox{}\page}
281@end tex
282
283@titlepage
284@sp 6
285@center @titlefont{An Introduction to}
286@sp 2
287@center @titlefont{Programming in Emacs Lisp}
288@sp 2
289@center Revised Third Edition
290@sp 4
291@center by Robert J. Chassell
292
293@page
294@vskip 0pt plus 1filll
295@insertcopying
296@end titlepage
297
298@iftex
299@headings off
300@evenheading @thispage @| @| @thischapter
301@oddheading @thissection @| @| @thispage
302@end iftex
303
304@ifnothtml
305@c Keep T.O.C. short by tightening up for largebook
306@ifset largebook
307@tex
308\global\parskip 2pt plus 1pt
309\global\advance\baselineskip by -1pt
310@end tex
311@end ifset
312@end ifnothtml
313
314@shortcontents
315@contents
316
317@ifnottex
d6adf7e7 318@node Top
8cda6f8f
GM
319@top An Introduction to Programming in Emacs Lisp
320
321@insertcopying
322
323This master menu first lists each chapter and index; then it lists
324every node in every chapter.
325@end ifnottex
326
327@c >>>> Set pageno appropriately <<<<
328
329@c The first page of the Preface is a roman numeral; it is the first
330@c right handed page after the Table of Contents; hence the following
331@c setting must be for an odd negative number.
332
a9097c6d
KB
333@c iftex
334@c global@pageno = -11
335@c end iftex
8cda6f8f 336
cb97cd2a
AS
337@set COUNT-WORDS count-words-example
338@c Length of variable name chosen so that things still line up when expanded.
339
8cda6f8f
GM
340@menu
341* Preface:: What to look for.
342* List Processing:: What is Lisp?
343* Practicing Evaluation:: Running several programs.
344* Writing Defuns:: How to write function definitions.
345* Buffer Walk Through:: Exploring a few buffer-related functions.
346* More Complex:: A few, even more complex functions.
347* Narrowing & Widening:: Restricting your and Emacs attention to
348 a region.
349* car cdr & cons:: Fundamental functions in Lisp.
350* Cutting & Storing Text:: Removing text and saving it.
351* List Implementation:: How lists are implemented in the computer.
352* Yanking:: Pasting stored text.
353* Loops & Recursion:: How to repeat a process.
354* Regexp Search:: Regular expression searches.
355* Counting Words:: A review of repetition and regexps.
356* Words in a defun:: Counting words in a @code{defun}.
357* Readying a Graph:: A prototype graph printing function.
358* Emacs Initialization:: How to write a @file{.emacs} file.
359* Debugging:: How to run the Emacs Lisp debuggers.
360* Conclusion:: Now you have the basics.
361* the-the:: An appendix: how to find reduplicated words.
362* Kill Ring:: An appendix: how the kill ring works.
09e80d9f 363* Full Graph:: How to create a graph with labeled axes.
8cda6f8f
GM
364* Free Software and Free Manuals::
365* GNU Free Documentation License::
366* Index::
367* About the Author::
368
369@detailmenu
370 --- The Detailed Node Listing ---
371
372Preface
373
374* Why:: Why learn Emacs Lisp?
375* On Reading this Text:: Read, gain familiarity, pick up habits....
376* Who You Are:: For whom this is written.
377* Lisp History::
378* Note for Novices:: You can read this as a novice.
379* Thank You::
380
381List Processing
382
383* Lisp Lists:: What are lists?
384* Run a Program:: Any list in Lisp is a program ready to run.
385* Making Errors:: Generating an error message.
386* Names & Definitions:: Names of symbols and function definitions.
387* Lisp Interpreter:: What the Lisp interpreter does.
388* Evaluation:: Running a program.
389* Variables:: Returning a value from a variable.
390* Arguments:: Passing information to a function.
391* set & setq:: Setting the value of a variable.
392* Summary:: The major points.
393* Error Message Exercises::
394
395Lisp Lists
396
397* Numbers Lists:: List have numbers, other lists, in them.
398* Lisp Atoms:: Elemental entities.
399* Whitespace in Lists:: Formatting lists to be readable.
400* Typing Lists:: How GNU Emacs helps you type lists.
401
402The Lisp Interpreter
403
404* Complications:: Variables, Special forms, Lists within.
405* Byte Compiling:: Specially processing code for speed.
406
407Evaluation
408
409* How the Interpreter Acts:: Returns and Side Effects...
410* Evaluating Inner Lists:: Lists within lists...
411
412Variables
413
414* fill-column Example::
415* Void Function:: The error message for a symbol
416 without a function.
417* Void Variable:: The error message for a symbol without a value.
418
419Arguments
420
421* Data types:: Types of data passed to a function.
422* Args as Variable or List:: An argument can be the value
423 of a variable or list.
424* Variable Number of Arguments:: Some functions may take a
425 variable number of arguments.
426* Wrong Type of Argument:: Passing an argument of the wrong type
427 to a function.
428* message:: A useful function for sending messages.
429
430Setting the Value of a Variable
431
432* Using set:: Setting values.
433* Using setq:: Setting a quoted value.
434* Counting:: Using @code{setq} to count.
435
436Practicing Evaluation
437
438* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
439 causes evaluation.
440* Buffer Names:: Buffers and files are different.
441* Getting Buffers:: Getting a buffer itself, not merely its name.
442* Switching Buffers:: How to change to another buffer.
443* Buffer Size & Locations:: Where point is located and the size of
444 the buffer.
445* Evaluation Exercise::
446
447How To Write Function Definitions
448
449* Primitive Functions::
450* defun:: The @code{defun} special form.
451* Install:: Install a function definition.
452* Interactive:: Making a function interactive.
453* Interactive Options:: Different options for @code{interactive}.
454* Permanent Installation:: Installing code permanently.
455* let:: Creating and initializing local variables.
456* if:: What if?
457* else:: If--then--else expressions.
458* Truth & Falsehood:: What Lisp considers false and true.
459* save-excursion:: Keeping track of point, mark, and buffer.
460* Review::
461* defun Exercises::
462
463Install a Function Definition
464
465* Effect of installation::
466* Change a defun:: How to change a function definition.
467
468Make a Function Interactive
469
470* Interactive multiply-by-seven:: An overview.
471* multiply-by-seven in detail:: The interactive version.
472
473@code{let}
474
475* Prevent confusion::
476* Parts of let Expression::
477* Sample let Expression::
478* Uninitialized let Variables::
479
480The @code{if} Special Form
481
482* if in more detail::
483* type-of-animal in detail:: An example of an @code{if} expression.
484
485Truth and Falsehood in Emacs Lisp
486
487* nil explained:: @code{nil} has two meanings.
488
489@code{save-excursion}
490
491* Point and mark:: A review of various locations.
492* Template for save-excursion::
493
494A Few Buffer--Related Functions
495
496* Finding More:: How to find more information.
497* simplified-beginning-of-buffer:: Shows @code{goto-char},
498 @code{point-min}, and @code{push-mark}.
499* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
500* append-to-buffer:: Uses @code{save-excursion} and
501 @code{insert-buffer-substring}.
502* Buffer Related Review:: Review.
503* Buffer Exercises::
504
505The Definition of @code{mark-whole-buffer}
506
507* mark-whole-buffer overview::
508* Body of mark-whole-buffer:: Only three lines of code.
509
510The Definition of @code{append-to-buffer}
511
512* append-to-buffer overview::
513* append interactive:: A two part interactive expression.
514* append-to-buffer body:: Incorporates a @code{let} expression.
515* append save-excursion:: How the @code{save-excursion} works.
516
517A Few More Complex Functions
518
519* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
520* insert-buffer:: Read-only, and with @code{or}.
521* beginning-of-buffer:: Shows @code{goto-char},
522 @code{point-min}, and @code{push-mark}.
523* Second Buffer Related Review::
524* optional Exercise::
525
526The Definition of @code{insert-buffer}
527
528* insert-buffer code::
529* insert-buffer interactive:: When you can read, but not write.
530* insert-buffer body:: The body has an @code{or} and a @code{let}.
531* if & or:: Using an @code{if} instead of an @code{or}.
532* Insert or:: How the @code{or} expression works.
533* Insert let:: Two @code{save-excursion} expressions.
534* New insert-buffer::
535
536The Interactive Expression in @code{insert-buffer}
537
538* Read-only buffer:: When a buffer cannot be modified.
539* b for interactive:: An existing buffer or else its name.
540
541Complete Definition of @code{beginning-of-buffer}
542
543* Optional Arguments::
544* beginning-of-buffer opt arg:: Example with optional argument.
545* beginning-of-buffer complete::
546
547@code{beginning-of-buffer} with an Argument
548
549* Disentangle beginning-of-buffer::
550* Large buffer case::
551* Small buffer case::
552
553Narrowing and Widening
554
555* Narrowing advantages:: The advantages of narrowing
556* save-restriction:: The @code{save-restriction} special form.
557* what-line:: The number of the line that point is on.
558* narrow Exercise::
559
560@code{car}, @code{cdr}, @code{cons}: Fundamental Functions
561
562* Strange Names:: An historical aside: why the strange names?
563* car & cdr:: Functions for extracting part of a list.
564* cons:: Constructing a list.
565* nthcdr:: Calling @code{cdr} repeatedly.
566* nth::
567* setcar:: Changing the first element of a list.
568* setcdr:: Changing the rest of a list.
569* cons Exercise::
570
571@code{cons}
572
573* Build a list::
574* length:: How to find the length of a list.
575
576Cutting and Storing Text
577
578* Storing Text:: Text is stored in a list.
579* zap-to-char:: Cutting out text up to a character.
580* kill-region:: Cutting text out of a region.
581* copy-region-as-kill:: A definition for copying text.
582* Digression into C:: Minor note on C programming language macros.
583* defvar:: How to give a variable an initial value.
584* cons & search-fwd Review::
585* search Exercises::
586
587@code{zap-to-char}
588
589* Complete zap-to-char:: The complete implementation.
590* zap-to-char interactive:: A three part interactive expression.
591* zap-to-char body:: A short overview.
592* search-forward:: How to search for a string.
593* progn:: The @code{progn} special form.
594* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
595
596@code{kill-region}
597
598* Complete kill-region:: The function definition.
599* condition-case:: Dealing with a problem.
600* Lisp macro::
601
602@code{copy-region-as-kill}
603
604* Complete copy-region-as-kill:: The complete function definition.
605* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
606
607The Body of @code{copy-region-as-kill}
608
609* last-command & this-command::
610* kill-append function::
611* kill-new function::
612
613Initializing a Variable with @code{defvar}
614
615* See variable current value::
616* defvar and asterisk::
617
618How Lists are Implemented
619
620* Lists diagrammed::
621* Symbols as Chest:: Exploring a powerful metaphor.
622* List Exercise::
623
624Yanking Text Back
625
626* Kill Ring Overview::
627* kill-ring-yank-pointer:: The kill ring is a list.
628* yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
629
630Loops and Recursion
631
632* while:: Causing a stretch of code to repeat.
633* dolist dotimes::
634* Recursion:: Causing a function to call itself.
635* Looping exercise::
636
637@code{while}
638
639* Looping with while:: Repeat so long as test returns true.
640* Loop Example:: A @code{while} loop that uses a list.
641* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
642* Incrementing Loop:: A loop with an incrementing counter.
643* Incrementing Loop Details::
644* Decrementing Loop:: A loop with a decrementing counter.
645
646Details of an Incrementing Loop
647
648* Incrementing Example:: Counting pebbles in a triangle.
649* Inc Example parts:: The parts of the function definition.
650* Inc Example altogether:: Putting the function definition together.
651
652Loop with a Decrementing Counter
653
654* Decrementing Example:: More pebbles on the beach.
655* Dec Example parts:: The parts of the function definition.
656* Dec Example altogether:: Putting the function definition together.
657
658Save your time: @code{dolist} and @code{dotimes}
659
660* dolist::
661* dotimes::
662
663Recursion
664
665* Building Robots:: Same model, different serial number ...
666* Recursive Definition Parts:: Walk until you stop ...
667* Recursion with list:: Using a list as the test whether to recurse.
668* Recursive triangle function::
669* Recursion with cond::
670* Recursive Patterns:: Often used templates.
671* No Deferment:: Don't store up work ...
672* No deferment solution::
673
674Recursion in Place of a Counter
675
676* Recursive Example arg of 1 or 2::
677* Recursive Example arg of 3 or 4::
678
679Recursive Patterns
680
681* Every::
682* Accumulate::
683* Keep::
684
685Regular Expression Searches
686
687* sentence-end:: The regular expression for @code{sentence-end}.
688* re-search-forward:: Very similar to @code{search-forward}.
689* forward-sentence:: A straightforward example of regexp search.
690* forward-paragraph:: A somewhat complex example.
691* etags:: How to create your own @file{TAGS} table.
692* Regexp Review::
693* re-search Exercises::
694
695@code{forward-sentence}
696
697* Complete forward-sentence::
698* fwd-sentence while loops:: Two @code{while} loops.
699* fwd-sentence re-search:: A regular expression search.
700
701@code{forward-paragraph}: a Goldmine of Functions
702
703* forward-paragraph in brief:: Key parts of the function definition.
704* fwd-para let:: The @code{let*} expression.
705* fwd-para while:: The forward motion @code{while} loop.
706
707Counting: Repetition and Regexps
708
709* Why Count Words::
ea4f7750 710* @value{COUNT-WORDS}:: Use a regexp, but find a problem.
8cda6f8f
GM
711* recursive-count-words:: Start with case of no words in region.
712* Counting Exercise::
713
ea4f7750 714The @code{@value{COUNT-WORDS}} Function
8cda6f8f 715
ea4f7750
GM
716* Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
717* Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
718
719Counting Words in a @code{defun}
720
721* Divide and Conquer::
722* Words and Symbols:: What to count?
723* Syntax:: What constitutes a word or symbol?
ea4f7750 724* count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
725* Several defuns:: Counting several defuns in a file.
726* Find a File:: Do you want to look at a file?
727* lengths-list-file:: A list of the lengths of many definitions.
728* Several files:: Counting in definitions in different files.
729* Several files recursively:: Recursively counting in different files.
730* Prepare the data:: Prepare the data for display in a graph.
731
732Count Words in @code{defuns} in Different Files
733
734* lengths-list-many-files:: Return a list of the lengths of defuns.
735* append:: Attach one list to another.
736
737Prepare the Data for Display in a Graph
738
739* Data for Display in Detail::
740* Sorting:: Sorting lists.
741* Files List:: Making a list of files.
742* Counting function definitions::
743
744Readying a Graph
745
746* Columns of a graph::
747* graph-body-print:: How to print the body of a graph.
748* recursive-graph-body-print::
749* Printed Axes::
750* Line Graph Exercise::
751
752Your @file{.emacs} File
753
754* Default Configuration::
755* Site-wide Init:: You can write site-wide init files.
756* defcustom:: Emacs will write code for you.
757* Beginning a .emacs File:: How to write a @code{.emacs file}.
758* Text and Auto-fill:: Automatically wrap lines.
759* Mail Aliases:: Use abbreviations for email addresses.
760* Indent Tabs Mode:: Don't use tabs with @TeX{}
761* Keybindings:: Create some personal keybindings.
762* Keymaps:: More about key binding.
763* Loading Files:: Load (i.e., evaluate) files automatically.
764* Autoload:: Make functions available.
765* Simple Extension:: Define a function; bind it to a key.
766* X11 Colors:: Colors in X.
767* Miscellaneous::
768* Mode Line:: How to customize your mode line.
769
770Debugging
771
772* debug:: How to use the built-in debugger.
773* debug-on-entry:: Start debugging when you call a function.
774* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
775* edebug:: How to use Edebug, a source level debugger.
776* Debugging Exercises::
777
778Handling the Kill Ring
779
780* What the Kill Ring Does::
781* current-kill::
782* yank:: Paste a copy of a clipped element.
783* yank-pop:: Insert element pointed to.
784* ring file::
785
786The @code{current-kill} Function
787
45d77375 788* Code for current-kill::
8cda6f8f
GM
789* Understanding current-kill::
790
791@code{current-kill} in Outline
792
793* Body of current-kill::
794* Digression concerning error:: How to mislead humans, but not computers.
795* Determining the Element::
796
09e80d9f 797A Graph with Labeled Axes
8cda6f8f 798
09e80d9f 799* Labeled Example::
8cda6f8f
GM
800* print-graph Varlist:: @code{let} expression in @code{print-graph}.
801* print-Y-axis:: Print a label for the vertical axis.
802* print-X-axis:: Print a horizontal label.
803* Print Whole Graph:: The function to print a complete graph.
804
805The @code{print-Y-axis} Function
806
807* print-Y-axis in Detail::
808* Height of label:: What height for the Y axis?
809* Compute a Remainder:: How to compute the remainder of a division.
810* Y Axis Element:: Construct a line for the Y axis.
811* Y-axis-column:: Generate a list of Y axis labels.
812* print-Y-axis Penultimate:: A not quite final version.
813
814The @code{print-X-axis} Function
815
816* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
817* X Axis Tic Marks:: Create tic marks for the horizontal axis.
818
819Printing the Whole Graph
820
821* The final version:: A few changes.
822* Test print-graph:: Run a short test.
823* Graphing words in defuns:: Executing the final code.
824* lambda:: How to write an anonymous function.
825* mapcar:: Apply a function to elements of a list.
826* Another Bug:: Yet another bug @dots{} most insidious.
827* Final printed graph:: The graph itself!
828
829@end detailmenu
830@end menu
831
d6adf7e7 832@node Preface
8cda6f8f
GM
833@unnumbered Preface
834
835Most of the GNU Emacs integrated environment is written in the programming
836language called Emacs Lisp. The code written in this programming
837language is the software---the sets of instructions---that tell the
838computer what to do when you give it commands. Emacs is designed so
839that you can write new code in Emacs Lisp and easily install it as an
840extension to the editor.
841
842(GNU Emacs is sometimes called an ``extensible editor'', but it does
843much more than provide editing capabilities. It is better to refer to
844Emacs as an ``extensible computing environment''. However, that
845phrase is quite a mouthful. It is easier to refer to Emacs simply as
846an editor. Moreover, everything you do in Emacs---find the Mayan date
847and phases of the moon, simplify polynomials, debug code, manage
848files, read letters, write books---all these activities are kinds of
849editing in the most general sense of the word.)
850
851@menu
852* Why:: Why learn Emacs Lisp?
853* On Reading this Text:: Read, gain familiarity, pick up habits....
854* Who You Are:: For whom this is written.
855* Lisp History::
856* Note for Novices:: You can read this as a novice.
857* Thank You::
858@end menu
859
8cda6f8f 860@ifnottex
d6adf7e7 861@node Why
8cda6f8f
GM
862@unnumberedsec Why Study Emacs Lisp?
863@end ifnottex
864
865Although Emacs Lisp is usually thought of in association only with Emacs,
866it is a full computer programming language. You can use Emacs Lisp as
867you would any other programming language.
868
869Perhaps you want to understand programming; perhaps you want to extend
870Emacs; or perhaps you want to become a programmer. This introduction to
871Emacs Lisp is designed to get you started: to guide you in learning the
872fundamentals of programming, and more importantly, to show you how you
873can teach yourself to go further.
874
d6adf7e7 875@node On Reading this Text
8cda6f8f
GM
876@unnumberedsec On Reading this Text
877
878All through this document, you will see little sample programs you can
879run inside of Emacs. If you read this document in Info inside of GNU
880Emacs, you can run the programs as they appear. (This is easy to do and
881is explained when the examples are presented.) Alternatively, you can
882read this introduction as a printed book while sitting beside a computer
883running Emacs. (This is what I like to do; I like printed books.) If
884you don't have a running Emacs beside you, you can still read this book,
885but in this case, it is best to treat it as a novel or as a travel guide
886to a country not yet visited: interesting, but not the same as being
887there.
888
40ba43b4 889Much of this introduction is dedicated to walkthroughs or guided tours
8cda6f8f
GM
890of code used in GNU Emacs. These tours are designed for two purposes:
891first, to give you familiarity with real, working code (code you use
892every day); and, second, to give you familiarity with the way Emacs
893works. It is interesting to see how a working environment is
894implemented.
895Also, I
896hope that you will pick up the habit of browsing through source code.
897You can learn from it and mine it for ideas. Having GNU Emacs is like
898having a dragon's cave of treasures.
899
900In addition to learning about Emacs as an editor and Emacs Lisp as a
901programming language, the examples and guided tours will give you an
902opportunity to get acquainted with Emacs as a Lisp programming
903environment. GNU Emacs supports programming and provides tools that
904you will want to become comfortable using, such as @kbd{M-.} (the key
905which invokes the @code{find-tag} command). You will also learn about
906buffers and other objects that are part of the environment.
907Learning about these features of Emacs is like learning new routes
908around your home town.
909
910@ignore
911In addition, I have written several programs as extended examples.
912Although these are examples, the programs are real. I use them.
913Other people use them. You may use them. Beyond the fragments of
914programs used for illustrations, there is very little in here that is
915`just for teaching purposes'; what you see is used. This is a great
916advantage of Emacs Lisp: it is easy to learn to use it for work.
917@end ignore
918
919Finally, I hope to convey some of the skills for using Emacs to
920learn aspects of programming that you don't know. You can often use
921Emacs to help you understand what puzzles you or to find out how to do
922something new. This self-reliance is not only a pleasure, but an
923advantage.
924
d6adf7e7 925@node Who You Are
8cda6f8f
GM
926@unnumberedsec For Whom This is Written
927
928This text is written as an elementary introduction for people who are
929not programmers. If you are a programmer, you may not be satisfied with
930this primer. The reason is that you may have become expert at reading
931reference manuals and be put off by the way this text is organized.
932
933An expert programmer who reviewed this text said to me:
934
935@quotation
936@i{I prefer to learn from reference manuals. I ``dive into'' each
937paragraph, and ``come up for air'' between paragraphs.}
938
939@i{When I get to the end of a paragraph, I assume that that subject is
940done, finished, that I know everything I need (with the
941possible exception of the case when the next paragraph starts talking
942about it in more detail). I expect that a well written reference manual
943will not have a lot of redundancy, and that it will have excellent
944pointers to the (one) place where the information I want is.}
945@end quotation
946
947This introduction is not written for this person!
948
949Firstly, I try to say everything at least three times: first, to
950introduce it; second, to show it in context; and third, to show it in a
951different context, or to review it.
952
953Secondly, I hardly ever put all the information about a subject in one
954place, much less in one paragraph. To my way of thinking, that imposes
955too heavy a burden on the reader. Instead I try to explain only what
956you need to know at the time. (Sometimes I include a little extra
957information so you won't be surprised later when the additional
958information is formally introduced.)
959
960When you read this text, you are not expected to learn everything the
961first time. Frequently, you need only make, as it were, a `nodding
962acquaintance' with some of the items mentioned. My hope is that I have
963structured the text and given you enough hints that you will be alert to
964what is important, and concentrate on it.
965
966You will need to ``dive into'' some paragraphs; there is no other way
967to read them. But I have tried to keep down the number of such
968paragraphs. This book is intended as an approachable hill, rather than
969as a daunting mountain.
970
971This introduction to @cite{Programming in Emacs Lisp} has a companion
972document,
973@iftex
974@cite{The GNU Emacs Lisp Reference Manual}.
975@end iftex
976@ifnottex
977@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
978Emacs Lisp Reference Manual}.
979@end ifnottex
980The reference manual has more detail than this introduction. In the
981reference manual, all the information about one topic is concentrated
982in one place. You should turn to it if you are like the programmer
983quoted above. And, of course, after you have read this
984@cite{Introduction}, you will find the @cite{Reference Manual} useful
985when you are writing your own programs.
986
d6adf7e7 987@node Lisp History
8cda6f8f
GM
988@unnumberedsec Lisp History
989@cindex Lisp history
990
991Lisp was first developed in the late 1950s at the Massachusetts
992Institute of Technology for research in artificial intelligence. The
993great power of the Lisp language makes it superior for other purposes as
994well, such as writing editor commands and integrated environments.
995
996@cindex Maclisp
997@cindex Common Lisp
998GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
999in the 1960s. It is somewhat inspired by Common Lisp, which became a
1000standard in the 1980s. However, Emacs Lisp is much simpler than Common
1001Lisp. (The standard Emacs distribution contains an optional extensions
1002file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1003
d6adf7e7 1004@node Note for Novices
8cda6f8f
GM
1005@unnumberedsec A Note for Novices
1006
1007If you don't know GNU Emacs, you can still read this document
1008profitably. However, I recommend you learn Emacs, if only to learn to
1009move around your computer screen. You can teach yourself how to use
1010Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
1011means you press and release the @key{CTRL} key and the @kbd{h} at the
1012same time, and then press and release @kbd{t}.)
1013
44e97401 1014Also, I often refer to one of Emacs's standard commands by listing the
8cda6f8f
GM
1015keys which you press to invoke the command and then giving the name of
1016the command in parentheses, like this: @kbd{M-C-\}
1017(@code{indent-region}). What this means is that the
1018@code{indent-region} command is customarily invoked by typing
1019@kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
1020invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
1021Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
1022@key{META} key, @key{CTRL} key and @key{\} key all at the same time.
09e80d9f 1023(On many modern keyboards the @key{META} key is labeled
8cda6f8f
GM
1024@key{ALT}.)
1025Sometimes a combination like this is called a keychord, since it is
1026similar to the way you play a chord on a piano. If your keyboard does
1027not have a @key{META} key, the @key{ESC} key prefix is used in place
1028of it. In this case, @kbd{M-C-\} means that you press and release your
1029@key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1030the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
09e80d9f 1031along with the key that is labeled @key{ALT} and, at the same time,
8cda6f8f
GM
1032press the @key{\} key.
1033
1034In addition to typing a lone keychord, you can prefix what you type
1035with @kbd{C-u}, which is called the `universal argument'. The
1036@kbd{C-u} keychord passes an argument to the subsequent command.
1037Thus, to indent a region of plain text by 6 spaces, mark the region,
1038and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
1039Emacs either passes the number 4 to the command or otherwise runs the
1040command differently than it would otherwise.) @xref{Arguments, ,
1041Numeric Arguments, emacs, The GNU Emacs Manual}.
1042
1043If you are reading this in Info using GNU Emacs, you can read through
1044this whole document just by pressing the space bar, @key{SPC}.
1045(To learn about Info, type @kbd{C-h i} and then select Info.)
1046
1047A note on terminology: when I use the word Lisp alone, I often am
1048referring to the various dialects of Lisp in general, but when I speak
1049of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1050
d6adf7e7 1051@node Thank You
8cda6f8f
GM
1052@unnumberedsec Thank You
1053
1054My thanks to all who helped me with this book. My especial thanks to
1055@r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1df7defd 1056McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.
8cda6f8f
GM
1057Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1058@w{Philip Johnson} and @w{David Stampe} for their patient
1059encouragement. My mistakes are my own.
1060
1061@flushright
1062Robert J. Chassell
4724cafb 1063@email{bob@@gnu.org}
8cda6f8f
GM
1064@end flushright
1065
1066@c ================ Beginning of main text ================
1067
1068@c Start main text on right-hand (verso) page
1069
1070@tex
1071\par\vfill\supereject
1072\headings off
1073\ifodd\pageno
1074 \par\vfill\supereject
1075\else
1076 \par\vfill\supereject
1077 \page\hbox{}\page
1078 \par\vfill\supereject
1079\fi
1080@end tex
1081
52af8e0a
GM
1082@c Note: this resetting of the page number back to 1 causes TeX to gripe
1083@c about already having seen page numbers 1-4 before (in the preface):
1084@c pdfTeX warning (ext4): destination with the same identifier (name{1})
1085@c has been already used, duplicate ignored
1086@c I guess that is harmless (what happens if a later part of the text
1087@c makes a link to something in the first 4 pages though?).
1df7defd 1088@c E.g., note that the Emacs manual has a preface, but does not bother
52af8e0a 1089@c resetting the page numbers back to 1 after that.
8cda6f8f
GM
1090@iftex
1091@headings off
1092@evenheading @thispage @| @| @thischapter
1093@oddheading @thissection @| @| @thispage
1094@global@pageno = 1
1095@end iftex
1096
d6adf7e7 1097@node List Processing
8cda6f8f
GM
1098@chapter List Processing
1099
1100To the untutored eye, Lisp is a strange programming language. In Lisp
1101code there are parentheses everywhere. Some people even claim that
1102the name stands for `Lots of Isolated Silly Parentheses'. But the
1103claim is unwarranted. Lisp stands for LISt Processing, and the
1104programming language handles @emph{lists} (and lists of lists) by
1105putting them between parentheses. The parentheses mark the boundaries
1106of the list. Sometimes a list is preceded by a single apostrophe or
1107quotation mark, @samp{'}@footnote{The single apostrophe or quotation
1108mark is an abbreviation for the function @code{quote}; you need not
1109think about functions now; functions are defined in @ref{Making
1110Errors, , Generate an Error Message}.} Lists are the basis of Lisp.
1111
1112@menu
1113* Lisp Lists:: What are lists?
1114* Run a Program:: Any list in Lisp is a program ready to run.
1115* Making Errors:: Generating an error message.
1116* Names & Definitions:: Names of symbols and function definitions.
1117* Lisp Interpreter:: What the Lisp interpreter does.
1118* Evaluation:: Running a program.
1119* Variables:: Returning a value from a variable.
1120* Arguments:: Passing information to a function.
1121* set & setq:: Setting the value of a variable.
1122* Summary:: The major points.
1123* Error Message Exercises::
1124@end menu
1125
d6adf7e7 1126@node Lisp Lists
8cda6f8f
GM
1127@section Lisp Lists
1128@cindex Lisp Lists
1129
1130In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1131This list is preceded by a single apostrophe. It could just as well be
1132written as follows, which looks more like the kind of list you are likely
1133to be familiar with:
1134
1135@smallexample
1136@group
1137'(rose
1138 violet
1139 daisy
1140 buttercup)
1141@end group
1142@end smallexample
1143
1144@noindent
1145The elements of this list are the names of the four different flowers,
1146separated from each other by whitespace and surrounded by parentheses,
1147like flowers in a field with a stone wall around them.
1148@cindex Flowers in a field
1149
1150@menu
1151* Numbers Lists:: List have numbers, other lists, in them.
1152* Lisp Atoms:: Elemental entities.
1153* Whitespace in Lists:: Formatting lists to be readable.
1154* Typing Lists:: How GNU Emacs helps you type lists.
1155@end menu
1156
8cda6f8f 1157@ifnottex
d6adf7e7 1158@node Numbers Lists
8cda6f8f
GM
1159@unnumberedsubsec Numbers, Lists inside of Lists
1160@end ifnottex
1161
1162Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1163This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1164separated by whitespace.
1165
1166In Lisp, both data and programs are represented the same way; that is,
1167they are both lists of words, numbers, or other lists, separated by
1168whitespace and surrounded by parentheses. (Since a program looks like
1169data, one program may easily serve as data for another; this is a very
1170powerful feature of Lisp.) (Incidentally, these two parenthetical
1171remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1172@samp{.} as punctuation marks.)
1173
1174@need 1200
1175Here is another list, this time with a list inside of it:
1176
1177@smallexample
1178'(this list has (a list inside of it))
1179@end smallexample
1180
1181The components of this list are the words @samp{this}, @samp{list},
1182@samp{has}, and the list @samp{(a list inside of it)}. The interior
1183list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1184@samp{of}, @samp{it}.
1185
d6adf7e7 1186@node Lisp Atoms
8cda6f8f
GM
1187@subsection Lisp Atoms
1188@cindex Lisp Atoms
1189
1190In Lisp, what we have been calling words are called @dfn{atoms}. This
1191term comes from the historical meaning of the word atom, which means
1192`indivisible'. As far as Lisp is concerned, the words we have been
1193using in the lists cannot be divided into any smaller parts and still
1194mean the same thing as part of a program; likewise with numbers and
1195single character symbols like @samp{+}. On the other hand, unlike an
1196ancient atom, a list can be split into parts. (@xref{car cdr & cons,
1197, @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1198
1199In a list, atoms are separated from each other by whitespace. They can be
1200right next to a parenthesis.
1201
1202@cindex @samp{empty list} defined
1203Technically speaking, a list in Lisp consists of parentheses surrounding
1204atoms separated by whitespace or surrounding other lists or surrounding
1205both atoms and other lists. A list can have just one atom in it or
1206have nothing in it at all. A list with nothing in it looks like this:
1207@code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1208empty list is considered both an atom and a list at the same time.
1209
1210@cindex Symbolic expressions, introduced
1211@cindex @samp{expression} defined
1212@cindex @samp{form} defined
1213The printed representation of both atoms and lists are called
1214@dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1215The word @dfn{expression} by itself can refer to either the printed
1216representation, or to the atom or list as it is held internally in the
1217computer. Often, people use the term @dfn{expression}
1218indiscriminately. (Also, in many texts, the word @dfn{form} is used
1219as a synonym for expression.)
1220
1221Incidentally, the atoms that make up our universe were named such when
1222they were thought to be indivisible; but it has been found that physical
1223atoms are not indivisible. Parts can split off an atom or it can
1224fission into two parts of roughly equal size. Physical atoms were named
1225prematurely, before their truer nature was found. In Lisp, certain
1226kinds of atom, such as an array, can be separated into parts; but the
1227mechanism for doing this is different from the mechanism for splitting a
1228list. As far as list operations are concerned, the atoms of a list are
1229unsplittable.
1230
1231As in English, the meanings of the component letters of a Lisp atom
1232are different from the meaning the letters make as a word. For
1233example, the word for the South American sloth, the @samp{ai}, is
1234completely different from the two words, @samp{a}, and @samp{i}.
1235
1236There are many kinds of atom in nature but only a few in Lisp: for
1237example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1238as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1239listed in the examples above are all symbols. In everyday Lisp
1240conversation, the word ``atom'' is not often used, because programmers
1241usually try to be more specific about what kind of atom they are dealing
1242with. Lisp programming is mostly about symbols (and sometimes numbers)
1243within lists. (Incidentally, the preceding three word parenthetical
1244remark is a proper list in Lisp, since it consists of atoms, which in
1245this case are symbols, separated by whitespace and enclosed by
1246parentheses, without any non-Lisp punctuation.)
1247
1248@need 1250
6c499932
CY
1249Text between double quotation marks---even sentences or
1250paragraphs---is also an atom. Here is an example:
8cda6f8f
GM
1251@cindex Text between double quotation marks
1252
1253@smallexample
1254'(this list includes "text between quotation marks.")
1255@end smallexample
1256
1257@cindex @samp{string} defined
1258@noindent
1259In Lisp, all of the quoted text including the punctuation mark and the
1260blank spaces is a single atom. This kind of atom is called a
1261@dfn{string} (for `string of characters') and is the sort of thing that
1262is used for messages that a computer can print for a human to read.
1263Strings are a different kind of atom than numbers or symbols and are
1264used differently.
1265
d6adf7e7 1266@node Whitespace in Lists
8cda6f8f
GM
1267@subsection Whitespace in Lists
1268@cindex Whitespace in lists
1269
1270@need 1200
1271The amount of whitespace in a list does not matter. From the point of view
1272of the Lisp language,
1273
1274@smallexample
1275@group
1276'(this list
1277 looks like this)
1278@end group
1279@end smallexample
1280
1281@need 800
1282@noindent
1283is exactly the same as this:
1284
1285@smallexample
1286'(this list looks like this)
1287@end smallexample
1288
1289Both examples show what to Lisp is the same list, the list made up of
1290the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1291@samp{this} in that order.
1292
1293Extra whitespace and newlines are designed to make a list more readable
1294by humans. When Lisp reads the expression, it gets rid of all the extra
1295whitespace (but it needs to have at least one space between atoms in
1296order to tell them apart.)
1297
1298Odd as it seems, the examples we have seen cover almost all of what Lisp
1299lists look like! Every other list in Lisp looks more or less like one
1300of these examples, except that the list may be longer and more complex.
1301In brief, a list is between parentheses, a string is between quotation
1302marks, a symbol looks like a word, and a number looks like a number.
1303(For certain situations, square brackets, dots and a few other special
1304characters may be used; however, we will go quite far without them.)
1305
d6adf7e7 1306@node Typing Lists
8cda6f8f
GM
1307@subsection GNU Emacs Helps You Type Lists
1308@cindex Help typing lists
1309@cindex Formatting help
1310
1311When you type a Lisp expression in GNU Emacs using either Lisp
1312Interaction mode or Emacs Lisp mode, you have available to you several
1313commands to format the Lisp expression so it is easy to read. For
1314example, pressing the @key{TAB} key automatically indents the line the
1315cursor is on by the right amount. A command to properly indent the
1316code in a region is customarily bound to @kbd{M-C-\}. Indentation is
1317designed so that you can see which elements of a list belong to which
1318list---elements of a sub-list are indented more than the elements of
1319the enclosing list.
1320
1321In addition, when you type a closing parenthesis, Emacs momentarily
1322jumps the cursor back to the matching opening parenthesis, so you can
1323see which one it is. This is very useful, since every list you type
1324in Lisp must have its closing parenthesis match its opening
1325parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
44e97401 1326Manual}, for more information about Emacs's modes.)
8cda6f8f 1327
d6adf7e7 1328@node Run a Program
8cda6f8f
GM
1329@section Run a Program
1330@cindex Run a program
1331@cindex Program, running one
1332
1333@cindex @samp{evaluate} defined
1334A list in Lisp---any list---is a program ready to run. If you run it
1335(for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1336of three things: do nothing except return to you the list itself; send
1337you an error message; or, treat the first symbol in the list as a
1338command to do something. (Usually, of course, it is the last of these
1339three things that you really want!)
1340
1341@c use code for the single apostrophe, not samp.
1342The single apostrophe, @code{'}, that I put in front of some of the
1343example lists in preceding sections is called a @dfn{quote}; when it
1344precedes a list, it tells Lisp to do nothing with the list, other than
1345take it as it is written. But if there is no quote preceding a list,
1346the first item of the list is special: it is a command for the computer
1347to obey. (In Lisp, these commands are called @emph{functions}.) The list
1348@code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1349understands that the @code{+} is an instruction to do something with the
1350rest of the list: add the numbers that follow.
1351
1352@need 1250
1353If you are reading this inside of GNU Emacs in Info, here is how you can
1354evaluate such a list: place your cursor immediately after the right
1355hand parenthesis of the following list and then type @kbd{C-x C-e}:
1356
1357@smallexample
1358(+ 2 2)
1359@end smallexample
1360
1361@c use code for the number four, not samp.
1362@noindent
1363You will see the number @code{4} appear in the echo area. (In the
1364jargon, what you have just done is ``evaluate the list.'' The echo area
1365is the line at the bottom of the screen that displays or ``echoes''
1366text.) Now try the same thing with a quoted list: place the cursor
1367right after the following list and type @kbd{C-x C-e}:
1368
1369@smallexample
1370'(this is a quoted list)
1371@end smallexample
1372
1373@noindent
1374You will see @code{(this is a quoted list)} appear in the echo area.
1375
1376@cindex Lisp interpreter, explained
1377@cindex Interpreter, Lisp, explained
1378In both cases, what you are doing is giving a command to the program
1379inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1380interpreter a command to evaluate the expression. The name of the Lisp
1381interpreter comes from the word for the task done by a human who comes
1382up with the meaning of an expression---who ``interprets'' it.
1383
1384You can also evaluate an atom that is not part of a list---one that is
1385not surrounded by parentheses; again, the Lisp interpreter translates
1386from the humanly readable expression to the language of the computer.
1387But before discussing this (@pxref{Variables}), we will discuss what the
1388Lisp interpreter does when you make an error.
1389
d6adf7e7 1390@node Making Errors
8cda6f8f
GM
1391@section Generate an Error Message
1392@cindex Generate an error message
1393@cindex Error message generation
1394
1395Partly so you won't worry if you do it accidentally, we will now give
1396a command to the Lisp interpreter that generates an error message.
1397This is a harmless activity; and indeed, we will often try to generate
1398error messages intentionally. Once you understand the jargon, error
1399messages can be informative. Instead of being called ``error''
1400messages, they should be called ``help'' messages. They are like
ee7683eb 1401signposts to a traveler in a strange country; deciphering them can be
8cda6f8f
GM
1402hard, but once understood, they can point the way.
1403
1404The error message is generated by a built-in GNU Emacs debugger. We
1405will `enter the debugger'. You get out of the debugger by typing @code{q}.
1406
1407What we will do is evaluate a list that is not quoted and does not
1408have a meaningful command as its first element. Here is a list almost
1409exactly the same as the one we just used, but without the single-quote
1410in front of it. Position the cursor right after it and type @kbd{C-x
1411C-e}:
1412
1413@smallexample
1414(this is an unquoted list)
1415@end smallexample
1416
8f4ea8e0 1417@ignore
8cda6f8f
GM
1418@noindent
1419What you see depends on which version of Emacs you are running. GNU
1420Emacs version 22 provides more information than version 20 and before.
1421First, the more recent result of generating an error; then the
1422earlier, version 20 result.
1423
1424@need 1250
1425@noindent
1426In GNU Emacs version 22, a @file{*Backtrace*} window will open up and
1427you will see the following in it:
8f4ea8e0
GM
1428@end ignore
1429
1430A @file{*Backtrace*} window will open up and you should see the
1431following in it:
8cda6f8f
GM
1432
1433@smallexample
1434@group
1435---------- Buffer: *Backtrace* ----------
1436Debugger entered--Lisp error: (void-function this)
1437 (this is an unquoted list)
1438 eval((this is an unquoted list))
1439 eval-last-sexp-1(nil)
1440 eval-last-sexp(nil)
1441 call-interactively(eval-last-sexp)
1442---------- Buffer: *Backtrace* ----------
1443@end group
1444@end smallexample
1445
1446@need 1200
1447@noindent
1448Your cursor will be in this window (you may have to wait a few seconds
1449before it becomes visible). To quit the debugger and make the
1450debugger window go away, type:
1451
1452@smallexample
1453q
1454@end smallexample
1455
1456@noindent
1457Please type @kbd{q} right now, so you become confident that you can
1458get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1459it.
1460
1461@cindex @samp{function} defined
1462Based on what we already know, we can almost read this error message.
1463
1464You read the @file{*Backtrace*} buffer from the bottom up; it tells
1465you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1466interactive call to the command @code{eval-last-sexp}. @code{eval} is
1467an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1468`symbolic expression'. The command means `evaluate last symbolic
1469expression', which is the expression just before your cursor.
1470
1471Each line above tells you what the Lisp interpreter evaluated next.
1472The most recent action is at the top. The buffer is called the
1473@file{*Backtrace*} buffer because it enables you to track Emacs
1474backwards.
1475
1476@need 800
1477At the top of the @file{*Backtrace*} buffer, you see the line:
1478
1479@smallexample
1480Debugger entered--Lisp error: (void-function this)
1481@end smallexample
1482
1483@noindent
1484The Lisp interpreter tried to evaluate the first atom of the list, the
1485word @samp{this}. It is this action that generated the error message
1486@samp{void-function this}.
1487
1488The message contains the words @samp{void-function} and @samp{this}.
1489
1490@cindex @samp{function} defined
1491The word @samp{function} was mentioned once before. It is a very
1492important word. For our purposes, we can define it by saying that a
1493@dfn{function} is a set of instructions to the computer that tell the
1494computer to do something.
1495
1496Now we can begin to understand the error message: @samp{void-function
1497this}. The function (that is, the word @samp{this}) does not have a
1498definition of any set of instructions for the computer to carry out.
1499
1500The slightly odd word, @samp{void-function}, is designed to cover the
1501way Emacs Lisp is implemented, which is that when a symbol does not
1502have a function definition attached to it, the place that should
1503contain the instructions is `void'.
1504
1505On the other hand, since we were able to add 2 plus 2 successfully, by
1506evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1507have a set of instructions for the computer to obey and those
1508instructions must be to add the numbers that follow the @code{+}.
1509
8f4ea8e0
GM
1510It is possible to prevent Emacs entering the debugger in cases like
1511this. We do not explain how to do that here, but we will mention what
1512the result looks like, because you may encounter a similar situation
1513if there is a bug in some Emacs code that you are using. In such
1514cases, you will see only one line of error message; it will appear in
1515the echo area and look like this:
8cda6f8f
GM
1516
1517@smallexample
1518Symbol's function definition is void:@: this
1519@end smallexample
1520
1521@noindent
8f4ea8e0 1522@ignore
8cda6f8f 1523(Also, your terminal may beep at you---some do, some don't; and others
8f4ea8e0
GM
1524blink. This is just a device to get your attention.)
1525@end ignore
1526The message goes away as soon as you type a key, even just to
1527move the cursor.
8cda6f8f
GM
1528
1529We know the meaning of the word @samp{Symbol}. It refers to the first
1530atom of the list, the word @samp{this}. The word @samp{function}
1531refers to the instructions that tell the computer what to do.
1532(Technically, the symbol tells the computer where to find the
1533instructions, but this is a complication we can ignore for the
1534moment.)
1535
1536The error message can be understood: @samp{Symbol's function
1537definition is void:@: this}. The symbol (that is, the word
1538@samp{this}) lacks instructions for the computer to carry out.
1539
d6adf7e7 1540@node Names & Definitions
8cda6f8f
GM
1541@section Symbol Names and Function Definitions
1542@cindex Symbol names
1543
1544We can articulate another characteristic of Lisp based on what we have
1545discussed so far---an important characteristic: a symbol, like
1546@code{+}, is not itself the set of instructions for the computer to
1547carry out. Instead, the symbol is used, perhaps temporarily, as a way
1548of locating the definition or set of instructions. What we see is the
1549name through which the instructions can be found. Names of people
1550work the same way. I can be referred to as @samp{Bob}; however, I am
1551not the letters @samp{B}, @samp{o}, @samp{b} but am, or was, the
1552consciousness consistently associated with a particular life-form.
1553The name is not me, but it can be used to refer to me.
1554
1555In Lisp, one set of instructions can be attached to several names.
1556For example, the computer instructions for adding numbers can be
1557linked to the symbol @code{plus} as well as to the symbol @code{+}
1558(and are in some dialects of Lisp). Among humans, I can be referred
1559to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1560
1561On the other hand, a symbol can have only one function definition
1562attached to it at a time. Otherwise, the computer would be confused as
1563to which definition to use. If this were the case among people, only
1564one person in the world could be named @samp{Bob}. However, the function
1565definition to which the name refers can be changed readily.
1566(@xref{Install, , Install a Function Definition}.)
1567
1568Since Emacs Lisp is large, it is customary to name symbols in a way
1569that identifies the part of Emacs to which the function belongs.
1570Thus, all the names for functions that deal with Texinfo start with
1571@samp{texinfo-} and those for functions that deal with reading mail
1572start with @samp{rmail-}.
1573
d6adf7e7 1574@node Lisp Interpreter
8cda6f8f
GM
1575@section The Lisp Interpreter
1576@cindex Lisp interpreter, what it does
1577@cindex Interpreter, what it does
1578
1579Based on what we have seen, we can now start to figure out what the
1580Lisp interpreter does when we command it to evaluate a list.
1581First, it looks to see whether there is a quote before the list; if
1582there is, the interpreter just gives us the list. On the other
1583hand, if there is no quote, the interpreter looks at the first element
1584in the list and sees whether it has a function definition. If it does,
1585the interpreter carries out the instructions in the function definition.
1586Otherwise, the interpreter prints an error message.
1587
1588This is how Lisp works. Simple. There are added complications which we
1589will get to in a minute, but these are the fundamentals. Of course, to
1590write Lisp programs, you need to know how to write function definitions
1591and attach them to names, and how to do this without confusing either
1592yourself or the computer.
1593
1594@menu
1595* Complications:: Variables, Special forms, Lists within.
1596* Byte Compiling:: Specially processing code for speed.
1597@end menu
1598
8cda6f8f 1599@ifnottex
d6adf7e7 1600@node Complications
8cda6f8f
GM
1601@unnumberedsubsec Complications
1602@end ifnottex
1603
1604Now, for the first complication. In addition to lists, the Lisp
1605interpreter can evaluate a symbol that is not quoted and does not have
1606parentheses around it. The Lisp interpreter will attempt to determine
1607the symbol's value as a @dfn{variable}. This situation is described
1608in the section on variables. (@xref{Variables}.)
1609
1610@cindex Special form
1611The second complication occurs because some functions are unusual and do
1612not work in the usual manner. Those that don't are called @dfn{special
1613forms}. They are used for special jobs, like defining a function, and
1614there are not many of them. In the next few chapters, you will be
1615introduced to several of the more important special forms.
1616
1617The third and final complication is this: if the function that the
1618Lisp interpreter is looking at is not a special form, and if it is part
1619of a list, the Lisp interpreter looks to see whether the list has a list
1620inside of it. If there is an inner list, the Lisp interpreter first
1621figures out what it should do with the inside list, and then it works on
1622the outside list. If there is yet another list embedded inside the
1623inner list, it works on that one first, and so on. It always works on
1624the innermost list first. The interpreter works on the innermost list
1625first, to evaluate the result of that list. The result may be
1626used by the enclosing expression.
1627
1628Otherwise, the interpreter works left to right, from one expression to
1629the next.
1630
d6adf7e7 1631@node Byte Compiling
8cda6f8f
GM
1632@subsection Byte Compiling
1633@cindex Byte compiling
1634
1635One other aspect of interpreting: the Lisp interpreter is able to
1636interpret two kinds of entity: humanly readable code, on which we will
1637focus exclusively, and specially processed code, called @dfn{byte
1638compiled} code, which is not humanly readable. Byte compiled code
1639runs faster than humanly readable code.
1640
1641You can transform humanly readable code into byte compiled code by
1642running one of the compile commands such as @code{byte-compile-file}.
1643Byte compiled code is usually stored in a file that ends with a
1644@file{.elc} extension rather than a @file{.el} extension. You will
1645see both kinds of file in the @file{emacs/lisp} directory; the files
1646to read are those with @file{.el} extensions.
1647
1648As a practical matter, for most things you might do to customize or
1649extend Emacs, you do not need to byte compile; and I will not discuss
1650the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1651The GNU Emacs Lisp Reference Manual}, for a full description of byte
1652compilation.
1653
d6adf7e7 1654@node Evaluation
8cda6f8f
GM
1655@section Evaluation
1656@cindex Evaluation
1657
1658When the Lisp interpreter works on an expression, the term for the
1659activity is called @dfn{evaluation}. We say that the interpreter
1660`evaluates the expression'. I've used this term several times before.
1661The word comes from its use in everyday language, `to ascertain the
1662value or amount of; to appraise', according to @cite{Webster's New
1663Collegiate Dictionary}.
1664
1665@menu
1666* How the Interpreter Acts:: Returns and Side Effects...
1667* Evaluating Inner Lists:: Lists within lists...
1668@end menu
1669
8cda6f8f 1670@ifnottex
d6adf7e7 1671@node How the Interpreter Acts
8cda6f8f
GM
1672@unnumberedsubsec How the Lisp Interpreter Acts
1673@end ifnottex
1674
1675@cindex @samp{returned value} explained
1676After evaluating an expression, the Lisp interpreter will most likely
1677@dfn{return} the value that the computer produces by carrying out the
1678instructions it found in the function definition, or perhaps it will
1679give up on that function and produce an error message. (The interpreter
1680may also find itself tossed, so to speak, to a different function or it
1681may attempt to repeat continually what it is doing for ever and ever in
1682what is called an `infinite loop'. These actions are less common; and
1683we can ignore them.) Most frequently, the interpreter returns a value.
1684
1685@cindex @samp{side effect} defined
1686At the same time the interpreter returns a value, it may do something
1687else as well, such as move a cursor or copy a file; this other kind of
1688action is called a @dfn{side effect}. Actions that we humans think are
1689important, such as printing results, are often ``side effects'' to the
1690Lisp interpreter. The jargon can sound peculiar, but it turns out that
1691it is fairly easy to learn to use side effects.
1692
1693In summary, evaluating a symbolic expression most commonly causes the
1694Lisp interpreter to return a value and perhaps carry out a side effect;
1695or else produce an error.
1696
d6adf7e7 1697@node Evaluating Inner Lists
8cda6f8f
GM
1698@subsection Evaluating Inner Lists
1699@cindex Inner list evaluation
1700@cindex Evaluating inner lists
1701
1702If evaluation applies to a list that is inside another list, the outer
1703list may use the value returned by the first evaluation as information
1704when the outer list is evaluated. This explains why inner expressions
1705are evaluated first: the values they return are used by the outer
1706expressions.
1707
1708@need 1250
1709We can investigate this process by evaluating another addition example.
1710Place your cursor after the following expression and type @kbd{C-x C-e}:
1711
1712@smallexample
1713(+ 2 (+ 3 3))
1714@end smallexample
1715
1716@noindent
1717The number 8 will appear in the echo area.
1718
1719What happens is that the Lisp interpreter first evaluates the inner
1720expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1721evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1722returns the value 8. Since there are no more enclosing expressions to
1723evaluate, the interpreter prints that value in the echo area.
1724
1725Now it is easy to understand the name of the command invoked by the
1726keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1727letters @code{sexp} are an abbreviation for `symbolic expression', and
1728@code{eval} is an abbreviation for `evaluate'. The command means
1729`evaluate last symbolic expression'.
1730
1731As an experiment, you can try evaluating the expression by putting the
1732cursor at the beginning of the next line immediately following the
1733expression, or inside the expression.
1734
1735@need 800
1736Here is another copy of the expression:
1737
1738@smallexample
1739(+ 2 (+ 3 3))
1740@end smallexample
1741
1742@noindent
1743If you place the cursor at the beginning of the blank line that
1744immediately follows the expression and type @kbd{C-x C-e}, you will
1745still get the value 8 printed in the echo area. Now try putting the
1746cursor inside the expression. If you put it right after the next to
1747last parenthesis (so it appears to sit on top of the last parenthesis),
1748you will get a 6 printed in the echo area! This is because the command
1749evaluates the expression @code{(+ 3 3)}.
1750
1751Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1752you will get the number itself. In Lisp, if you evaluate a number, you
1753get the number itself---this is how numbers differ from symbols. If you
1754evaluate a list starting with a symbol like @code{+}, you will get a
1755value returned that is the result of the computer carrying out the
1756instructions in the function definition attached to that name. If a
1757symbol by itself is evaluated, something different happens, as we will
1758see in the next section.
1759
d6adf7e7 1760@node Variables
8cda6f8f
GM
1761@section Variables
1762@cindex Variables
1763
1764In Emacs Lisp, a symbol can have a value attached to it just as it can
1765have a function definition attached to it. The two are different.
1766The function definition is a set of instructions that a computer will
1767obey. A value, on the other hand, is something, such as number or a
1768name, that can vary (which is why such a symbol is called a variable).
1769The value of a symbol can be any expression in Lisp, such as a symbol,
1770number, list, or string. A symbol that has a value is often called a
1771@dfn{variable}.
1772
1773A symbol can have both a function definition and a value attached to
1774it at the same time. Or it can have just one or the other.
1775The two are separate. This is somewhat similar
1776to the way the name Cambridge can refer to the city in Massachusetts
1777and have some information attached to the name as well, such as
1778``great programming center''.
1779
1780@ignore
1781(Incidentally, in Emacs Lisp, a symbol can have two
1782other things attached to it, too: a property list and a documentation
1783string; these are discussed later.)
1784@end ignore
1785
1786Another way to think about this is to imagine a symbol as being a chest
1787of drawers. The function definition is put in one drawer, the value in
1788another, and so on. What is put in the drawer holding the value can be
1789changed without affecting the contents of the drawer holding the
1790function definition, and vice-verse.
1791
1792@menu
1793* fill-column Example::
1794* Void Function:: The error message for a symbol
1795 without a function.
1796* Void Variable:: The error message for a symbol without a value.
1797@end menu
1798
8cda6f8f 1799@ifnottex
d6adf7e7 1800@node fill-column Example
8cda6f8f
GM
1801@unnumberedsubsec @code{fill-column}, an Example Variable
1802@end ifnottex
1803
1804@findex fill-column, @r{an example variable}
1805@cindex Example variable, @code{fill-column}
1806@cindex Variable, example of, @code{fill-column}
1807The variable @code{fill-column} illustrates a symbol with a value
1808attached to it: in every GNU Emacs buffer, this symbol is set to some
1809value, usually 72 or 70, but sometimes to some other value. To find the
1810value of this symbol, evaluate it by itself. If you are reading this in
1811Info inside of GNU Emacs, you can do this by putting the cursor after
1812the symbol and typing @kbd{C-x C-e}:
1813
1814@smallexample
1815fill-column
1816@end smallexample
1817
1818@noindent
1819After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1820area. This is the value for which @code{fill-column} is set for me as I
1821write this. It may be different for you in your Info buffer. Notice
1822that the value returned as a variable is printed in exactly the same way
1823as the value returned by a function carrying out its instructions. From
1824the point of view of the Lisp interpreter, a value returned is a value
1825returned. What kind of expression it came from ceases to matter once
1826the value is known.
1827
1828A symbol can have any value attached to it or, to use the jargon, we can
1829@dfn{bind} the variable to a value: to a number, such as 72; to a
1830string, @code{"such as this"}; to a list, such as @code{(spruce pine
1831oak)}; we can even bind a variable to a function definition.
1832
1833A symbol can be bound to a value in several ways. @xref{set & setq, ,
1834Setting the Value of a Variable}, for information about one way to do
1835this.
1836
d6adf7e7 1837@node Void Function
8cda6f8f
GM
1838@subsection Error Message for a Symbol Without a Function
1839@cindex Symbol without function error
1840@cindex Error for symbol without function
1841
1842When we evaluated @code{fill-column} to find its value as a variable,
1843we did not place parentheses around the word. This is because we did
1844not intend to use it as a function name.
1845
1846If @code{fill-column} were the first or only element of a list, the
1847Lisp interpreter would attempt to find the function definition
1848attached to it. But @code{fill-column} has no function definition.
1849Try evaluating this:
1850
1851@smallexample
1852(fill-column)
1853@end smallexample
1854
1855@need 1250
1856@noindent
8f4ea8e0 1857You will create a @file{*Backtrace*} buffer that says:
8cda6f8f
GM
1858
1859@smallexample
1860@group
1861---------- Buffer: *Backtrace* ----------
1862Debugger entered--Lisp error: (void-function fill-column)
1863 (fill-column)
1864 eval((fill-column))
1865 eval-last-sexp-1(nil)
1866 eval-last-sexp(nil)
1867 call-interactively(eval-last-sexp)
1868---------- Buffer: *Backtrace* ----------
1869@end group
1870@end smallexample
1871
1872@noindent
1873(Remember, to quit the debugger and make the debugger window go away,
1874type @kbd{q} in the @file{*Backtrace*} buffer.)
1875
1876@ignore
1877@need 800
1878In GNU Emacs 20 and before, you will produce an error message that says:
1879
1880@smallexample
1881Symbol's function definition is void:@: fill-column
1882@end smallexample
1883
1884@noindent
1885(The message will go away as soon as you move the cursor or type
1886another key.)
1887@end ignore
1888
d6adf7e7 1889@node Void Variable
8cda6f8f
GM
1890@subsection Error Message for a Symbol Without a Value
1891@cindex Symbol without value error
1892@cindex Error for symbol without value
1893
1894If you attempt to evaluate a symbol that does not have a value bound to
1895it, you will receive an error message. You can see this by
1896experimenting with our 2 plus 2 addition. In the following expression,
1897put your cursor right after the @code{+}, before the first number 2,
1898type @kbd{C-x C-e}:
1899
1900@smallexample
1901(+ 2 2)
1902@end smallexample
1903
1904@need 1500
1905@noindent
1906In GNU Emacs 22, you will create a @file{*Backtrace*} buffer that
1907says:
1908
1909@smallexample
1910@group
1911---------- Buffer: *Backtrace* ----------
1912Debugger entered--Lisp error: (void-variable +)
1913 eval(+)
1914 eval-last-sexp-1(nil)
1915 eval-last-sexp(nil)
1916 call-interactively(eval-last-sexp)
1917---------- Buffer: *Backtrace* ----------
1918@end group
1919@end smallexample
1920
1921@noindent
8f4ea8e0 1922(Again, you can quit the debugger by
8cda6f8f
GM
1923typing @kbd{q} in the @file{*Backtrace*} buffer.)
1924
1925This backtrace is different from the very first error message we saw,
1926which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1927In this case, the function does not have a value as a variable; while
1928in the other error message, the function (the word `this') did not
1929have a definition.
1930
1931In this experiment with the @code{+}, what we did was cause the Lisp
1932interpreter to evaluate the @code{+} and look for the value of the
1933variable instead of the function definition. We did this by placing the
1934cursor right after the symbol rather than after the parenthesis of the
1935enclosing list as we did before. As a consequence, the Lisp interpreter
8f4ea8e0 1936evaluated the preceding s-expression, which in this case was
8cda6f8f
GM
1937@code{+} by itself.
1938
1939Since @code{+} does not have a value bound to it, just the function
1940definition, the error message reported that the symbol's value as a
1941variable was void.
1942
1943@ignore
1944@need 800
1945In GNU Emacs version 20 and before, your error message will say:
1946
1947@example
1948Symbol's value as variable is void:@: +
1949@end example
1950
1951@noindent
1952The meaning is the same as in GNU Emacs 22.
1953@end ignore
1954
d6adf7e7 1955@node Arguments
8cda6f8f
GM
1956@section Arguments
1957@cindex Arguments
1958@cindex Passing information to functions
1959
1960To see how information is passed to functions, let's look again at
1961our old standby, the addition of two plus two. In Lisp, this is written
1962as follows:
1963
1964@smallexample
1965(+ 2 2)
1966@end smallexample
1967
1968If you evaluate this expression, the number 4 will appear in your echo
1969area. What the Lisp interpreter does is add the numbers that follow
1970the @code{+}.
1971
1972@cindex @samp{argument} defined
1973The numbers added by @code{+} are called the @dfn{arguments} of the
1974function @code{+}. These numbers are the information that is given to
1975or @dfn{passed} to the function.
1976
1977The word `argument' comes from the way it is used in mathematics and
1978does not refer to a disputation between two people; instead it refers to
1979the information presented to the function, in this case, to the
1980@code{+}. In Lisp, the arguments to a function are the atoms or lists
1981that follow the function. The values returned by the evaluation of
1982these atoms or lists are passed to the function. Different functions
1983require different numbers of arguments; some functions require none at
1984all.@footnote{It is curious to track the path by which the word `argument'
1985came to have two different meanings, one in mathematics and the other in
1986everyday English. According to the @cite{Oxford English Dictionary},
1987the word derives from the Latin for @samp{to make clear, prove}; thus it
1988came to mean, by one thread of derivation, `the evidence offered as
1989proof', which is to say, `the information offered', which led to its
1990meaning in Lisp. But in the other thread of derivation, it came to mean
1991`to assert in a manner against which others may make counter
1992assertions', which led to the meaning of the word as a disputation.
1993(Note here that the English word has two different definitions attached
1994to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1995have two different function definitions at the same time.)}
1996
1997@menu
1998* Data types:: Types of data passed to a function.
1999* Args as Variable or List:: An argument can be the value
2000 of a variable or list.
2001* Variable Number of Arguments:: Some functions may take a
2002 variable number of arguments.
2003* Wrong Type of Argument:: Passing an argument of the wrong type
2004 to a function.
2005* message:: A useful function for sending messages.
2006@end menu
2007
d6adf7e7 2008@node Data types
8cda6f8f
GM
2009@subsection Arguments' Data Types
2010@cindex Data types
2011@cindex Types of data
2012@cindex Arguments' data types
2013
2014The type of data that should be passed to a function depends on what
2015kind of information it uses. The arguments to a function such as
2016@code{+} must have values that are numbers, since @code{+} adds numbers.
2017Other functions use different kinds of data for their arguments.
2018
2019@need 1250
2020@findex concat
2021For example, the @code{concat} function links together or unites two or
2022more strings of text to produce a string. The arguments are strings.
2023Concatenating the two character strings @code{abc}, @code{def} produces
2024the single string @code{abcdef}. This can be seen by evaluating the
2025following:
2026
2027@smallexample
2028(concat "abc" "def")
2029@end smallexample
2030
2031@noindent
2032The value produced by evaluating this expression is @code{"abcdef"}.
2033
2034A function such as @code{substring} uses both a string and numbers as
2035arguments. The function returns a part of the string, a substring of
2036the first argument. This function takes three arguments. Its first
2037argument is the string of characters, the second and third arguments are
2038numbers that indicate the beginning and end of the substring. The
2039numbers are a count of the number of characters (including spaces and
e4920bc9 2040punctuation) from the beginning of the string.
8cda6f8f
GM
2041
2042@need 800
2043For example, if you evaluate the following:
2044
2045@smallexample
2046(substring "The quick brown fox jumped." 16 19)
2047@end smallexample
2048
2049@noindent
2050you will see @code{"fox"} appear in the echo area. The arguments are the
2051string and the two numbers.
2052
2053Note that the string passed to @code{substring} is a single atom even
2054though it is made up of several words separated by spaces. Lisp counts
2055everything between the two quotation marks as part of the string,
2056including the spaces. You can think of the @code{substring} function as
2057a kind of `atom smasher' since it takes an otherwise indivisible atom
2058and extracts a part. However, @code{substring} is only able to extract
2059a substring from an argument that is a string, not from another type of
2060atom such as a number or symbol.
2061
d6adf7e7 2062@node Args as Variable or List
8cda6f8f
GM
2063@subsection An Argument as the Value of a Variable or List
2064
2065An argument can be a symbol that returns a value when it is evaluated.
2066For example, when the symbol @code{fill-column} by itself is evaluated,
2067it returns a number. This number can be used in an addition.
2068
2069@need 1250
2070Position the cursor after the following expression and type @kbd{C-x
2071C-e}:
2072
2073@smallexample
2074(+ 2 fill-column)
2075@end smallexample
2076
2077@noindent
2078The value will be a number two more than what you get by evaluating
2079@code{fill-column} alone. For me, this is 74, because my value of
2080@code{fill-column} is 72.
2081
2082As we have just seen, an argument can be a symbol that returns a value
2083when evaluated. In addition, an argument can be a list that returns a
2084value when it is evaluated. For example, in the following expression,
2085the arguments to the function @code{concat} are the strings
2086@w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2087@code{(number-to-string (+ 2 fill-column))}.
2088
2089@c For GNU Emacs 22, need number-to-string
2090@smallexample
2091(concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2092@end smallexample
2093
2094@noindent
2095If you evaluate this expression---and if, as with my Emacs,
2096@code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2097appear in the echo area. (Note that you must put spaces after the
2098word @samp{The} and before the word @samp{red} so they will appear in
2099the final string. The function @code{number-to-string} converts the
2100integer that the addition function returns to a string.
2101@code{number-to-string} is also known as @code{int-to-string}.)
2102
d6adf7e7 2103@node Variable Number of Arguments
8cda6f8f
GM
2104@subsection Variable Number of Arguments
2105@cindex Variable number of arguments
2106@cindex Arguments, variable number of
2107
2108Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2109number of arguments. (The @code{*} is the symbol for multiplication.)
2110This can be seen by evaluating each of the following expressions in
2111the usual way. What you will see in the echo area is printed in this
2112text after @samp{@result{}}, which you may read as `evaluates to'.
2113
2114@need 1250
2115In the first set, the functions have no arguments:
2116
2117@smallexample
2118@group
2119(+) @result{} 0
2120
2121(*) @result{} 1
2122@end group
2123@end smallexample
2124
2125@need 1250
2126In this set, the functions have one argument each:
2127
2128@smallexample
2129@group
2130(+ 3) @result{} 3
2131
2132(* 3) @result{} 3
2133@end group
2134@end smallexample
2135
2136@need 1250
2137In this set, the functions have three arguments each:
2138
2139@smallexample
2140@group
2141(+ 3 4 5) @result{} 12
2142
2143(* 3 4 5) @result{} 60
2144@end group
2145@end smallexample
2146
d6adf7e7 2147@node Wrong Type of Argument
8cda6f8f
GM
2148@subsection Using the Wrong Type Object as an Argument
2149@cindex Wrong type of argument
2150@cindex Argument, wrong type of
2151
2152When a function is passed an argument of the wrong type, the Lisp
2153interpreter produces an error message. For example, the @code{+}
2154function expects the values of its arguments to be numbers. As an
2155experiment we can pass it the quoted symbol @code{hello} instead of a
2156number. Position the cursor after the following expression and type
2157@kbd{C-x C-e}:
2158
2159@smallexample
2160(+ 2 'hello)
2161@end smallexample
2162
2163@noindent
2164When you do this you will generate an error message. What has happened
2165is that @code{+} has tried to add the 2 to the value returned by
2166@code{'hello}, but the value returned by @code{'hello} is the symbol
2167@code{hello}, not a number. Only numbers can be added. So @code{+}
2168could not carry out its addition.
2169
2170@need 1250
8f4ea8e0 2171You will create and enter a @file{*Backtrace*} buffer that says:
8cda6f8f
GM
2172
2173@noindent
2174@smallexample
2175@group
2176---------- Buffer: *Backtrace* ----------
2177Debugger entered--Lisp error:
2178 (wrong-type-argument number-or-marker-p hello)
2179 +(2 hello)
2180 eval((+ 2 (quote hello)))
2181 eval-last-sexp-1(nil)
2182 eval-last-sexp(nil)
2183 call-interactively(eval-last-sexp)
2184---------- Buffer: *Backtrace* ----------
2185@end group
2186@end smallexample
2187
2188@need 1250
2189As usual, the error message tries to be helpful and makes sense after you
2190learn how to read it.@footnote{@code{(quote hello)} is an expansion of
2191the abbreviation @code{'hello}.}
2192
2193The first part of the error message is straightforward; it says
2194@samp{wrong type argument}. Next comes the mysterious jargon word
2195@w{@samp{number-or-marker-p}}. This word is trying to tell you what
2196kind of argument the @code{+} expected.
2197
2198The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2199trying to determine whether the information presented it (the value of
2200the argument) is a number or a marker (a special object representing a
2201buffer position). What it does is test to see whether the @code{+} is
2202being given numbers to add. It also tests to see whether the
2203argument is something called a marker, which is a specific feature of
2204Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2205When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2206its position is kept as a marker. The mark can be considered a
2207number---the number of characters the location is from the beginning
2208of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2209numeric value of marker positions as numbers.
2210
2211The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2212practice started in the early days of Lisp programming. The @samp{p}
2213stands for `predicate'. In the jargon used by the early Lisp
2214researchers, a predicate refers to a function to determine whether some
2215property is true or false. So the @samp{p} tells us that
2216@code{number-or-marker-p} is the name of a function that determines
2217whether it is true or false that the argument supplied is a number or
2218a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2219a function that tests whether its argument has the value of zero, and
2220@code{listp}, a function that tests whether its argument is a list.
2221
2222Finally, the last part of the error message is the symbol @code{hello}.
2223This is the value of the argument that was passed to @code{+}. If the
2224addition had been passed the correct type of object, the value passed
2225would have been a number, such as 37, rather than a symbol like
2226@code{hello}. But then you would not have got the error message.
2227
2228@ignore
2229@need 1250
2230In GNU Emacs version 20 and before, the echo area displays an error
2231message that says:
2232
2233@smallexample
2234Wrong type argument:@: number-or-marker-p, hello
2235@end smallexample
2236
2237This says, in different words, the same as the top line of the
2238@file{*Backtrace*} buffer.
2239@end ignore
2240
d6adf7e7 2241@node message
8cda6f8f
GM
2242@subsection The @code{message} Function
2243@findex message
2244
2245Like @code{+}, the @code{message} function takes a variable number of
2246arguments. It is used to send messages to the user and is so useful
2247that we will describe it here.
2248
2249@need 1250
2250A message is printed in the echo area. For example, you can print a
2251message in your echo area by evaluating the following list:
2252
2253@smallexample
2254(message "This message appears in the echo area!")
2255@end smallexample
2256
2257The whole string between double quotation marks is a single argument
2258and is printed @i{in toto}. (Note that in this example, the message
2259itself will appear in the echo area within double quotes; that is
2260because you see the value returned by the @code{message} function. In
2261most uses of @code{message} in programs that you write, the text will
2262be printed in the echo area as a side-effect, without the quotes.
2263@xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2264detail}, for an example of this.)
2265
2266However, if there is a @samp{%s} in the quoted string of characters, the
2267@code{message} function does not print the @samp{%s} as such, but looks
2268to the argument that follows the string. It evaluates the second
2269argument and prints the value at the location in the string where the
2270@samp{%s} is.
2271
2272@need 1250
2273You can see this by positioning the cursor after the following
2274expression and typing @kbd{C-x C-e}:
2275
2276@smallexample
2277(message "The name of this buffer is: %s." (buffer-name))
2278@end smallexample
2279
2280@noindent
2281In Info, @code{"The name of this buffer is: *info*."} will appear in the
2282echo area. The function @code{buffer-name} returns the name of the
2283buffer as a string, which the @code{message} function inserts in place
2284of @code{%s}.
2285
2286To print a value as an integer, use @samp{%d} in the same way as
2287@samp{%s}. For example, to print a message in the echo area that
2288states the value of the @code{fill-column}, evaluate the following:
2289
2290@smallexample
2291(message "The value of fill-column is %d." fill-column)
2292@end smallexample
2293
2294@noindent
2295On my system, when I evaluate this list, @code{"The value of
2296fill-column is 72."} appears in my echo area@footnote{Actually, you
2297can use @code{%s} to print a number. It is non-specific. @code{%d}
2298prints only the part of a number left of a decimal point, and not
2299anything that is not a number.}.
2300
2301If there is more than one @samp{%s} in the quoted string, the value of
2302the first argument following the quoted string is printed at the
2303location of the first @samp{%s} and the value of the second argument is
2304printed at the location of the second @samp{%s}, and so on.
2305
2306@need 1250
2307For example, if you evaluate the following,
2308
2309@smallexample
2310@group
2311(message "There are %d %s in the office!"
2312 (- fill-column 14) "pink elephants")
2313@end group
2314@end smallexample
2315
2316@noindent
2317a rather whimsical message will appear in your echo area. On my system
2318it says, @code{"There are 58 pink elephants in the office!"}.
2319
2320The expression @code{(- fill-column 14)} is evaluated and the resulting
2321number is inserted in place of the @samp{%d}; and the string in double
2322quotes, @code{"pink elephants"}, is treated as a single argument and
2323inserted in place of the @samp{%s}. (That is to say, a string between
2324double quotes evaluates to itself, like a number.)
2325
2326Finally, here is a somewhat complex example that not only illustrates
2327the computation of a number, but also shows how you can use an
2328expression within an expression to generate the text that is substituted
2329for @samp{%s}:
2330
2331@smallexample
2332@group
2333(message "He saw %d %s"
2334 (- fill-column 32)
2335 (concat "red "
2336 (substring
2337 "The quick brown foxes jumped." 16 21)
2338 " leaping."))
2339@end group
2340@end smallexample
2341
2342In this example, @code{message} has three arguments: the string,
2343@code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2344the expression beginning with the function @code{concat}. The value
2345resulting from the evaluation of @code{(- fill-column 32)} is inserted
2346in place of the @samp{%d}; and the value returned by the expression
2347beginning with @code{concat} is inserted in place of the @samp{%s}.
2348
2349When your fill column is 70 and you evaluate the expression, the
2350message @code{"He saw 38 red foxes leaping."} appears in your echo
2351area.
2352
d6adf7e7 2353@node set & setq
8cda6f8f
GM
2354@section Setting the Value of a Variable
2355@cindex Variable, setting value
2356@cindex Setting value of variable
2357
2358@cindex @samp{bind} defined
2359There are several ways by which a variable can be given a value. One of
2360the ways is to use either the function @code{set} or the function
2361@code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2362jargon for this process is to @dfn{bind} a variable to a value.)
2363
2364The following sections not only describe how @code{set} and @code{setq}
2365work but also illustrate how arguments are passed.
2366
2367@menu
2368* Using set:: Setting values.
2369* Using setq:: Setting a quoted value.
2370* Counting:: Using @code{setq} to count.
2371@end menu
2372
d6adf7e7 2373@node Using set
8cda6f8f
GM
2374@subsection Using @code{set}
2375@findex set
2376
2377To set the value of the symbol @code{flowers} to the list @code{'(rose
2378violet daisy buttercup)}, evaluate the following expression by
2379positioning the cursor after the expression and typing @kbd{C-x C-e}.
2380
2381@smallexample
2382(set 'flowers '(rose violet daisy buttercup))
2383@end smallexample
2384
2385@noindent
2386The list @code{(rose violet daisy buttercup)} will appear in the echo
2387area. This is what is @emph{returned} by the @code{set} function. As a
2388side effect, the symbol @code{flowers} is bound to the list; that is,
2389the symbol @code{flowers}, which can be viewed as a variable, is given
2390the list as its value. (This process, by the way, illustrates how a
2391side effect to the Lisp interpreter, setting the value, can be the
2392primary effect that we humans are interested in. This is because every
2393Lisp function must return a value if it does not get an error, but it
2394will only have a side effect if it is designed to have one.)
2395
2396After evaluating the @code{set} expression, you can evaluate the symbol
2397@code{flowers} and it will return the value you just set. Here is the
2398symbol. Place your cursor after it and type @kbd{C-x C-e}.
2399
2400@smallexample
2401flowers
2402@end smallexample
2403
2404@noindent
2405When you evaluate @code{flowers}, the list
2406@code{(rose violet daisy buttercup)} appears in the echo area.
2407
2408Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2409in front of it, what you will see in the echo area is the symbol itself,
2410@code{flowers}. Here is the quoted symbol, so you can try this:
2411
2412@smallexample
2413'flowers
2414@end smallexample
2415
2416Note also, that when you use @code{set}, you need to quote both
2417arguments to @code{set}, unless you want them evaluated. Since we do
2418not want either argument evaluated, neither the variable
2419@code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2420are quoted. (When you use @code{set} without quoting its first
2421argument, the first argument is evaluated before anything else is
2422done. If you did this and @code{flowers} did not have a value
2423already, you would get an error message that the @samp{Symbol's value
2424as variable is void}; on the other hand, if @code{flowers} did return
2425a value after it was evaluated, the @code{set} would attempt to set
2426the value that was returned. There are situations where this is the
2427right thing for the function to do; but such situations are rare.)
2428
d6adf7e7 2429@node Using setq
8cda6f8f
GM
2430@subsection Using @code{setq}
2431@findex setq
2432
2433As a practical matter, you almost always quote the first argument to
2434@code{set}. The combination of @code{set} and a quoted first argument
2435is so common that it has its own name: the special form @code{setq}.
2436This special form is just like @code{set} except that the first argument
2437is quoted automatically, so you don't need to type the quote mark
2438yourself. Also, as an added convenience, @code{setq} permits you to set
2439several different variables to different values, all in one expression.
2440
2441To set the value of the variable @code{carnivores} to the list
2442@code{'(lion tiger leopard)} using @code{setq}, the following expression
2443is used:
2444
2445@smallexample
2446(setq carnivores '(lion tiger leopard))
2447@end smallexample
2448
2449@noindent
2450This is exactly the same as using @code{set} except the first argument
2451is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2452means @code{quote}.)
2453
2454@need 1250
2455With @code{set}, the expression would look like this:
2456
2457@smallexample
2458(set 'carnivores '(lion tiger leopard))
2459@end smallexample
2460
2461Also, @code{setq} can be used to assign different values to
2462different variables. The first argument is bound to the value
2463of the second argument, the third argument is bound to the value of the
2464fourth argument, and so on. For example, you could use the following to
2465assign a list of trees to the symbol @code{trees} and a list of herbivores
2466to the symbol @code{herbivores}:
2467
2468@smallexample
2469@group
2470(setq trees '(pine fir oak maple)
2471 herbivores '(gazelle antelope zebra))
2472@end group
2473@end smallexample
2474
2475@noindent
2476(The expression could just as well have been on one line, but it might
2477not have fit on a page; and humans find it easier to read nicely
2478formatted lists.)
2479
2480Although I have been using the term `assign', there is another way of
2481thinking about the workings of @code{set} and @code{setq}; and that is to
2482say that @code{set} and @code{setq} make the symbol @emph{point} to the
2483list. This latter way of thinking is very common and in forthcoming
2484chapters we shall come upon at least one symbol that has `pointer' as
2485part of its name. The name is chosen because the symbol has a value,
2486specifically a list, attached to it; or, expressed another way,
2487the symbol is set to ``point'' to the list.
2488
d6adf7e7 2489@node Counting
8cda6f8f
GM
2490@subsection Counting
2491@cindex Counting
2492
2493Here is an example that shows how to use @code{setq} in a counter. You
2494might use this to count how many times a part of your program repeats
2495itself. First set a variable to zero; then add one to the number each
2496time the program repeats itself. To do this, you need a variable that
2497serves as a counter, and two expressions: an initial @code{setq}
2498expression that sets the counter variable to zero; and a second
2499@code{setq} expression that increments the counter each time it is
2500evaluated.
2501
2502@smallexample
2503@group
2504(setq counter 0) ; @r{Let's call this the initializer.}
2505
2506(setq counter (+ counter 1)) ; @r{This is the incrementer.}
2507
2508counter ; @r{This is the counter.}
2509@end group
2510@end smallexample
2511
2512@noindent
2513(The text following the @samp{;} are comments. @xref{Change a
2514defun, , Change a Function Definition}.)
2515
2516If you evaluate the first of these expressions, the initializer,
2517@code{(setq counter 0)}, and then evaluate the third expression,
2518@code{counter}, the number @code{0} will appear in the echo area. If
2519you then evaluate the second expression, the incrementer, @code{(setq
2520counter (+ counter 1))}, the counter will get the value 1. So if you
2521again evaluate @code{counter}, the number @code{1} will appear in the
2522echo area. Each time you evaluate the second expression, the value of
2523the counter will be incremented.
2524
2525When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2526the Lisp interpreter first evaluates the innermost list; this is the
2527addition. In order to evaluate this list, it must evaluate the variable
2528@code{counter} and the number @code{1}. When it evaluates the variable
2529@code{counter}, it receives its current value. It passes this value and
2530the number @code{1} to the @code{+} which adds them together. The sum
2531is then returned as the value of the inner list and passed to the
2532@code{setq} which sets the variable @code{counter} to this new value.
2533Thus, the value of the variable, @code{counter}, is changed.
2534
d6adf7e7 2535@node Summary
8cda6f8f
GM
2536@section Summary
2537
2538Learning Lisp is like climbing a hill in which the first part is the
2539steepest. You have now climbed the most difficult part; what remains
2540becomes easier as you progress onwards.
2541
2542@need 1000
2543In summary,
2544
2545@itemize @bullet
2546
2547@item
2548Lisp programs are made up of expressions, which are lists or single atoms.
2549
2550@item
2551Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2552surrounded by parentheses. A list can be empty.
2553
2554@item
2555Atoms are multi-character symbols, like @code{forward-paragraph}, single
2556character symbols like @code{+}, strings of characters between double
2557quotation marks, or numbers.
2558
2559@item
2560A number evaluates to itself.
2561
2562@item
2563A string between double quotes also evaluates to itself.
2564
2565@item
2566When you evaluate a symbol by itself, its value is returned.
2567
2568@item
2569When you evaluate a list, the Lisp interpreter looks at the first symbol
2570in the list and then at the function definition bound to that symbol.
2571Then the instructions in the function definition are carried out.
2572
2573@item
2574A single quotation mark,
2575@ifinfo
2576'
2577@end ifinfo
2578@ifnotinfo
2579@code{'}
2580@end ifnotinfo
2581, tells the Lisp interpreter that it should
2582return the following expression as written, and not evaluate it as it
2583would if the quote were not there.
2584
2585@item
2586Arguments are the information passed to a function. The arguments to a
2587function are computed by evaluating the rest of the elements of the list
2588of which the function is the first element.
2589
2590@item
2591A function always returns a value when it is evaluated (unless it gets
2592an error); in addition, it may also carry out some action called a
2593``side effect''. In many cases, a function's primary purpose is to
2594create a side effect.
2595@end itemize
2596
d6adf7e7 2597@node Error Message Exercises
8cda6f8f
GM
2598@section Exercises
2599
2600A few simple exercises:
2601
2602@itemize @bullet
2603@item
2604Generate an error message by evaluating an appropriate symbol that is
2605not within parentheses.
2606
2607@item
2608Generate an error message by evaluating an appropriate symbol that is
2609between parentheses.
2610
2611@item
2612Create a counter that increments by two rather than one.
2613
2614@item
2615Write an expression that prints a message in the echo area when
2616evaluated.
2617@end itemize
2618
d6adf7e7 2619@node Practicing Evaluation
8cda6f8f
GM
2620@chapter Practicing Evaluation
2621@cindex Practicing evaluation
2622@cindex Evaluation practice
2623
2624Before learning how to write a function definition in Emacs Lisp, it is
2625useful to spend a little time evaluating various expressions that have
2626already been written. These expressions will be lists with the
2627functions as their first (and often only) element. Since some of the
2628functions associated with buffers are both simple and interesting, we
2629will start with those. In this section, we will evaluate a few of
2630these. In another section, we will study the code of several other
2631buffer-related functions, to see how they were written.
2632
2633@menu
2634* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2635 causes evaluation.
2636* Buffer Names:: Buffers and files are different.
2637* Getting Buffers:: Getting a buffer itself, not merely its name.
2638* Switching Buffers:: How to change to another buffer.
2639* Buffer Size & Locations:: Where point is located and the size of
2640 the buffer.
2641* Evaluation Exercise::
2642@end menu
2643
8cda6f8f 2644@ifnottex
d6adf7e7 2645@node How to Evaluate
8cda6f8f
GM
2646@unnumberedsec How to Evaluate
2647@end ifnottex
2648
2649@i{Whenever you give an editing command} to Emacs Lisp, such as the
2650command to move the cursor or to scroll the screen, @i{you are evaluating
2651an expression,} the first element of which is a function. @i{This is
2652how Emacs works.}
2653
2654@cindex @samp{interactive function} defined
2655@cindex @samp{command} defined
2656When you type keys, you cause the Lisp interpreter to evaluate an
2657expression and that is how you get your results. Even typing plain text
2658involves evaluating an Emacs Lisp function, in this case, one that uses
2659@code{self-insert-command}, which simply inserts the character you
2660typed. The functions you evaluate by typing keystrokes are called
2661@dfn{interactive} functions, or @dfn{commands}; how you make a function
2662interactive will be illustrated in the chapter on how to write function
2663definitions. @xref{Interactive, , Making a Function Interactive}.
2664
2665In addition to typing keyboard commands, we have seen a second way to
2666evaluate an expression: by positioning the cursor after a list and
2667typing @kbd{C-x C-e}. This is what we will do in the rest of this
2668section. There are other ways to evaluate an expression as well; these
2669will be described as we come to them.
2670
2671Besides being used for practicing evaluation, the functions shown in the
2672next few sections are important in their own right. A study of these
2673functions makes clear the distinction between buffers and files, how to
2674switch to a buffer, and how to determine a location within it.
2675
d6adf7e7 2676@node Buffer Names
8cda6f8f
GM
2677@section Buffer Names
2678@findex buffer-name
2679@findex buffer-file-name
2680
2681The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2682the difference between a file and a buffer. When you evaluate the
2683following expression, @code{(buffer-name)}, the name of the buffer
2684appears in the echo area. When you evaluate @code{(buffer-file-name)},
2685the name of the file to which the buffer refers appears in the echo
2686area. Usually, the name returned by @code{(buffer-name)} is the same as
2687the name of the file to which it refers, and the name returned by
2688@code{(buffer-file-name)} is the full path-name of the file.
2689
2690A file and a buffer are two different entities. A file is information
2691recorded permanently in the computer (unless you delete it). A buffer,
2692on the other hand, is information inside of Emacs that will vanish at
2693the end of the editing session (or when you kill the buffer). Usually,
2694a buffer contains information that you have copied from a file; we say
2695the buffer is @dfn{visiting} that file. This copy is what you work on
2696and modify. Changes to the buffer do not change the file, until you
2697save the buffer. When you save the buffer, the buffer is copied to the file
2698and is thus saved permanently.
2699
2700@need 1250
2701If you are reading this in Info inside of GNU Emacs, you can evaluate
2702each of the following expressions by positioning the cursor after it and
2703typing @kbd{C-x C-e}.
2704
2705@example
2706@group
2707(buffer-name)
2708
2709(buffer-file-name)
2710@end group
2711@end example
2712
2713@noindent
2714When I do this in Info, the value returned by evaluating
2715@code{(buffer-name)} is @file{"*info*"}, and the value returned by
2716evaluating @code{(buffer-file-name)} is @file{nil}.
2717
a9097c6d 2718On the other hand, while I am writing this document, the value
8cda6f8f
GM
2719returned by evaluating @code{(buffer-name)} is
2720@file{"introduction.texinfo"}, and the value returned by evaluating
2721@code{(buffer-file-name)} is
2722@file{"/gnu/work/intro/introduction.texinfo"}.
2723
2724@cindex @code{nil}, history of word
2725The former is the name of the buffer and the latter is the name of the
2726file. In Info, the buffer name is @file{"*info*"}. Info does not
2727point to any file, so the result of evaluating
2728@code{(buffer-file-name)} is @file{nil}. The symbol @code{nil} is
2729from the Latin word for `nothing'; in this case, it means that the
2730buffer is not associated with any file. (In Lisp, @code{nil} is also
2731used to mean `false' and is a synonym for the empty list, @code{()}.)
2732
2733When I am writing, the name of my buffer is
2734@file{"introduction.texinfo"}. The name of the file to which it
2735points is @file{"/gnu/work/intro/introduction.texinfo"}.
2736
2737(In the expressions, the parentheses tell the Lisp interpreter to
2738treat @w{@code{buffer-name}} and @w{@code{buffer-file-name}} as
2739functions; without the parentheses, the interpreter would attempt to
2740evaluate the symbols as variables. @xref{Variables}.)
2741
2742In spite of the distinction between files and buffers, you will often
2743find that people refer to a file when they mean a buffer and vice-verse.
2744Indeed, most people say, ``I am editing a file,'' rather than saying,
2745``I am editing a buffer which I will soon save to a file.'' It is
2746almost always clear from context what people mean. When dealing with
2747computer programs, however, it is important to keep the distinction in mind,
2748since the computer is not as smart as a person.
2749
2750@cindex Buffer, history of word
2751The word `buffer', by the way, comes from the meaning of the word as a
2752cushion that deadens the force of a collision. In early computers, a
2753buffer cushioned the interaction between files and the computer's
2754central processing unit. The drums or tapes that held a file and the
2755central processing unit were pieces of equipment that were very
2756different from each other, working at their own speeds, in spurts. The
2757buffer made it possible for them to work together effectively.
2758Eventually, the buffer grew from being an intermediary, a temporary
2759holding place, to being the place where work is done. This
2760transformation is rather like that of a small seaport that grew into a
2761great city: once it was merely the place where cargo was warehoused
2762temporarily before being loaded onto ships; then it became a business
2763and cultural center in its own right.
2764
2765Not all buffers are associated with files. For example, a
2766@file{*scratch*} buffer does not visit any file. Similarly, a
2767@file{*Help*} buffer is not associated with any file.
2768
2769In the old days, when you lacked a @file{~/.emacs} file and started an
2770Emacs session by typing the command @code{emacs} alone, without naming
2771any files, Emacs started with the @file{*scratch*} buffer visible.
2772Nowadays, you will see a splash screen. You can follow one of the
2773commands suggested on the splash screen, visit a file, or press the
2774spacebar to reach the @file{*scratch*} buffer.
2775
2776If you switch to the @file{*scratch*} buffer, type
2777@code{(buffer-name)}, position the cursor after it, and then type
2778@kbd{C-x C-e} to evaluate the expression. The name @code{"*scratch*"}
2779will be returned and will appear in the echo area. @code{"*scratch*"}
2780is the name of the buffer. When you type @code{(buffer-file-name)} in
2781the @file{*scratch*} buffer and evaluate that, @code{nil} will appear
2782in the echo area, just as it does when you evaluate
2783@code{(buffer-file-name)} in Info.
2784
2785Incidentally, if you are in the @file{*scratch*} buffer and want the
2786value returned by an expression to appear in the @file{*scratch*}
2787buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2788instead of @kbd{C-x C-e}. This causes the value returned to appear
2789after the expression. The buffer will look like this:
2790
2791@smallexample
2792(buffer-name)"*scratch*"
2793@end smallexample
2794
2795@noindent
2796You cannot do this in Info since Info is read-only and it will not allow
2797you to change the contents of the buffer. But you can do this in any
2798buffer you can edit; and when you write code or documentation (such as
2799this book), this feature is very useful.
2800
d6adf7e7 2801@node Getting Buffers
8cda6f8f
GM
2802@section Getting Buffers
2803@findex current-buffer
2804@findex other-buffer
2805@cindex Getting a buffer
2806
2807The @code{buffer-name} function returns the @emph{name} of the buffer;
2808to get the buffer @emph{itself}, a different function is needed: the
2809@code{current-buffer} function. If you use this function in code, what
2810you get is the buffer itself.
2811
2812A name and the object or entity to which the name refers are different
2813from each other. You are not your name. You are a person to whom
2814others refer by name. If you ask to speak to George and someone hands you
2815a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2816@samp{g}, and @samp{e} written on it, you might be amused, but you would
2817not be satisfied. You do not want to speak to the name, but to the
2818person to whom the name refers. A buffer is similar: the name of the
2819scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2820get a buffer itself, you need to use a function such as
2821@code{current-buffer}.
2822
2823However, there is a slight complication: if you evaluate
2824@code{current-buffer} in an expression on its own, as we will do here,
2825what you see is a printed representation of the name of the buffer
2826without the contents of the buffer. Emacs works this way for two
2827reasons: the buffer may be thousands of lines long---too long to be
2828conveniently displayed; and, another buffer may have the same contents
2829but a different name, and it is important to distinguish between them.
2830
2831@need 800
2832Here is an expression containing the function:
2833
2834@smallexample
2835(current-buffer)
2836@end smallexample
2837
2838@noindent
2839If you evaluate this expression in Info in Emacs in the usual way,
2840@file{#<buffer *info*>} will appear in the echo area. The special
2841format indicates that the buffer itself is being returned, rather than
2842just its name.
2843
2844Incidentally, while you can type a number or symbol into a program, you
2845cannot do that with the printed representation of a buffer: the only way
2846to get a buffer itself is with a function such as @code{current-buffer}.
2847
2848A related function is @code{other-buffer}. This returns the most
2849recently selected buffer other than the one you are in currently, not
2850a printed representation of its name. If you have recently switched
2851back and forth from the @file{*scratch*} buffer, @code{other-buffer}
2852will return that buffer.
2853
2854@need 800
2855You can see this by evaluating the expression:
2856
2857@smallexample
2858(other-buffer)
2859@end smallexample
2860
2861@noindent
2862You should see @file{#<buffer *scratch*>} appear in the echo area, or
2863the name of whatever other buffer you switched back from most
2864recently@footnote{Actually, by default, if the buffer from which you
2865just switched is visible to you in another window, @code{other-buffer}
2866will choose the most recent buffer that you cannot see; this is a
2867subtlety that I often forget.}.
2868
d6adf7e7 2869@node Switching Buffers
8cda6f8f
GM
2870@section Switching Buffers
2871@findex switch-to-buffer
2872@findex set-buffer
2873@cindex Switching to a buffer
2874
2875The @code{other-buffer} function actually provides a buffer when it is
2876used as an argument to a function that requires one. We can see this
2877by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2878different buffer.
2879
2880But first, a brief introduction to the @code{switch-to-buffer}
2881function. When you switched back and forth from Info to the
2882@file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2883likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2884rather, to save typing, you probably only typed @kbd{RET} if the
2885default buffer was @file{*scratch*}, or if it was different, then you
2886typed just part of the name, such as @code{*sc}, pressed your
2887@kbd{TAB} key to cause it to expand to the full name, and then typed
8f4ea8e0 2888@kbd{RET}.} when prompted in the minibuffer for the name of
8cda6f8f
GM
2889the buffer to which you wanted to switch. The keystrokes, @kbd{C-x
2890b}, cause the Lisp interpreter to evaluate the interactive function
2891@code{switch-to-buffer}. As we said before, this is how Emacs works:
2892different keystrokes call or run different functions. For example,
2893@kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2894@code{forward-sentence}, and so on.
2895
2896By writing @code{switch-to-buffer} in an expression, and giving it a
2897buffer to switch to, we can switch buffers just the way @kbd{C-x b}
8f4ea8e0 2898does:
8cda6f8f
GM
2899
2900@smallexample
2901(switch-to-buffer (other-buffer))
2902@end smallexample
2903
2904@noindent
2905The symbol @code{switch-to-buffer} is the first element of the list,
2906so the Lisp interpreter will treat it as a function and carry out the
2907instructions that are attached to it. But before doing that, the
2908interpreter will note that @code{other-buffer} is inside parentheses
2909and work on that symbol first. @code{other-buffer} is the first (and
2910in this case, the only) element of this list, so the Lisp interpreter
2911calls or runs the function. It returns another buffer. Next, the
2912interpreter runs @code{switch-to-buffer}, passing to it, as an
2913argument, the other buffer, which is what Emacs will switch to. If
2914you are reading this in Info, try this now. Evaluate the expression.
2915(To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2916expression will move you to your most recent other buffer that you
2917cannot see. If you really want to go to your most recently selected
2918buffer, even if you can still see it, you need to evaluate the
2919following more complex expression:
2920
2921@smallexample
2922(switch-to-buffer (other-buffer (current-buffer) t))
2923@end smallexample
2924
2925@c noindent
2926In this case, the first argument to @code{other-buffer} tells it which
2927buffer to skip---the current one---and the second argument tells
2928@code{other-buffer} it is OK to switch to a visible buffer.
2929In regular use, @code{switch-to-buffer} takes you to an invisible
2930window since you would most likely use @kbd{C-x o} (@code{other-window})
2931to go to another visible buffer.}
2932
2933In the programming examples in later sections of this document, you will
2934see the function @code{set-buffer} more often than
2935@code{switch-to-buffer}. This is because of a difference between
2936computer programs and humans: humans have eyes and expect to see the
2937buffer on which they are working on their computer terminals. This is
2938so obvious, it almost goes without saying. However, programs do not
2939have eyes. When a computer program works on a buffer, that buffer does
2940not need to be visible on the screen.
2941
2942@code{switch-to-buffer} is designed for humans and does two different
44e97401 2943things: it switches the buffer to which Emacs's attention is directed; and
8cda6f8f
GM
2944it switches the buffer displayed in the window to the new buffer.
2945@code{set-buffer}, on the other hand, does only one thing: it switches
2946the attention of the computer program to a different buffer. The buffer
2947on the screen remains unchanged (of course, normally nothing happens
2948there until the command finishes running).
2949
2950@cindex @samp{call} defined
2951Also, we have just introduced another jargon term, the word @dfn{call}.
2952When you evaluate a list in which the first symbol is a function, you
2953are calling that function. The use of the term comes from the notion of
2954the function as an entity that can do something for you if you `call'
2955it---just as a plumber is an entity who can fix a leak if you call him
2956or her.
2957
d6adf7e7 2958@node Buffer Size & Locations
8cda6f8f
GM
2959@section Buffer Size and the Location of Point
2960@cindex Size of buffer
2961@cindex Buffer size
2962@cindex Point location
2963@cindex Location of point
2964
2965Finally, let's look at several rather simple functions,
2966@code{buffer-size}, @code{point}, @code{point-min}, and
2967@code{point-max}. These give information about the size of a buffer and
2968the location of point within it.
2969
2970The function @code{buffer-size} tells you the size of the current
2971buffer; that is, the function returns a count of the number of
2972characters in the buffer.
2973
2974@smallexample
2975(buffer-size)
2976@end smallexample
2977
2978@noindent
2979You can evaluate this in the usual way, by positioning the
2980cursor after the expression and typing @kbd{C-x C-e}.
2981
2982@cindex @samp{point} defined
2983In Emacs, the current position of the cursor is called @dfn{point}.
2984The expression @code{(point)} returns a number that tells you where the
2985cursor is located as a count of the number of characters from the
2986beginning of the buffer up to point.
2987
2988@need 1250
2989You can see the character count for point in this buffer by evaluating
2990the following expression in the usual way:
2991
2992@smallexample
2993(point)
2994@end smallexample
2995
2996@noindent
2997As I write this, the value of @code{point} is 65724. The @code{point}
2998function is frequently used in some of the examples later in this
2999book.
3000
3001@need 1250
3002The value of point depends, of course, on its location within the
3003buffer. If you evaluate point in this spot, the number will be larger:
3004
3005@smallexample
3006(point)
3007@end smallexample
3008
3009@noindent
3010For me, the value of point in this location is 66043, which means that
3011there are 319 characters (including spaces) between the two
3012expressions. (Doubtless, you will see different numbers, since I will
3013have edited this since I first evaluated point.)
3014
3015@cindex @samp{narrowing} defined
3016The function @code{point-min} is somewhat similar to @code{point}, but
3017it returns the value of the minimum permissible value of point in the
3018current buffer. This is the number 1 unless @dfn{narrowing} is in
3019effect. (Narrowing is a mechanism whereby you can restrict yourself,
3020or a program, to operations on just a part of a buffer.
3021@xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
3022function @code{point-max} returns the value of the maximum permissible
3023value of point in the current buffer.
3024
d6adf7e7 3025@node Evaluation Exercise
8cda6f8f
GM
3026@section Exercise
3027
3028Find a file with which you are working and move towards its middle.
3029Find its buffer name, file name, length, and your position in the file.
3030
d6adf7e7 3031@node Writing Defuns
8cda6f8f
GM
3032@chapter How To Write Function Definitions
3033@cindex Definition writing
3034@cindex Function definition writing
3035@cindex Writing a function definition
3036
3037When the Lisp interpreter evaluates a list, it looks to see whether the
3038first symbol on the list has a function definition attached to it; or,
3039put another way, whether the symbol points to a function definition. If
3040it does, the computer carries out the instructions in the definition. A
3041symbol that has a function definition is called, simply, a function
3042(although, properly speaking, the definition is the function and the
3043symbol refers to it.)
3044
3045@menu
3046* Primitive Functions::
3047* defun:: The @code{defun} special form.
3048* Install:: Install a function definition.
3049* Interactive:: Making a function interactive.
3050* Interactive Options:: Different options for @code{interactive}.
3051* Permanent Installation:: Installing code permanently.
3052* let:: Creating and initializing local variables.
3053* if:: What if?
3054* else:: If--then--else expressions.
3055* Truth & Falsehood:: What Lisp considers false and true.
3056* save-excursion:: Keeping track of point, mark, and buffer.
3057* Review::
3058* defun Exercises::
3059@end menu
3060
8cda6f8f 3061@ifnottex
d6adf7e7 3062@node Primitive Functions
8cda6f8f
GM
3063@unnumberedsec An Aside about Primitive Functions
3064@end ifnottex
3065@cindex Primitive functions
3066@cindex Functions, primitive
3067
3068@cindex C language primitives
3069@cindex Primitives written in C
3070All functions are defined in terms of other functions, except for a few
3071@dfn{primitive} functions that are written in the C programming
3072language. When you write functions' definitions, you will write them in
3073Emacs Lisp and use other functions as your building blocks. Some of the
3074functions you will use will themselves be written in Emacs Lisp (perhaps
1df7defd 3075by you) and some will be primitives written in C@. The primitive
8cda6f8f
GM
3076functions are used exactly like those written in Emacs Lisp and behave
3077like them. They are written in C so we can easily run GNU Emacs on any
3078computer that has sufficient power and can run C.
3079
3080Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3081distinguish between the use of functions written in C and the use of
3082functions written in Emacs Lisp. The difference is irrelevant. I
3083mention the distinction only because it is interesting to know. Indeed,
3084unless you investigate, you won't know whether an already-written
3085function is written in Emacs Lisp or C.
3086
d6adf7e7 3087@node defun
8cda6f8f
GM
3088@section The @code{defun} Special Form
3089@findex defun
3090@cindex Special form of @code{defun}
3091
3092@cindex @samp{function definition} defined
3093In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3094it that tells the computer what to do when the function is called.
3095This code is called the @dfn{function definition} and is created by
3096evaluating a Lisp expression that starts with the symbol @code{defun}
3097(which is an abbreviation for @emph{define function}). Because
3098@code{defun} does not evaluate its arguments in the usual way, it is
3099called a @dfn{special form}.
3100
3101In subsequent sections, we will look at function definitions from the
3102Emacs source code, such as @code{mark-whole-buffer}. In this section,
3103we will describe a simple function definition so you can see how it
3104looks. This function definition uses arithmetic because it makes for a
3105simple example. Some people dislike examples using arithmetic; however,
3106if you are such a person, do not despair. Hardly any of the code we
3107will study in the remainder of this introduction involves arithmetic or
3108mathematics. The examples mostly involve text in one way or another.
3109
3110A function definition has up to five parts following the word
3111@code{defun}:
3112
3113@enumerate
3114@item
3115The name of the symbol to which the function definition should be
3116attached.
3117
3118@item
3119A list of the arguments that will be passed to the function. If no
3120arguments will be passed to the function, this is an empty list,
3121@code{()}.
3122
3123@item
3124Documentation describing the function. (Technically optional, but
3125strongly recommended.)
3126
3127@item
3128Optionally, an expression to make the function interactive so you can
3129use it by typing @kbd{M-x} and then the name of the function; or by
3130typing an appropriate key or keychord.
3131
3132@cindex @samp{body} defined
3133@item
3134The code that instructs the computer what to do: the @dfn{body} of the
3135function definition.
3136@end enumerate
3137
3138It is helpful to think of the five parts of a function definition as
3139being organized in a template, with slots for each part:
3140
3141@smallexample
3142@group
3143(defun @var{function-name} (@var{arguments}@dots{})
3144 "@var{optional-documentation}@dots{}"
3145 (interactive @var{argument-passing-info}) ; @r{optional}
3146 @var{body}@dots{})
3147@end group
3148@end smallexample
3149
3150As an example, here is the code for a function that multiplies its
3151argument by 7. (This example is not interactive. @xref{Interactive,
3152, Making a Function Interactive}, for that information.)
3153
3154@smallexample
3155@group
3156(defun multiply-by-seven (number)
3157 "Multiply NUMBER by seven."
3158 (* 7 number))
3159@end group
3160@end smallexample
3161
3162This definition begins with a parenthesis and the symbol @code{defun},
3163followed by the name of the function.
3164
3165@cindex @samp{argument list} defined
3166The name of the function is followed by a list that contains the
3167arguments that will be passed to the function. This list is called
3168the @dfn{argument list}. In this example, the list has only one
3169element, the symbol, @code{number}. When the function is used, the
3170symbol will be bound to the value that is used as the argument to the
3171function.
3172
3173Instead of choosing the word @code{number} for the name of the argument,
3174I could have picked any other name. For example, I could have chosen
3175the word @code{multiplicand}. I picked the word `number' because it
3176tells what kind of value is intended for this slot; but I could just as
3177well have chosen the word `multiplicand' to indicate the role that the
3178value placed in this slot will play in the workings of the function. I
3179could have called it @code{foogle}, but that would have been a bad
3180choice because it would not tell humans what it means. The choice of
3181name is up to the programmer and should be chosen to make the meaning of
3182the function clear.
3183
3184Indeed, you can choose any name you wish for a symbol in an argument
3185list, even the name of a symbol used in some other function: the name
3186you use in an argument list is private to that particular definition.
3187In that definition, the name refers to a different entity than any use
3188of the same name outside the function definition. Suppose you have a
3189nick-name `Shorty' in your family; when your family members refer to
3190`Shorty', they mean you. But outside your family, in a movie, for
3191example, the name `Shorty' refers to someone else. Because a name in an
3192argument list is private to the function definition, you can change the
3193value of such a symbol inside the body of a function without changing
3194its value outside the function. The effect is similar to that produced
3195by a @code{let} expression. (@xref{let, , @code{let}}.)
3196
3197@ignore
3198Note also that we discuss the word `number' in two different ways: as a
3199symbol that appears in the code, and as the name of something that will
3200be replaced by a something else during the evaluation of the function.
3201In the first case, @code{number} is a symbol, not a number; it happens
3202that within the function, it is a variable who value is the number in
3203question, but our primary interest in it is as a symbol. On the other
3204hand, when we are talking about the function, our interest is that we
3205will substitute a number for the word @var{number}. To keep this
3206distinction clear, we use different typography for the two
3207circumstances. When we talk about this function, or about how it works,
3208we refer to this number by writing @var{number}. In the function
3209itself, we refer to it by writing @code{number}.
3210@end ignore
3211
3212The argument list is followed by the documentation string that
3213describes the function. This is what you see when you type
3214@w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3215write a documentation string like this, you should make the first line
3216a complete sentence since some commands, such as @code{apropos}, print
3217only the first line of a multi-line documentation string. Also, you
3218should not indent the second line of a documentation string, if you
3219have one, because that looks odd when you use @kbd{C-h f}
3220(@code{describe-function}). The documentation string is optional, but
3221it is so useful, it should be included in almost every function you
3222write.
3223
3224@findex * @r{(multiplication)}
3225The third line of the example consists of the body of the function
3226definition. (Most functions' definitions, of course, are longer than
3227this.) In this function, the body is the list, @code{(* 7 number)}, which
3228says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3229@code{*} is the function for multiplication, just as @code{+} is the
3230function for addition.)
3231
3232When you use the @code{multiply-by-seven} function, the argument
3233@code{number} evaluates to the actual number you want used. Here is an
3234example that shows how @code{multiply-by-seven} is used; but don't try
3235to evaluate this yet!
3236
3237@smallexample
3238(multiply-by-seven 3)
3239@end smallexample
3240
3241@noindent
3242The symbol @code{number}, specified in the function definition in the
3243next section, is given or ``bound to'' the value 3 in the actual use of
3244the function. Note that although @code{number} was inside parentheses
3245in the function definition, the argument passed to the
3246@code{multiply-by-seven} function is not in parentheses. The
3247parentheses are written in the function definition so the computer can
3248figure out where the argument list ends and the rest of the function
3249definition begins.
3250
3251If you evaluate this example, you are likely to get an error message.
3252(Go ahead, try it!) This is because we have written the function
3253definition, but not yet told the computer about the definition---we have
3254not yet installed (or `loaded') the function definition in Emacs.
3255Installing a function is the process that tells the Lisp interpreter the
3256definition of the function. Installation is described in the next
3257section.
3258
d6adf7e7 3259@node Install
8cda6f8f
GM
3260@section Install a Function Definition
3261@cindex Install a Function Definition
3262@cindex Definition installation
3263@cindex Function definition installation
3264
3265If you are reading this inside of Info in Emacs, you can try out the
3266@code{multiply-by-seven} function by first evaluating the function
3267definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3268the function definition follows. Place the cursor after the last
3269parenthesis of the function definition and type @kbd{C-x C-e}. When you
3270do this, @code{multiply-by-seven} will appear in the echo area. (What
3271this means is that when a function definition is evaluated, the value it
3272returns is the name of the defined function.) At the same time, this
3273action installs the function definition.
3274
3275@smallexample
3276@group
3277(defun multiply-by-seven (number)
3278 "Multiply NUMBER by seven."
3279 (* 7 number))
3280@end group
3281@end smallexample
3282
3283@noindent
3284By evaluating this @code{defun}, you have just installed
3285@code{multiply-by-seven} in Emacs. The function is now just as much a
3286part of Emacs as @code{forward-word} or any other editing function you
3287use. (@code{multiply-by-seven} will stay installed until you quit
3288Emacs. To reload code automatically whenever you start Emacs, see
3289@ref{Permanent Installation, , Installing Code Permanently}.)
3290
3291@menu
3292* Effect of installation::
3293* Change a defun:: How to change a function definition.
3294@end menu
3295
8cda6f8f 3296@ifnottex
d6adf7e7 3297@node Effect of installation
8cda6f8f
GM
3298@unnumberedsubsec The effect of installation
3299@end ifnottex
3300
3301You can see the effect of installing @code{multiply-by-seven} by
3302evaluating the following sample. Place the cursor after the following
3303expression and type @kbd{C-x C-e}. The number 21 will appear in the
3304echo area.
3305
3306@smallexample
3307(multiply-by-seven 3)
3308@end smallexample
3309
3310If you wish, you can read the documentation for the function by typing
3311@kbd{C-h f} (@code{describe-function}) and then the name of the
3312function, @code{multiply-by-seven}. When you do this, a
3313@file{*Help*} window will appear on your screen that says:
3314
3315@smallexample
3316@group
3317multiply-by-seven is a Lisp function.
3318(multiply-by-seven NUMBER)
3319
3320Multiply NUMBER by seven.
3321@end group
3322@end smallexample
3323
3324@noindent
3325(To return to a single window on your screen, type @kbd{C-x 1}.)
3326
d6adf7e7 3327@node Change a defun
8cda6f8f
GM
3328@subsection Change a Function Definition
3329@cindex Changing a function definition
3330@cindex Function definition, how to change
3331@cindex Definition, how to change
3332
3333If you want to change the code in @code{multiply-by-seven}, just rewrite
3334it. To install the new version in place of the old one, evaluate the
3335function definition again. This is how you modify code in Emacs. It is
3336very simple.
3337
3338As an example, you can change the @code{multiply-by-seven} function to
3339add the number to itself seven times instead of multiplying the number
3340by seven. It produces the same answer, but by a different path. At
3341the same time, we will add a comment to the code; a comment is text
3342that the Lisp interpreter ignores, but that a human reader may find
3343useful or enlightening. The comment is that this is the ``second
3344version''.
3345
3346@smallexample
3347@group
3348(defun multiply-by-seven (number) ; @r{Second version.}
3349 "Multiply NUMBER by seven."
3350 (+ number number number number number number number))
3351@end group
3352@end smallexample
3353
3354@cindex Comments in Lisp code
3355The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3356line that follows a semicolon is a comment. The end of the line is the
3357end of the comment. To stretch a comment over two or more lines, begin
3358each line with a semicolon.
3359
3360@xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3361File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3362Reference Manual}, for more about comments.
3363
3364You can install this version of the @code{multiply-by-seven} function by
3365evaluating it in the same way you evaluated the first function: place
3366the cursor after the last parenthesis and type @kbd{C-x C-e}.
3367
3368In summary, this is how you write code in Emacs Lisp: you write a
3369function; install it; test it; and then make fixes or enhancements and
3370install it again.
3371
d6adf7e7 3372@node Interactive
8cda6f8f
GM
3373@section Make a Function Interactive
3374@cindex Interactive functions
3375@findex interactive
3376
3377You make a function interactive by placing a list that begins with
3378the special form @code{interactive} immediately after the
3379documentation. A user can invoke an interactive function by typing
3380@kbd{M-x} and then the name of the function; or by typing the keys to
3381which it is bound, for example, by typing @kbd{C-n} for
3382@code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3383
3384Interestingly, when you call an interactive function interactively,
3385the value returned is not automatically displayed in the echo area.
3386This is because you often call an interactive function for its side
3387effects, such as moving forward by a word or line, and not for the
3388value returned. If the returned value were displayed in the echo area
3389each time you typed a key, it would be very distracting.
3390
3391@menu
3392* Interactive multiply-by-seven:: An overview.
3393* multiply-by-seven in detail:: The interactive version.
3394@end menu
3395
8cda6f8f 3396@ifnottex
d6adf7e7 3397@node Interactive multiply-by-seven
8cda6f8f
GM
3398@unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3399@end ifnottex
3400
3401Both the use of the special form @code{interactive} and one way to
3402display a value in the echo area can be illustrated by creating an
3403interactive version of @code{multiply-by-seven}.
3404
3405@need 1250
3406Here is the code:
3407
3408@smallexample
3409@group
3410(defun multiply-by-seven (number) ; @r{Interactive version.}
3411 "Multiply NUMBER by seven."
3412 (interactive "p")
3413 (message "The result is %d" (* 7 number)))
3414@end group
3415@end smallexample
3416
3417@noindent
3418You can install this code by placing your cursor after it and typing
3419@kbd{C-x C-e}. The name of the function will appear in your echo area.
3420Then, you can use this code by typing @kbd{C-u} and a number and then
3421typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3422@samp{The result is @dots{}} followed by the product will appear in the
3423echo area.
3424
3425Speaking more generally, you invoke a function like this in either of two
3426ways:
3427
3428@enumerate
3429@item
3430By typing a prefix argument that contains the number to be passed, and
3431then typing @kbd{M-x} and the name of the function, as with
3432@kbd{C-u 3 M-x forward-sentence}; or,
3433
3434@item
3435By typing whatever key or keychord the function is bound to, as with
3436@kbd{C-u 3 M-e}.
3437@end enumerate
3438
3439@noindent
3440Both the examples just mentioned work identically to move point forward
3441three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3442it could not be used as an example of key binding.)
3443
3444(@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3445to a key.)
3446
3447A prefix argument is passed to an interactive function by typing the
3448@key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3449typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3450type @kbd{C-u} without a number, it defaults to 4).
3451
d6adf7e7 3452@node multiply-by-seven in detail
8cda6f8f
GM
3453@subsection An Interactive @code{multiply-by-seven}
3454
3455Let's look at the use of the special form @code{interactive} and then at
3456the function @code{message} in the interactive version of
3457@code{multiply-by-seven}. You will recall that the function definition
3458looks like this:
3459
3460@smallexample
3461@group
3462(defun multiply-by-seven (number) ; @r{Interactive version.}
3463 "Multiply NUMBER by seven."
3464 (interactive "p")
3465 (message "The result is %d" (* 7 number)))
3466@end group
3467@end smallexample
3468
3469In this function, the expression, @code{(interactive "p")}, is a list of
3470two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3471the function and use its value for the argument of the function.
3472
3473@need 1000
3474The argument will be a number. This means that the symbol
3475@code{number} will be bound to a number in the line:
3476
3477@smallexample
3478(message "The result is %d" (* 7 number))
3479@end smallexample
3480
3481@need 1250
3482@noindent
3483For example, if your prefix argument is 5, the Lisp interpreter will
3484evaluate the line as if it were:
3485
3486@smallexample
3487(message "The result is %d" (* 7 5))
3488@end smallexample
3489
3490@noindent
3491(If you are reading this in GNU Emacs, you can evaluate this expression
3492yourself.) First, the interpreter will evaluate the inner list, which
3493is @code{(* 7 5)}. This returns a value of 35. Next, it
3494will evaluate the outer list, passing the values of the second and
3495subsequent elements of the list to the function @code{message}.
3496
3497As we have seen, @code{message} is an Emacs Lisp function especially
3498designed for sending a one line message to a user. (@xref{message, ,
3499The @code{message} function}.) In summary, the @code{message}
3500function prints its first argument in the echo area as is, except for
3501occurrences of @samp{%d} or @samp{%s} (and various other %-sequences
3502which we have not mentioned). When it sees a control sequence, the
3503function looks to the second or subsequent arguments and prints the
3504value of the argument in the location in the string where the control
3505sequence is located.
3506
3507In the interactive @code{multiply-by-seven} function, the control string
3508is @samp{%d}, which requires a number, and the value returned by
3509evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3510is printed in place of the @samp{%d} and the message is @samp{The result
3511is 35}.
3512
3513(Note that when you call the function @code{multiply-by-seven}, the
3514message is printed without quotes, but when you call @code{message}, the
3515text is printed in double quotes. This is because the value returned by
3516@code{message} is what appears in the echo area when you evaluate an
3517expression whose first element is @code{message}; but when embedded in a
3518function, @code{message} prints the text as a side effect without
3519quotes.)
3520
d6adf7e7 3521@node Interactive Options
8cda6f8f
GM
3522@section Different Options for @code{interactive}
3523@cindex Options for @code{interactive}
3524@cindex Interactive options
3525
3526In the example, @code{multiply-by-seven} used @code{"p"} as the
3527argument to @code{interactive}. This argument told Emacs to interpret
3528your typing either @kbd{C-u} followed by a number or @key{META}
3529followed by a number as a command to pass that number to the function
3530as its argument. Emacs has more than twenty characters predefined for
3531use with @code{interactive}. In almost every case, one of these
3532options will enable you to pass the right information interactively to
3533a function. (@xref{Interactive Codes, , Code Characters for
3534@code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3535
3536@need 1250
3537Consider the function @code{zap-to-char}. Its interactive expression
3538is
3539
3540@smallexample
3541(interactive "p\ncZap to char: ")
3542@end smallexample
3543
3544The first part of the argument to @code{interactive} is @samp{p}, with
3545which you are already familiar. This argument tells Emacs to
3546interpret a `prefix', as a number to be passed to the function. You
3547can specify a prefix either by typing @kbd{C-u} followed by a number
3548or by typing @key{META} followed by a number. The prefix is the
3549number of specified characters. Thus, if your prefix is three and the
3550specified character is @samp{x}, then you will delete all the text up
3551to and including the third next @samp{x}. If you do not set a prefix,
3552then you delete all the text up to and including the specified
3553character, but no more.
3554
3555The @samp{c} tells the function the name of the character to which to delete.
3556
3557More formally, a function with two or more arguments can have
3558information passed to each argument by adding parts to the string that
3559follows @code{interactive}. When you do this, the information is
3560passed to each argument in the same order it is specified in the
3561@code{interactive} list. In the string, each part is separated from
3562the next part by a @samp{\n}, which is a newline. For example, you
3563can follow @samp{p} with a @samp{\n} and an @samp{cZap to char:@: }.
3564This causes Emacs to pass the value of the prefix argument (if there
3565is one) and the character.
3566
3567In this case, the function definition looks like the following, where
3568@code{arg} and @code{char} are the symbols to which @code{interactive}
3569binds the prefix argument and the specified character:
3570
3571@smallexample
3572@group
3573(defun @var{name-of-function} (arg char)
3574 "@var{documentation}@dots{}"
3575 (interactive "p\ncZap to char: ")
3576 @var{body-of-function}@dots{})
3577@end group
3578@end smallexample
3579
3580@noindent
3581(The space after the colon in the prompt makes it look better when you
3582are prompted. @xref{copy-to-buffer, , The Definition of
3583@code{copy-to-buffer}}, for an example.)
3584
3585When a function does not take arguments, @code{interactive} does not
3586require any. Such a function contains the simple expression
3587@code{(interactive)}. The @code{mark-whole-buffer} function is like
3588this.
3589
3590Alternatively, if the special letter-codes are not right for your
3591application, you can pass your own arguments to @code{interactive} as
3592a list.
3593
3594@xref{append-to-buffer, , The Definition of @code{append-to-buffer}},
3595for an example. @xref{Using Interactive, , Using @code{Interactive},
3596elisp, The GNU Emacs Lisp Reference Manual}, for a more complete
3597explanation about this technique.
3598
d6adf7e7 3599@node Permanent Installation
8cda6f8f
GM
3600@section Install Code Permanently
3601@cindex Install code permanently
3602@cindex Permanent code installation
3603@cindex Code installation
3604
3605When you install a function definition by evaluating it, it will stay
3606installed until you quit Emacs. The next time you start a new session
3607of Emacs, the function will not be installed unless you evaluate the
3608function definition again.
3609
3610At some point, you may want to have code installed automatically
3611whenever you start a new session of Emacs. There are several ways of
3612doing this:
3613
3614@itemize @bullet
3615@item
3616If you have code that is just for yourself, you can put the code for the
3617function definition in your @file{.emacs} initialization file. When you
3618start Emacs, your @file{.emacs} file is automatically evaluated and all
3619the function definitions within it are installed.
3620@xref{Emacs Initialization, , Your @file{.emacs} File}.
3621
3622@item
3623Alternatively, you can put the function definitions that you want
3624installed in one or more files of their own and use the @code{load}
3625function to cause Emacs to evaluate and thereby install each of the
3626functions in the files.
3627@xref{Loading Files, , Loading Files}.
3628
3629@item
3630Thirdly, if you have code that your whole site will use, it is usual
3631to put it in a file called @file{site-init.el} that is loaded when
3632Emacs is built. This makes the code available to everyone who uses
3633your machine. (See the @file{INSTALL} file that is part of the Emacs
3634distribution.)
3635@end itemize
3636
3637Finally, if you have code that everyone who uses Emacs may want, you
3638can post it on a computer network or send a copy to the Free Software
3639Foundation. (When you do this, please license the code and its
3640documentation under a license that permits other people to run, copy,
3641study, modify, and redistribute the code and which protects you from
3642having your work taken from you.) If you send a copy of your code to
3643the Free Software Foundation, and properly protect yourself and
3644others, it may be included in the next release of Emacs. In large
3645part, this is how Emacs has grown over the past years, by donations.
3646
d6adf7e7 3647@node let
8cda6f8f
GM
3648@section @code{let}
3649@findex let
3650
3651The @code{let} expression is a special form in Lisp that you will need
3652to use in most function definitions.
3653
3654@code{let} is used to attach or bind a symbol to a value in such a way
3655that the Lisp interpreter will not confuse the variable with a
3656variable of the same name that is not part of the function.
3657
3658To understand why the @code{let} special form is necessary, consider
3659the situation in which you own a home that you generally refer to as
3660`the house', as in the sentence, ``The house needs painting.'' If you
3661are visiting a friend and your host refers to `the house', he is
3662likely to be referring to @emph{his} house, not yours, that is, to a
3663different house.
3664
3665If your friend is referring to his house and you think he is referring
3666to your house, you may be in for some confusion. The same thing could
3667happen in Lisp if a variable that is used inside of one function has
3668the same name as a variable that is used inside of another function,
3669and the two are not intended to refer to the same value. The
3670@code{let} special form prevents this kind of confusion.
3671
3672@menu
3673* Prevent confusion::
3674* Parts of let Expression::
3675* Sample let Expression::
3676* Uninitialized let Variables::
3677@end menu
3678
8cda6f8f 3679@ifnottex
d6adf7e7 3680@node Prevent confusion
8cda6f8f
GM
3681@unnumberedsubsec @code{let} Prevents Confusion
3682@end ifnottex
3683
3684@cindex @samp{local variable} defined
3685@cindex @samp{variable, local}, defined
3686The @code{let} special form prevents confusion. @code{let} creates a
3687name for a @dfn{local variable} that overshadows any use of the same
3688name outside the @code{let} expression. This is like understanding
3689that whenever your host refers to `the house', he means his house, not
3690yours. (Symbols used in argument lists work the same way.
3691@xref{defun, , The @code{defun} Special Form}.)
3692
3693Local variables created by a @code{let} expression retain their value
3694@emph{only} within the @code{let} expression itself (and within
3695expressions called within the @code{let} expression); the local
3696variables have no effect outside the @code{let} expression.
3697
3698Another way to think about @code{let} is that it is like a @code{setq}
3699that is temporary and local. The values set by @code{let} are
3700automatically undone when the @code{let} is finished. The setting
3701only affects expressions that are inside the bounds of the @code{let}
3702expression. In computer science jargon, we would say ``the binding of
3703a symbol is visible only in functions called in the @code{let} form;
3704in Emacs Lisp, scoping is dynamic, not lexical.''
3705
3706@code{let} can create more than one variable at once. Also,
3707@code{let} gives each variable it creates an initial value, either a
3708value specified by you, or @code{nil}. (In the jargon, this is called
3709`binding the variable to the value'.) After @code{let} has created
3710and bound the variables, it executes the code in the body of the
3711@code{let}, and returns the value of the last expression in the body,
3712as the value of the whole @code{let} expression. (`Execute' is a jargon
3713term that means to evaluate a list; it comes from the use of the word
3714meaning `to give practical effect to' (@cite{Oxford English
3715Dictionary}). Since you evaluate an expression to perform an action,
3716`execute' has evolved as a synonym to `evaluate'.)
3717
d6adf7e7 3718@node Parts of let Expression
8cda6f8f
GM
3719@subsection The Parts of a @code{let} Expression
3720@cindex @code{let} expression, parts of
3721@cindex Parts of @code{let} expression
3722
3723@cindex @samp{varlist} defined
3724A @code{let} expression is a list of three parts. The first part is
3725the symbol @code{let}. The second part is a list, called a
3726@dfn{varlist}, each element of which is either a symbol by itself or a
3727two-element list, the first element of which is a symbol. The third
3728part of the @code{let} expression is the body of the @code{let}. The
3729body usually consists of one or more lists.
3730
3731@need 800
3732A template for a @code{let} expression looks like this:
3733
3734@smallexample
3735(let @var{varlist} @var{body}@dots{})
3736@end smallexample
3737
3738@noindent
3739The symbols in the varlist are the variables that are given initial
3740values by the @code{let} special form. Symbols by themselves are given
3741the initial value of @code{nil}; and each symbol that is the first
3742element of a two-element list is bound to the value that is returned
3743when the Lisp interpreter evaluates the second element.
3744
3745Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3746this case, in a @code{let} expression, Emacs binds the symbol
3747@code{thread} to an initial value of @code{nil}, and binds the symbol
3748@code{needles} to an initial value of 3.
3749
3750When you write a @code{let} expression, what you do is put the
3751appropriate expressions in the slots of the @code{let} expression
3752template.
3753
3754If the varlist is composed of two-element lists, as is often the case,
3755the template for the @code{let} expression looks like this:
3756
3757@smallexample
3758@group
3759(let ((@var{variable} @var{value})
3760 (@var{variable} @var{value})
3761 @dots{})
3762 @var{body}@dots{})
3763@end group
3764@end smallexample
3765
d6adf7e7 3766@node Sample let Expression
8cda6f8f
GM
3767@subsection Sample @code{let} Expression
3768@cindex Sample @code{let} expression
3769@cindex @code{let} expression sample
3770
3771The following expression creates and gives initial values
3772to the two variables @code{zebra} and @code{tiger}. The body of the
3773@code{let} expression is a list which calls the @code{message} function.
3774
3775@smallexample
3776@group
3777(let ((zebra 'stripes)
3778 (tiger 'fierce))
3779 (message "One kind of animal has %s and another is %s."
3780 zebra tiger))
3781@end group
3782@end smallexample
3783
3784Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3785
3786The two variables are @code{zebra} and @code{tiger}. Each variable is
3787the first element of a two-element list and each value is the second
3788element of its two-element list. In the varlist, Emacs binds the
3789variable @code{zebra} to the value @code{stripes}@footnote{According
3790to Jared Diamond in @cite{Guns, Germs, and Steel}, ``@dots{} zebras
3791become impossibly dangerous as they grow older'' but the claim here is
3792that they do not become fierce like a tiger. (1997, W. W. Norton and
3793Co., ISBN 0-393-03894-2, page 171)}, and binds the
3794variable @code{tiger} to the value @code{fierce}. In this example,
3795both values are symbols preceded by a quote. The values could just as
3796well have been another list or a string. The body of the @code{let}
3797follows after the list holding the variables. In this example, the
3798body is a list that uses the @code{message} function to print a string
3799in the echo area.
3800
3801@need 1500
3802You may evaluate the example in the usual fashion, by placing the
3803cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3804this, the following will appear in the echo area:
3805
3806@smallexample
3807"One kind of animal has stripes and another is fierce."
3808@end smallexample
3809
3810As we have seen before, the @code{message} function prints its first
3811argument, except for @samp{%s}. In this example, the value of the variable
3812@code{zebra} is printed at the location of the first @samp{%s} and the
3813value of the variable @code{tiger} is printed at the location of the
3814second @samp{%s}.
3815
d6adf7e7 3816@node Uninitialized let Variables
8cda6f8f
GM
3817@subsection Uninitialized Variables in a @code{let} Statement
3818@cindex Uninitialized @code{let} variables
3819@cindex @code{let} variables uninitialized
3820
3821If you do not bind the variables in a @code{let} statement to specific
3822initial values, they will automatically be bound to an initial value of
3823@code{nil}, as in the following expression:
3824
3825@smallexample
3826@group
3827(let ((birch 3)
3828 pine
3829 fir
3830 (oak 'some))
3831 (message
3832 "Here are %d variables with %s, %s, and %s value."
3833 birch pine fir oak))
3834@end group
3835@end smallexample
3836
3837@noindent
3838Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3839
3840@need 1250
3841If you evaluate this expression in the usual way, the following will
3842appear in your echo area:
3843
3844@smallexample
3845"Here are 3 variables with nil, nil, and some value."
3846@end smallexample
3847
3848@noindent
3849In this example, Emacs binds the symbol @code{birch} to the number 3,
3850binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3851the symbol @code{oak} to the value @code{some}.
3852
3853Note that in the first part of the @code{let}, the variables @code{pine}
3854and @code{fir} stand alone as atoms that are not surrounded by
3855parentheses; this is because they are being bound to @code{nil}, the
3856empty list. But @code{oak} is bound to @code{some} and so is a part of
3857the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3858number 3 and so is in a list with that number. (Since a number
3859evaluates to itself, the number does not need to be quoted. Also, the
3860number is printed in the message using a @samp{%d} rather than a
3861@samp{%s}.) The four variables as a group are put into a list to
3862delimit them from the body of the @code{let}.
3863
d6adf7e7 3864@node if
8cda6f8f
GM
3865@section The @code{if} Special Form
3866@findex if
3867@cindex Conditional with @code{if}
3868
3869A third special form, in addition to @code{defun} and @code{let}, is the
3870conditional @code{if}. This form is used to instruct the computer to
3871make decisions. You can write function definitions without using
3872@code{if}, but it is used often enough, and is important enough, to be
3873included here. It is used, for example, in the code for the
3874function @code{beginning-of-buffer}.
3875
3876The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3877@emph{then} an expression is evaluated.'' If the test is not true, the
3878expression is not evaluated. For example, you might make a decision
3879such as, ``if it is warm and sunny, then go to the beach!''
3880
3881@menu
3882* if in more detail::
3883* type-of-animal in detail:: An example of an @code{if} expression.
3884@end menu
3885
8cda6f8f 3886@ifnottex
d6adf7e7 3887@node if in more detail
8cda6f8f
GM
3888@unnumberedsubsec @code{if} in more detail
3889@end ifnottex
3890
3891@cindex @samp{if-part} defined
3892@cindex @samp{then-part} defined
3893An @code{if} expression written in Lisp does not use the word `then';
3894the test and the action are the second and third elements of the list
3895whose first element is @code{if}. Nonetheless, the test part of an
3896@code{if} expression is often called the @dfn{if-part} and the second
3897argument is often called the @dfn{then-part}.
3898
3899Also, when an @code{if} expression is written, the true-or-false-test
3900is usually written on the same line as the symbol @code{if}, but the
3901action to carry out if the test is true, the ``then-part'', is written
3902on the second and subsequent lines. This makes the @code{if}
3903expression easier to read.
3904
3905@smallexample
3906@group
3907(if @var{true-or-false-test}
3908 @var{action-to-carry-out-if-test-is-true})
3909@end group
3910@end smallexample
3911
3912@noindent
3913The true-or-false-test will be an expression that
3914is evaluated by the Lisp interpreter.
3915
3916Here is an example that you can evaluate in the usual manner. The test
3917is whether the number 5 is greater than the number 4. Since it is, the
3918message @samp{5 is greater than 4!} will be printed.
3919
3920@smallexample
3921@group
3922(if (> 5 4) ; @r{if-part}
3923 (message "5 is greater than 4!")) ; @r{then-part}
3924@end group
3925@end smallexample
3926
3927@noindent
3928(The function @code{>} tests whether its first argument is greater than
3929its second argument and returns true if it is.)
3930@findex > (greater than)
3931
3932Of course, in actual use, the test in an @code{if} expression will not
3933be fixed for all time as it is by the expression @code{(> 5 4)}.
3934Instead, at least one of the variables used in the test will be bound to
3935a value that is not known ahead of time. (If the value were known ahead
3936of time, we would not need to run the test!)
3937
3938For example, the value may be bound to an argument of a function
3939definition. In the following function definition, the character of the
3940animal is a value that is passed to the function. If the value bound to
3941@code{characteristic} is @code{fierce}, then the message, @samp{It's a
3942tiger!} will be printed; otherwise, @code{nil} will be returned.
3943
3944@smallexample
3945@group
3946(defun type-of-animal (characteristic)
3947 "Print message in echo area depending on CHARACTERISTIC.
3948If the CHARACTERISTIC is the symbol `fierce',
3949then warn of a tiger."
3950 (if (equal characteristic 'fierce)
3951 (message "It's a tiger!")))
3952@end group
3953@end smallexample
3954
3955@need 1500
3956@noindent
3957If you are reading this inside of GNU Emacs, you can evaluate the
3958function definition in the usual way to install it in Emacs, and then you
3959can evaluate the following two expressions to see the results:
3960
3961@smallexample
3962@group
3963(type-of-animal 'fierce)
3964
3965(type-of-animal 'zebra)
3966
3967@end group
3968@end smallexample
3969
3970@c Following sentences rewritten to prevent overfull hbox.
3971@noindent
3972When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3973following message printed in the echo area: @code{"It's a tiger!"}; and
3974when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3975printed in the echo area.
3976
d6adf7e7 3977@node type-of-animal in detail
8cda6f8f
GM
3978@subsection The @code{type-of-animal} Function in Detail
3979
3980Let's look at the @code{type-of-animal} function in detail.
3981
3982The function definition for @code{type-of-animal} was written by filling
3983the slots of two templates, one for a function definition as a whole, and
3984a second for an @code{if} expression.
3985
3986@need 1250
3987The template for every function that is not interactive is:
3988
3989@smallexample
3990@group
3991(defun @var{name-of-function} (@var{argument-list})
3992 "@var{documentation}@dots{}"
3993 @var{body}@dots{})
3994@end group
3995@end smallexample
3996
3997@need 800
3998The parts of the function that match this template look like this:
3999
4000@smallexample
4001@group
4002(defun type-of-animal (characteristic)
4003 "Print message in echo area depending on CHARACTERISTIC.
4004If the CHARACTERISTIC is the symbol `fierce',
4005then warn of a tiger."
4006 @var{body: the} @code{if} @var{expression})
4007@end group
4008@end smallexample
4009
4010The name of function is @code{type-of-animal}; it is passed the value
4011of one argument. The argument list is followed by a multi-line
4012documentation string. The documentation string is included in the
4013example because it is a good habit to write documentation string for
4014every function definition. The body of the function definition
4015consists of the @code{if} expression.
4016
4017@need 800
4018The template for an @code{if} expression looks like this:
4019
4020@smallexample
4021@group
4022(if @var{true-or-false-test}
4023 @var{action-to-carry-out-if-the-test-returns-true})
4024@end group
4025@end smallexample
4026
4027@need 1250
4028In the @code{type-of-animal} function, the code for the @code{if}
4029looks like this:
4030
4031@smallexample
4032@group
4033(if (equal characteristic 'fierce)
4034 (message "It's a tiger!")))
4035@end group
4036@end smallexample
4037
4038@need 800
4039Here, the true-or-false-test is the expression:
4040
4041@smallexample
4042(equal characteristic 'fierce)
4043@end smallexample
4044
4045@noindent
4046In Lisp, @code{equal} is a function that determines whether its first
4047argument is equal to its second argument. The second argument is the
4048quoted symbol @code{'fierce} and the first argument is the value of the
4049symbol @code{characteristic}---in other words, the argument passed to
4050this function.
4051
4052In the first exercise of @code{type-of-animal}, the argument
4053@code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
4054is equal to @code{fierce}, the expression, @code{(equal characteristic
4055'fierce)}, returns a value of true. When this happens, the @code{if}
4056evaluates the second argument or then-part of the @code{if}:
4057@code{(message "It's tiger!")}.
4058
4059On the other hand, in the second exercise of @code{type-of-animal}, the
4060argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
4061is not equal to @code{fierce}, so the then-part is not evaluated and
4062@code{nil} is returned by the @code{if} expression.
4063
d6adf7e7 4064@node else
8cda6f8f
GM
4065@section If--then--else Expressions
4066@cindex Else
4067
4068An @code{if} expression may have an optional third argument, called
4069the @dfn{else-part}, for the case when the true-or-false-test returns
4070false. When this happens, the second argument or then-part of the
4071overall @code{if} expression is @emph{not} evaluated, but the third or
4072else-part @emph{is} evaluated. You might think of this as the cloudy
4073day alternative for the decision ``if it is warm and sunny, then go to
4074the beach, else read a book!''.
4075
4076The word ``else'' is not written in the Lisp code; the else-part of an
4077@code{if} expression comes after the then-part. In the written Lisp, the
4078else-part is usually written to start on a line of its own and is
4079indented less than the then-part:
4080
4081@smallexample
4082@group
4083(if @var{true-or-false-test}
4084 @var{action-to-carry-out-if-the-test-returns-true}
4085 @var{action-to-carry-out-if-the-test-returns-false})
4086@end group
4087@end smallexample
4088
4089For example, the following @code{if} expression prints the message @samp{4
4090is not greater than 5!} when you evaluate it in the usual way:
4091
4092@smallexample
4093@group
4094(if (> 4 5) ; @r{if-part}
4095 (message "4 falsely greater than 5!") ; @r{then-part}
4096 (message "4 is not greater than 5!")) ; @r{else-part}
4097@end group
4098@end smallexample
4099
4100@noindent
4101Note that the different levels of indentation make it easy to
4102distinguish the then-part from the else-part. (GNU Emacs has several
4103commands that automatically indent @code{if} expressions correctly.
4104@xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4105
4106We can extend the @code{type-of-animal} function to include an
4107else-part by simply incorporating an additional part to the @code{if}
4108expression.
4109
4110@need 1500
4111You can see the consequences of doing this if you evaluate the following
4112version of the @code{type-of-animal} function definition to install it
4113and then evaluate the two subsequent expressions to pass different
4114arguments to the function.
4115
4116@smallexample
4117@group
4118(defun type-of-animal (characteristic) ; @r{Second version.}
4119 "Print message in echo area depending on CHARACTERISTIC.
4120If the CHARACTERISTIC is the symbol `fierce',
4121then warn of a tiger;
4122else say it's not fierce."
4123 (if (equal characteristic 'fierce)
4124 (message "It's a tiger!")
4125 (message "It's not fierce!")))
4126@end group
4127@end smallexample
4128@sp 1
4129
4130@smallexample
4131@group
4132(type-of-animal 'fierce)
4133
4134(type-of-animal 'zebra)
4135
4136@end group
4137@end smallexample
4138
4139@c Following sentence rewritten to prevent overfull hbox.
4140@noindent
4141When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4142following message printed in the echo area: @code{"It's a tiger!"}; but
4143when you evaluate @code{(type-of-animal 'zebra)}, you will see
4144@code{"It's not fierce!"}.
4145
4146(Of course, if the @var{characteristic} were @code{ferocious}, the
4147message @code{"It's not fierce!"} would be printed; and it would be
4148misleading! When you write code, you need to take into account the
4149possibility that some such argument will be tested by the @code{if}
4150and write your program accordingly.)
4151
d6adf7e7 4152@node Truth & Falsehood
8cda6f8f
GM
4153@section Truth and Falsehood in Emacs Lisp
4154@cindex Truth and falsehood in Emacs Lisp
4155@cindex Falsehood and truth in Emacs Lisp
4156@findex nil
4157
4158There is an important aspect to the truth test in an @code{if}
4159expression. So far, we have spoken of `true' and `false' as values of
4160predicates as if they were new kinds of Emacs Lisp objects. In fact,
4161`false' is just our old friend @code{nil}. Anything else---anything
4162at all---is `true'.
4163
4164The expression that tests for truth is interpreted as @dfn{true}
4165if the result of evaluating it is a value that is not @code{nil}. In
4166other words, the result of the test is considered true if the value
4167returned is a number such as 47, a string such as @code{"hello"}, or a
4168symbol (other than @code{nil}) such as @code{flowers}, or a list (so
4169long as it is not empty), or even a buffer!
4170
4171@menu
4172* nil explained:: @code{nil} has two meanings.
4173@end menu
4174
8cda6f8f 4175@ifnottex
d6adf7e7 4176@node nil explained
8cda6f8f
GM
4177@unnumberedsubsec An explanation of @code{nil}
4178@end ifnottex
4179
4180Before illustrating a test for truth, we need an explanation of @code{nil}.
4181
4182In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4183empty list. Second, it means false and is the value returned when a
4184true-or-false-test tests false. @code{nil} can be written as an empty
4185list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4186concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4187to use @code{nil} for false and @code{()} for the empty list.
4188
4189In Emacs Lisp, any value that is not @code{nil}---is not the empty
4190list---is considered true. This means that if an evaluation returns
4191something that is not an empty list, an @code{if} expression will test
4192true. For example, if a number is put in the slot for the test, it
4193will be evaluated and will return itself, since that is what numbers
4194do when evaluated. In this conditional, the @code{if} expression will
4195test true. The expression tests false only when @code{nil}, an empty
4196list, is returned by evaluating the expression.
4197
4198You can see this by evaluating the two expressions in the following examples.
4199
4200In the first example, the number 4 is evaluated as the test in the
4201@code{if} expression and returns itself; consequently, the then-part
4202of the expression is evaluated and returned: @samp{true} appears in
4203the echo area. In the second example, the @code{nil} indicates false;
4204consequently, the else-part of the expression is evaluated and
4205returned: @samp{false} appears in the echo area.
4206
4207@smallexample
4208@group
4209(if 4
4210 'true
4211 'false)
4212@end group
4213
4214@group
4215(if nil
4216 'true
4217 'false)
4218@end group
4219@end smallexample
4220
4221@need 1250
4222Incidentally, if some other useful value is not available for a test that
4223returns true, then the Lisp interpreter will return the symbol @code{t}
4224for true. For example, the expression @code{(> 5 4)} returns @code{t}
4225when evaluated, as you can see by evaluating it in the usual way:
4226
4227@smallexample
4228(> 5 4)
4229@end smallexample
4230
4231@need 1250
4232@noindent
4233On the other hand, this function returns @code{nil} if the test is false.
4234
4235@smallexample
4236(> 4 5)
4237@end smallexample
4238
d6adf7e7 4239@node save-excursion
8cda6f8f
GM
4240@section @code{save-excursion}
4241@findex save-excursion
4242@cindex Region, what it is
4243@cindex Preserving point, mark, and buffer
4244@cindex Point, mark, buffer preservation
4245@findex point
4246@findex mark
4247
4248The @code{save-excursion} function is the fourth and final special form
4249that we will discuss in this chapter.
4250
4251In Emacs Lisp programs used for editing, the @code{save-excursion}
4252function is very common. It saves the location of point and mark,
4253executes the body of the function, and then restores point and mark to
4254their previous positions if their locations were changed. Its primary
4255purpose is to keep the user from being surprised and disturbed by
4256unexpected movement of point or mark.
4257
4258@menu
4259* Point and mark:: A review of various locations.
4260* Template for save-excursion::
4261@end menu
4262
8cda6f8f 4263@ifnottex
d6adf7e7 4264@node Point and mark
8cda6f8f
GM
4265@unnumberedsubsec Point and Mark
4266@end ifnottex
4267
4268Before discussing @code{save-excursion}, however, it may be useful
4269first to review what point and mark are in GNU Emacs. @dfn{Point} is
4270the current location of the cursor. Wherever the cursor
4271is, that is point. More precisely, on terminals where the cursor
4272appears to be on top of a character, point is immediately before the
4273character. In Emacs Lisp, point is an integer. The first character in
4274a buffer is number one, the second is number two, and so on. The
4275function @code{point} returns the current position of the cursor as a
4276number. Each buffer has its own value for point.
4277
4278The @dfn{mark} is another position in the buffer; its value can be set
4279with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4280a mark has been set, you can use the command @kbd{C-x C-x}
4281(@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4282and set the mark to be the previous position of point. In addition, if
4283you set another mark, the position of the previous mark is saved in the
4284mark ring. Many mark positions can be saved this way. You can jump the
4285cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4286times.
4287
4288The part of the buffer between point and mark is called @dfn{the
4289region}. Numerous commands work on the region, including
4290@code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4291@code{print-region}.
4292
4293The @code{save-excursion} special form saves the locations of point and
4294mark and restores those positions after the code within the body of the
4295special form is evaluated by the Lisp interpreter. Thus, if point were
4296in the beginning of a piece of text and some code moved point to the end
4297of the buffer, the @code{save-excursion} would put point back to where
4298it was before, after the expressions in the body of the function were
4299evaluated.
4300
4301In Emacs, a function frequently moves point as part of its internal
4302workings even though a user would not expect this. For example,
4303@code{count-lines-region} moves point. To prevent the user from being
4304bothered by jumps that are both unexpected and (from the user's point of
4305view) unnecessary, @code{save-excursion} is often used to keep point and
4306mark in the location expected by the user. The use of
4307@code{save-excursion} is good housekeeping.
4308
4309To make sure the house stays clean, @code{save-excursion} restores the
4310values of point and mark even if something goes wrong in the code inside
4311of it (or, to be more precise and to use the proper jargon, ``in case of
4312abnormal exit''). This feature is very helpful.
4313
4314In addition to recording the values of point and mark,
4315@code{save-excursion} keeps track of the current buffer, and restores
4316it, too. This means you can write code that will change the buffer and
4317have @code{save-excursion} switch you back to the original buffer.
4318This is how @code{save-excursion} is used in @code{append-to-buffer}.
4319(@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4320
d6adf7e7 4321@node Template for save-excursion
8cda6f8f
GM
4322@subsection Template for a @code{save-excursion} Expression
4323
4324@need 800
4325The template for code using @code{save-excursion} is simple:
4326
4327@smallexample
4328@group
4329(save-excursion
4330 @var{body}@dots{})
4331@end group
4332@end smallexample
4333
4334@noindent
4335The body of the function is one or more expressions that will be
4336evaluated in sequence by the Lisp interpreter. If there is more than
4337one expression in the body, the value of the last one will be returned
4338as the value of the @code{save-excursion} function. The other
4339expressions in the body are evaluated only for their side effects; and
4340@code{save-excursion} itself is used only for its side effect (which
4341is restoring the positions of point and mark).
4342
4343@need 1250
4344In more detail, the template for a @code{save-excursion} expression
4345looks like this:
4346
4347@smallexample
4348@group
4349(save-excursion
4350 @var{first-expression-in-body}
4351 @var{second-expression-in-body}
4352 @var{third-expression-in-body}
4353 @dots{}
4354 @var{last-expression-in-body})
4355@end group
4356@end smallexample
4357
4358@noindent
4359An expression, of course, may be a symbol on its own or a list.
4360
4361In Emacs Lisp code, a @code{save-excursion} expression often occurs
4362within the body of a @code{let} expression. It looks like this:
4363
4364@smallexample
4365@group
4366(let @var{varlist}
4367 (save-excursion
4368 @var{body}@dots{}))
4369@end group
4370@end smallexample
4371
d6adf7e7 4372@node Review
8cda6f8f
GM
4373@section Review
4374
4375In the last few chapters we have introduced a fair number of functions
4376and special forms. Here they are described in brief, along with a few
4377similar functions that have not been mentioned yet.
4378
4379@table @code
4380@item eval-last-sexp
4381Evaluate the last symbolic expression before the current location of
4382point. The value is printed in the echo area unless the function is
4383invoked with an argument; in that case, the output is printed in the
4384current buffer. This command is normally bound to @kbd{C-x C-e}.
4385
4386@item defun
4387Define function. This special form has up to five parts: the name,
4388a template for the arguments that will be passed to the function,
4389documentation, an optional interactive declaration, and the body of the
4390definition.
4391
4392@need 1250
4393For example, in an early version of Emacs, the function definition was
4394as follows. (It is slightly more complex now that it seeks the first
4395non-whitespace character rather than the first visible character.)
4396
4397@smallexample
4398@group
4399(defun back-to-indentation ()
4400 "Move point to first visible character on line."
4401 (interactive)
4402 (beginning-of-line 1)
4403 (skip-chars-forward " \t"))
4404@end group
4405@end smallexample
4406
4407@ignore
4408In GNU Emacs 22,
4409
4410(defun backward-to-indentation (&optional arg)
4411 "Move backward ARG lines and position at first nonblank character."
4412 (interactive "p")
4413 (forward-line (- (or arg 1)))
4414 (skip-chars-forward " \t"))
4415
4416(defun back-to-indentation ()
4417 "Move point to the first non-whitespace character on this line."
4418 (interactive)
4419 (beginning-of-line 1)
4420 (skip-syntax-forward " " (line-end-position))
4421 ;; Move back over chars that have whitespace syntax but have the p flag.
4422 (backward-prefix-chars))
4423@end ignore
4424
4425@item interactive
4426Declare to the interpreter that the function can be used
4427interactively. This special form may be followed by a string with one
4428or more parts that pass the information to the arguments of the
4429function, in sequence. These parts may also tell the interpreter to
4430prompt for information. Parts of the string are separated by
4431newlines, @samp{\n}.
4432
4433@need 1000
4434Common code characters are:
4435
4436@table @code
4437@item b
4438The name of an existing buffer.
4439
4440@item f
4441The name of an existing file.
4442
4443@item p
4444The numeric prefix argument. (Note that this `p' is lower case.)
4445
4446@item r
4447Point and the mark, as two numeric arguments, smallest first. This
4448is the only code letter that specifies two successive arguments
4449rather than one.
4450@end table
4451
4452@xref{Interactive Codes, , Code Characters for @samp{interactive},
4453elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4454code characters.
4455
4456@item let
4457Declare that a list of variables is for use within the body of the
4458@code{let} and give them an initial value, either @code{nil} or a
4459specified value; then evaluate the rest of the expressions in the body
4460of the @code{let} and return the value of the last one. Inside the
4461body of the @code{let}, the Lisp interpreter does not see the values of
4462the variables of the same names that are bound outside of the
4463@code{let}.
4464
4465@need 1250
4466For example,
4467
4468@smallexample
4469@group
4470(let ((foo (buffer-name))
4471 (bar (buffer-size)))
4472 (message
4473 "This buffer is %s and has %d characters."
4474 foo bar))
4475@end group
4476@end smallexample
4477
4478@item save-excursion
4479Record the values of point and mark and the current buffer before
4480evaluating the body of this special form. Restore the values of point
4481and mark and buffer afterward.
4482
4483@need 1250
4484For example,
4485
4486@smallexample
4487@group
4488(message "We are %d characters into this buffer."
4489 (- (point)
4490 (save-excursion
4491 (goto-char (point-min)) (point))))
4492@end group
4493@end smallexample
4494
4495@item if
4496Evaluate the first argument to the function; if it is true, evaluate
4497the second argument; else evaluate the third argument, if there is one.
4498
4499The @code{if} special form is called a @dfn{conditional}. There are
4500other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4501commonly used.
4502
4503@need 1250
4504For example,
4505
4506@smallexample
4507@group
4508(if (= 22 emacs-major-version)
4509 (message "This is version 22 Emacs")
4510 (message "This is not version 22 Emacs"))
4511@end group
4512@end smallexample
4513
4514@need 1250
4515@item <
4516@itemx >
4517@itemx <=
4518@itemx >=
4519The @code{<} function tests whether its first argument is smaller than
4520its second argument. A corresponding function, @code{>}, tests whether
4521the first argument is greater than the second. Likewise, @code{<=}
4522tests whether the first argument is less than or equal to the second and
4523@code{>=} tests whether the first argument is greater than or equal to
4524the second. In all cases, both arguments must be numbers or markers
4525(markers indicate positions in buffers).
4526
4527@need 800
4528@item =
4529The @code{=} function tests whether two arguments, both numbers or
4530markers, are equal.
4531
4532@need 1250
4533@item equal
4534@itemx eq
4535Test whether two objects are the same. @code{equal} uses one meaning
4536of the word `same' and @code{eq} uses another: @code{equal} returns
4537true if the two objects have a similar structure and contents, such as
4538two copies of the same book. On the other hand, @code{eq}, returns
4539true if both arguments are actually the same object.
4540@findex equal
4541@findex eq
4542
4543@need 1250
4544@item string<
4545@itemx string-lessp
4546@itemx string=
4547@itemx string-equal
4548The @code{string-lessp} function tests whether its first argument is
4549smaller than the second argument. A shorter, alternative name for the
4550same function (a @code{defalias}) is @code{string<}.
4551
4552The arguments to @code{string-lessp} must be strings or symbols; the
4553ordering is lexicographic, so case is significant. The print names of
4554symbols are used instead of the symbols themselves.
4555
4556@cindex @samp{empty string} defined
4557An empty string, @samp{""}, a string with no characters in it, is
4558smaller than any string of characters.
4559
4560@code{string-equal} provides the corresponding test for equality. Its
4561shorter, alternative name is @code{string=}. There are no string test
4562functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4563
4564@item message
4565Print a message in the echo area. The first argument is a string that
4566can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4567arguments that follow the string. The argument used by @samp{%s} must
4568be a string or a symbol; the argument used by @samp{%d} must be a
4569number. The argument used by @samp{%c} must be an @sc{ascii} code
4570number; it will be printed as the character with that @sc{ascii} code.
4571(Various other %-sequences have not been mentioned.)
4572
4573@item setq
4574@itemx set
4575The @code{setq} function sets the value of its first argument to the
4576value of the second argument. The first argument is automatically
4577quoted by @code{setq}. It does the same for succeeding pairs of
4578arguments. Another function, @code{set}, takes only two arguments and
4579evaluates both of them before setting the value returned by its first
4580argument to the value returned by its second argument.
4581
4582@item buffer-name
4583Without an argument, return the name of the buffer, as a string.
4584
4585@itemx buffer-file-name
4586Without an argument, return the name of the file the buffer is
4587visiting.
4588
4589@item current-buffer
4590Return the buffer in which Emacs is active; it may not be
4591the buffer that is visible on the screen.
4592
4593@item other-buffer
4594Return the most recently selected buffer (other than the buffer passed
4595to @code{other-buffer} as an argument and other than the current
4596buffer).
4597
4598@item switch-to-buffer
4599Select a buffer for Emacs to be active in and display it in the current
4600window so users can look at it. Usually bound to @kbd{C-x b}.
4601
4602@item set-buffer
44e97401 4603Switch Emacs's attention to a buffer on which programs will run. Don't
8cda6f8f
GM
4604alter what the window is showing.
4605
4606@item buffer-size
4607Return the number of characters in the current buffer.
4608
4609@item point
4610Return the value of the current position of the cursor, as an
4611integer counting the number of characters from the beginning of the
4612buffer.
4613
4614@item point-min
4615Return the minimum permissible value of point in
4616the current buffer. This is 1, unless narrowing is in effect.
4617
4618@item point-max
4619Return the value of the maximum permissible value of point in the
4620current buffer. This is the end of the buffer, unless narrowing is in
4621effect.
4622@end table
4623
4624@need 1500
d6adf7e7 4625@node defun Exercises
8cda6f8f
GM
4626@section Exercises
4627
4628@itemize @bullet
4629@item
4630Write a non-interactive function that doubles the value of its
4631argument, a number. Make that function interactive.
4632
4633@item
4634Write a function that tests whether the current value of
4635@code{fill-column} is greater than the argument passed to the function,
4636and if so, prints an appropriate message.
4637@end itemize
4638
d6adf7e7 4639@node Buffer Walk Through
8cda6f8f
GM
4640@chapter A Few Buffer--Related Functions
4641
4642In this chapter we study in detail several of the functions used in GNU
4643Emacs. This is called a ``walk-through''. These functions are used as
4644examples of Lisp code, but are not imaginary examples; with the
4645exception of the first, simplified function definition, these functions
4646show the actual code used in GNU Emacs. You can learn a great deal from
4647these definitions. The functions described here are all related to
4648buffers. Later, we will study other functions.
4649
4650@menu
4651* Finding More:: How to find more information.
4652* simplified-beginning-of-buffer:: Shows @code{goto-char},
4653 @code{point-min}, and @code{push-mark}.
4654* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4655* append-to-buffer:: Uses @code{save-excursion} and
4656 @code{insert-buffer-substring}.
4657* Buffer Related Review:: Review.
4658* Buffer Exercises::
4659@end menu
4660
d6adf7e7 4661@node Finding More
8cda6f8f
GM
4662@section Finding More Information
4663
4664@findex describe-function, @r{introduced}
4665@cindex Find function documentation
4666In this walk-through, I will describe each new function as we come to
4667it, sometimes in detail and sometimes briefly. If you are interested,
4668you can get the full documentation of any Emacs Lisp function at any
4669time by typing @kbd{C-h f} and then the name of the function (and then
4670@key{RET}). Similarly, you can get the full documentation for a
4671variable by typing @kbd{C-h v} and then the name of the variable (and
4672then @key{RET}).
4673
4674@cindex Find source of function
4675@c In version 22, tells location both of C and of Emacs Lisp
4676Also, @code{describe-function} will tell you the location of the
4677function definition.
4678
4679Put point into the name of the file that contains the function and
4680press the @key{RET} key. In this case, @key{RET} means
4681@code{push-button} rather than `return' or `enter'. Emacs will take
4682you directly to the function definition.
4683
4684@ignore
4685Not In version 22
4686
4687If you move point over the file name and press
4688the @key{RET} key, which in this case means @code{help-follow} rather
4689than `return' or `enter', Emacs will take you directly to the function
4690definition.
4691@end ignore
4692
4693More generally, if you want to see a function in its original source
88c26f5c
GM
4694file, you can use the @code{find-tag} function to jump to it.
4695@code{find-tag} works with a wide variety of languages, not just
8cda6f8f 4696Lisp, and C, and it works with non-programming text as well. For
88c26f5c 4697example, @code{find-tag} will jump to the various nodes in the
8cda6f8f 4698Texinfo source file of this document.
88c26f5c 4699The @code{find-tag} function depends on `tags tables' that record
8cda6f8f 4700the locations of the functions, variables, and other items to which
88c26f5c 4701@code{find-tag} jumps.
8cda6f8f 4702
88c26f5c 4703To use the @code{find-tag} command, type @kbd{M-.} (i.e., press the
8cda6f8f
GM
4704period key while holding down the @key{META} key, or else type the
4705@key{ESC} key and then type the period key), and then, at the prompt,
4706type in the name of the function whose source code you want to see,
4707such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4708switch buffers and display the source code for the function on your
4709screen. To switch back to your current buffer, type @kbd{C-x b
09e80d9f 4710@key{RET}}. (On some keyboards, the @key{META} key is labeled
8cda6f8f
GM
4711@key{ALT}.)
4712
4713@c !!! 22.1.1 tags table location in this paragraph
4714@cindex TAGS table, specifying
88c26f5c 4715@findex find-tag
8cda6f8f
GM
4716Depending on how the initial default values of your copy of Emacs are
4717set, you may also need to specify the location of your `tags table',
4718which is a file called @file{TAGS}. For example, if you are
4719interested in Emacs sources, the tags table you will most likely want,
4720if it has already been created for you, will be in a subdirectory of
4721the @file{/usr/local/share/emacs/} directory; thus you would use the
4722@code{M-x visit-tags-table} command and specify a pathname such as
4723@file{/usr/local/share/emacs/22.1.1/lisp/TAGS}. If the tags table
4724has not already been created, you will have to create it yourself. It
0ca10bb7 4725will be in a file such as @file{/usr/local/src/emacs/src/TAGS}.
8cda6f8f
GM
4726
4727@need 1250
4728To create a @file{TAGS} file in a specific directory, switch to that
4729directory in Emacs using @kbd{M-x cd} command, or list the directory
4730with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4731@w{@code{etags *.el}} as the command to execute:
4732
4733@smallexample
4734M-x compile RET etags *.el RET
4735@end smallexample
4736
4737For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4738
4739After you become more familiar with Emacs Lisp, you will find that you will
88c26f5c 4740frequently use @code{find-tag} to navigate your way around source code;
8cda6f8f
GM
4741and you will create your own @file{TAGS} tables.
4742
4743@cindex Library, as term for `file'
4744Incidentally, the files that contain Lisp code are conventionally
4745called @dfn{libraries}. The metaphor is derived from that of a
4746specialized library, such as a law library or an engineering library,
4747rather than a general library. Each library, or file, contains
4748functions that relate to a particular topic or activity, such as
4749@file{abbrev.el} for handling abbreviations and other typing
4750shortcuts, and @file{help.el} for on-line help. (Sometimes several
4751libraries provide code for a single activity, as the various
4752@file{rmail@dots{}} files provide code for reading electronic mail.)
4753In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4754@kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4755by topic keywords.''
4756
d6adf7e7 4757@node simplified-beginning-of-buffer
8cda6f8f
GM
4758@section A Simplified @code{beginning-of-buffer} Definition
4759@findex simplified-beginning-of-buffer
4760
4761The @code{beginning-of-buffer} command is a good function to start with
4762since you are likely to be familiar with it and it is easy to
4763understand. Used as an interactive command, @code{beginning-of-buffer}
4764moves the cursor to the beginning of the buffer, leaving the mark at the
4765previous position. It is generally bound to @kbd{M-<}.
4766
4767In this section, we will discuss a shortened version of the function
4768that shows how it is most frequently used. This shortened function
4769works as written, but it does not contain the code for a complex option.
4770In another section, we will describe the entire function.
4771(@xref{beginning-of-buffer, , Complete Definition of
4772@code{beginning-of-buffer}}.)
4773
4774Before looking at the code, let's consider what the function
4775definition has to contain: it must include an expression that makes
4776the function interactive so it can be called by typing @kbd{M-x
4777beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4778must include code to leave a mark at the original position in the
4779buffer; and it must include code to move the cursor to the beginning
4780of the buffer.
4781
4782@need 1250
4783Here is the complete text of the shortened version of the function:
4784
4785@smallexample
4786@group
4787(defun simplified-beginning-of-buffer ()
4788 "Move point to the beginning of the buffer;
4789leave mark at previous position."
4790 (interactive)
4791 (push-mark)
4792 (goto-char (point-min)))
4793@end group
4794@end smallexample
4795
4796Like all function definitions, this definition has five parts following
4797the special form @code{defun}:
4798
4799@enumerate
4800@item
4801The name: in this example, @code{simplified-beginning-of-buffer}.
4802
4803@item
4804A list of the arguments: in this example, an empty list, @code{()},
4805
4806@item
4807The documentation string.
4808
4809@item
4810The interactive expression.
4811
4812@item
4813The body.
4814@end enumerate
4815
4816@noindent
4817In this function definition, the argument list is empty; this means that
4818this function does not require any arguments. (When we look at the
4819definition for the complete function, we will see that it may be passed
4820an optional argument.)
4821
4822The interactive expression tells Emacs that the function is intended to
4823be used interactively. In this example, @code{interactive} does not have
4824an argument because @code{simplified-beginning-of-buffer} does not
4825require one.
4826
4827@need 800
4828The body of the function consists of the two lines:
4829
4830@smallexample
4831@group
4832(push-mark)
4833(goto-char (point-min))
4834@end group
4835@end smallexample
4836
4837The first of these lines is the expression, @code{(push-mark)}. When
4838this expression is evaluated by the Lisp interpreter, it sets a mark at
4839the current position of the cursor, wherever that may be. The position
4840of this mark is saved in the mark ring.
4841
4842The next line is @code{(goto-char (point-min))}. This expression
4843jumps the cursor to the minimum point in the buffer, that is, to the
4844beginning of the buffer (or to the beginning of the accessible portion
4845of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4846Narrowing and Widening}.)
4847
4848The @code{push-mark} command sets a mark at the place where the cursor
4849was located before it was moved to the beginning of the buffer by the
4850@code{(goto-char (point-min))} expression. Consequently, you can, if
4851you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4852
4853That is all there is to the function definition!
4854
4855@findex describe-function
4856When you are reading code such as this and come upon an unfamiliar
4857function, such as @code{goto-char}, you can find out what it does by
4858using the @code{describe-function} command. To use this command, type
4859@kbd{C-h f} and then type in the name of the function and press
4860@key{RET}. The @code{describe-function} command will print the
4861function's documentation string in a @file{*Help*} window. For
4862example, the documentation for @code{goto-char} is:
4863
4864@smallexample
4865@group
4866Set point to POSITION, a number or marker.
4867Beginning of buffer is position (point-min), end is (point-max).
4868@end group
4869@end smallexample
4870
4871@noindent
4872The function's one argument is the desired position.
4873
4874@noindent
4875(The prompt for @code{describe-function} will offer you the symbol
4876under or preceding the cursor, so you can save typing by positioning
4877the cursor right over or after the function and then typing @kbd{C-h f
4878@key{RET}}.)
4879
4880The @code{end-of-buffer} function definition is written in the same way as
4881the @code{beginning-of-buffer} definition except that the body of the
4882function contains the expression @code{(goto-char (point-max))} in place
4883of @code{(goto-char (point-min))}.
4884
d6adf7e7 4885@node mark-whole-buffer
8cda6f8f
GM
4886@section The Definition of @code{mark-whole-buffer}
4887@findex mark-whole-buffer
4888
4889The @code{mark-whole-buffer} function is no harder to understand than the
4890@code{simplified-beginning-of-buffer} function. In this case, however,
4891we will look at the complete function, not a shortened version.
4892
4893The @code{mark-whole-buffer} function is not as commonly used as the
4894@code{beginning-of-buffer} function, but is useful nonetheless: it
4895marks a whole buffer as a region by putting point at the beginning and
4896a mark at the end of the buffer. It is generally bound to @kbd{C-x
4897h}.
4898
4899@menu
4900* mark-whole-buffer overview::
4901* Body of mark-whole-buffer:: Only three lines of code.
4902@end menu
4903
8cda6f8f 4904@ifnottex
d6adf7e7 4905@node mark-whole-buffer overview
8cda6f8f
GM
4906@unnumberedsubsec An overview of @code{mark-whole-buffer}
4907@end ifnottex
4908
4909@need 1250
4910In GNU Emacs 22, the code for the complete function looks like this:
4911
4912@smallexample
4913@group
4914(defun mark-whole-buffer ()
4915 "Put point at beginning and mark at end of buffer.
4916You probably should not use this function in Lisp programs;
4917it is usually a mistake for a Lisp function to use any subroutine
4918that uses or sets the mark."
4919 (interactive)
4920 (push-mark (point))
4921 (push-mark (point-max) nil t)
4922 (goto-char (point-min)))
4923@end group
4924@end smallexample
4925
4926@need 1250
4927Like all other functions, the @code{mark-whole-buffer} function fits
4928into the template for a function definition. The template looks like
4929this:
4930
4931@smallexample
4932@group
4933(defun @var{name-of-function} (@var{argument-list})
4934 "@var{documentation}@dots{}"
4935 (@var{interactive-expression}@dots{})
4936 @var{body}@dots{})
4937@end group
4938@end smallexample
4939
4940Here is how the function works: the name of the function is
4941@code{mark-whole-buffer}; it is followed by an empty argument list,
4942@samp{()}, which means that the function does not require arguments.
4943The documentation comes next.
4944
4945The next line is an @code{(interactive)} expression that tells Emacs
4946that the function will be used interactively. These details are similar
4947to the @code{simplified-beginning-of-buffer} function described in the
4948previous section.
4949
4950@need 1250
d6adf7e7 4951@node Body of mark-whole-buffer
8cda6f8f
GM
4952@subsection Body of @code{mark-whole-buffer}
4953
4954The body of the @code{mark-whole-buffer} function consists of three
4955lines of code:
4956
4957@c GNU Emacs 22
4958@smallexample
4959@group
4960(push-mark (point))
4961(push-mark (point-max) nil t)
4962(goto-char (point-min))
4963@end group
4964@end smallexample
4965
4966The first of these lines is the expression, @code{(push-mark (point))}.
4967
4968This line does exactly the same job as the first line of the body of
4969the @code{simplified-beginning-of-buffer} function, which is written
4970@code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4971at the current position of the cursor.
4972
4973I don't know why the expression in @code{mark-whole-buffer} is written
4974@code{(push-mark (point))} and the expression in
4975@code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4976whoever wrote the code did not know that the arguments for
4977@code{push-mark} are optional and that if @code{push-mark} is not
4978passed an argument, the function automatically sets mark at the
4979location of point by default. Or perhaps the expression was written
4980so as to parallel the structure of the next line. In any case, the
4981line causes Emacs to determine the position of point and set a mark
4982there.
4983
4984In earlier versions of GNU Emacs, the next line of
4985@code{mark-whole-buffer} was @code{(push-mark (point-max))}. This
4986expression sets a mark at the point in the buffer that has the highest
4987number. This will be the end of the buffer (or, if the buffer is
4988narrowed, the end of the accessible portion of the buffer.
4989@xref{Narrowing & Widening, , Narrowing and Widening}, for more about
4990narrowing.) After this mark has been set, the previous mark, the one
4991set at point, is no longer set, but Emacs remembers its position, just
4992as all other recent marks are always remembered. This means that you
4993can, if you wish, go back to that position by typing @kbd{C-u
4994C-@key{SPC}} twice.
4995
4996@need 1250
4997In GNU Emacs 22, the @code{(point-max)} is slightly more complicated.
4998The line reads
4999
5000@smallexample
5001(push-mark (point-max) nil t)
5002@end smallexample
5003
5004@noindent
5005The expression works nearly the same as before. It sets a mark at the
5006highest numbered place in the buffer that it can. However, in this
5007version, @code{push-mark} has two additional arguments. The second
5008argument to @code{push-mark} is @code{nil}. This tells the function
5009it @emph{should} display a message that says `Mark set' when it pushes
5010the mark. The third argument is @code{t}. This tells
5011@code{push-mark} to activate the mark when Transient Mark mode is
5012turned on. Transient Mark mode highlights the currently active
5013region. It is often turned off.
5014
5015Finally, the last line of the function is @code{(goto-char
5016(point-min)))}. This is written exactly the same way as it is written
5017in @code{beginning-of-buffer}. The expression moves the cursor to
5018the minimum point in the buffer, that is, to the beginning of the buffer
5019(or to the beginning of the accessible portion of the buffer). As a
5020result of this, point is placed at the beginning of the buffer and mark
5021is set at the end of the buffer. The whole buffer is, therefore, the
5022region.
5023
d6adf7e7 5024@node append-to-buffer
8cda6f8f
GM
5025@section The Definition of @code{append-to-buffer}
5026@findex append-to-buffer
5027
5028The @code{append-to-buffer} command is more complex than the
5029@code{mark-whole-buffer} command. What it does is copy the region
5030(that is, the part of the buffer between point and mark) from the
5031current buffer to a specified buffer.
5032
5033@menu
5034* append-to-buffer overview::
5035* append interactive:: A two part interactive expression.
5036* append-to-buffer body:: Incorporates a @code{let} expression.
5037* append save-excursion:: How the @code{save-excursion} works.
5038@end menu
5039
8cda6f8f 5040@ifnottex
d6adf7e7 5041@node append-to-buffer overview
8cda6f8f
GM
5042@unnumberedsubsec An Overview of @code{append-to-buffer}
5043@end ifnottex
5044
5045@findex insert-buffer-substring
5046The @code{append-to-buffer} command uses the
5047@code{insert-buffer-substring} function to copy the region.
5048@code{insert-buffer-substring} is described by its name: it takes a
5049string of characters from part of a buffer, a ``substring'', and
5050inserts them into another buffer.
5051
5052Most of @code{append-to-buffer} is
5053concerned with setting up the conditions for
5054@code{insert-buffer-substring} to work: the code must specify both the
5055buffer to which the text will go, the window it comes from and goes
5056to, and the region that will be copied.
5057
5058@need 1250
5059Here is the complete text of the function:
5060
5061@smallexample
5062@group
5063(defun append-to-buffer (buffer start end)
5064 "Append to specified buffer the text of the region.
5065It is inserted into that buffer before its point.
5066@end group
5067
5068@group
5069When calling from a program, give three arguments:
5070BUFFER (or buffer name), START and END.
5071START and END specify the portion of the current buffer to be copied."
5072 (interactive
5073 (list (read-buffer "Append to buffer: " (other-buffer
5074 (current-buffer) t))
5075 (region-beginning) (region-end)))
5076@end group
5077@group
5078 (let ((oldbuf (current-buffer)))
5079 (save-excursion
5080 (let* ((append-to (get-buffer-create buffer))
5081 (windows (get-buffer-window-list append-to t t))
5082 point)
5083 (set-buffer append-to)
5084 (setq point (point))
5085 (barf-if-buffer-read-only)
5086 (insert-buffer-substring oldbuf start end)
5087 (dolist (window windows)
5088 (when (= (window-point window) point)
5089 (set-window-point window (point))))))))
5090@end group
5091@end smallexample
5092
5093The function can be understood by looking at it as a series of
5094filled-in templates.
5095
5096The outermost template is for the function definition. In this
5097function, it looks like this (with several slots filled in):
5098
5099@smallexample
5100@group
5101(defun append-to-buffer (buffer start end)
5102 "@var{documentation}@dots{}"
5103 (interactive @dots{})
5104 @var{body}@dots{})
5105@end group
5106@end smallexample
5107
5108The first line of the function includes its name and three arguments.
5109The arguments are the @code{buffer} to which the text will be copied, and
5110the @code{start} and @code{end} of the region in the current buffer that
5111will be copied.
5112
5113The next part of the function is the documentation, which is clear and
5114complete. As is conventional, the three arguments are written in
5115upper case so you will notice them easily. Even better, they are
5116described in the same order as in the argument list.
5117
5118Note that the documentation distinguishes between a buffer and its
5119name. (The function can handle either.)
5120
d6adf7e7 5121@node append interactive
8cda6f8f
GM
5122@subsection The @code{append-to-buffer} Interactive Expression
5123
5124Since the @code{append-to-buffer} function will be used interactively,
5125the function must have an @code{interactive} expression. (For a
5126review of @code{interactive}, see @ref{Interactive, , Making a
5127Function Interactive}.) The expression reads as follows:
5128
5129@smallexample
5130@group
5131(interactive
5132 (list (read-buffer
5133 "Append to buffer: "
5134 (other-buffer (current-buffer) t))
5135 (region-beginning)
5136 (region-end)))
5137@end group
5138@end smallexample
5139
5140@noindent
5141This expression is not one with letters standing for parts, as
5142described earlier. Instead, it starts a list with these parts:
5143
5144The first part of the list is an expression to read the name of a
5145buffer and return it as a string. That is @code{read-buffer}. The
5146function requires a prompt as its first argument, @samp{"Append to
5147buffer: "}. Its second argument tells the command what value to
5148provide if you don't specify anything.
5149
5150In this case that second argument is an expression containing the
5151function @code{other-buffer}, an exception, and a @samp{t}, standing
5152for true.
5153
5154The first argument to @code{other-buffer}, the exception, is yet
5155another function, @code{current-buffer}. That is not going to be
5156returned. The second argument is the symbol for true, @code{t}. that
5157tells @code{other-buffer} that it may show visible buffers (except in
5158this case, it will not show the current buffer, which makes sense).
5159
5160@need 1250
5161The expression looks like this:
5162
5163@smallexample
5164(other-buffer (current-buffer) t)
5165@end smallexample
5166
5167The second and third arguments to the @code{list} expression are
5168@code{(region-beginning)} and @code{(region-end)}. These two
5169functions specify the beginning and end of the text to be appended.
5170
5171@need 1250
5172Originally, the command used the letters @samp{B} and @samp{r}.
5173The whole @code{interactive} expression looked like this:
5174
5175@smallexample
5176(interactive "BAppend to buffer:@: \nr")
5177@end smallexample
5178
5179@noindent
5180But when that was done, the default value of the buffer switched to
5181was invisible. That was not wanted.
5182
5183(The prompt was separated from the second argument with a newline,
5184@samp{\n}. It was followed by an @samp{r} that told Emacs to bind the
5185two arguments that follow the symbol @code{buffer} in the function's
5186argument list (that is, @code{start} and @code{end}) to the values of
5187point and mark. That argument worked fine.)
5188
d6adf7e7 5189@node append-to-buffer body
8cda6f8f
GM
5190@subsection The Body of @code{append-to-buffer}
5191
5192@ignore
5193in GNU Emacs 22 in /usr/local/src/emacs/lisp/simple.el
5194
5195(defun append-to-buffer (buffer start end)
5196 "Append to specified buffer the text of the region.
5197It is inserted into that buffer before its point.
5198
5199When calling from a program, give three arguments:
5200BUFFER (or buffer name), START and END.
5201START and END specify the portion of the current buffer to be copied."
5202 (interactive
5203 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
5204 (region-beginning) (region-end)))
5205 (let ((oldbuf (current-buffer)))
5206 (save-excursion
5207 (let* ((append-to (get-buffer-create buffer))
5208 (windows (get-buffer-window-list append-to t t))
5209 point)
5210 (set-buffer append-to)
5211 (setq point (point))
5212 (barf-if-buffer-read-only)
5213 (insert-buffer-substring oldbuf start end)
5214 (dolist (window windows)
5215 (when (= (window-point window) point)
5216 (set-window-point window (point))))))))
5217@end ignore
5218
5219The body of the @code{append-to-buffer} function begins with @code{let}.
5220
5221As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5222@code{let} expression is to create and give initial values to one or
5223more variables that will only be used within the body of the
5224@code{let}. This means that such a variable will not be confused with
5225any variable of the same name outside the @code{let} expression.
5226
5227We can see how the @code{let} expression fits into the function as a
5228whole by showing a template for @code{append-to-buffer} with the
5229@code{let} expression in outline:
5230
5231@smallexample
5232@group
5233(defun append-to-buffer (buffer start end)
5234 "@var{documentation}@dots{}"
5235 (interactive @dots{})
5236 (let ((@var{variable} @var{value}))
5237 @var{body}@dots{})
5238@end group
5239@end smallexample
5240
5241The @code{let} expression has three elements:
5242
5243@enumerate
5244@item
5245The symbol @code{let};
5246
5247@item
5248A varlist containing, in this case, a single two-element list,
5249@code{(@var{variable} @var{value})};
5250
5251@item
5252The body of the @code{let} expression.
5253@end enumerate
5254
5255@need 800
5256In the @code{append-to-buffer} function, the varlist looks like this:
5257
5258@smallexample
5259(oldbuf (current-buffer))
5260@end smallexample
5261
5262@noindent
5263In this part of the @code{let} expression, the one variable,
5264@code{oldbuf}, is bound to the value returned by the
5265@code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5266used to keep track of the buffer in which you are working and from
5267which you will copy.
5268
5269The element or elements of a varlist are surrounded by a set of
5270parentheses so the Lisp interpreter can distinguish the varlist from
5271the body of the @code{let}. As a consequence, the two-element list
5272within the varlist is surrounded by a circumscribing set of parentheses.
5273The line looks like this:
5274
5275@smallexample
5276@group
5277(let ((oldbuf (current-buffer)))
5278 @dots{} )
5279@end group
5280@end smallexample
5281
5282@noindent
5283The two parentheses before @code{oldbuf} might surprise you if you did
5284not realize that the first parenthesis before @code{oldbuf} marks the
5285boundary of the varlist and the second parenthesis marks the beginning
5286of the two-element list, @code{(oldbuf (current-buffer))}.
5287
d6adf7e7 5288@node append save-excursion
8cda6f8f
GM
5289@subsection @code{save-excursion} in @code{append-to-buffer}
5290
5291The body of the @code{let} expression in @code{append-to-buffer}
5292consists of a @code{save-excursion} expression.
5293
5294The @code{save-excursion} function saves the locations of point and
5295mark, and restores them to those positions after the expressions in the
5296body of the @code{save-excursion} complete execution. In addition,
5297@code{save-excursion} keeps track of the original buffer, and
5298restores it. This is how @code{save-excursion} is used in
5299@code{append-to-buffer}.
5300
5301@need 1500
5302@cindex Indentation for formatting
5303@cindex Formatting convention
5304Incidentally, it is worth noting here that a Lisp function is normally
5305formatted so that everything that is enclosed in a multi-line spread is
5306indented more to the right than the first symbol. In this function
5307definition, the @code{let} is indented more than the @code{defun}, and
5308the @code{save-excursion} is indented more than the @code{let}, like
5309this:
5310
5311@smallexample
5312@group
5313(defun @dots{}
5314 @dots{}
5315 @dots{}
5316 (let@dots{}
5317 (save-excursion
5318 @dots{}
5319@end group
5320@end smallexample
5321
5322@need 1500
5323@noindent
5324This formatting convention makes it easy to see that the lines in
5325the body of the @code{save-excursion} are enclosed by the parentheses
5326associated with @code{save-excursion}, just as the
5327@code{save-excursion} itself is enclosed by the parentheses associated
5328with the @code{let}:
5329
5330@smallexample
5331@group
5332(let ((oldbuf (current-buffer)))
5333 (save-excursion
5334 @dots{}
5335 (set-buffer @dots{})
5336 (insert-buffer-substring oldbuf start end)
5337 @dots{}))
5338@end group
5339@end smallexample
5340
5341@need 1200
5342The use of the @code{save-excursion} function can be viewed as a process
5343of filling in the slots of a template:
5344
5345@smallexample
5346@group
5347(save-excursion
5348 @var{first-expression-in-body}
5349 @var{second-expression-in-body}
5350 @dots{}
5351 @var{last-expression-in-body})
5352@end group
5353@end smallexample
5354
5355@need 1200
5356@noindent
5357In this function, the body of the @code{save-excursion} contains only
5358one expression, the @code{let*} expression. You know about a
5359@code{let} function. The @code{let*} function is different. It has a
5360@samp{*} in its name. It enables Emacs to set each variable in its
5361varlist in sequence, one after another.
5362
5363Its critical feature is that variables later in the varlist can make
5364use of the values to which Emacs set variables earlier in the varlist.
5365@xref{fwd-para let, , The @code{let*} expression}.
5366
5367We will skip functions like @code{let*} and focus on two: the
5368@code{set-buffer} function and the @code{insert-buffer-substring}
5369function.
5370
5371@need 1250
5372In the old days, the @code{set-buffer} expression was simply
5373
5374@smallexample
5375(set-buffer (get-buffer-create buffer))
5376@end smallexample
5377
5378@need 1250
5379@noindent
5380but now it is
5381
5382@smallexample
5383(set-buffer append-to)
5384@end smallexample
5385
5386@noindent
5387@code{append-to} is bound to @code{(get-buffer-create buffer)} earlier
5388on in the @code{let*} expression. That extra binding would not be
5389necessary except for that @code{append-to} is used later in the
5390varlist as an argument to @code{get-buffer-window-list}.
5391
5392@ignore
5393in GNU Emacs 22
5394
5395 (let ((oldbuf (current-buffer)))
5396 (save-excursion
5397 (let* ((append-to (get-buffer-create buffer))
5398 (windows (get-buffer-window-list append-to t t))
5399 point)
5400 (set-buffer append-to)
5401 (setq point (point))
5402 (barf-if-buffer-read-only)
5403 (insert-buffer-substring oldbuf start end)
5404 (dolist (window windows)
5405 (when (= (window-point window) point)
5406 (set-window-point window (point))))))))
5407@end ignore
5408
5409The @code{append-to-buffer} function definition inserts text from the
5410buffer in which you are currently to a named buffer. It happens that
5411@code{insert-buffer-substring} copies text from another buffer to the
5412current buffer, just the reverse---that is why the
5413@code{append-to-buffer} definition starts out with a @code{let} that
5414binds the local symbol @code{oldbuf} to the value returned by
5415@code{current-buffer}.
5416
5417@need 1250
5418The @code{insert-buffer-substring} expression looks like this:
5419
5420@smallexample
5421(insert-buffer-substring oldbuf start end)
5422@end smallexample
5423
5424@noindent
5425The @code{insert-buffer-substring} function copies a string
5426@emph{from} the buffer specified as its first argument and inserts the
5427string into the present buffer. In this case, the argument to
5428@code{insert-buffer-substring} is the value of the variable created
5429and bound by the @code{let}, namely the value of @code{oldbuf}, which
5430was the current buffer when you gave the @code{append-to-buffer}
5431command.
5432
5433After @code{insert-buffer-substring} has done its work,
5434@code{save-excursion} will restore the action to the original buffer
5435and @code{append-to-buffer} will have done its job.
5436
5437@need 800
5438Written in skeletal form, the workings of the body look like this:
5439
5440@smallexample
5441@group
5442(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5443 (save-excursion ; @r{Keep track of buffer.}
5444 @var{change-buffer}
5445 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5446
5447 @var{change-back-to-original-buffer-when-finished}
5448@var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5449@end group
5450@end smallexample
5451
5452In summary, @code{append-to-buffer} works as follows: it saves the
5453value of the current buffer in the variable called @code{oldbuf}. It
44e97401 5454gets the new buffer (creating one if need be) and switches Emacs's
8cda6f8f
GM
5455attention to it. Using the value of @code{oldbuf}, it inserts the
5456region of text from the old buffer into the new buffer; and then using
5457@code{save-excursion}, it brings you back to your original buffer.
5458
5459In looking at @code{append-to-buffer}, you have explored a fairly
5460complex function. It shows how to use @code{let} and
5461@code{save-excursion}, and how to change to and come back from another
5462buffer. Many function definitions use @code{let},
5463@code{save-excursion}, and @code{set-buffer} this way.
5464
d6adf7e7 5465@node Buffer Related Review
8cda6f8f
GM
5466@section Review
5467
5468Here is a brief summary of the various functions discussed in this chapter.
5469
5470@table @code
5471@item describe-function
5472@itemx describe-variable
5473Print the documentation for a function or variable.
5474Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5475
5476@item find-tag
5477Find the file containing the source for a function or variable and
5478switch buffers to it, positioning point at the beginning of the item.
5479Conventionally bound to @kbd{M-.} (that's a period following the
5480@key{META} key).
5481
5482@item save-excursion
5483Save the location of point and mark and restore their values after the
5484arguments to @code{save-excursion} have been evaluated. Also, remember
5485the current buffer and return to it.
5486
5487@item push-mark
5488Set mark at a location and record the value of the previous mark on the
5489mark ring. The mark is a location in the buffer that will keep its
5490relative position even if text is added to or removed from the buffer.
5491
5492@item goto-char
5493Set point to the location specified by the value of the argument, which
5494can be a number, a marker, or an expression that returns the number of
5495a position, such as @code{(point-min)}.
5496
5497@item insert-buffer-substring
5498Copy a region of text from a buffer that is passed to the function as
5499an argument and insert the region into the current buffer.
5500
5501@item mark-whole-buffer
5502Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5503
5504@item set-buffer
5505Switch the attention of Emacs to another buffer, but do not change the
5506window being displayed. Used when the program rather than a human is
5507to work on a different buffer.
5508
5509@item get-buffer-create
5510@itemx get-buffer
5511Find a named buffer or create one if a buffer of that name does not
5512exist. The @code{get-buffer} function returns @code{nil} if the named
5513buffer does not exist.
5514@end table
5515
5516@need 1500
d6adf7e7 5517@node Buffer Exercises
8cda6f8f
GM
5518@section Exercises
5519
5520@itemize @bullet
5521@item
5522Write your own @code{simplified-end-of-buffer} function definition;
5523then test it to see whether it works.
5524
5525@item
5526Use @code{if} and @code{get-buffer} to write a function that prints a
5527message telling you whether a buffer exists.
5528
5529@item
5530Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5531function.
5532@end itemize
5533
d6adf7e7 5534@node More Complex
8cda6f8f
GM
5535@chapter A Few More Complex Functions
5536
5537In this chapter, we build on what we have learned in previous chapters
5538by looking at more complex functions. The @code{copy-to-buffer}
5539function illustrates use of two @code{save-excursion} expressions in
5540one definition, while the @code{insert-buffer} function illustrates
5541use of an asterisk in an @code{interactive} expression, use of
5542@code{or}, and the important distinction between a name and the object
5543to which the name refers.
5544
5545@menu
5546* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5547* insert-buffer:: Read-only, and with @code{or}.
5548* beginning-of-buffer:: Shows @code{goto-char},
5549 @code{point-min}, and @code{push-mark}.
5550* Second Buffer Related Review::
5551* optional Exercise::
5552@end menu
5553
d6adf7e7 5554@node copy-to-buffer
8cda6f8f
GM
5555@section The Definition of @code{copy-to-buffer}
5556@findex copy-to-buffer
5557
5558After understanding how @code{append-to-buffer} works, it is easy to
5559understand @code{copy-to-buffer}. This function copies text into a
5560buffer, but instead of adding to the second buffer, it replaces all the
5561previous text in the second buffer.
5562
5563@need 800
5564The body of @code{copy-to-buffer} looks like this,
5565
5566@smallexample
5567@group
5568@dots{}
5569(interactive "BCopy to buffer: \nr")
5570(let ((oldbuf (current-buffer)))
5571 (with-current-buffer (get-buffer-create buffer)
5572 (barf-if-buffer-read-only)
5573 (erase-buffer)
5574 (save-excursion
5575 (insert-buffer-substring oldbuf start end)))))
5576@end group
5577@end smallexample
5578
5579The @code{copy-to-buffer} function has a simpler @code{interactive}
5580expression than @code{append-to-buffer}.
5581
5582@need 800
5583The definition then says
5584
5585@smallexample
5586(with-current-buffer (get-buffer-create buffer) @dots{}
5587@end smallexample
5588
5589First, look at the earliest inner expression; that is evaluated first.
5590That expression starts with @code{get-buffer-create buffer}. The
5591function tells the computer to use the buffer with the name specified
5592as the one to which you are copying, or if such a buffer does not
5593exist, to create it. Then, the @code{with-current-buffer} function
5594evaluates its body with that buffer temporarily current.
5595
5596(This demonstrates another way to shift the computer's attention but
5597not the user's. The @code{append-to-buffer} function showed how to do
5598the same with @code{save-excursion} and @code{set-buffer}.
5599@code{with-current-buffer} is a newer, and arguably easier,
5600mechanism.)
5601
5602The @code{barf-if-buffer-read-only} function sends you an error
5603message saying the buffer is read-only if you cannot modify it.
5604
5605The next line has the @code{erase-buffer} function as its sole
5606contents. That function erases the buffer.
5607
5608Finally, the last two lines contain the @code{save-excursion}
5609expression with @code{insert-buffer-substring} as its body.
5610The @code{insert-buffer-substring} expression copies the text from
5611the buffer you are in (and you have not seen the computer shift its
5612attention, so you don't know that that buffer is now called
5613@code{oldbuf}).
5614
5615Incidentally, this is what is meant by `replacement'. To replace text,
5616Emacs erases the previous text and then inserts new text.
5617
5618@need 1250
5619In outline, the body of @code{copy-to-buffer} looks like this:
5620
5621@smallexample
5622@group
5623(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5624 (@var{with-the-buffer-you-are-copying-to}
5625 (@var{but-do-not-erase-or-copy-to-a-read-only-buffer})
5626 (erase-buffer)
5627 (save-excursion
5628 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5629@end group
5630@end smallexample
5631
d6adf7e7 5632@node insert-buffer
8cda6f8f
GM
5633@section The Definition of @code{insert-buffer}
5634@findex insert-buffer
5635
5636@code{insert-buffer} is yet another buffer-related function. This
5637command copies another buffer @emph{into} the current buffer. It is the
5638reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5639copy a region of text @emph{from} the current buffer to another buffer.
5640
5641Here is a discussion based on the original code. The code was
5642simplified in 2003 and is harder to understand.
5643
5644(@xref{New insert-buffer, , New Body for @code{insert-buffer}}, to see
5645a discussion of the new body.)
5646
5647In addition, this code illustrates the use of @code{interactive} with a
5648buffer that might be @dfn{read-only} and the important distinction
5649between the name of an object and the object actually referred to.
5650
5651@menu
5652* insert-buffer code::
5653* insert-buffer interactive:: When you can read, but not write.
5654* insert-buffer body:: The body has an @code{or} and a @code{let}.
5655* if & or:: Using an @code{if} instead of an @code{or}.
5656* Insert or:: How the @code{or} expression works.
5657* Insert let:: Two @code{save-excursion} expressions.
5658* New insert-buffer::
5659@end menu
5660
8cda6f8f 5661@ifnottex
d6adf7e7 5662@node insert-buffer code
8cda6f8f
GM
5663@unnumberedsubsec The Code for @code{insert-buffer}
5664@end ifnottex
5665
5666@need 800
5667Here is the earlier code:
5668
5669@smallexample
5670@group
5671(defun insert-buffer (buffer)
5672 "Insert after point the contents of BUFFER.
5673Puts mark after the inserted text.
5674BUFFER may be a buffer or a buffer name."
5675 (interactive "*bInsert buffer:@: ")
5676@end group
5677@group
5678 (or (bufferp buffer)
5679 (setq buffer (get-buffer buffer)))
5680 (let (start end newmark)
5681 (save-excursion
5682 (save-excursion
5683 (set-buffer buffer)
5684 (setq start (point-min) end (point-max)))
5685@end group
5686@group
5687 (insert-buffer-substring buffer start end)
5688 (setq newmark (point)))
5689 (push-mark newmark)))
5690@end group
5691@end smallexample
5692
5693@need 1200
5694As with other function definitions, you can use a template to see an
5695outline of the function:
5696
5697@smallexample
5698@group
5699(defun insert-buffer (buffer)
5700 "@var{documentation}@dots{}"
5701 (interactive "*bInsert buffer:@: ")
5702 @var{body}@dots{})
5703@end group
5704@end smallexample
5705
d6adf7e7 5706@node insert-buffer interactive
8cda6f8f
GM
5707@subsection The Interactive Expression in @code{insert-buffer}
5708@findex interactive, @r{example use of}
5709
5710In @code{insert-buffer}, the argument to the @code{interactive}
5711declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5712buffer:@: }.
5713
5714@menu
5715* Read-only buffer:: When a buffer cannot be modified.
5716* b for interactive:: An existing buffer or else its name.
5717@end menu
5718
d6adf7e7 5719@node Read-only buffer
8cda6f8f
GM
5720@unnumberedsubsubsec A Read-only Buffer
5721@cindex Read-only buffer
5722@cindex Asterisk for read-only buffer
5723@findex * @r{for read-only buffer}
5724
5725The asterisk is for the situation when the current buffer is a
5726read-only buffer---a buffer that cannot be modified. If
5727@code{insert-buffer} is called when the current buffer is read-only, a
5728message to this effect is printed in the echo area and the terminal
5729may beep or blink at you; you will not be permitted to insert anything
5730into current buffer. The asterisk does not need to be followed by a
5731newline to separate it from the next argument.
5732
d6adf7e7 5733@node b for interactive
8cda6f8f
GM
5734@unnumberedsubsubsec @samp{b} in an Interactive Expression
5735
5736The next argument in the interactive expression starts with a lower
5737case @samp{b}. (This is different from the code for
5738@code{append-to-buffer}, which uses an upper-case @samp{B}.
5739@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5740The lower-case @samp{b} tells the Lisp interpreter that the argument
5741for @code{insert-buffer} should be an existing buffer or else its
5742name. (The upper-case @samp{B} option provides for the possibility
5743that the buffer does not exist.) Emacs will prompt you for the name
5744of the buffer, offering you a default buffer, with name completion
5745enabled. If the buffer does not exist, you receive a message that
5746says ``No match''; your terminal may beep at you as well.
5747
5748The new and simplified code generates a list for @code{interactive}.
5749It uses the @code{barf-if-buffer-read-only} and @code{read-buffer}
5750functions with which we are already familiar and the @code{progn}
5751special form with which we are not. (It will be described later.)
5752
d6adf7e7 5753@node insert-buffer body
8cda6f8f
GM
5754@subsection The Body of the @code{insert-buffer} Function
5755
5756The body of the @code{insert-buffer} function has two major parts: an
5757@code{or} expression and a @code{let} expression. The purpose of the
5758@code{or} expression is to ensure that the argument @code{buffer} is
5759bound to a buffer and not just the name of a buffer. The body of the
5760@code{let} expression contains the code which copies the other buffer
5761into the current buffer.
5762
5763@need 1250
5764In outline, the two expressions fit into the @code{insert-buffer}
5765function like this:
5766
5767@smallexample
5768@group
5769(defun insert-buffer (buffer)
5770 "@var{documentation}@dots{}"
5771 (interactive "*bInsert buffer:@: ")
5772 (or @dots{}
5773 @dots{}
5774@end group
5775@group
5776 (let (@var{varlist})
5777 @var{body-of-}@code{let}@dots{} )
5778@end group
5779@end smallexample
5780
5781To understand how the @code{or} expression ensures that the argument
5782@code{buffer} is bound to a buffer and not to the name of a buffer, it
5783is first necessary to understand the @code{or} function.
5784
5785Before doing this, let me rewrite this part of the function using
5786@code{if} so that you can see what is done in a manner that will be familiar.
5787
d6adf7e7 5788@node if & or
8cda6f8f
GM
5789@subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5790
5791The job to be done is to make sure the value of @code{buffer} is a
5792buffer itself and not the name of a buffer. If the value is the name,
5793then the buffer itself must be got.
5794
5795You can imagine yourself at a conference where an usher is wandering
5796around holding a list with your name on it and looking for you: the
5797usher is ``bound'' to your name, not to you; but when the usher finds
5798you and takes your arm, the usher becomes ``bound'' to you.
5799
5800@need 800
5801In Lisp, you might describe this situation like this:
5802
5803@smallexample
5804@group
5805(if (not (holding-on-to-guest))
5806 (find-and-take-arm-of-guest))
5807@end group
5808@end smallexample
5809
5810We want to do the same thing with a buffer---if we do not have the
5811buffer itself, we want to get it.
5812
5813@need 1200
5814Using a predicate called @code{bufferp} that tells us whether we have a
5815buffer (rather than its name), we can write the code like this:
5816
5817@smallexample
5818@group
5819(if (not (bufferp buffer)) ; @r{if-part}
5820 (setq buffer (get-buffer buffer))) ; @r{then-part}
5821@end group
5822@end smallexample
5823
5824@noindent
5825Here, the true-or-false-test of the @code{if} expression is
5826@w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5827@w{@code{(setq buffer (get-buffer buffer))}}.
5828
5829In the test, the function @code{bufferp} returns true if its argument is
5830a buffer---but false if its argument is the name of the buffer. (The
5831last character of the function name @code{bufferp} is the character
5832@samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5833indicates that the function is a predicate, which is a term that means
5834that the function will determine whether some property is true or false.
5835@xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5836Argument}.)
5837
5838@need 1200
5839The function @code{not} precedes the expression @code{(bufferp buffer)},
5840so the true-or-false-test looks like this:
5841
5842@smallexample
5843(not (bufferp buffer))
5844@end smallexample
5845
5846@noindent
5847@code{not} is a function that returns true if its argument is false
5848and false if its argument is true. So if @code{(bufferp buffer)}
5849returns true, the @code{not} expression returns false and vice-verse:
5850what is ``not true'' is false and what is ``not false'' is true.
5851
5852Using this test, the @code{if} expression works as follows: when the
5853value of the variable @code{buffer} is actually a buffer rather than
5854its name, the true-or-false-test returns false and the @code{if}
5855expression does not evaluate the then-part. This is fine, since we do
5856not need to do anything to the variable @code{buffer} if it really is
5857a buffer.
5858
5859On the other hand, when the value of @code{buffer} is not a buffer
5860itself, but the name of a buffer, the true-or-false-test returns true
5861and the then-part of the expression is evaluated. In this case, the
5862then-part is @code{(setq buffer (get-buffer buffer))}. This
5863expression uses the @code{get-buffer} function to return an actual
5864buffer itself, given its name. The @code{setq} then sets the variable
5865@code{buffer} to the value of the buffer itself, replacing its previous
5866value (which was the name of the buffer).
5867
d6adf7e7 5868@node Insert or
8cda6f8f
GM
5869@subsection The @code{or} in the Body
5870
5871The purpose of the @code{or} expression in the @code{insert-buffer}
5872function is to ensure that the argument @code{buffer} is bound to a
5873buffer and not just to the name of a buffer. The previous section shows
5874how the job could have been done using an @code{if} expression.
5875However, the @code{insert-buffer} function actually uses @code{or}.
5876To understand this, it is necessary to understand how @code{or} works.
5877
5878@findex or
5879An @code{or} function can have any number of arguments. It evaluates
5880each argument in turn and returns the value of the first of its
5881arguments that is not @code{nil}. Also, and this is a crucial feature
5882of @code{or}, it does not evaluate any subsequent arguments after
5883returning the first non-@code{nil} value.
5884
5885@need 800
5886The @code{or} expression looks like this:
5887
5888@smallexample
5889@group
5890(or (bufferp buffer)
5891 (setq buffer (get-buffer buffer)))
5892@end group
5893@end smallexample
5894
5895@noindent
5896The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5897This expression returns true (a non-@code{nil} value) if the buffer is
5898actually a buffer, and not just the name of a buffer. In the @code{or}
5899expression, if this is the case, the @code{or} expression returns this
5900true value and does not evaluate the next expression---and this is fine
5901with us, since we do not want to do anything to the value of
5902@code{buffer} if it really is a buffer.
5903
5904On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5905which it will be if the value of @code{buffer} is the name of a buffer,
5906the Lisp interpreter evaluates the next element of the @code{or}
5907expression. This is the expression @code{(setq buffer (get-buffer
5908buffer))}. This expression returns a non-@code{nil} value, which
5909is the value to which it sets the variable @code{buffer}---and this
5910value is a buffer itself, not the name of a buffer.
5911
5912The result of all this is that the symbol @code{buffer} is always
5913bound to a buffer itself rather than to the name of a buffer. All
5914this is necessary because the @code{set-buffer} function in a
5915following line only works with a buffer itself, not with the name to a
5916buffer.
5917
5918@need 1250
5919Incidentally, using @code{or}, the situation with the usher would be
5920written like this:
5921
5922@smallexample
5923(or (holding-on-to-guest) (find-and-take-arm-of-guest))
5924@end smallexample
5925
d6adf7e7 5926@node Insert let
8cda6f8f
GM
5927@subsection The @code{let} Expression in @code{insert-buffer}
5928
5929After ensuring that the variable @code{buffer} refers to a buffer itself
5930and not just to the name of a buffer, the @code{insert-buffer function}
5931continues with a @code{let} expression. This specifies three local
5932variables, @code{start}, @code{end}, and @code{newmark} and binds them
5933to the initial value @code{nil}. These variables are used inside the
5934remainder of the @code{let} and temporarily hide any other occurrence of
5935variables of the same name in Emacs until the end of the @code{let}.
5936
5937@need 1200
5938The body of the @code{let} contains two @code{save-excursion}
5939expressions. First, we will look at the inner @code{save-excursion}
5940expression in detail. The expression looks like this:
5941
5942@smallexample
5943@group
5944(save-excursion
5945 (set-buffer buffer)
5946 (setq start (point-min) end (point-max)))
5947@end group
5948@end smallexample
5949
5950@noindent
44e97401 5951The expression @code{(set-buffer buffer)} changes Emacs's attention
8cda6f8f
GM
5952from the current buffer to the one from which the text will copied.
5953In that buffer, the variables @code{start} and @code{end} are set to
5954the beginning and end of the buffer, using the commands
5955@code{point-min} and @code{point-max}. Note that we have here an
5956illustration of how @code{setq} is able to set two variables in the
5957same expression. The first argument of @code{setq} is set to the
5958value of its second, and its third argument is set to the value of its
5959fourth.
5960
5961After the body of the inner @code{save-excursion} is evaluated, the
5962@code{save-excursion} restores the original buffer, but @code{start} and
5963@code{end} remain set to the values of the beginning and end of the
5964buffer from which the text will be copied.
5965
5966@need 1250
5967The outer @code{save-excursion} expression looks like this:
5968
5969@smallexample
5970@group
5971(save-excursion
5972 (@var{inner-}@code{save-excursion}@var{-expression}
5973 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5974 (insert-buffer-substring buffer start end)
5975 (setq newmark (point)))
5976@end group
5977@end smallexample
5978
5979@noindent
5980The @code{insert-buffer-substring} function copies the text
5981@emph{into} the current buffer @emph{from} the region indicated by
5982@code{start} and @code{end} in @code{buffer}. Since the whole of the
5983second buffer lies between @code{start} and @code{end}, the whole of
5984the second buffer is copied into the buffer you are editing. Next,
5985the value of point, which will be at the end of the inserted text, is
5986recorded in the variable @code{newmark}.
5987
5988After the body of the outer @code{save-excursion} is evaluated, point
5989and mark are relocated to their original places.
5990
5991However, it is convenient to locate a mark at the end of the newly
5992inserted text and locate point at its beginning. The @code{newmark}
5993variable records the end of the inserted text. In the last line of
5994the @code{let} expression, the @code{(push-mark newmark)} expression
5995function sets a mark to this location. (The previous location of the
5996mark is still accessible; it is recorded on the mark ring and you can
5997go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5998located at the beginning of the inserted text, which is where it was
5999before you called the insert function, the position of which was saved
6000by the first @code{save-excursion}.
6001
6002@need 1250
6003The whole @code{let} expression looks like this:
6004
6005@smallexample
6006@group
6007(let (start end newmark)
6008 (save-excursion
6009 (save-excursion
6010 (set-buffer buffer)
6011 (setq start (point-min) end (point-max)))
6012 (insert-buffer-substring buffer start end)
6013 (setq newmark (point)))
6014 (push-mark newmark))
6015@end group
6016@end smallexample
6017
6018Like the @code{append-to-buffer} function, the @code{insert-buffer}
6019function uses @code{let}, @code{save-excursion}, and
6020@code{set-buffer}. In addition, the function illustrates one way to
6021use @code{or}. All these functions are building blocks that we will
6022find and use again and again.
6023
d6adf7e7 6024@node New insert-buffer
8cda6f8f
GM
6025@subsection New Body for @code{insert-buffer}
6026@findex insert-buffer, new version body
6027@findex new version body for insert-buffer
6028
6029The body in the GNU Emacs 22 version is more confusing than the original.
6030
6031@need 1250
6032It consists of two expressions,
6033
6034@smallexample
6035@group
6036 (push-mark
6037 (save-excursion
6038 (insert-buffer-substring (get-buffer buffer))
6039 (point)))
6040
6041 nil
6042@end group
6043@end smallexample
6044
6045@noindent
6046except, and this is what confuses novices, very important work is done
6047inside the @code{push-mark} expression.
6048
6049The @code{get-buffer} function returns a buffer with the name
6050provided. You will note that the function is @emph{not} called
6051@code{get-buffer-create}; it does not create a buffer if one does not
6052already exist. The buffer returned by @code{get-buffer}, an existing
6053buffer, is passed to @code{insert-buffer-substring}, which inserts the
6054whole of the buffer (since you did not specify anything else).
6055
6056The location into which the buffer is inserted is recorded by
6057@code{push-mark}. Then the function returns @code{nil}, the value of
6058its last command. Put another way, the @code{insert-buffer} function
6059exists only to produce a side effect, inserting another buffer, not to
6060return any value.
6061
d6adf7e7 6062@node beginning-of-buffer
8cda6f8f
GM
6063@section Complete Definition of @code{beginning-of-buffer}
6064@findex beginning-of-buffer
6065
6066The basic structure of the @code{beginning-of-buffer} function has
6067already been discussed. (@xref{simplified-beginning-of-buffer, , A
6068Simplified @code{beginning-of-buffer} Definition}.)
6069This section describes the complex part of the definition.
6070
6071As previously described, when invoked without an argument,
6072@code{beginning-of-buffer} moves the cursor to the beginning of the
6073buffer (in truth, the beginning of the accessible portion of the
6074buffer), leaving the mark at the previous position. However, when the
6075command is invoked with a number between one and ten, the function
6076considers that number to be a fraction of the length of the buffer,
6077measured in tenths, and Emacs moves the cursor that fraction of the
6078way from the beginning of the buffer. Thus, you can either call this
6079function with the key command @kbd{M-<}, which will move the cursor to
6080the beginning of the buffer, or with a key command such as @kbd{C-u 7
6081M-<} which will move the cursor to a point 70% of the way through the
6082buffer. If a number bigger than ten is used for the argument, it
6083moves to the end of the buffer.
6084
6085The @code{beginning-of-buffer} function can be called with or without an
6086argument. The use of the argument is optional.
6087
6088@menu
6089* Optional Arguments::
6090* beginning-of-buffer opt arg:: Example with optional argument.
6091* beginning-of-buffer complete::
6092@end menu
6093
d6adf7e7 6094@node Optional Arguments
8cda6f8f
GM
6095@subsection Optional Arguments
6096
6097Unless told otherwise, Lisp expects that a function with an argument in
6098its function definition will be called with a value for that argument.
6099If that does not happen, you get an error and a message that says
6100@samp{Wrong number of arguments}.
6101
6102@cindex Optional arguments
6103@cindex Keyword
6104@findex optional
6105However, optional arguments are a feature of Lisp: a particular
6106@dfn{keyword} is used to tell the Lisp interpreter that an argument is
6107optional. The keyword is @code{&optional}. (The @samp{&} in front of
6108@samp{optional} is part of the keyword.) In a function definition, if
6109an argument follows the keyword @code{&optional}, no value need be
6110passed to that argument when the function is called.
6111
6112@need 1200
6113The first line of the function definition of @code{beginning-of-buffer}
6114therefore looks like this:
6115
6116@smallexample
6117(defun beginning-of-buffer (&optional arg)
6118@end smallexample
6119
6120@need 1250
6121In outline, the whole function looks like this:
6122
6123@smallexample
6124@group
6125(defun beginning-of-buffer (&optional arg)
6126 "@var{documentation}@dots{}"
6127 (interactive "P")
6128 (or (@var{is-the-argument-a-cons-cell} arg)
6129 (and @var{are-both-transient-mark-mode-and-mark-active-true})
6130 (push-mark))
6131 (let (@var{determine-size-and-set-it})
6132 (goto-char
6133 (@var{if-there-is-an-argument}
6134 @var{figure-out-where-to-go}
6135 @var{else-go-to}
6136 (point-min))))
6137 @var{do-nicety}
6138@end group
6139@end smallexample
6140
6141The function is similar to the @code{simplified-beginning-of-buffer}
6142function except that the @code{interactive} expression has @code{"P"}
6143as an argument and the @code{goto-char} function is followed by an
6144if-then-else expression that figures out where to put the cursor if
6145there is an argument that is not a cons cell.
6146
6147(Since I do not explain a cons cell for many more chapters, please
6148consider ignoring the function @code{consp}. @xref{List
6149Implementation, , How Lists are Implemented}, and @ref{Cons Cell Type,
6150, Cons Cell and List Types, elisp, The GNU Emacs Lisp Reference
6151Manual}.)
6152
6153The @code{"P"} in the @code{interactive} expression tells Emacs to
6154pass a prefix argument, if there is one, to the function in raw form.
6155A prefix argument is made by typing the @key{META} key followed by a
6156number, or by typing @kbd{C-u} and then a number. (If you don't type
6157a number, @kbd{C-u} defaults to a cons cell with a 4. A lowercase
6158@code{"p"} in the @code{interactive} expression causes the function to
6159convert a prefix arg to a number.)
6160
6161The true-or-false-test of the @code{if} expression looks complex, but
6162it is not: it checks whether @code{arg} has a value that is not
6163@code{nil} and whether it is a cons cell. (That is what @code{consp}
6164does; it checks whether its argument is a cons cell.) If @code{arg}
6165has a value that is not @code{nil} (and is not a cons cell), which
6166will be the case if @code{beginning-of-buffer} is called with a
6167numeric argument, then this true-or-false-test will return true and
6168the then-part of the @code{if} expression will be evaluated. On the
6169other hand, if @code{beginning-of-buffer} is not called with an
6170argument, the value of @code{arg} will be @code{nil} and the else-part
6171of the @code{if} expression will be evaluated. The else-part is
6172simply @code{point-min}, and when this is the outcome, the whole
6173@code{goto-char} expression is @code{(goto-char (point-min))}, which
6174is how we saw the @code{beginning-of-buffer} function in its
6175simplified form.
6176
d6adf7e7 6177@node beginning-of-buffer opt arg
8cda6f8f
GM
6178@subsection @code{beginning-of-buffer} with an Argument
6179
6180When @code{beginning-of-buffer} is called with an argument, an
6181expression is evaluated which calculates what value to pass to
6182@code{goto-char}. This expression is rather complicated at first sight.
6183It includes an inner @code{if} expression and much arithmetic. It looks
6184like this:
6185
6186@smallexample
6187@group
6188(if (> (buffer-size) 10000)
6189 ;; @r{Avoid overflow for large buffer sizes!}
6190 (* (prefix-numeric-value arg)
6191 (/ size 10))
6192 (/
6193 (+ 10
6194 (*
6195 size (prefix-numeric-value arg))) 10)))
6196@end group
6197@end smallexample
6198
6199@menu
6200* Disentangle beginning-of-buffer::
6201* Large buffer case::
6202* Small buffer case::
6203@end menu
6204
8cda6f8f 6205@ifnottex
d6adf7e7 6206@node Disentangle beginning-of-buffer
8cda6f8f
GM
6207@unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
6208@end ifnottex
6209
6210Like other complex-looking expressions, the conditional expression
6211within @code{beginning-of-buffer} can be disentangled by looking at it
6212as parts of a template, in this case, the template for an if-then-else
6213expression. In skeletal form, the expression looks like this:
6214
6215@smallexample
6216@group
6217(if (@var{buffer-is-large}
6218 @var{divide-buffer-size-by-10-and-multiply-by-arg}
6219 @var{else-use-alternate-calculation}
6220@end group
6221@end smallexample
6222
6223The true-or-false-test of this inner @code{if} expression checks the
6224size of the buffer. The reason for this is that the old version 18
6225Emacs used numbers that are no bigger than eight million or so and in
6226the computation that followed, the programmer feared that Emacs might
6227try to use over-large numbers if the buffer were large. The term
6228`overflow', mentioned in the comment, means numbers that are over
6229large. More recent versions of Emacs use larger numbers, but this
6230code has not been touched, if only because people now look at buffers
6231that are far, far larger than ever before.
6232
6233There are two cases: if the buffer is large and if it is not.
6234
d6adf7e7 6235@node Large buffer case
8cda6f8f
GM
6236@unnumberedsubsubsec What happens in a large buffer
6237
6238In @code{beginning-of-buffer}, the inner @code{if} expression tests
6239whether the size of the buffer is greater than 10,000 characters. To do
6240this, it uses the @code{>} function and the computation of @code{size}
6241that comes from the let expression.
6242
6243In the old days, the function @code{buffer-size} was used. Not only
6244was that function called several times, it gave the size of the whole
6245buffer, not the accessible part. The computation makes much more
6246sense when it handles just the accessible part. (@xref{Narrowing &
6247Widening, , Narrowing and Widening}, for more information on focusing
6248attention to an `accessible' part.)
6249
6250@need 800
6251The line looks like this:
6252
6253@smallexample
6254(if (> size 10000)
6255@end smallexample
6256
6257@need 1200
6258@noindent
6259When the buffer is large, the then-part of the @code{if} expression is
6260evaluated. It reads like this (after formatting for easy reading):
6261
6262@smallexample
6263@group
6264(*
6265 (prefix-numeric-value arg)
6266 (/ size 10))
6267@end group
6268@end smallexample
6269
6270@noindent
6271This expression is a multiplication, with two arguments to the function
6272@code{*}.
6273
6274The first argument is @code{(prefix-numeric-value arg)}. When
6275@code{"P"} is used as the argument for @code{interactive}, the value
6276passed to the function as its argument is passed a ``raw prefix
6277argument'', and not a number. (It is a number in a list.) To perform
6278the arithmetic, a conversion is necessary, and
6279@code{prefix-numeric-value} does the job.
6280
6281@findex / @r{(division)}
6282@cindex Division
6283The second argument is @code{(/ size 10)}. This expression divides
6284the numeric value by ten --- the numeric value of the size of the
6285accessible portion of the buffer. This produces a number that tells
6286how many characters make up one tenth of the buffer size. (In Lisp,
6287@code{/} is used for division, just as @code{*} is used for
6288multiplication.)
6289
6290@need 1200
6291In the multiplication expression as a whole, this amount is multiplied
6292by the value of the prefix argument---the multiplication looks like this:
6293
6294@smallexample
6295@group
6296(* @var{numeric-value-of-prefix-arg}
6297 @var{number-of-characters-in-one-tenth-of-the-accessible-buffer})
6298@end group
6299@end smallexample
6300
6301@noindent
6302If, for example, the prefix argument is @samp{7}, the one-tenth value
6303will be multiplied by 7 to give a position 70% of the way through.
6304
6305@need 1200
6306The result of all this is that if the accessible portion of the buffer
6307is large, the @code{goto-char} expression reads like this:
6308
6309@smallexample
6310@group
6311(goto-char (* (prefix-numeric-value arg)
6312 (/ size 10)))
6313@end group
6314@end smallexample
6315
6316This puts the cursor where we want it.
6317
d6adf7e7 6318@node Small buffer case
8cda6f8f
GM
6319@unnumberedsubsubsec What happens in a small buffer
6320
6321If the buffer contains fewer than 10,000 characters, a slightly
6322different computation is performed. You might think this is not
6323necessary, since the first computation could do the job. However, in
6324a small buffer, the first method may not put the cursor on exactly the
6325desired line; the second method does a better job.
6326
6327@need 800
6328The code looks like this:
6329
6330@c Keep this on one line.
6331@smallexample
6332(/ (+ 10 (* size (prefix-numeric-value arg))) 10))
6333@end smallexample
6334
6335@need 1200
6336@noindent
6337This is code in which you figure out what happens by discovering how the
6338functions are embedded in parentheses. It is easier to read if you
6339reformat it with each expression indented more deeply than its
6340enclosing expression:
6341
6342@smallexample
6343@group
6344 (/
6345 (+ 10
6346 (*
6347 size
6348 (prefix-numeric-value arg)))
6349 10))
6350@end group
6351@end smallexample
6352
6353@need 1200
6354@noindent
6355Looking at parentheses, we see that the innermost operation is
6356@code{(prefix-numeric-value arg)}, which converts the raw argument to
6357a number. In the following expression, this number is multiplied by
6358the size of the accessible portion of the buffer:
6359
6360@smallexample
6361(* size (prefix-numeric-value arg))
6362@end smallexample
6363
6364@noindent
6365This multiplication creates a number that may be larger than the size of
6366the buffer---seven times larger if the argument is 7, for example. Ten
6367is then added to this number and finally the large number is divided by
6368ten to provide a value that is one character larger than the percentage
6369position in the buffer.
6370
6371The number that results from all this is passed to @code{goto-char} and
6372the cursor is moved to that point.
6373
6374@need 1500
d6adf7e7 6375@node beginning-of-buffer complete
8cda6f8f
GM
6376@subsection The Complete @code{beginning-of-buffer}
6377
6378@need 1000
6379Here is the complete text of the @code{beginning-of-buffer} function:
6380@sp 1
6381
6382@c In GNU Emacs 22
6383@smallexample
6384@group
6385(defun beginning-of-buffer (&optional arg)
6386 "Move point to the beginning of the buffer;
6387leave mark at previous position.
6388With \\[universal-argument] prefix,
6389do not set mark at previous position.
6390With numeric arg N,
6391put point N/10 of the way from the beginning.
6392
6393If the buffer is narrowed,
6394this command uses the beginning and size
6395of the accessible part of the buffer.
6396@end group
6397
6398@group
6399Don't use this command in Lisp programs!
6400\(goto-char (point-min)) is faster
6401and avoids clobbering the mark."
6402 (interactive "P")
6403 (or (consp arg)
6404 (and transient-mark-mode mark-active)
6405 (push-mark))
6406@end group
6407@group
6408 (let ((size (- (point-max) (point-min))))
6409 (goto-char (if (and arg (not (consp arg)))
6410 (+ (point-min)
6411 (if (> size 10000)
6412 ;; Avoid overflow for large buffer sizes!
6413 (* (prefix-numeric-value arg)
6414 (/ size 10))
a9097c6d
KB
6415 (/ (+ 10 (* size (prefix-numeric-value arg)))
6416 10)))
8cda6f8f
GM
6417 (point-min))))
6418 (if arg (forward-line 1)))
6419@end group
6420@end smallexample
6421
6422@ignore
6423From before GNU Emacs 22
6424@smallexample
6425@group
6426(defun beginning-of-buffer (&optional arg)
6427 "Move point to the beginning of the buffer;
6428leave mark at previous position.
6429With arg N, put point N/10 of the way
6430from the true beginning.
6431@end group
6432@group
6433Don't use this in Lisp programs!
6434\(goto-char (point-min)) is faster
6435and does not set the mark."
6436 (interactive "P")
6437 (push-mark)
6438@end group
6439@group
6440 (goto-char
6441 (if arg
6442 (if (> (buffer-size) 10000)
6443 ;; @r{Avoid overflow for large buffer sizes!}
6444 (* (prefix-numeric-value arg)
6445 (/ (buffer-size) 10))
6446@end group
6447@group
6448 (/ (+ 10 (* (buffer-size)
6449 (prefix-numeric-value arg)))
6450 10))
6451 (point-min)))
6452 (if arg (forward-line 1)))
6453@end group
6454@end smallexample
6455@end ignore
6456
6457@noindent
6458Except for two small points, the previous discussion shows how this
6459function works. The first point deals with a detail in the
6460documentation string, and the second point concerns the last line of
6461the function.
6462
6463@need 800
6464In the documentation string, there is reference to an expression:
6465
6466@smallexample
6467\\[universal-argument]
6468@end smallexample
6469
6470@noindent
6471A @samp{\\} is used before the first square bracket of this
6472expression. This @samp{\\} tells the Lisp interpreter to substitute
6473whatever key is currently bound to the @samp{[@dots{}]}. In the case
6474of @code{universal-argument}, that is usually @kbd{C-u}, but it might
6475be different. (@xref{Documentation Tips, , Tips for Documentation
6476Strings, elisp, The GNU Emacs Lisp Reference Manual}, for more
6477information.)
6478
6479@need 1200
6480Finally, the last line of the @code{beginning-of-buffer} command says
6481to move point to the beginning of the next line if the command is
6482invoked with an argument:
6483
6484@smallexample
6485(if arg (forward-line 1)))
6486@end smallexample
6487
6488@noindent
6489This puts the cursor at the beginning of the first line after the
6490appropriate tenths position in the buffer. This is a flourish that
6491means that the cursor is always located @emph{at least} the requested
6492tenths of the way through the buffer, which is a nicety that is,
6493perhaps, not necessary, but which, if it did not occur, would be sure
6494to draw complaints.
6495
6496On the other hand, it also means that if you specify the command with
6497a @kbd{C-u}, but without a number, that is to say, if the `raw prefix
6498argument' is simply a cons cell, then the command puts you at the
6499beginning of the second line @dots{} I don't know whether this is
6500intended or whether no one has dealt with the code to avoid this
6501happening.
6502
d6adf7e7 6503@node Second Buffer Related Review
8cda6f8f
GM
6504@section Review
6505
6506Here is a brief summary of some of the topics covered in this chapter.
6507
6508@table @code
6509@item or
6510Evaluate each argument in sequence, and return the value of the first
6511argument that is not @code{nil}; if none return a value that is not
6512@code{nil}, return @code{nil}. In brief, return the first true value
6513of the arguments; return a true value if one @emph{or} any of the
6514others are true.
6515
6516@item and
6517Evaluate each argument in sequence, and if any are @code{nil}, return
6518@code{nil}; if none are @code{nil}, return the value of the last
6519argument. In brief, return a true value only if all the arguments are
6520true; return a true value if one @emph{and} each of the others is
6521true.
6522
6523@item &optional
6524A keyword used to indicate that an argument to a function definition
6525is optional; this means that the function can be evaluated without the
6526argument, if desired.
6527
6528@item prefix-numeric-value
6529Convert the `raw prefix argument' produced by @code{(interactive
6530"P")} to a numeric value.
6531
6532@item forward-line
6533Move point forward to the beginning of the next line, or if the argument
6534is greater than one, forward that many lines. If it can't move as far
6535forward as it is supposed to, @code{forward-line} goes forward as far as
6536it can and then returns a count of the number of additional lines it was
6537supposed to move but couldn't.
6538
6539@item erase-buffer
6540Delete the entire contents of the current buffer.
6541
6542@item bufferp
6543Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6544@end table
6545
d6adf7e7 6546@node optional Exercise
8cda6f8f
GM
6547@section @code{optional} Argument Exercise
6548
6549Write an interactive function with an optional argument that tests
6550whether its argument, a number, is greater than or equal to, or else,
6551less than the value of @code{fill-column}, and tells you which, in a
6552message. However, if you do not pass an argument to the function, use
655356 as a default value.
6554
d6adf7e7 6555@node Narrowing & Widening
8cda6f8f
GM
6556@chapter Narrowing and Widening
6557@cindex Focusing attention (narrowing)
6558@cindex Narrowing
6559@cindex Widening
6560
6561Narrowing is a feature of Emacs that makes it possible for you to focus
6562on a specific part of a buffer, and work without accidentally changing
6563other parts. Narrowing is normally disabled since it can confuse
6564novices.
6565
6566@menu
6567* Narrowing advantages:: The advantages of narrowing
6568* save-restriction:: The @code{save-restriction} special form.
6569* what-line:: The number of the line that point is on.
6570* narrow Exercise::
6571@end menu
6572
8cda6f8f 6573@ifnottex
d6adf7e7 6574@node Narrowing advantages
8cda6f8f
GM
6575@unnumberedsec The Advantages of Narrowing
6576@end ifnottex
6577
6578With narrowing, the rest of a buffer is made invisible, as if it weren't
6579there. This is an advantage if, for example, you want to replace a word
6580in one part of a buffer but not in another: you narrow to the part you want
6581and the replacement is carried out only in that section, not in the rest
6582of the buffer. Searches will only work within a narrowed region, not
6583outside of one, so if you are fixing a part of a document, you can keep
6584yourself from accidentally finding parts you do not need to fix by
6585narrowing just to the region you want.
6586(The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6587
6588However, narrowing does make the rest of the buffer invisible, which
6589can scare people who inadvertently invoke narrowing and think they
6590have deleted a part of their file. Moreover, the @code{undo} command
6591(which is usually bound to @kbd{C-x u}) does not turn off narrowing
6592(nor should it), so people can become quite desperate if they do not
6593know that they can return the rest of a buffer to visibility with the
6594@code{widen} command.
6595(The key binding for @code{widen} is @kbd{C-x n w}.)
6596
6597Narrowing is just as useful to the Lisp interpreter as to a human.
6598Often, an Emacs Lisp function is designed to work on just part of a
6599buffer; or conversely, an Emacs Lisp function needs to work on all of a
6600buffer that has been narrowed. The @code{what-line} function, for
6601example, removes the narrowing from a buffer, if it has any narrowing
6602and when it has finished its job, restores the narrowing to what it was.
7001d579
GZ
6603On the other hand, the @code{count-lines} function
6604uses narrowing to restrict itself to just that portion
8cda6f8f
GM
6605of the buffer in which it is interested and then restores the previous
6606situation.
6607
d6adf7e7 6608@node save-restriction
8cda6f8f
GM
6609@section The @code{save-restriction} Special Form
6610@findex save-restriction
6611
6612In Emacs Lisp, you can use the @code{save-restriction} special form to
6613keep track of whatever narrowing is in effect, if any. When the Lisp
6614interpreter meets with @code{save-restriction}, it executes the code
6615in the body of the @code{save-restriction} expression, and then undoes
6616any changes to narrowing that the code caused. If, for example, the
6617buffer is narrowed and the code that follows @code{save-restriction}
6618gets rid of the narrowing, @code{save-restriction} returns the buffer
6619to its narrowed region afterwards. In the @code{what-line} command,
6620any narrowing the buffer may have is undone by the @code{widen}
6621command that immediately follows the @code{save-restriction} command.
6622Any original narrowing is restored just before the completion of the
6623function.
6624
6625@need 1250
6626The template for a @code{save-restriction} expression is simple:
6627
6628@smallexample
6629@group
6630(save-restriction
6631 @var{body}@dots{} )
6632@end group
6633@end smallexample
6634
6635@noindent
6636The body of the @code{save-restriction} is one or more expressions that
6637will be evaluated in sequence by the Lisp interpreter.
6638
6639Finally, a point to note: when you use both @code{save-excursion} and
6640@code{save-restriction}, one right after the other, you should use
6641@code{save-excursion} outermost. If you write them in reverse order,
6642you may fail to record narrowing in the buffer to which Emacs switches
6643after calling @code{save-excursion}. Thus, when written together,
6644@code{save-excursion} and @code{save-restriction} should be written
6645like this:
6646
6647@smallexample
6648@group
6649(save-excursion
6650 (save-restriction
6651 @var{body}@dots{}))
6652@end group
6653@end smallexample
6654
6655In other circumstances, when not written together, the
6656@code{save-excursion} and @code{save-restriction} special forms must
6657be written in the order appropriate to the function.
6658
6659@need 1250
6660For example,
6661
6662@smallexample
6663@group
6664 (save-restriction
6665 (widen)
6666 (save-excursion
6667 @var{body}@dots{}))
6668@end group
6669@end smallexample
6670
6671@ignore
6672Emacs 22
6673/usr/local/src/emacs/lisp/simple.el
6674
6675(defun what-line ()
6676 "Print the current buffer line number and narrowed line number of point."
6677 (interactive)
6678 (let ((start (point-min))
6679 (n (line-number-at-pos)))
6680 (if (= start 1)
6681 (message "Line %d" n)
6682 (save-excursion
6683 (save-restriction
6684 (widen)
6685 (message "line %d (narrowed line %d)"
6686 (+ n (line-number-at-pos start) -1) n))))))
6687
6688(defun line-number-at-pos (&optional pos)
6689 "Return (narrowed) buffer line number at position POS.
6690If POS is nil, use current buffer location.
6691Counting starts at (point-min), so the value refers
6692to the contents of the accessible portion of the buffer."
6693 (let ((opoint (or pos (point))) start)
6694 (save-excursion
6695 (goto-char (point-min))
6696 (setq start (point))
6697 (goto-char opoint)
6698 (forward-line 0)
6699 (1+ (count-lines start (point))))))
6700
6701(defun count-lines (start end)
6702 "Return number of lines between START and END.
6703This is usually the number of newlines between them,
6704but can be one more if START is not equal to END
6705and the greater of them is not at the start of a line."
6706 (save-excursion
6707 (save-restriction
6708 (narrow-to-region start end)
6709 (goto-char (point-min))
6710 (if (eq selective-display t)
6711 (save-match-data
6712 (let ((done 0))
6713 (while (re-search-forward "[\n\C-m]" nil t 40)
6714 (setq done (+ 40 done)))
6715 (while (re-search-forward "[\n\C-m]" nil t 1)
6716 (setq done (+ 1 done)))
6717 (goto-char (point-max))
6718 (if (and (/= start end)
6719 (not (bolp)))
6720 (1+ done)
6721 done)))
6722 (- (buffer-size) (forward-line (buffer-size)))))))
6723@end ignore
6724
d6adf7e7 6725@node what-line
8cda6f8f
GM
6726@section @code{what-line}
6727@findex what-line
6728@cindex Widening, example of
6729
6730The @code{what-line} command tells you the number of the line in which
6731the cursor is located. The function illustrates the use of the
6732@code{save-restriction} and @code{save-excursion} commands. Here is the
6733original text of the function:
6734
6735@smallexample
6736@group
6737(defun what-line ()
6738 "Print the current line number (in the buffer) of point."
6739 (interactive)
6740 (save-restriction
6741 (widen)
6742 (save-excursion
6743 (beginning-of-line)
6744 (message "Line %d"
6745 (1+ (count-lines 1 (point)))))))
6746@end group
6747@end smallexample
6748
6749(In recent versions of GNU Emacs, the @code{what-line} function has
6750been expanded to tell you your line number in a narrowed buffer as
6751well as your line number in a widened buffer. The recent version is
6752more complex than the version shown here. If you feel adventurous,
6753you might want to look at it after figuring out how this version
6754works. You will probably need to use @kbd{C-h f}
6755(@code{describe-function}). The newer version uses a conditional to
6756determine whether the buffer has been narrowed.
6757
6758(Also, it uses @code{line-number-at-pos}, which among other simple
6759expressions, such as @code{(goto-char (point-min))}, moves point to
6760the beginning of the current line with @code{(forward-line 0)} rather
6761than @code{beginning-of-line}.)
6762
6763The @code{what-line} function as shown here has a documentation line
6764and is interactive, as you would expect. The next two lines use the
6765functions @code{save-restriction} and @code{widen}.
6766
6767The @code{save-restriction} special form notes whatever narrowing is in
6768effect, if any, in the current buffer and restores that narrowing after
6769the code in the body of the @code{save-restriction} has been evaluated.
6770
6771The @code{save-restriction} special form is followed by @code{widen}.
6772This function undoes any narrowing the current buffer may have had
6773when @code{what-line} was called. (The narrowing that was there is
6774the narrowing that @code{save-restriction} remembers.) This widening
6775makes it possible for the line counting commands to count from the
6776beginning of the buffer. Otherwise, they would have been limited to
6777counting within the accessible region. Any original narrowing is
6778restored just before the completion of the function by the
6779@code{save-restriction} special form.
6780
6781The call to @code{widen} is followed by @code{save-excursion}, which
6782saves the location of the cursor (i.e., of point) and of the mark, and
6783restores them after the code in the body of the @code{save-excursion}
6784uses the @code{beginning-of-line} function to move point.
6785
6786(Note that the @code{(widen)} expression comes between the
6787@code{save-restriction} and @code{save-excursion} special forms. When
6788you write the two @code{save- @dots{}} expressions in sequence, write
6789@code{save-excursion} outermost.)
6790
6791@need 1200
6792The last two lines of the @code{what-line} function are functions to
6793count the number of lines in the buffer and then print the number in the
6794echo area.
6795
6796@smallexample
6797@group
6798(message "Line %d"
6799 (1+ (count-lines 1 (point)))))))
6800@end group
6801@end smallexample
6802
6803The @code{message} function prints a one-line message at the bottom of
6804the Emacs screen. The first argument is inside of quotation marks and
6805is printed as a string of characters. However, it may contain a
6806@samp{%d} expression to print a following argument. @samp{%d} prints
6807the argument as a decimal, so the message will say something such as
6808@samp{Line 243}.
6809
6810@need 1200
6811The number that is printed in place of the @samp{%d} is computed by the
6812last line of the function:
6813
6814@smallexample
6815(1+ (count-lines 1 (point)))
6816@end smallexample
6817
6818@ignore
6819GNU Emacs 22
6820
6821(defun count-lines (start end)
6822 "Return number of lines between START and END.
6823This is usually the number of newlines between them,
6824but can be one more if START is not equal to END
6825and the greater of them is not at the start of a line."
6826 (save-excursion
6827 (save-restriction
6828 (narrow-to-region start end)
6829 (goto-char (point-min))
6830 (if (eq selective-display t)
6831 (save-match-data
6832 (let ((done 0))
6833 (while (re-search-forward "[\n\C-m]" nil t 40)
6834 (setq done (+ 40 done)))
6835 (while (re-search-forward "[\n\C-m]" nil t 1)
6836 (setq done (+ 1 done)))
6837 (goto-char (point-max))
6838 (if (and (/= start end)
6839 (not (bolp)))
6840 (1+ done)
6841 done)))
6842 (- (buffer-size) (forward-line (buffer-size)))))))
6843@end ignore
6844
6845@noindent
6846What this does is count the lines from the first position of the
6847buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6848one to that number. (The @code{1+} function adds one to its
6849argument.) We add one to it because line 2 has only one line before
6850it, and @code{count-lines} counts only the lines @emph{before} the
6851current line.
6852
6853After @code{count-lines} has done its job, and the message has been
6854printed in the echo area, the @code{save-excursion} restores point and
6855mark to their original positions; and @code{save-restriction} restores
6856the original narrowing, if any.
6857
d6adf7e7 6858@node narrow Exercise
8cda6f8f
GM
6859@section Exercise with Narrowing
6860
6861Write a function that will display the first 60 characters of the
6862current buffer, even if you have narrowed the buffer to its latter
6863half so that the first line is inaccessible. Restore point, mark, and
6864narrowing. For this exercise, you need to use a whole potpourri of
6865functions, including @code{save-restriction}, @code{widen},
6866@code{goto-char}, @code{point-min}, @code{message}, and
6867@code{buffer-substring}.
6868
6869@cindex Properties, mention of @code{buffer-substring-no-properties}
6870(@code{buffer-substring} is a previously unmentioned function you will
6871have to investigate yourself; or perhaps you will have to use
6872@code{buffer-substring-no-properties} or
6873@code{filter-buffer-substring} @dots{}, yet other functions. Text
6874properties are a feature otherwise not discussed here. @xref{Text
6875Properties, , Text Properties, elisp, The GNU Emacs Lisp Reference
6876Manual}.)
6877
6878Additionally, do you really need @code{goto-char} or @code{point-min}?
6879Or can you write the function without them?
6880
d6adf7e7 6881@node car cdr & cons
8cda6f8f
GM
6882@chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6883@findex car, @r{introduced}
6884@findex cdr, @r{introduced}
6885
6886In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6887functions. The @code{cons} function is used to construct lists, and
6888the @code{car} and @code{cdr} functions are used to take them apart.
6889
6890In the walk through of the @code{copy-region-as-kill} function, we
6891will see @code{cons} as well as two variants on @code{cdr},
6892namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6893
6894@menu
6895* Strange Names:: An historical aside: why the strange names?
6896* car & cdr:: Functions for extracting part of a list.
6897* cons:: Constructing a list.
6898* nthcdr:: Calling @code{cdr} repeatedly.
6899* nth::
6900* setcar:: Changing the first element of a list.
6901* setcdr:: Changing the rest of a list.
6902* cons Exercise::
6903@end menu
6904
8cda6f8f 6905@ifnottex
d6adf7e7 6906@node Strange Names
8cda6f8f
GM
6907@unnumberedsec Strange Names
6908@end ifnottex
6909
6910The name of the @code{cons} function is not unreasonable: it is an
6911abbreviation of the word `construct'. The origins of the names for
6912@code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6913is an acronym from the phrase `Contents of the Address part of the
6914Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6915the phrase `Contents of the Decrement part of the Register'. These
6916phrases refer to specific pieces of hardware on the very early
6917computer on which the original Lisp was developed. Besides being
6918obsolete, the phrases have been completely irrelevant for more than 25
6919years to anyone thinking about Lisp. Nonetheless, although a few
6920brave scholars have begun to use more reasonable names for these
6921functions, the old terms are still in use. In particular, since the
6922terms are used in the Emacs Lisp source code, we will use them in this
6923introduction.
6924
d6adf7e7 6925@node car & cdr
8cda6f8f
GM
6926@section @code{car} and @code{cdr}
6927
6928The @sc{car} of a list is, quite simply, the first item in the list.
6929Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6930@code{rose}.
6931
6932@need 1200
6933If you are reading this in Info in GNU Emacs, you can see this by
6934evaluating the following:
6935
6936@smallexample
6937(car '(rose violet daisy buttercup))
6938@end smallexample
6939
6940@noindent
6941After evaluating the expression, @code{rose} will appear in the echo
6942area.
6943
6944Clearly, a more reasonable name for the @code{car} function would be
6945@code{first} and this is often suggested.
6946
6947@code{car} does not remove the first item from the list; it only reports
6948what it is. After @code{car} has been applied to a list, the list is
6949still the same as it was. In the jargon, @code{car} is
6950`non-destructive'. This feature turns out to be important.
6951
6952The @sc{cdr} of a list is the rest of the list, that is, the
6953@code{cdr} function returns the part of the list that follows the
6954first item. Thus, while the @sc{car} of the list @code{'(rose violet
6955daisy buttercup)} is @code{rose}, the rest of the list, the value
6956returned by the @code{cdr} function, is @code{(violet daisy
6957buttercup)}.
6958
6959@need 800
6960You can see this by evaluating the following in the usual way:
6961
6962@smallexample
6963(cdr '(rose violet daisy buttercup))
6964@end smallexample
6965
6966@noindent
6967When you evaluate this, @code{(violet daisy buttercup)} will appear in
6968the echo area.
6969
6970Like @code{car}, @code{cdr} does not remove any elements from the
6971list---it just returns a report of what the second and subsequent
6972elements are.
6973
6974Incidentally, in the example, the list of flowers is quoted. If it were
6975not, the Lisp interpreter would try to evaluate the list by calling
6976@code{rose} as a function. In this example, we do not want to do that.
6977
6978Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6979
6980(There is a lesson here: when you name new functions, consider very
6981carefully what you are doing, since you may be stuck with the names
6982for far longer than you expect. The reason this document perpetuates
6983these names is that the Emacs Lisp source code uses them, and if I did
6984not use them, you would have a hard time reading the code; but do,
6985please, try to avoid using these terms yourself. The people who come
6986after you will be grateful to you.)
6987
6988When @code{car} and @code{cdr} are applied to a list made up of symbols,
6989such as the list @code{(pine fir oak maple)}, the element of the list
6990returned by the function @code{car} is the symbol @code{pine} without
6991any parentheses around it. @code{pine} is the first element in the
6992list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6993oak maple)}, as you can see by evaluating the following expressions in
6994the usual way:
6995
6996@smallexample
6997@group
6998(car '(pine fir oak maple))
6999
7000(cdr '(pine fir oak maple))
7001@end group
7002@end smallexample
7003
7004On the other hand, in a list of lists, the first element is itself a
7005list. @code{car} returns this first element as a list. For example,
7006the following list contains three sub-lists, a list of carnivores, a
7007list of herbivores and a list of sea mammals:
7008
7009@smallexample
7010@group
7011(car '((lion tiger cheetah)
7012 (gazelle antelope zebra)
7013 (whale dolphin seal)))
7014@end group
7015@end smallexample
7016
7017@noindent
7018In this example, the first element or @sc{car} of the list is the list of
7019carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
7020@code{((gazelle antelope zebra) (whale dolphin seal))}.
7021
7022@smallexample
7023@group
7024(cdr '((lion tiger cheetah)
7025 (gazelle antelope zebra)
7026 (whale dolphin seal)))
7027@end group
7028@end smallexample
7029
7030It is worth saying again that @code{car} and @code{cdr} are
7031non-destructive---that is, they do not modify or change lists to which
7032they are applied. This is very important for how they are used.
7033
7034Also, in the first chapter, in the discussion about atoms, I said that
7035in Lisp, ``certain kinds of atom, such as an array, can be separated
7036into parts; but the mechanism for doing this is different from the
7037mechanism for splitting a list. As far as Lisp is concerned, the
7038atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
7039@code{car} and @code{cdr} functions are used for splitting lists and
7040are considered fundamental to Lisp. Since they cannot split or gain
7041access to the parts of an array, an array is considered an atom.
7042Conversely, the other fundamental function, @code{cons}, can put
7043together or construct a list, but not an array. (Arrays are handled
7044by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
7045Emacs Lisp Reference Manual}.)
7046
d6adf7e7 7047@node cons
8cda6f8f
GM
7048@section @code{cons}
7049@findex cons, @r{introduced}
7050
7051The @code{cons} function constructs lists; it is the inverse of
7052@code{car} and @code{cdr}. For example, @code{cons} can be used to make
7053a four element list from the three element list, @code{(fir oak maple)}:
7054
7055@smallexample
7056(cons 'pine '(fir oak maple))
7057@end smallexample
7058
7059@need 800
7060@noindent
7061After evaluating this list, you will see
7062
7063@smallexample
7064(pine fir oak maple)
7065@end smallexample
7066
7067@noindent
7068appear in the echo area. @code{cons} causes the creation of a new
7069list in which the element is followed by the elements of the original
7070list.
7071
7072We often say that `@code{cons} puts a new element at the beginning of
7073a list; it attaches or pushes elements onto the list', but this
7074phrasing can be misleading, since @code{cons} does not change an
7075existing list, but creates a new one.
7076
7077Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
7078
7079@menu
7080* Build a list::
7081* length:: How to find the length of a list.
7082@end menu
7083
8cda6f8f 7084@ifnottex
d6adf7e7 7085@node Build a list
8cda6f8f
GM
7086@unnumberedsubsec Build a list
7087@end ifnottex
7088
7089@code{cons} must have a list to attach to.@footnote{Actually, you can
7090@code{cons} an element to an atom to produce a dotted pair. Dotted
7091pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
7092Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
7093cannot start from absolutely nothing. If you are building a list, you
7094need to provide at least an empty list at the beginning. Here is a
7095series of @code{cons} expressions that build up a list of flowers. If
7096you are reading this in Info in GNU Emacs, you can evaluate each of
7097the expressions in the usual way; the value is printed in this text
7098after @samp{@result{}}, which you may read as `evaluates to'.
7099
7100@smallexample
7101@group
7102(cons 'buttercup ())
7103 @result{} (buttercup)
7104@end group
7105
7106@group
7107(cons 'daisy '(buttercup))
7108 @result{} (daisy buttercup)
7109@end group
7110
7111@group
7112(cons 'violet '(daisy buttercup))
7113 @result{} (violet daisy buttercup)
7114@end group
7115
7116@group
7117(cons 'rose '(violet daisy buttercup))
7118 @result{} (rose violet daisy buttercup)
7119@end group
7120@end smallexample
7121
7122@noindent
7123In the first example, the empty list is shown as @code{()} and a list
7124made up of @code{buttercup} followed by the empty list is constructed.
7125As you can see, the empty list is not shown in the list that was
7126constructed. All that you see is @code{(buttercup)}. The empty list is
7127not counted as an element of a list because there is nothing in an empty
7128list. Generally speaking, an empty list is invisible.
7129
7130The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
7131two element list by putting @code{daisy} in front of @code{buttercup};
7132and the third example constructs a three element list by putting
7133@code{violet} in front of @code{daisy} and @code{buttercup}.
7134
d6adf7e7 7135@node length
8cda6f8f
GM
7136@subsection Find the Length of a List: @code{length}
7137@findex length
7138
7139You can find out how many elements there are in a list by using the Lisp
7140function @code{length}, as in the following examples:
7141
7142@smallexample
7143@group
7144(length '(buttercup))
7145 @result{} 1
7146@end group
7147
7148@group
7149(length '(daisy buttercup))
7150 @result{} 2
7151@end group
7152
7153@group
7154(length (cons 'violet '(daisy buttercup)))
7155 @result{} 3
7156@end group
7157@end smallexample
7158
7159@noindent
7160In the third example, the @code{cons} function is used to construct a
7161three element list which is then passed to the @code{length} function as
7162its argument.
7163
7164@need 1200
7165We can also use @code{length} to count the number of elements in an
7166empty list:
7167
7168@smallexample
7169@group
7170(length ())
7171 @result{} 0
7172@end group
7173@end smallexample
7174
7175@noindent
7176As you would expect, the number of elements in an empty list is zero.
7177
7178An interesting experiment is to find out what happens if you try to find
7179the length of no list at all; that is, if you try to call @code{length}
7180without giving it an argument, not even an empty list:
7181
7182@smallexample
7183(length )
7184@end smallexample
7185
7186@need 800
7187@noindent
7188What you see, if you evaluate this, is the error message
7189
7190@smallexample
7191Lisp error: (wrong-number-of-arguments length 0)
7192@end smallexample
7193
7194@noindent
7195This means that the function receives the wrong number of
7196arguments, zero, when it expects some other number of arguments. In
7197this case, one argument is expected, the argument being a list whose
7198length the function is measuring. (Note that @emph{one} list is
7199@emph{one} argument, even if the list has many elements inside it.)
7200
7201The part of the error message that says @samp{length} is the name of
7202the function.
7203
7204@ignore
7205@code{length} is still a subroutine, but you need C-h f to discover that.
7206
7207In an earlier version:
7208 This is written with a special notation, @samp{#<subr},
7209 that indicates that the function @code{length} is one of the primitive
7210 functions written in C rather than in Emacs Lisp. (@samp{subr} is an
7211 abbreviation for `subroutine'.) @xref{What Is a Function, , What Is a
7212 Function?, elisp , The GNU Emacs Lisp Reference Manual}, for more
7213 about subroutines.
7214@end ignore
7215
d6adf7e7 7216@node nthcdr
8cda6f8f
GM
7217@section @code{nthcdr}
7218@findex nthcdr
7219
7220The @code{nthcdr} function is associated with the @code{cdr} function.
7221What it does is take the @sc{cdr} of a list repeatedly.
7222
7223If you take the @sc{cdr} of the list @code{(pine fir
7224oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
7225repeat this on what was returned, you will be returned the list
7226@code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
7227list will just give you the original @sc{cdr} since the function does
7228not change the list. You need to evaluate the @sc{cdr} of the
7229@sc{cdr} and so on.) If you continue this, eventually you will be
7230returned an empty list, which in this case, instead of being shown as
7231@code{()} is shown as @code{nil}.
7232
7233@need 1200
7234For review, here is a series of repeated @sc{cdr}s, the text following
7235the @samp{@result{}} shows what is returned.
7236
7237@smallexample
7238@group
7239(cdr '(pine fir oak maple))
7240 @result{}(fir oak maple)
7241@end group
7242
7243@group
7244(cdr '(fir oak maple))
7245 @result{} (oak maple)
7246@end group
7247
7248@group
7249(cdr '(oak maple))
7250 @result{}(maple)
7251@end group
7252
7253@group
7254(cdr '(maple))
7255 @result{} nil
7256@end group
7257
7258@group
7259(cdr 'nil)
7260 @result{} nil
7261@end group
7262
7263@group
7264(cdr ())
7265 @result{} nil
7266@end group
7267@end smallexample
7268
7269@need 1200
7270You can also do several @sc{cdr}s without printing the values in
7271between, like this:
7272
7273@smallexample
7274@group
7275(cdr (cdr '(pine fir oak maple)))
7276 @result{} (oak maple)
7277@end group
7278@end smallexample
7279
7280@noindent
7281In this example, the Lisp interpreter evaluates the innermost list first.
7282The innermost list is quoted, so it just passes the list as it is to the
7283innermost @code{cdr}. This @code{cdr} passes a list made up of the
7284second and subsequent elements of the list to the outermost @code{cdr},
7285which produces a list composed of the third and subsequent elements of
7286the original list. In this example, the @code{cdr} function is repeated
7287and returns a list that consists of the original list without its
7288first two elements.
7289
7290The @code{nthcdr} function does the same as repeating the call to
7291@code{cdr}. In the following example, the argument 2 is passed to the
7292function @code{nthcdr}, along with the list, and the value returned is
7293the list without its first two items, which is exactly the same
7294as repeating @code{cdr} twice on the list:
7295
7296@smallexample
7297@group
7298(nthcdr 2 '(pine fir oak maple))
7299 @result{} (oak maple)
7300@end group
7301@end smallexample
7302
7303@need 1200
7304Using the original four element list, we can see what happens when
7305various numeric arguments are passed to @code{nthcdr}, including 0, 1,
7306and 5:
7307
7308@smallexample
7309@group
7310;; @r{Leave the list as it was.}
7311(nthcdr 0 '(pine fir oak maple))
7312 @result{} (pine fir oak maple)
7313@end group
7314
7315@group
7316;; @r{Return a copy without the first element.}
7317(nthcdr 1 '(pine fir oak maple))
7318 @result{} (fir oak maple)
7319@end group
7320
7321@group
7322;; @r{Return a copy of the list without three elements.}
7323(nthcdr 3 '(pine fir oak maple))
7324 @result{} (maple)
7325@end group
7326
7327@group
7328;; @r{Return a copy lacking all four elements.}
7329(nthcdr 4 '(pine fir oak maple))
7330 @result{} nil
7331@end group
7332
7333@group
7334;; @r{Return a copy lacking all elements.}
7335(nthcdr 5 '(pine fir oak maple))
7336 @result{} nil
7337@end group
7338@end smallexample
7339
d6adf7e7 7340@node nth
8cda6f8f
GM
7341@section @code{nth}
7342@findex nth
7343
7344The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
7345The @code{nth} function takes the @sc{car} of the result returned by
7346@code{nthcdr}. It returns the Nth element of the list.
7347
7348@need 1500
7349Thus, if it were not defined in C for speed, the definition of
7350@code{nth} would be:
7351
7352@smallexample
7353@group
7354(defun nth (n list)
7355 "Returns the Nth element of LIST.
7356N counts from zero. If LIST is not that long, nil is returned."
7357 (car (nthcdr n list)))
7358@end group
7359@end smallexample
7360
7361@noindent
7362(Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
7363but its definition was redone in C in the 1980s.)
7364
7365The @code{nth} function returns a single element of a list.
7366This can be very convenient.
7367
7368Note that the elements are numbered from zero, not one. That is to
7369say, the first element of a list, its @sc{car} is the zeroth element.
7370This is called `zero-based' counting and often bothers people who
7371are accustomed to the first element in a list being number one, which
7372is `one-based'.
7373
7374@need 1250
7375For example:
7376
7377@smallexample
7378@group
7379(nth 0 '("one" "two" "three"))
7380 @result{} "one"
7381
7382(nth 1 '("one" "two" "three"))
7383 @result{} "two"
7384@end group
7385@end smallexample
7386
7387It is worth mentioning that @code{nth}, like @code{nthcdr} and
7388@code{cdr}, does not change the original list---the function is
7389non-destructive. This is in sharp contrast to the @code{setcar} and
7390@code{setcdr} functions.
7391
d6adf7e7 7392@node setcar
8cda6f8f
GM
7393@section @code{setcar}
7394@findex setcar
7395
7396As you might guess from their names, the @code{setcar} and @code{setcdr}
7397functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7398They actually change the original list, unlike @code{car} and @code{cdr}
7399which leave the original list as it was. One way to find out how this
7400works is to experiment. We will start with the @code{setcar} function.
7401
7402@need 1200
7403First, we can make a list and then set the value of a variable to the
7404list, using the @code{setq} function. Here is a list of animals:
7405
7406@smallexample
7407(setq animals '(antelope giraffe lion tiger))
7408@end smallexample
7409
7410@noindent
7411If you are reading this in Info inside of GNU Emacs, you can evaluate
7412this expression in the usual fashion, by positioning the cursor after
7413the expression and typing @kbd{C-x C-e}. (I'm doing this right here
7414as I write this. This is one of the advantages of having the
7415interpreter built into the computing environment. Incidentally, when
7416there is nothing on the line after the final parentheses, such as a
7417comment, point can be on the next line. Thus, if your cursor is in
7418the first column of the next line, you do not need to move it.
7419Indeed, Emacs permits any amount of white space after the final
7420parenthesis.)
7421
7422@need 1200
7423When we evaluate the variable @code{animals}, we see that it is bound to
7424the list @code{(antelope giraffe lion tiger)}:
7425
7426@smallexample
7427@group
7428animals
7429 @result{} (antelope giraffe lion tiger)
7430@end group
7431@end smallexample
7432
7433@noindent
7434Put another way, the variable @code{animals} points to the list
7435@code{(antelope giraffe lion tiger)}.
7436
7437Next, evaluate the function @code{setcar} while passing it two
7438arguments, the variable @code{animals} and the quoted symbol
7439@code{hippopotamus}; this is done by writing the three element list
7440@code{(setcar animals 'hippopotamus)} and then evaluating it in the
7441usual fashion:
7442
7443@smallexample
7444(setcar animals 'hippopotamus)
7445@end smallexample
7446
7447@need 1200
7448@noindent
7449After evaluating this expression, evaluate the variable @code{animals}
7450again. You will see that the list of animals has changed:
7451
7452@smallexample
7453@group
7454animals
7455 @result{} (hippopotamus giraffe lion tiger)
7456@end group
7457@end smallexample
7458
7459@noindent
7460The first element on the list, @code{antelope} is replaced by
7461@code{hippopotamus}.
7462
7463So we can see that @code{setcar} did not add a new element to the list
7464as @code{cons} would have; it replaced @code{antelope} with
7465@code{hippopotamus}; it @emph{changed} the list.
7466
d6adf7e7 7467@node setcdr
8cda6f8f
GM
7468@section @code{setcdr}
7469@findex setcdr
7470
7471The @code{setcdr} function is similar to the @code{setcar} function,
7472except that the function replaces the second and subsequent elements of
7473a list rather than the first element.
7474
7475(To see how to change the last element of a list, look ahead to
7476@ref{kill-new function, , The @code{kill-new} function}, which uses
7477the @code{nthcdr} and @code{setcdr} functions.)
7478
7479@need 1200
7480To see how this works, set the value of the variable to a list of
7481domesticated animals by evaluating the following expression:
7482
7483@smallexample
7484(setq domesticated-animals '(horse cow sheep goat))
7485@end smallexample
7486
7487@need 1200
7488@noindent
7489If you now evaluate the list, you will be returned the list
7490@code{(horse cow sheep goat)}:
7491
7492@smallexample
7493@group
7494domesticated-animals
7495 @result{} (horse cow sheep goat)
7496@end group
7497@end smallexample
7498
7499@need 1200
7500Next, evaluate @code{setcdr} with two arguments, the name of the
7501variable which has a list as its value, and the list to which the
7502@sc{cdr} of the first list will be set;
7503
7504@smallexample
7505(setcdr domesticated-animals '(cat dog))
7506@end smallexample
7507
7508@noindent
7509If you evaluate this expression, the list @code{(cat dog)} will appear
7510in the echo area. This is the value returned by the function. The
7511result we are interested in is the ``side effect'', which we can see by
7512evaluating the variable @code{domesticated-animals}:
7513
7514@smallexample
7515@group
7516domesticated-animals
7517 @result{} (horse cat dog)
7518@end group
7519@end smallexample
7520
7521@noindent
7522Indeed, the list is changed from @code{(horse cow sheep goat)} to
7523@code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7524@code{(cow sheep goat)} to @code{(cat dog)}.
7525
d6adf7e7 7526@node cons Exercise
8cda6f8f
GM
7527@section Exercise
7528
7529Construct a list of four birds by evaluating several expressions with
7530@code{cons}. Find out what happens when you @code{cons} a list onto
7531itself. Replace the first element of the list of four birds with a
7532fish. Replace the rest of that list with a list of other fish.
7533
d6adf7e7 7534@node Cutting & Storing Text
8cda6f8f
GM
7535@chapter Cutting and Storing Text
7536@cindex Cutting and storing text
7537@cindex Storing and cutting text
7538@cindex Killing text
7539@cindex Clipping text
7540@cindex Erasing text
7541@cindex Deleting text
7542
7543Whenever you cut or clip text out of a buffer with a `kill' command in
7544GNU Emacs, it is stored in a list and you can bring it back with a
7545`yank' command.
7546
7547(The use of the word `kill' in Emacs for processes which specifically
7548@emph{do not} destroy the values of the entities is an unfortunate
7549historical accident. A much more appropriate word would be `clip' since
7550that is what the kill commands do; they clip text out of a buffer and
7551put it into storage from which it can be brought back. I have often
7552been tempted to replace globally all occurrences of `kill' in the Emacs
7553sources with `clip' and all occurrences of `killed' with `clipped'.)
7554
7555@menu
7556* Storing Text:: Text is stored in a list.
7557* zap-to-char:: Cutting out text up to a character.
7558* kill-region:: Cutting text out of a region.
7559* copy-region-as-kill:: A definition for copying text.
7560* Digression into C:: Minor note on C programming language macros.
7561* defvar:: How to give a variable an initial value.
7562* cons & search-fwd Review::
7563* search Exercises::
7564@end menu
7565
8cda6f8f 7566@ifnottex
d6adf7e7 7567@node Storing Text
8cda6f8f
GM
7568@unnumberedsec Storing Text in a List
7569@end ifnottex
7570
7571When text is cut out of a buffer, it is stored on a list. Successive
7572pieces of text are stored on the list successively, so the list might
7573look like this:
7574
7575@smallexample
7576("a piece of text" "previous piece")
7577@end smallexample
7578
7579@need 1200
7580@noindent
7581The function @code{cons} can be used to create a new list from a piece
7582of text (an `atom', to use the jargon) and an existing list, like
7583this:
7584
7585@smallexample
7586@group
7587(cons "another piece"
7588 '("a piece of text" "previous piece"))
7589@end group
7590@end smallexample
7591
7592@need 1200
7593@noindent
7594If you evaluate this expression, a list of three elements will appear in
7595the echo area:
7596
7597@smallexample
7598("another piece" "a piece of text" "previous piece")
7599@end smallexample
7600
7601With the @code{car} and @code{nthcdr} functions, you can retrieve
7602whichever piece of text you want. For example, in the following code,
7603@code{nthcdr 1 @dots{}} returns the list with the first item removed;
7604and the @code{car} returns the first element of that remainder---the
7605second element of the original list:
7606
7607@smallexample
7608@group
7609(car (nthcdr 1 '("another piece"
7610 "a piece of text"
7611 "previous piece")))
7612 @result{} "a piece of text"
7613@end group
7614@end smallexample
7615
7616The actual functions in Emacs are more complex than this, of course.
7617The code for cutting and retrieving text has to be written so that
7618Emacs can figure out which element in the list you want---the first,
7619second, third, or whatever. In addition, when you get to the end of
7620the list, Emacs should give you the first element of the list, rather
7621than nothing at all.
7622
7623The list that holds the pieces of text is called the @dfn{kill ring}.
7624This chapter leads up to a description of the kill ring and how it is
7625used by first tracing how the @code{zap-to-char} function works. This
7626function uses (or `calls') a function that invokes a function that
7627manipulates the kill ring. Thus, before reaching the mountains, we
7628climb the foothills.
7629
7630A subsequent chapter describes how text that is cut from the buffer is
7631retrieved. @xref{Yanking, , Yanking Text Back}.
7632
d6adf7e7 7633@node zap-to-char
8cda6f8f
GM
7634@section @code{zap-to-char}
7635@findex zap-to-char
7636
8f4ea8e0 7637@c FIXME remove obsolete stuff
8cda6f8f
GM
7638The @code{zap-to-char} function changed little between GNU Emacs
7639version 19 and GNU Emacs version 22. However, @code{zap-to-char}
7640calls another function, @code{kill-region}, which enjoyed a major
7641rewrite.
7642
7643The @code{kill-region} function in Emacs 19 is complex, but does not
7644use code that is important at this time. We will skip it.
7645
7646The @code{kill-region} function in Emacs 22 is easier to read than the
7647same function in Emacs 19 and introduces a very important concept,
7648that of error handling. We will walk through the function.
7649
7650But first, let us look at the interactive @code{zap-to-char} function.
7651
7652@menu
7653* Complete zap-to-char:: The complete implementation.
7654* zap-to-char interactive:: A three part interactive expression.
7655* zap-to-char body:: A short overview.
7656* search-forward:: How to search for a string.
7657* progn:: The @code{progn} special form.
7658* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7659@end menu
7660
8cda6f8f 7661@ifnottex
d6adf7e7 7662@node Complete zap-to-char
8cda6f8f
GM
7663@unnumberedsubsec The Complete @code{zap-to-char} Implementation
7664@end ifnottex
7665
7666The @code{zap-to-char} function removes the text in the region between
7667the location of the cursor (i.e., of point) up to and including the
7668next occurrence of a specified character. The text that
7669@code{zap-to-char} removes is put in the kill ring; and it can be
7670retrieved from the kill ring by typing @kbd{C-y} (@code{yank}). If
7671the command is given an argument, it removes text through that number
7672of occurrences. Thus, if the cursor were at the beginning of this
7673sentence and the character were @samp{s}, @samp{Thus} would be
7674removed. If the argument were two, @samp{Thus, if the curs} would be
7675removed, up to and including the @samp{s} in @samp{cursor}.
7676
7677If the specified character is not found, @code{zap-to-char} will say
7678``Search failed'', tell you the character you typed, and not remove
7679any text.
7680
7681In order to determine how much text to remove, @code{zap-to-char} uses
7682a search function. Searches are used extensively in code that
7683manipulates text, and we will focus attention on them as well as on the
7684deletion command.
7685
7686@ignore
7687@c GNU Emacs version 19
7688(defun zap-to-char (arg char) ; version 19 implementation
7689 "Kill up to and including ARG'th occurrence of CHAR.
7690Goes backward if ARG is negative; error if CHAR not found."
7691 (interactive "*p\ncZap to char: ")
7692 (kill-region (point)
7693 (progn
7694 (search-forward
7695 (char-to-string char) nil nil arg)
7696 (point))))
7697@end ignore
7698
7699@need 1250
7700Here is the complete text of the version 22 implementation of the function:
7701
7702@c GNU Emacs 22
7703@smallexample
7704@group
7705(defun zap-to-char (arg char)
7706 "Kill up to and including ARG'th occurrence of CHAR.
7707Case is ignored if `case-fold-search' is non-nil in the current buffer.
7708Goes backward if ARG is negative; error if CHAR not found."
7709 (interactive "p\ncZap to char: ")
7710 (if (char-table-p translation-table-for-input)
7711 (setq char (or (aref translation-table-for-input char) char)))
7712 (kill-region (point) (progn
a9097c6d
KB
7713 (search-forward (char-to-string char)
7714 nil nil arg)
8cda6f8f
GM
7715 (point))))
7716@end group
7717@end smallexample
7718
7719The documentation is thorough. You do need to know the jargon meaning
7720of the word `kill'.
7721
d6adf7e7 7722@node zap-to-char interactive
8cda6f8f
GM
7723@subsection The @code{interactive} Expression
7724
7725@need 800
7726The interactive expression in the @code{zap-to-char} command looks like
7727this:
7728
7729@smallexample
7730(interactive "p\ncZap to char: ")
7731@end smallexample
7732
7733The part within quotation marks, @code{"p\ncZap to char:@: "}, specifies
7734two different things. First, and most simply, is the @samp{p}.
7735This part is separated from the next part by a newline, @samp{\n}.
7736The @samp{p} means that the first argument to the function will be
7737passed the value of a `processed prefix'. The prefix argument is
7738passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7739the function is called interactively without a prefix, 1 is passed to
7740this argument.
7741
7742The second part of @code{"p\ncZap to char:@: "} is
7743@samp{cZap to char:@: }. In this part, the lower case @samp{c}
7744indicates that @code{interactive} expects a prompt and that the
7745argument will be a character. The prompt follows the @samp{c} and is
7746the string @samp{Zap to char:@: } (with a space after the colon to
7747make it look good).
7748
7749What all this does is prepare the arguments to @code{zap-to-char} so they
7750are of the right type, and give the user a prompt.
7751
7752In a read-only buffer, the @code{zap-to-char} function copies the text
7753to the kill ring, but does not remove it. The echo area displays a
7754message saying that the buffer is read-only. Also, the terminal may
7755beep or blink at you.
7756
d6adf7e7 7757@node zap-to-char body
8cda6f8f
GM
7758@subsection The Body of @code{zap-to-char}
7759
7760The body of the @code{zap-to-char} function contains the code that
7761kills (that is, removes) the text in the region from the current
7762position of the cursor up to and including the specified character.
7763
7764The first part of the code looks like this:
7765
7766@smallexample
7767(if (char-table-p translation-table-for-input)
7768 (setq char (or (aref translation-table-for-input char) char)))
7769(kill-region (point) (progn
7770 (search-forward (char-to-string char) nil nil arg)
7771 (point)))
7772@end smallexample
7773
7774@noindent
7775@code{char-table-p} is an hitherto unseen function. It determines
7776whether its argument is a character table. When it is, it sets the
7777character passed to @code{zap-to-char} to one of them, if that
7778character exists, or to the character itself. (This becomes important
7779for certain characters in non-European languages. The @code{aref}
7780function extracts an element from an array. It is an array-specific
7781function that is not described in this document. @xref{Arrays, ,
7782Arrays, elisp, The GNU Emacs Lisp Reference Manual}.)
7783
7784@noindent
7785@code{(point)} is the current position of the cursor.
7786
7787The next part of the code is an expression using @code{progn}. The body
7788of the @code{progn} consists of calls to @code{search-forward} and
7789@code{point}.
7790
7791It is easier to understand how @code{progn} works after learning about
7792@code{search-forward}, so we will look at @code{search-forward} and
7793then at @code{progn}.
7794
d6adf7e7 7795@node search-forward
8cda6f8f
GM
7796@subsection The @code{search-forward} Function
7797@findex search-forward
7798
7799The @code{search-forward} function is used to locate the
7800zapped-for-character in @code{zap-to-char}. If the search is
7801successful, @code{search-forward} leaves point immediately after the
7802last character in the target string. (In @code{zap-to-char}, the
7803target string is just one character long. @code{zap-to-char} uses the
7804function @code{char-to-string} to ensure that the computer treats that
7805character as a string.) If the search is backwards,
7806@code{search-forward} leaves point just before the first character in
7807the target. Also, @code{search-forward} returns @code{t} for true.
7808(Moving point is therefore a `side effect'.)
7809
7810@need 1250
7811In @code{zap-to-char}, the @code{search-forward} function looks like this:
7812
7813@smallexample
7814(search-forward (char-to-string char) nil nil arg)
7815@end smallexample
7816
7817The @code{search-forward} function takes four arguments:
7818
7819@enumerate
7820@item
7821The first argument is the target, what is searched for. This must be a
7822string, such as @samp{"z"}.
7823
7824As it happens, the argument passed to @code{zap-to-char} is a single
7825character. Because of the way computers are built, the Lisp
7826interpreter may treat a single character as being different from a
7827string of characters. Inside the computer, a single character has a
7828different electronic format than a string of one character. (A single
7829character can often be recorded in the computer using exactly one
7830byte; but a string may be longer, and the computer needs to be ready
7831for this.) Since the @code{search-forward} function searches for a
7832string, the character that the @code{zap-to-char} function receives as
7833its argument must be converted inside the computer from one format to
7834the other; otherwise the @code{search-forward} function will fail.
7835The @code{char-to-string} function is used to make this conversion.
7836
7837@item
7838The second argument bounds the search; it is specified as a position in
7839the buffer. In this case, the search can go to the end of the buffer,
7840so no bound is set and the second argument is @code{nil}.
7841
7842@item
7843The third argument tells the function what it should do if the search
7844fails---it can signal an error (and print a message) or it can return
7845@code{nil}. A @code{nil} as the third argument causes the function to
7846signal an error when the search fails.
7847
7848@item
7849The fourth argument to @code{search-forward} is the repeat count---how
7850many occurrences of the string to look for. This argument is optional
7851and if the function is called without a repeat count, this argument is
7852passed the value 1. If this argument is negative, the search goes
7853backwards.
7854@end enumerate
7855
7856@need 800
7857In template form, a @code{search-forward} expression looks like this:
7858
7859@smallexample
7860@group
7861(search-forward "@var{target-string}"
7862 @var{limit-of-search}
7863 @var{what-to-do-if-search-fails}
7864 @var{repeat-count})
7865@end group
7866@end smallexample
7867
7868We will look at @code{progn} next.
7869
d6adf7e7 7870@node progn
8cda6f8f
GM
7871@subsection The @code{progn} Special Form
7872@findex progn
7873
7874@code{progn} is a special form that causes each of its arguments to be
7875evaluated in sequence and then returns the value of the last one. The
7876preceding expressions are evaluated only for the side effects they
7877perform. The values produced by them are discarded.
7878
7879@need 800
7880The template for a @code{progn} expression is very simple:
7881
7882@smallexample
7883@group
7884(progn
7885 @var{body}@dots{})
7886@end group
7887@end smallexample
7888
7889In @code{zap-to-char}, the @code{progn} expression has to do two things:
7890put point in exactly the right position; and return the location of
7891point so that @code{kill-region} will know how far to kill to.
7892
7893The first argument to the @code{progn} is @code{search-forward}. When
7894@code{search-forward} finds the string, the function leaves point
7895immediately after the last character in the target string. (In this
7896case the target string is just one character long.) If the search is
7897backwards, @code{search-forward} leaves point just before the first
7898character in the target. The movement of point is a side effect.
7899
7900The second and last argument to @code{progn} is the expression
7901@code{(point)}. This expression returns the value of point, which in
7902this case will be the location to which it has been moved by
7903@code{search-forward}. (In the source, a line that tells the function
7904to go to the previous character, if it is going forward, was commented
7905out in 1999; I don't remember whether that feature or mis-feature was
7906ever a part of the distributed source.) The value of @code{point} is
7907returned by the @code{progn} expression and is passed to
7908@code{kill-region} as @code{kill-region}'s second argument.
7909
d6adf7e7 7910@node Summing up zap-to-char
8cda6f8f
GM
7911@subsection Summing up @code{zap-to-char}
7912
7913Now that we have seen how @code{search-forward} and @code{progn} work,
7914we can see how the @code{zap-to-char} function works as a whole.
7915
7916The first argument to @code{kill-region} is the position of the cursor
7917when the @code{zap-to-char} command is given---the value of point at
7918that time. Within the @code{progn}, the search function then moves
7919point to just after the zapped-to-character and @code{point} returns the
7920value of this location. The @code{kill-region} function puts together
7921these two values of point, the first one as the beginning of the region
7922and the second one as the end of the region, and removes the region.
7923
7924The @code{progn} special form is necessary because the
7925@code{kill-region} command takes two arguments; and it would fail if
7926@code{search-forward} and @code{point} expressions were written in
7927sequence as two additional arguments. The @code{progn} expression is
7928a single argument to @code{kill-region} and returns the one value that
7929@code{kill-region} needs for its second argument.
7930
d6adf7e7 7931@node kill-region
8cda6f8f
GM
7932@section @code{kill-region}
7933@findex kill-region
7934
7935The @code{zap-to-char} function uses the @code{kill-region} function.
7936This function clips text from a region and copies that text to
7937the kill ring, from which it may be retrieved.
7938
7939@ignore
7940GNU Emacs 22:
7941
7942(defun kill-region (beg end &optional yank-handler)
7943 "Kill (\"cut\") text between point and mark.
7944This deletes the text from the buffer and saves it in the kill ring.
7945The command \\[yank] can retrieve it from there.
7946\(If you want to kill and then yank immediately, use \\[kill-ring-save].)
7947
7948If you want to append the killed region to the last killed text,
7949use \\[append-next-kill] before \\[kill-region].
7950
7951If the buffer is read-only, Emacs will beep and refrain from deleting
7952the text, but put the text in the kill ring anyway. This means that
7953you can use the killing commands to copy text from a read-only buffer.
7954
7955This is the primitive for programs to kill text (as opposed to deleting it).
7956Supply two arguments, character positions indicating the stretch of text
7957 to be killed.
7958Any command that calls this function is a \"kill command\".
7959If the previous command was also a kill command,
7960the text killed this time appends to the text killed last time
7961to make one entry in the kill ring.
7962
7963In Lisp code, optional third arg YANK-HANDLER, if non-nil,
7964specifies the yank-handler text property to be set on the killed
7965text. See `insert-for-yank'."
7966 ;; Pass point first, then mark, because the order matters
7967 ;; when calling kill-append.
7968 (interactive (list (point) (mark)))
7969 (unless (and beg end)
7970 (error "The mark is not set now, so there is no region"))
7971 (condition-case nil
7972 (let ((string (filter-buffer-substring beg end t)))
7973 (when string ;STRING is nil if BEG = END
7974 ;; Add that string to the kill ring, one way or another.
7975 (if (eq last-command 'kill-region)
7976 (kill-append string (< end beg) yank-handler)
7977 (kill-new string nil yank-handler)))
7978 (when (or string (eq last-command 'kill-region))
7979 (setq this-command 'kill-region))
7980 nil)
7981 ((buffer-read-only text-read-only)
7982 ;; The code above failed because the buffer, or some of the characters
7983 ;; in the region, are read-only.
7984 ;; We should beep, in case the user just isn't aware of this.
7985 ;; However, there's no harm in putting
7986 ;; the region's text in the kill ring, anyway.
7987 (copy-region-as-kill beg end)
7988 ;; Set this-command now, so it will be set even if we get an error.
7989 (setq this-command 'kill-region)
7990 ;; This should barf, if appropriate, and give us the correct error.
7991 (if kill-read-only-ok
7992 (progn (message "Read only text copied to kill ring") nil)
7993 ;; Signal an error if the buffer is read-only.
7994 (barf-if-buffer-read-only)
7995 ;; If the buffer isn't read-only, the text is.
7996 (signal 'text-read-only (list (current-buffer)))))))
7997@end ignore
7998
7999The Emacs 22 version of that function uses @code{condition-case} and
8000@code{copy-region-as-kill}, both of which we will explain.
8001@code{condition-case} is an important special form.
8002
8003In essence, the @code{kill-region} function calls
8004@code{condition-case}, which takes three arguments. In this function,
8005the first argument does nothing. The second argument contains the
8006code that does the work when all goes well. The third argument
8007contains the code that is called in the event of an error.
8008
8009@menu
8010* Complete kill-region:: The function definition.
8011* condition-case:: Dealing with a problem.
8012* Lisp macro::
8013@end menu
8014
8cda6f8f 8015@ifnottex
d6adf7e7 8016@node Complete kill-region
8cda6f8f
GM
8017@unnumberedsubsec The Complete @code{kill-region} Definition
8018@end ifnottex
8019
8020@need 1200
8021We will go through the @code{condition-case} code in a moment. First,
8022let us look at the definition of @code{kill-region}, with comments
8023added:
8024
8025@c GNU Emacs 22:
8026@smallexample
8027@group
8028(defun kill-region (beg end)
8029 "Kill (\"cut\") text between point and mark.
8030This deletes the text from the buffer and saves it in the kill ring.
8031The command \\[yank] can retrieve it from there. @dots{} "
8032@end group
8033
8034@group
8035 ;; @bullet{} Since order matters, pass point first.
8036 (interactive (list (point) (mark)))
8037 ;; @bullet{} And tell us if we cannot cut the text.
8038 ;; `unless' is an `if' without a then-part.
8039 (unless (and beg end)
8040 (error "The mark is not set now, so there is no region"))
8041@end group
8042
8043@group
8044 ;; @bullet{} `condition-case' takes three arguments.
8045 ;; If the first argument is nil, as it is here,
8046 ;; information about the error signal is not
8047 ;; stored for use by another function.
8048 (condition-case nil
8049@end group
8050
8051@group
8052 ;; @bullet{} The second argument to `condition-case' tells the
8053 ;; Lisp interpreter what to do when all goes well.
8054@end group
8055
8056@group
8057 ;; It starts with a `let' function that extracts the string
8058 ;; and tests whether it exists. If so (that is what the
8059 ;; `when' checks), it calls an `if' function that determines
8060 ;; whether the previous command was another call to
8061 ;; `kill-region'; if it was, then the new text is appended to
8062 ;; the previous text; if not, then a different function,
8063 ;; `kill-new', is called.
8064@end group
8065
8066@group
8067 ;; The `kill-append' function concatenates the new string and
8068 ;; the old. The `kill-new' function inserts text into a new
8069 ;; item in the kill ring.
8070@end group
8071
8072@group
8073 ;; `when' is an `if' without an else-part. The second `when'
8074 ;; again checks whether the current string exists; in
8075 ;; addition, it checks whether the previous command was
8076 ;; another call to `kill-region'. If one or the other
8077 ;; condition is true, then it sets the current command to
8078 ;; be `kill-region'.
8079@end group
8080@group
8081 (let ((string (filter-buffer-substring beg end t)))
8082 (when string ;STRING is nil if BEG = END
8083 ;; Add that string to the kill ring, one way or another.
8084 (if (eq last-command 'kill-region)
8085@end group
8086@group
8087 ;; @minus{} `yank-handler' is an optional argument to
8088 ;; `kill-region' that tells the `kill-append' and
8089 ;; `kill-new' functions how deal with properties
8090 ;; added to the text, such as `bold' or `italics'.
8091 (kill-append string (< end beg) yank-handler)
8092 (kill-new string nil yank-handler)))
8093 (when (or string (eq last-command 'kill-region))
8094 (setq this-command 'kill-region))
8095 nil)
8096@end group
8097
8098@group
8099 ;; @bullet{} The third argument to `condition-case' tells the interpreter
8100 ;; what to do with an error.
8101@end group
8102@group
8103 ;; The third argument has a conditions part and a body part.
8104 ;; If the conditions are met (in this case,
8105 ;; if text or buffer are read-only)
8106 ;; then the body is executed.
8107@end group
8108@group
8109 ;; The first part of the third argument is the following:
8110 ((buffer-read-only text-read-only) ;; the if-part
8111 ;; @dots{} the then-part
8112 (copy-region-as-kill beg end)
8113@end group
8114@group
8115 ;; Next, also as part of the then-part, set this-command, so
8116 ;; it will be set in an error
8117 (setq this-command 'kill-region)
8118 ;; Finally, in the then-part, send a message if you may copy
8350f087 8119 ;; the text to the kill ring without signaling an error, but
8cda6f8f
GM
8120 ;; don't if you may not.
8121@end group
8122@group
8123 (if kill-read-only-ok
8124 (progn (message "Read only text copied to kill ring") nil)
8125 (barf-if-buffer-read-only)
8126 ;; If the buffer isn't read-only, the text is.
8127 (signal 'text-read-only (list (current-buffer)))))
8128@end group
8129@end smallexample
8130
8131@ignore
8132@c v 21
8133@smallexample
8134@group
8135(defun kill-region (beg end)
8136 "Kill between point and mark.
8137The text is deleted but saved in the kill ring."
8138 (interactive "r")
8139@end group
8140
8141@group
8142 ;; 1. `condition-case' takes three arguments.
8143 ;; If the first argument is nil, as it is here,
8144 ;; information about the error signal is not
8145 ;; stored for use by another function.
8146 (condition-case nil
8147@end group
8148
8149@group
8150 ;; 2. The second argument to `condition-case'
8151 ;; tells the Lisp interpreter what to do when all goes well.
8152@end group
8153
8154@group
8155 ;; The `delete-and-extract-region' function usually does the
8156 ;; work. If the beginning and ending of the region are both
8157 ;; the same, then the variable `string' will be empty, or nil
8158 (let ((string (delete-and-extract-region beg end)))
8159@end group
8160
8161@group
8162 ;; `when' is an `if' clause that cannot take an `else-part'.
8163 ;; Emacs normally sets the value of `last-command' to the
8164 ;; previous command.
8165@end group
8166@group
8167 ;; `kill-append' concatenates the new string and the old.
8168 ;; `kill-new' inserts text into a new item in the kill ring.
8169 (when string
8170 (if (eq last-command 'kill-region)
8171 ;; if true, prepend string
8172 (kill-append string (< end beg))
8173 (kill-new string)))
8174 (setq this-command 'kill-region))
8175@end group
8176
8177@group
8178 ;; 3. The third argument to `condition-case' tells the interpreter
8179 ;; what to do with an error.
8180@end group
8181@group
8182 ;; The third argument has a conditions part and a body part.
8183 ;; If the conditions are met (in this case,
8184 ;; if text or buffer are read-only)
8185 ;; then the body is executed.
8186@end group
8187@group
8188 ((buffer-read-only text-read-only) ;; this is the if-part
8189 ;; then...
8190 (copy-region-as-kill beg end)
8191@end group
8192@group
8193 (if kill-read-only-ok ;; usually this variable is nil
8194 (message "Read only text copied to kill ring")
8195 ;; or else, signal an error if the buffer is read-only;
8196 (barf-if-buffer-read-only)
8197 ;; and, in any case, signal that the text is read-only.
8198 (signal 'text-read-only (list (current-buffer)))))))
8199@end group
8200@end smallexample
8201@end ignore
8202
d6adf7e7 8203@node condition-case
8cda6f8f
GM
8204@subsection @code{condition-case}
8205@findex condition-case
8206
8207As we have seen earlier (@pxref{Making Errors, , Generate an Error
8208Message}), when the Emacs Lisp interpreter has trouble evaluating an
8209expression, it provides you with help; in the jargon, this is called
8210``signaling an error''. Usually, the computer stops the program and
8211shows you a message.
8212
8213However, some programs undertake complicated actions. They should not
8214simply stop on an error. In the @code{kill-region} function, the most
8215likely error is that you will try to kill text that is read-only and
8216cannot be removed. So the @code{kill-region} function contains code
8217to handle this circumstance. This code, which makes up the body of
8218the @code{kill-region} function, is inside of a @code{condition-case}
8219special form.
8220
8221@need 800
8222The template for @code{condition-case} looks like this:
8223
8224@smallexample
8225@group
8226(condition-case
8227 @var{var}
8228 @var{bodyform}
8229 @var{error-handler}@dots{})
8230@end group
8231@end smallexample
8232
8233The second argument, @var{bodyform}, is straightforward. The
8234@code{condition-case} special form causes the Lisp interpreter to
8235evaluate the code in @var{bodyform}. If no error occurs, the special
8236form returns the code's value and produces the side-effects, if any.
8237
8238In short, the @var{bodyform} part of a @code{condition-case}
8239expression determines what should happen when everything works
8240correctly.
8241
8242However, if an error occurs, among its other actions, the function
8243generating the error signal will define one or more error condition
8244names.
8245
8246An error handler is the third argument to @code{condition case}.
8247An error handler has two parts, a @var{condition-name} and a
8248@var{body}. If the @var{condition-name} part of an error handler
8249matches a condition name generated by an error, then the @var{body}
8250part of the error handler is run.
8251
8252As you will expect, the @var{condition-name} part of an error handler
8253may be either a single condition name or a list of condition names.
8254
8255Also, a complete @code{condition-case} expression may contain more
8256than one error handler. When an error occurs, the first applicable
8257handler is run.
8258
8259Lastly, the first argument to the @code{condition-case} expression,
8260the @var{var} argument, is sometimes bound to a variable that
8261contains information about the error. However, if that argument is
8262nil, as is the case in @code{kill-region}, that information is
8263discarded.
8264
8265@need 1200
8266In brief, in the @code{kill-region} function, the code
8267@code{condition-case} works like this:
8268
8269@smallexample
8270@group
8271@var{If no errors}, @var{run only this code}
8272 @var{but}, @var{if errors}, @var{run this other code}.
8273@end group
8274@end smallexample
8275
8276@ignore
82772006 Oct 24
8278In Emacs 22,
8279copy-region-as-kill is short, 12 lines, and uses
8280filter-buffer-substring, which is longer, 39 lines
8281and has delete-and-extract-region in it.
8282delete-and-extract-region is written in C.
8283
8284see Initializing a Variable with @code{defvar}
8285this is line 8054
8286Initializing a Variable with @code{defvar} includes line 8350
8287@end ignore
8288
d6adf7e7 8289@node Lisp macro
8cda6f8f
GM
8290@subsection Lisp macro
8291@cindex Macro, lisp
8292@cindex Lisp macro
8293
8294The part of the @code{condition-case} expression that is evaluated in
8295the expectation that all goes well has a @code{when}. The code uses
8296@code{when} to determine whether the @code{string} variable points to
8297text that exists.
8298
8299A @code{when} expression is simply a programmers' convenience. It is
8300an @code{if} without the possibility of an else clause. In your mind,
8301you can replace @code{when} with @code{if} and understand what goes
8302on. That is what the Lisp interpreter does.
8303
8304Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
8305enables you to define new control constructs and other language
8306features. It tells the interpreter how to compute another Lisp
8307expression which will in turn compute the value. In this case, the
8308`other expression' is an @code{if} expression.
8309
8310The @code{kill-region} function definition also has an @code{unless}
8311macro; it is the converse of @code{when}. The @code{unless} macro is
8312an @code{if} without a then clause
8313
8314For more about Lisp macros, see @ref{Macros, , Macros, elisp, The GNU
8315Emacs Lisp Reference Manual}. The C programming language also
8316provides macros. These are different, but also useful.
8317
8318@ignore
8319We will briefly look at C macros in
8320@ref{Digression into C}.
8321@end ignore
8322
8323@need 1200
8324Regarding the @code{when} macro, in the @code{condition-case}
8325expression, when the string has content, then another conditional
8326expression is executed. This is an @code{if} with both a then-part
8327and an else-part.
8328
8329@smallexample
8330@group
8331(if (eq last-command 'kill-region)
8332 (kill-append string (< end beg) yank-handler)
8333 (kill-new string nil yank-handler))
8334@end group
8335@end smallexample
8336
8337The then-part is evaluated if the previous command was another call to
8338@code{kill-region}; if not, the else-part is evaluated.
8339
8340@code{yank-handler} is an optional argument to @code{kill-region} that
8341tells the @code{kill-append} and @code{kill-new} functions how deal
8342with properties added to the text, such as `bold' or `italics'.
8343
8344@code{last-command} is a variable that comes with Emacs that we have
8345not seen before. Normally, whenever a function is executed, Emacs
8346sets the value of @code{last-command} to the previous command.
8347
8348@need 1200
8349In this segment of the definition, the @code{if} expression checks
8350whether the previous command was @code{kill-region}. If it was,
8351
8352@smallexample
8353(kill-append string (< end beg) yank-handler)
8354@end smallexample
8355
8356@noindent
8357concatenates a copy of the newly clipped text to the just previously
8358clipped text in the kill ring.
8359
d6adf7e7 8360@node copy-region-as-kill
8cda6f8f
GM
8361@section @code{copy-region-as-kill}
8362@findex copy-region-as-kill
8363@findex nthcdr
8364
8365The @code{copy-region-as-kill} function copies a region of text from a
8366buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8367in the @code{kill-ring}.
8368
8369If you call @code{copy-region-as-kill} immediately after a
8370@code{kill-region} command, Emacs appends the newly copied text to the
8371previously copied text. This means that if you yank back the text, you
8372get it all, from both this and the previous operation. On the other
8373hand, if some other command precedes the @code{copy-region-as-kill},
8374the function copies the text into a separate entry in the kill ring.
8375
8376@menu
8377* Complete copy-region-as-kill:: The complete function definition.
8378* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8379@end menu
8380
8cda6f8f 8381@ifnottex
d6adf7e7 8382@node Complete copy-region-as-kill
8cda6f8f
GM
8383@unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8384@end ifnottex
8385
8386@need 1200
8387Here is the complete text of the version 22 @code{copy-region-as-kill}
8388function:
8389
8390@smallexample
8391@group
8392(defun copy-region-as-kill (beg end)
8393 "Save the region as if killed, but don't kill it.
8394In Transient Mark mode, deactivate the mark.
8395If `interprogram-cut-function' is non-nil, also save the text for a window
8396system cut and paste."
8397 (interactive "r")
8398@end group
8399@group
8400 (if (eq last-command 'kill-region)
8401 (kill-append (filter-buffer-substring beg end) (< end beg))
8402 (kill-new (filter-buffer-substring beg end)))
8403@end group
8404@group
8405 (if transient-mark-mode
8406 (setq deactivate-mark t))
8407 nil)
8408@end group
8409@end smallexample
8410
8411@need 800
8412As usual, this function can be divided into its component parts:
8413
8414@smallexample
8415@group
8416(defun copy-region-as-kill (@var{argument-list})
8417 "@var{documentation}@dots{}"
8418 (interactive "r")
8419 @var{body}@dots{})
8420@end group
8421@end smallexample
8422
8423The arguments are @code{beg} and @code{end} and the function is
8424interactive with @code{"r"}, so the two arguments must refer to the
8425beginning and end of the region. If you have been reading though this
8426document from the beginning, understanding these parts of a function is
8427almost becoming routine.
8428
8429The documentation is somewhat confusing unless you remember that the
8430word `kill' has a meaning different from usual. The `Transient Mark'
8431and @code{interprogram-cut-function} comments explain certain
8432side-effects.
8433
8434After you once set a mark, a buffer always contains a region. If you
8435wish, you can use Transient Mark mode to highlight the region
8436temporarily. (No one wants to highlight the region all the time, so
8437Transient Mark mode highlights it only at appropriate times. Many
8438people turn off Transient Mark mode, so the region is never
8439highlighted.)
8440
8441Also, a windowing system allows you to copy, cut, and paste among
8442different programs. In the X windowing system, for example, the
8443@code{interprogram-cut-function} function is @code{x-select-text},
8444which works with the windowing system's equivalent of the Emacs kill
8445ring.
8446
8447The body of the @code{copy-region-as-kill} function starts with an
8448@code{if} clause. What this clause does is distinguish between two
8449different situations: whether or not this command is executed
8450immediately after a previous @code{kill-region} command. In the first
8451case, the new region is appended to the previously copied text.
8452Otherwise, it is inserted into the beginning of the kill ring as a
8453separate piece of text from the previous piece.
8454
8455The last two lines of the function prevent the region from lighting up
8456if Transient Mark mode is turned on.
8457
8458The body of @code{copy-region-as-kill} merits discussion in detail.
8459
d6adf7e7 8460@node copy-region-as-kill body
8cda6f8f
GM
8461@subsection The Body of @code{copy-region-as-kill}
8462
8463The @code{copy-region-as-kill} function works in much the same way as
8464the @code{kill-region} function. Both are written so that two or more
8465kills in a row combine their text into a single entry. If you yank
8466back the text from the kill ring, you get it all in one piece.
8467Moreover, kills that kill forward from the current position of the
8468cursor are added to the end of the previously copied text and commands
8469that copy text backwards add it to the beginning of the previously
8470copied text. This way, the words in the text stay in the proper
8471order.
8472
8473Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8474use of the @code{last-command} variable that keeps track of the
8475previous Emacs command.
8476
8477@menu
8478* last-command & this-command::
8479* kill-append function::
8480* kill-new function::
8481@end menu
8482
8cda6f8f 8483@ifnottex
d6adf7e7 8484@node last-command & this-command
8cda6f8f
GM
8485@unnumberedsubsubsec @code{last-command} and @code{this-command}
8486@end ifnottex
8487
8488Normally, whenever a function is executed, Emacs sets the value of
8489@code{this-command} to the function being executed (which in this case
8490would be @code{copy-region-as-kill}). At the same time, Emacs sets
8491the value of @code{last-command} to the previous value of
8492@code{this-command}.
8493
8494In the first part of the body of the @code{copy-region-as-kill}
8495function, an @code{if} expression determines whether the value of
8496@code{last-command} is @code{kill-region}. If so, the then-part of
8497the @code{if} expression is evaluated; it uses the @code{kill-append}
8498function to concatenate the text copied at this call to the function
8499with the text already in the first element (the @sc{car}) of the kill
8500ring. On the other hand, if the value of @code{last-command} is not
8501@code{kill-region}, then the @code{copy-region-as-kill} function
8502attaches a new element to the kill ring using the @code{kill-new}
8503function.
8504
8505@need 1250
8506The @code{if} expression reads as follows; it uses @code{eq}:
8507
8508@smallexample
8509@group
8510 (if (eq last-command 'kill-region)
8511 ;; @r{then-part}
8512 (kill-append (filter-buffer-substring beg end) (< end beg))
8513 ;; @r{else-part}
8514 (kill-new (filter-buffer-substring beg end)))
8515@end group
8516@end smallexample
8517
8518@findex filter-buffer-substring
8519(The @code{filter-buffer-substring} function returns a filtered
8520substring of the buffer, if any. Optionally---the arguments are not
8521here, so neither is done---the function may delete the initial text or
8522return the text without its properties; this function is a replacement
8523for the older @code{buffer-substring} function, which came before text
8524properties were implemented.)
8525
8526@findex eq @r{(example of use)}
8527@noindent
8528The @code{eq} function tests whether its first argument is the same Lisp
8529object as its second argument. The @code{eq} function is similar to the
8530@code{equal} function in that it is used to test for equality, but
8531differs in that it determines whether two representations are actually
8532the same object inside the computer, but with different names.
8533@code{equal} determines whether the structure and contents of two
8534expressions are the same.
8535
8536If the previous command was @code{kill-region}, then the Emacs Lisp
8537interpreter calls the @code{kill-append} function
8538
d6adf7e7 8539@node kill-append function
8cda6f8f
GM
8540@unnumberedsubsubsec The @code{kill-append} function
8541@findex kill-append
8542
8543@need 800
8544The @code{kill-append} function looks like this:
8545
8546@c in GNU Emacs 22
8547@smallexample
8548@group
8549(defun kill-append (string before-p &optional yank-handler)
8550 "Append STRING to the end of the latest kill in the kill ring.
8551If BEFORE-P is non-nil, prepend STRING to the kill.
8552@dots{} "
8553 (let* ((cur (car kill-ring)))
8554 (kill-new (if before-p (concat string cur) (concat cur string))
8555 (or (= (length cur) 0)
8556 (equal yank-handler
8557 (get-text-property 0 'yank-handler cur)))
8558 yank-handler)))
8559@end group
8560@end smallexample
8561
8562@ignore
8563was:
8564(defun kill-append (string before-p)
8565 "Append STRING to the end of the latest kill in the kill ring.
8566If BEFORE-P is non-nil, prepend STRING to the kill.
8567If `interprogram-cut-function' is set, pass the resulting kill to
8568it."
8569 (kill-new (if before-p
8570 (concat string (car kill-ring))
8571 (concat (car kill-ring) string))
8572 t))
8573@end ignore
8574
8575@noindent
8576The @code{kill-append} function is fairly straightforward. It uses
8577the @code{kill-new} function, which we will discuss in more detail in
8578a moment.
8579
8580(Also, the function provides an optional argument called
8581@code{yank-handler}; when invoked, this argument tells the function
8582how to deal with properties added to the text, such as `bold' or
8583`italics'.)
8584
8585@c !!! bug in GNU Emacs 22 version of kill-append ?
8586It has a @code{let*} function to set the value of the first element of
8587the kill ring to @code{cur}. (I do not know why the function does not
8588use @code{let} instead; only one value is set in the expression.
8589Perhaps this is a bug that produces no problems?)
8590
8591Consider the conditional that is one of the two arguments to
8592@code{kill-new}. It uses @code{concat} to concatenate the new text to
8593the @sc{car} of the kill ring. Whether it prepends or appends the
8594text depends on the results of an @code{if} expression:
8595
8596@smallexample
8597@group
8598(if before-p ; @r{if-part}
8599 (concat string cur) ; @r{then-part}
8600 (concat cur string)) ; @r{else-part}
8601@end group
8602@end smallexample
8603
8604@noindent
8605If the region being killed is before the region that was killed in the
8606last command, then it should be prepended before the material that was
8607saved in the previous kill; and conversely, if the killed text follows
8608what was just killed, it should be appended after the previous text.
8609The @code{if} expression depends on the predicate @code{before-p} to
8610decide whether the newly saved text should be put before or after the
8611previously saved text.
8612
8613The symbol @code{before-p} is the name of one of the arguments to
8614@code{kill-append}. When the @code{kill-append} function is
8615evaluated, it is bound to the value returned by evaluating the actual
8616argument. In this case, this is the expression @code{(< end beg)}.
8617This expression does not directly determine whether the killed text in
8618this command is located before or after the kill text of the last
8619command; what it does is determine whether the value of the variable
8620@code{end} is less than the value of the variable @code{beg}. If it
8621is, it means that the user is most likely heading towards the
8622beginning of the buffer. Also, the result of evaluating the predicate
8623expression, @code{(< end beg)}, will be true and the text will be
8624prepended before the previous text. On the other hand, if the value of
8625the variable @code{end} is greater than the value of the variable
8626@code{beg}, the text will be appended after the previous text.
8627
8628@need 800
8629When the newly saved text will be prepended, then the string with the new
8630text will be concatenated before the old text:
8631
8632@smallexample
8633(concat string cur)
8634@end smallexample
8635
8636@need 1200
8637@noindent
8638But if the text will be appended, it will be concatenated
8639after the old text:
8640
8641@smallexample
8642(concat cur string))
8643@end smallexample
8644
8645To understand how this works, we first need to review the
8646@code{concat} function. The @code{concat} function links together or
8647unites two strings of text. The result is a string. For example:
8648
8649@smallexample
8650@group
8651(concat "abc" "def")
8652 @result{} "abcdef"
8653@end group
8654
8655@group
8656(concat "new "
8657 (car '("first element" "second element")))
8658 @result{} "new first element"
8659
8660(concat (car
8661 '("first element" "second element")) " modified")
8662 @result{} "first element modified"
8663@end group
8664@end smallexample
8665
8666We can now make sense of @code{kill-append}: it modifies the contents
8667of the kill ring. The kill ring is a list, each element of which is
8668saved text. The @code{kill-append} function uses the @code{kill-new}
8669function which in turn uses the @code{setcar} function.
8670
d6adf7e7 8671@node kill-new function
8cda6f8f
GM
8672@unnumberedsubsubsec The @code{kill-new} function
8673@findex kill-new
8674
8675@c in GNU Emacs 22, additional documentation to kill-new:
8676@ignore
8677Optional third arguments YANK-HANDLER controls how the STRING is later
8678inserted into a buffer; see `insert-for-yank' for details.
8679When a yank handler is specified, STRING must be non-empty (the yank
8680handler, if non-nil, is stored as a `yank-handler' text property on STRING).
8681
8682When the yank handler has a non-nil PARAM element, the original STRING
8683argument is not used by `insert-for-yank'. However, since Lisp code
8684may access and use elements from the kill ring directly, the STRING
8685argument should still be a \"useful\" string for such uses."
8686@end ignore
8687@need 1200
8688The @code{kill-new} function looks like this:
8689
8690@smallexample
8691@group
8692(defun kill-new (string &optional replace yank-handler)
8693 "Make STRING the latest kill in the kill ring.
8694Set `kill-ring-yank-pointer' to point to it.
8695
8696If `interprogram-cut-function' is non-nil, apply it to STRING.
8697Optional second argument REPLACE non-nil means that STRING will replace
8698the front of the kill ring, rather than being added to the list.
8699@dots{}"
8700@end group
8701@group
8702 (if (> (length string) 0)
8703 (if yank-handler
8704 (put-text-property 0 (length string)
8705 'yank-handler yank-handler string))
8706 (if yank-handler
8707 (signal 'args-out-of-range
8708 (list string "yank-handler specified for empty string"))))
8709@end group
8710@group
8711 (if (fboundp 'menu-bar-update-yank-menu)
8712 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8713@end group
8714@group
8715 (if (and replace kill-ring)
8716 (setcar kill-ring string)
8717 (push string kill-ring)
8718 (if (> (length kill-ring) kill-ring-max)
8719 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8720@end group
8721@group
8722 (setq kill-ring-yank-pointer kill-ring)
8723 (if interprogram-cut-function
8724 (funcall interprogram-cut-function string (not replace))))
8725@end group
8726@end smallexample
8727@ignore
8728was:
8729(defun kill-new (string &optional replace)
8730 "Make STRING the latest kill in the kill ring.
8731Set the kill-ring-yank pointer to point to it.
8732If `interprogram-cut-function' is non-nil, apply it to STRING.
8733Optional second argument REPLACE non-nil means that STRING will replace
8734the front of the kill ring, rather than being added to the list."
8735 (and (fboundp 'menu-bar-update-yank-menu)
8736 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8737 (if (and replace kill-ring)
8738 (setcar kill-ring string)
8739 (setq kill-ring (cons string kill-ring))
8740 (if (> (length kill-ring) kill-ring-max)
8741 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8742 (setq kill-ring-yank-pointer kill-ring)
8743 (if interprogram-cut-function
8744 (funcall interprogram-cut-function string (not replace))))
8745@end ignore
8746
8747(Notice that the function is not interactive.)
8748
8749As usual, we can look at this function in parts.
8750
8751The function definition has an optional @code{yank-handler} argument,
8752which when invoked tells the function how to deal with properties
8753added to the text, such as `bold' or `italics'. We will skip that.
8754
8755@need 1200
8756The first line of the documentation makes sense:
8757
8758@smallexample
8759Make STRING the latest kill in the kill ring.
8760@end smallexample
8761
8762@noindent
8763Let's skip over the rest of the documentation for the moment.
8764
8765@noindent
8766Also, let's skip over the initial @code{if} expression and those lines
8767of code involving @code{menu-bar-update-yank-menu}. We will explain
8768them below.
8769
8770@need 1200
8771The critical lines are these:
8772
8773@smallexample
8774@group
8775 (if (and replace kill-ring)
8776 ;; @r{then}
8777 (setcar kill-ring string)
8778@end group
8779@group
8780 ;; @r{else}
8781 (push string kill-ring)
8782@end group
8783@group
8784 (setq kill-ring (cons string kill-ring))
8785 (if (> (length kill-ring) kill-ring-max)
8786 ;; @r{avoid overly long kill ring}
8787 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8788@end group
8789@group
8790 (setq kill-ring-yank-pointer kill-ring)
8791 (if interprogram-cut-function
8792 (funcall interprogram-cut-function string (not replace))))
8793@end group
8794@end smallexample
8795
8796The conditional test is @w{@code{(and replace kill-ring)}}.
8797This will be true when two conditions are met: the kill ring has
8798something in it, and the @code{replace} variable is true.
8799
8800@need 1250
8801When the @code{kill-append} function sets @code{replace} to be true
8802and when the kill ring has at least one item in it, the @code{setcar}
8803expression is executed:
8804
8805@smallexample
8806(setcar kill-ring string)
8807@end smallexample
8808
8809The @code{setcar} function actually changes the first element of the
8810@code{kill-ring} list to the value of @code{string}. It replaces the
8811first element.
8812
8813@need 1250
8814On the other hand, if the kill ring is empty, or replace is false, the
8815else-part of the condition is executed:
8816
8817@smallexample
8818(push string kill-ring)
8819@end smallexample
8820
8821@noindent
8822@need 1250
8823@code{push} puts its first argument onto the second. It is similar to
8824the older
8825
8826@smallexample
8827(setq kill-ring (cons string kill-ring))
8828@end smallexample
8829
8830@noindent
8831@need 1250
8832or the newer
8833
8834@smallexample
8835(add-to-list kill-ring string)
8836@end smallexample
8837
8838@noindent
8839When it is false, the expression first constructs a new version of the
8840kill ring by prepending @code{string} to the existing kill ring as a
8841new element (that is what the @code{push} does). Then it executes a
8842second @code{if} clause. This second @code{if} clause keeps the kill
8843ring from growing too long.
8844
8845Let's look at these two expressions in order.
8846
8847The @code{push} line of the else-part sets the new value of the kill
8848ring to what results from adding the string being killed to the old
8849kill ring.
8850
8851We can see how this works with an example.
8852
8853@need 800
8854First,
8855
8856@smallexample
8857(setq example-list '("here is a clause" "another clause"))
8858@end smallexample
8859
8860@need 1200
8861@noindent
8862After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8863@code{example-list} and see what it returns:
8864
8865@smallexample
8866@group
8867example-list
8868 @result{} ("here is a clause" "another clause")
8869@end group
8870@end smallexample
8871
8872@need 1200
8873@noindent
8874Now, we can add a new element on to this list by evaluating the
8875following expression:
8876@findex push, @r{example}
8877
8878@smallexample
8879(push "a third clause" example-list)
8880@end smallexample
8881
8882@need 800
8883@noindent
8884When we evaluate @code{example-list}, we find its value is:
8885
8886@smallexample
8887@group
8888example-list
8889 @result{} ("a third clause" "here is a clause" "another clause")
8890@end group
8891@end smallexample
8892
8893@noindent
8894Thus, the third clause is added to the list by @code{push}.
8895
8896@need 1200
8897Now for the second part of the @code{if} clause. This expression
8898keeps the kill ring from growing too long. It looks like this:
8899
8900@smallexample
8901@group
8902(if (> (length kill-ring) kill-ring-max)
8903 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8904@end group
8905@end smallexample
8906
8907The code checks whether the length of the kill ring is greater than
8908the maximum permitted length. This is the value of
8909@code{kill-ring-max} (which is 60, by default). If the length of the
8910kill ring is too long, then this code sets the last element of the
8911kill ring to @code{nil}. It does this by using two functions,
8912@code{nthcdr} and @code{setcdr}.
8913
8914We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8915It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8916@sc{car} of a list. In this case, however, @code{setcdr} will not be
8917setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8918function is used to cause it to set the @sc{cdr} of the next to last
8919element of the kill ring---this means that since the @sc{cdr} of the
8920next to last element is the last element of the kill ring, it will set
8921the last element of the kill ring.
8922
8923@findex nthcdr, @r{example}
8924The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8925list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8926@dots{} It does this @var{N} times and returns the results.
8927(@xref{nthcdr, , @code{nthcdr}}.)
8928
8929@findex setcdr, @r{example}
8930Thus, if we had a four element list that was supposed to be three
8931elements long, we could set the @sc{cdr} of the next to last element
8932to @code{nil}, and thereby shorten the list. (If you set the last
8933element to some other value than @code{nil}, which you could do, then
8934you would not have shortened the list. @xref{setcdr, ,
8935@code{setcdr}}.)
8936
8937You can see shortening by evaluating the following three expressions
8938in turn. First set the value of @code{trees} to @code{(maple oak pine
8939birch)}, then set the @sc{cdr} of its second @sc{cdr} to @code{nil}
8940and then find the value of @code{trees}:
8941
8942@smallexample
8943@group
8944(setq trees '(maple oak pine birch))
8945 @result{} (maple oak pine birch)
8946@end group
8947
8948@group
8949(setcdr (nthcdr 2 trees) nil)
8950 @result{} nil
8951
8952trees
8953 @result{} (maple oak pine)
8954@end group
8955@end smallexample
8956
8957@noindent
8958(The value returned by the @code{setcdr} expression is @code{nil} since
8959that is what the @sc{cdr} is set to.)
8960
8961To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8962@sc{cdr} a number of times that is one less than the maximum permitted
8963size of the kill ring and @code{setcdr} sets the @sc{cdr} of that
8964element (which will be the rest of the elements in the kill ring) to
8965@code{nil}. This prevents the kill ring from growing too long.
8966
8967@need 800
8968The next to last expression in the @code{kill-new} function is
8969
8970@smallexample
8971(setq kill-ring-yank-pointer kill-ring)
8972@end smallexample
8973
8974The @code{kill-ring-yank-pointer} is a global variable that is set to be
8975the @code{kill-ring}.
8976
8977Even though the @code{kill-ring-yank-pointer} is called a
8978@samp{pointer}, it is a variable just like the kill ring. However, the
8979name has been chosen to help humans understand how the variable is used.
8980
8981@need 1200
8982Now, to return to an early expression in the body of the function:
8983
8984@smallexample
8985@group
8986 (if (fboundp 'menu-bar-update-yank-menu)
8987 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8988@end group
8989@end smallexample
8990
8991@noindent
8992It starts with an @code{if} expression
8993
8994In this case, the expression tests first to see whether
8995@code{menu-bar-update-yank-menu} exists as a function, and if so,
8996calls it. The @code{fboundp} function returns true if the symbol it
8997is testing has a function definition that `is not void'. If the
8998symbol's function definition were void, we would receive an error
8999message, as we did when we created errors intentionally (@pxref{Making
9000Errors, , Generate an Error Message}).
9001
9002@noindent
9003The then-part contains an expression whose first element is the
9004function @code{and}.
9005
9006@findex and
9007The @code{and} special form evaluates each of its arguments until one
9008of the arguments returns a value of @code{nil}, in which case the
9009@code{and} expression returns @code{nil}; however, if none of the
9010arguments returns a value of @code{nil}, the value resulting from
9011evaluating the last argument is returned. (Since such a value is not
9012@code{nil}, it is considered true in Emacs Lisp.) In other words, an
9013@code{and} expression returns a true value only if all its arguments
9014are true. (@xref{Second Buffer Related Review}.)
9015
9016The expression determines whether the second argument to
9017@code{menu-bar-update-yank-menu} is true or not.
9018@ignore
9019 ;; If we're supposed to be extending an existing string, and that
9020 ;; string really is at the front of the menu, then update it in place.
9021@end ignore
9022
9023@code{menu-bar-update-yank-menu} is one of the functions that make it
9024possible to use the `Select and Paste' menu in the Edit item of a menu
9025bar; using a mouse, you can look at the various pieces of text you
9026have saved and select one piece to paste.
9027
9028The last expression in the @code{kill-new} function adds the newly
9029copied string to whatever facility exists for copying and pasting
9030among different programs running in a windowing system. In the X
9031Windowing system, for example, the @code{x-select-text} function takes
1df7defd 9032the string and stores it in memory operated by X@. You can paste the
8cda6f8f
GM
9033string in another program, such as an Xterm.
9034
9035@need 1200
9036The expression looks like this:
9037
9038@smallexample
9039@group
9040 (if interprogram-cut-function
9041 (funcall interprogram-cut-function string (not replace))))
9042@end group
9043@end smallexample
9044
9045If an @code{interprogram-cut-function} exists, then Emacs executes
9046@code{funcall}, which in turn calls its first argument as a function
9047and passes the remaining arguments to it. (Incidentally, as far as I
9048can see, this @code{if} expression could be replaced by an @code{and}
9049expression similar to the one in the first part of the function.)
9050
9051We are not going to discuss windowing systems and other programs
9052further, but merely note that this is a mechanism that enables GNU
9053Emacs to work easily and well with other programs.
9054
9055This code for placing text in the kill ring, either concatenated with
9056an existing element or as a new element, leads us to the code for
9057bringing back text that has been cut out of the buffer---the yank
9058commands. However, before discussing the yank commands, it is better
9059to learn how lists are implemented in a computer. This will make
9060clear such mysteries as the use of the term `pointer'. But before
9061that, we will digress into C.
9062
9063@ignore
9064@c is this true in Emacs 22? Does not seems to be
9065
9066 (If the @w{@code{(< end beg))}}
9067expression is true, @code{kill-append} prepends the string to the just
9068previously clipped text. For a detailed discussion, see
9069@ref{kill-append function, , The @code{kill-append} function}.)
9070
9071If you then yank back the text, i.e., `paste' it, you get both
9072pieces of text at once. That way, if you delete two words in a row,
9073and then yank them back, you get both words, in their proper order,
9074with one yank. (The @w{@code{(< end beg))}} expression makes sure the
9075order is correct.)
9076
9077On the other hand, if the previous command is not @code{kill-region},
9078then the @code{kill-new} function is called, which adds the text to
9079the kill ring as the latest item, and sets the
9080@code{kill-ring-yank-pointer} variable to point to it.
9081@end ignore
9082@ignore
9083
9084@c Evidently, changed for Emacs 22. The zap-to-char command does not
9085@c use the delete-and-extract-region function
9086
90872006 Oct 26, the Digression into C is now OK but should come after
9088copy-region-as-kill and filter-buffer-substring
9089
90902006 Oct 24
9091In Emacs 22,
9092copy-region-as-kill is short, 12 lines, and uses
9093filter-buffer-substring, which is longer, 39 lines
9094and has delete-and-extract-region in it.
9095delete-and-extract-region is written in C.
9096
9097see Initializing a Variable with @code{defvar}
9098@end ignore
9099
d6adf7e7 9100@node Digression into C
8cda6f8f
GM
9101@section Digression into C
9102@findex delete-and-extract-region
9103@cindex C, a digression into
9104@cindex Digression into C
9105
9106The @code{copy-region-as-kill} function (@pxref{copy-region-as-kill, ,
9107@code{copy-region-as-kill}}) uses the @code{filter-buffer-substring}
9108function, which in turn uses the @code{delete-and-extract-region}
9109function. It removes the contents of a region and you cannot get them
9110back.
9111
9112Unlike the other code discussed here, the
9113@code{delete-and-extract-region} function is not written in Emacs
9114Lisp; it is written in C and is one of the primitives of the GNU Emacs
9115system. Since it is very simple, I will digress briefly from Lisp and
9116describe it here.
9117
9118@c GNU Emacs 22 in /usr/local/src/emacs/src/editfns.c
9119@c the DEFUN for buffer-substring-no-properties
9120
9121@need 1500
9122Like many of the other Emacs primitives,
9123@code{delete-and-extract-region} is written as an instance of a C
9124macro, a macro being a template for code. The complete macro looks
9125like this:
9126
9127@smallexample
9128@group
9129DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
9130 Sbuffer_substring_no_properties, 2, 2, 0,
9131 doc: /* Return the characters of part of the buffer,
9132without the text properties.
9133The two arguments START and END are character positions;
9134they can be in either order. */)
9135 (start, end)
9136 Lisp_Object start, end;
9137@{
9138 register int b, e;
9139
9140 validate_region (&start, &end);
9141 b = XINT (start);
9142 e = XINT (end);
9143
9144 return make_buffer_string (b, e, 0);
9145@}
9146@end group
9147@end smallexample
9148
9149Without going into the details of the macro writing process, let me
9150point out that this macro starts with the word @code{DEFUN}. The word
9151@code{DEFUN} was chosen since the code serves the same purpose as
9152@code{defun} does in Lisp. (The @code{DEFUN} C macro is defined in
9153@file{emacs/src/lisp.h}.)
9154
9155The word @code{DEFUN} is followed by seven parts inside of
9156parentheses:
9157
9158@itemize @bullet
9159@item
9160The first part is the name given to the function in Lisp,
9161@code{delete-and-extract-region}.
9162
9163@item
9164The second part is the name of the function in C,
9165@code{Fdelete_and_extract_region}. By convention, it starts with
9166@samp{F}. Since C does not use hyphens in names, underscores are used
9167instead.
9168
9169@item
9170The third part is the name for the C constant structure that records
9171information on this function for internal use. It is the name of the
9172function in C but begins with an @samp{S} instead of an @samp{F}.
9173
9174@item
9175The fourth and fifth parts specify the minimum and maximum number of
9176arguments the function can have. This function demands exactly 2
9177arguments.
9178
9179@item
9180The sixth part is nearly like the argument that follows the
9181@code{interactive} declaration in a function written in Lisp: a letter
9182followed, perhaps, by a prompt. The only difference from the Lisp is
9183when the macro is called with no arguments. Then you write a @code{0}
9184(which is a `null string'), as in this macro.
9185
9186If you were to specify arguments, you would place them between
9187quotation marks. The C macro for @code{goto-char} includes
9188@code{"NGoto char: "} in this position to indicate that the function
9189expects a raw prefix, in this case, a numerical location in a buffer,
9190and provides a prompt.
9191
9192@item
9193The seventh part is a documentation string, just like the one for a
9194function written in Emacs Lisp, except that every newline must be
9195written explicitly as @samp{\n} followed by a backslash and carriage
9196return.
9197
9198@need 1000
9199Thus, the first two lines of documentation for @code{goto-char} are
9200written like this:
9201
9202@smallexample
9203@group
9204 "Set point to POSITION, a number or marker.\n\
9205Beginning of buffer is position (point-min), end is (point-max)."
9206@end group
9207@end smallexample
9208@end itemize
9209
9210@need 1200
9211In a C macro, the formal parameters come next, with a statement of
9212what kind of object they are, followed by what might be called the `body'
9213of the macro. For @code{delete-and-extract-region} the `body'
9214consists of the following four lines:
9215
9216@smallexample
9217@group
9218validate_region (&start, &end);
9219if (XINT (start) == XINT (end))
9220 return build_string ("");
9221return del_range_1 (XINT (start), XINT (end), 1, 1);
9222@end group
9223@end smallexample
9224
9225The @code{validate_region} function checks whether the values
9226passed as the beginning and end of the region are the proper type and
9227are within range. If the beginning and end positions are the same,
9228then return and empty string.
9229
9230The @code{del_range_1} function actually deletes the text. It is a
9231complex function we will not look into. It updates the buffer and
9232does other things. However, it is worth looking at the two arguments
9233passed to @code{del_range}. These are @w{@code{XINT (start)}} and
9234@w{@code{XINT (end)}}.
9235
9236As far as the C language is concerned, @code{start} and @code{end} are
9237two integers that mark the beginning and end of the region to be
9238deleted@footnote{More precisely, and requiring more expert knowledge
9239to understand, the two integers are of type `Lisp_Object', which can
9240also be a C union instead of an integer type.}.
9241
9242In early versions of Emacs, these two numbers were thirty-two bits
9243long, but the code is slowly being generalized to handle other
9244lengths. Three of the available bits are used to specify the type of
9245information; the remaining bits are used as `content'.
9246
9247@samp{XINT} is a C macro that extracts the relevant number from the
9248longer collection of bits; the three other bits are discarded.
9249
9250@need 800
9251The command in @code{delete-and-extract-region} looks like this:
9252
9253@smallexample
9254del_range_1 (XINT (start), XINT (end), 1, 1);
9255@end smallexample
9256
9257@noindent
9258It deletes the region between the beginning position, @code{start},
9259and the ending position, @code{end}.
9260
9261From the point of view of the person writing Lisp, Emacs is all very
9262simple; but hidden underneath is a great deal of complexity to make it
9263all work.
9264
d6adf7e7 9265@node defvar
8cda6f8f
GM
9266@section Initializing a Variable with @code{defvar}
9267@findex defvar
9268@cindex Initializing a variable
9269@cindex Variable initialization
9270
9271@ignore
92722006 Oct 24
9273In Emacs 22,
9274copy-region-as-kill is short, 12 lines, and uses
9275filter-buffer-substring, which is longer, 39 lines
9276and has delete-and-extract-region in it.
9277delete-and-extract-region is written in C.
9278
9279see Initializing a Variable with @code{defvar}
9280
9281@end ignore
9282
9283The @code{copy-region-as-kill} function is written in Emacs Lisp. Two
9284functions within it, @code{kill-append} and @code{kill-new}, copy a
9285region in a buffer and save it in a variable called the
9286@code{kill-ring}. This section describes how the @code{kill-ring}
9287variable is created and initialized using the @code{defvar} special
9288form.
9289
9290(Again we note that the term @code{kill-ring} is a misnomer. The text
9291that is clipped out of the buffer can be brought back; it is not a ring
9292of corpses, but a ring of resurrectable text.)
9293
9294In Emacs Lisp, a variable such as the @code{kill-ring} is created and
9295given an initial value by using the @code{defvar} special form. The
9296name comes from ``define variable''.
9297
9298The @code{defvar} special form is similar to @code{setq} in that it sets
9299the value of a variable. It is unlike @code{setq} in two ways: first,
9300it only sets the value of the variable if the variable does not already
9301have a value. If the variable already has a value, @code{defvar} does
9302not override the existing value. Second, @code{defvar} has a
9303documentation string.
9304
9305(Another special form, @code{defcustom}, is designed for variables
9306that people customize. It has more features than @code{defvar}.
9307(@xref{defcustom, , Setting Variables with @code{defcustom}}.)
9308
9309@menu
9310* See variable current value::
9311* defvar and asterisk::
9312@end menu
9313
8cda6f8f 9314@ifnottex
d6adf7e7 9315@node See variable current value
8cda6f8f
GM
9316@unnumberedsubsec Seeing the Current Value of a Variable
9317@end ifnottex
9318
9319You can see the current value of a variable, any variable, by using
9320the @code{describe-variable} function, which is usually invoked by
9321typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
9322(followed by @key{RET}) when prompted, you will see what is in your
9323current kill ring---this may be quite a lot! Conversely, if you have
9324been doing nothing this Emacs session except read this document, you
9325may have nothing in it. Also, you will see the documentation for
9326@code{kill-ring}:
9327
9328@smallexample
9329@group
9330Documentation:
9331List of killed text sequences.
9332Since the kill ring is supposed to interact nicely with cut-and-paste
9333facilities offered by window systems, use of this variable should
9334@end group
9335@group
9336interact nicely with `interprogram-cut-function' and
9337`interprogram-paste-function'. The functions `kill-new',
9338`kill-append', and `current-kill' are supposed to implement this
9339interaction; you may want to use them instead of manipulating the kill
9340ring directly.
9341@end group
9342@end smallexample
9343
9344@need 800
9345The kill ring is defined by a @code{defvar} in the following way:
9346
9347@smallexample
9348@group
9349(defvar kill-ring nil
9350 "List of killed text sequences.
9351@dots{}")
9352@end group
9353@end smallexample
9354
9355@noindent
9356In this variable definition, the variable is given an initial value of
9357@code{nil}, which makes sense, since if you have saved nothing, you want
9358nothing back if you give a @code{yank} command. The documentation
9359string is written just like the documentation string of a @code{defun}.
9360As with the documentation string of the @code{defun}, the first line of
9361the documentation should be a complete sentence, since some commands,
9362like @code{apropos}, print only the first line of documentation.
9363Succeeding lines should not be indented; otherwise they look odd when
9364you use @kbd{C-h v} (@code{describe-variable}).
9365
d6adf7e7 9366@node defvar and asterisk
8cda6f8f
GM
9367@subsection @code{defvar} and an asterisk
9368@findex defvar @r{for a user customizable variable}
9369@findex defvar @r{with an asterisk}
9370
9371In the past, Emacs used the @code{defvar} special form both for
9372internal variables that you would not expect a user to change and for
9373variables that you do expect a user to change. Although you can still
9374use @code{defvar} for user customizable variables, please use
9375@code{defcustom} instead, since that special form provides a path into
9376the Customization commands. (@xref{defcustom, , Specifying Variables
9377using @code{defcustom}}.)
9378
9379When you specified a variable using the @code{defvar} special form,
943157cf
GM
9380you could distinguish a variable that a user might want to change from
9381others by typing an asterisk, @samp{*}, in the first column of its
9382documentation string. For example:
8cda6f8f
GM
9383
9384@smallexample
9385@group
9386(defvar shell-command-default-error-buffer nil
9387 "*Buffer name for `shell-command' @dots{} error output.
9388@dots{} ")
9389@end group
9390@end smallexample
9391
9392@findex set-variable
9393@noindent
9394You could (and still can) use the @code{set-variable} command to
9395change the value of @code{shell-command-default-error-buffer}
9396temporarily. However, options set using @code{set-variable} are set
9397only for the duration of your editing session. The new values are not
9398saved between sessions. Each time Emacs starts, it reads the original
9399value, unless you change the value within your @file{.emacs} file,
9400either by setting it manually or by using @code{customize}.
9401@xref{Emacs Initialization, , Your @file{.emacs} File}.
9402
9403For me, the major use of the @code{set-variable} command is to suggest
9404variables that I might want to set in my @file{.emacs} file. There
9405are now more than 700 such variables --- far too many to remember
9406readily. Fortunately, you can press @key{TAB} after calling the
9407@code{M-x set-variable} command to see the list of variables.
9408(@xref{Examining, , Examining and Setting Variables, emacs,
9409The GNU Emacs Manual}.)
9410
9411@need 1250
d6adf7e7 9412@node cons & search-fwd Review
8cda6f8f
GM
9413@section Review
9414
9415Here is a brief summary of some recently introduced functions.
9416
9417@table @code
9418@item car
9419@itemx cdr
9420@code{car} returns the first element of a list; @code{cdr} returns the
9421second and subsequent elements of a list.
9422
9423@need 1250
9424For example:
9425
9426@smallexample
9427@group
9428(car '(1 2 3 4 5 6 7))
9429 @result{} 1
9430(cdr '(1 2 3 4 5 6 7))
9431 @result{} (2 3 4 5 6 7)
9432@end group
9433@end smallexample
9434
9435@item cons
9436@code{cons} constructs a list by prepending its first argument to its
9437second argument.
9438
9439@need 1250
9440For example:
9441
9442@smallexample
9443@group
9444(cons 1 '(2 3 4))
9445 @result{} (1 2 3 4)
9446@end group
9447@end smallexample
9448
9449@item funcall
9450@code{funcall} evaluates its first argument as a function. It passes
9451its remaining arguments to its first argument.
9452
9453@item nthcdr
9454Return the result of taking @sc{cdr} `n' times on a list.
9455@iftex
9456The
9457@tex
9458$n^{th}$
9459@end tex
9460@code{cdr}.
9461@end iftex
9462The `rest of the rest', as it were.
9463
9464@need 1250
9465For example:
9466
9467@smallexample
9468@group
9469(nthcdr 3 '(1 2 3 4 5 6 7))
9470 @result{} (4 5 6 7)
9471@end group
9472@end smallexample
9473
9474@item setcar
9475@itemx setcdr
9476@code{setcar} changes the first element of a list; @code{setcdr}
9477changes the second and subsequent elements of a list.
9478
9479@need 1250
9480For example:
9481
9482@smallexample
9483@group
9484(setq triple '(1 2 3))
9485
9486(setcar triple '37)
9487
9488triple
9489 @result{} (37 2 3)
9490
9491(setcdr triple '("foo" "bar"))
9492
9493triple
9494 @result{} (37 "foo" "bar")
9495@end group
9496@end smallexample
9497
9498@item progn
9499Evaluate each argument in sequence and then return the value of the
9500last.
9501
9502@need 1250
9503For example:
9504
9505@smallexample
9506@group
9507(progn 1 2 3 4)
9508 @result{} 4
9509@end group
9510@end smallexample
9511
9512@item save-restriction
9513Record whatever narrowing is in effect in the current buffer, if any,
9514and restore that narrowing after evaluating the arguments.
9515
9516@item search-forward
9517Search for a string, and if the string is found, move point. With a
9518regular expression, use the similar @code{re-search-forward}.
9519(@xref{Regexp Search, , Regular Expression Searches}, for an
9520explanation of regular expression patterns and searches.)
9521
9522@need 1250
9523@noindent
9524@code{search-forward} and @code{re-search-forward} take four
9525arguments:
9526
9527@enumerate
9528@item
9529The string or regular expression to search for.
9530
9531@item
9532Optionally, the limit of the search.
9533
9534@item
9535Optionally, what to do if the search fails, return @code{nil} or an
9536error message.
9537
9538@item
9539Optionally, how many times to repeat the search; if negative, the
9540search goes backwards.
9541@end enumerate
9542
9543@item kill-region
9544@itemx delete-and-extract-region
9545@itemx copy-region-as-kill
9546
9547@code{kill-region} cuts the text between point and mark from the
9548buffer and stores that text in the kill ring, so you can get it back
9549by yanking.
9550
9551@code{copy-region-as-kill} copies the text between point and mark into
9552the kill ring, from which you can get it by yanking. The function
9553does not cut or remove the text from the buffer.
9554@end table
9555
9556@code{delete-and-extract-region} removes the text between point and
9557mark from the buffer and throws it away. You cannot get it back.
9558(This is not an interactive command.)
9559
9560@need 1500
d6adf7e7 9561@node search Exercises
8cda6f8f
GM
9562@section Searching Exercises
9563
9564@itemize @bullet
9565@item
9566Write an interactive function that searches for a string. If the
9567search finds the string, leave point after it and display a message
9568that says ``Found!''. (Do not use @code{search-forward} for the name
9569of this function; if you do, you will overwrite the existing version of
9570@code{search-forward} that comes with Emacs. Use a name such as
9571@code{test-search} instead.)
9572
9573@item
9574Write a function that prints the third element of the kill ring in the
9575echo area, if any; if the kill ring does not contain a third element,
9576print an appropriate message.
9577@end itemize
9578
d6adf7e7 9579@node List Implementation
8cda6f8f
GM
9580@chapter How Lists are Implemented
9581@cindex Lists in a computer
9582
9583In Lisp, atoms are recorded in a straightforward fashion; if the
9584implementation is not straightforward in practice, it is, nonetheless,
9585straightforward in theory. The atom @samp{rose}, for example, is
9586recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
9587@samp{e}. A list, on the other hand, is kept differently. The mechanism
9588is equally simple, but it takes a moment to get used to the idea. A
9589list is kept using a series of pairs of pointers. In the series, the
9590first pointer in each pair points to an atom or to another list, and the
9591second pointer in each pair points to the next pair, or to the symbol
9592@code{nil}, which marks the end of the list.
9593
9594A pointer itself is quite simply the electronic address of what is
9595pointed to. Hence, a list is kept as a series of electronic addresses.
9596
9597@menu
9598* Lists diagrammed::
9599* Symbols as Chest:: Exploring a powerful metaphor.
9600* List Exercise::
9601@end menu
9602
8cda6f8f 9603@ifnottex
d6adf7e7 9604@node Lists diagrammed
8cda6f8f
GM
9605@unnumberedsec Lists diagrammed
9606@end ifnottex
9607
9608For example, the list @code{(rose violet buttercup)} has three elements,
9609@samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
9610electronic address of @samp{rose} is recorded in a segment of computer
9611memory along with the address that gives the electronic address of where
9612the atom @samp{violet} is located; and that address (the one that tells
9613where @samp{violet} is located) is kept along with an address that tells
9614where the address for the atom @samp{buttercup} is located.
9615
9616@need 1200
9617This sounds more complicated than it is and is easier seen in a diagram:
9618
9619@c clear print-postscript-figures
9620@c !!! cons-cell-diagram #1
9621@ifnottex
9622@smallexample
9623@group
9624 ___ ___ ___ ___ ___ ___
9625 |___|___|--> |___|___|--> |___|___|--> nil
9626 | | |
9627 | | |
9628 --> rose --> violet --> buttercup
9629@end group
9630@end smallexample
9631@end ifnottex
9632@ifset print-postscript-figures
9633@sp 1
9634@tex
9635@center @image{cons-1}
9636%%%% old method of including an image
9637% \input /usr/local/lib/tex/inputs/psfig.tex
9638% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
9639% \catcode`\@=0 %
9640@end tex
9641@sp 1
9642@end ifset
9643@ifclear print-postscript-figures
9644@iftex
9645@smallexample
9646@group
9647 ___ ___ ___ ___ ___ ___
9648 |___|___|--> |___|___|--> |___|___|--> nil
9649 | | |
9650 | | |
9651 --> rose --> violet --> buttercup
9652@end group
9653@end smallexample
9654@end iftex
9655@end ifclear
9656
9657@noindent
9658In the diagram, each box represents a word of computer memory that
9659holds a Lisp object, usually in the form of a memory address. The boxes,
1df7defd 9660i.e., the addresses, are in pairs. Each arrow points to what the address
8cda6f8f
GM
9661is the address of, either an atom or another pair of addresses. The
9662first box is the electronic address of @samp{rose} and the arrow points
9663to @samp{rose}; the second box is the address of the next pair of boxes,
9664the first part of which is the address of @samp{violet} and the second
9665part of which is the address of the next pair. The very last box
9666points to the symbol @code{nil}, which marks the end of the list.
9667
9668@need 1200
9669When a variable is set to a list with a function such as @code{setq},
9670it stores the address of the first box in the variable. Thus,
9671evaluation of the expression
9672
9673@smallexample
9674(setq bouquet '(rose violet buttercup))
9675@end smallexample
9676
9677@need 1250
9678@noindent
9679creates a situation like this:
9680
9681@c cons-cell-diagram #2
9682@ifnottex
9683@smallexample
9684@group
9685bouquet
9686 |
9687 | ___ ___ ___ ___ ___ ___
9688 --> |___|___|--> |___|___|--> |___|___|--> nil
9689 | | |
9690 | | |
9691 --> rose --> violet --> buttercup
9692@end group
9693@end smallexample
9694@end ifnottex
9695@ifset print-postscript-figures
9696@sp 1
9697@tex
9698@center @image{cons-2}
9699%%%% old method of including an image
9700% \input /usr/local/lib/tex/inputs/psfig.tex
9701% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9702% \catcode`\@=0 %
9703@end tex
9704@sp 1
9705@end ifset
9706@ifclear print-postscript-figures
9707@iftex
9708@smallexample
9709@group
9710bouquet
9711 |
9712 | ___ ___ ___ ___ ___ ___
9713 --> |___|___|--> |___|___|--> |___|___|--> nil
9714 | | |
9715 | | |
9716 --> rose --> violet --> buttercup
9717@end group
9718@end smallexample
9719@end iftex
9720@end ifclear
9721
9722@noindent
9723In this example, the symbol @code{bouquet} holds the address of the first
9724pair of boxes.
9725
9726@need 1200
9727This same list can be illustrated in a different sort of box notation
9728like this:
9729
9730@c cons-cell-diagram #2a
9731@ifnottex
9732@smallexample
9733@group
9734bouquet
9735 |
9736 | -------------- --------------- ----------------
9737 | | car | cdr | | car | cdr | | car | cdr |
9738 -->| rose | o------->| violet | o------->| butter- | nil |
9739 | | | | | | | cup | |
9740 -------------- --------------- ----------------
9741@end group
9742@end smallexample
9743@end ifnottex
9744@ifset print-postscript-figures
9745@sp 1
9746@tex
9747@center @image{cons-2a}
9748%%%% old method of including an image
9749% \input /usr/local/lib/tex/inputs/psfig.tex
9750% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9751% \catcode`\@=0 %
9752@end tex
9753@sp 1
9754@end ifset
9755@ifclear print-postscript-figures
9756@iftex
9757@smallexample
9758@group
9759bouquet
9760 |
9761 | -------------- --------------- ----------------
9762 | | car | cdr | | car | cdr | | car | cdr |
9763 -->| rose | o------->| violet | o------->| butter- | nil |
9764 | | | | | | | cup | |
9765 -------------- --------------- ----------------
9766@end group
9767@end smallexample
9768@end iftex
9769@end ifclear
9770
9771(Symbols consist of more than pairs of addresses, but the structure of
9772a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9773consists of a group of address-boxes, one of which is the address of
9774the printed word @samp{bouquet}, a second of which is the address of a
9775function definition attached to the symbol, if any, a third of which
9776is the address of the first pair of address-boxes for the list
9777@code{(rose violet buttercup)}, and so on. Here we are showing that
9778the symbol's third address-box points to the first pair of
9779address-boxes for the list.)
9780
9781If a symbol is set to the @sc{cdr} of a list, the list itself is not
9782changed; the symbol simply has an address further down the list. (In
9783the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9784evaluation of the following expression
9785
9786@smallexample
9787(setq flowers (cdr bouquet))
9788@end smallexample
9789
9790@need 800
9791@noindent
9792produces this:
9793
9794@c cons-cell-diagram #3
9795@ifnottex
9796@sp 1
9797@smallexample
9798@group
9799bouquet flowers
9800 | |
9801 | ___ ___ | ___ ___ ___ ___
9802 --> | | | --> | | | | | |
9803 |___|___|----> |___|___|--> |___|___|--> nil
9804 | | |
9805 | | |
9806 --> rose --> violet --> buttercup
9807@end group
9808@end smallexample
9809@sp 1
9810@end ifnottex
9811@ifset print-postscript-figures
9812@sp 1
9813@tex
9814@center @image{cons-3}
9815%%%% old method of including an image
9816% \input /usr/local/lib/tex/inputs/psfig.tex
9817% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9818% \catcode`\@=0 %
9819@end tex
9820@sp 1
9821@end ifset
9822@ifclear print-postscript-figures
9823@iftex
9824@sp 1
9825@smallexample
9826@group
9827bouquet flowers
9828 | |
9829 | ___ ___ | ___ ___ ___ ___
9830 --> | | | --> | | | | | |
9831 |___|___|----> |___|___|--> |___|___|--> nil
9832 | | |
9833 | | |
9834 --> rose --> violet --> buttercup
9835@end group
9836@end smallexample
9837@sp 1
9838@end iftex
9839@end ifclear
9840
9841@noindent
9842The value of @code{flowers} is @code{(violet buttercup)}, which is
9843to say, the symbol @code{flowers} holds the address of the pair of
9844address-boxes, the first of which holds the address of @code{violet},
9845and the second of which holds the address of @code{buttercup}.
9846
9847A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9848pair}. @xref{Cons Cell Type, , Cons Cell and List Types, elisp, The GNU Emacs Lisp
9849Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9850Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9851information about cons cells and dotted pairs.
9852
9853@need 1200
9854The function @code{cons} adds a new pair of addresses to the front of
9855a series of addresses like that shown above. For example, evaluating
9856the expression
9857
9858@smallexample
9859(setq bouquet (cons 'lily bouquet))
9860@end smallexample
9861
9862@need 1500
9863@noindent
9864produces:
9865
9866@c cons-cell-diagram #4
9867@ifnottex
9868@sp 1
9869@smallexample
9870@group
9871bouquet flowers
9872 | |
9873 | ___ ___ ___ ___ | ___ ___ ___ ___
9874 --> | | | | | | --> | | | | | |
9875 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9876 | | | |
9877 | | | |
9878 --> lily --> rose --> violet --> buttercup
9879@end group
9880@end smallexample
9881@sp 1
9882@end ifnottex
9883@ifset print-postscript-figures
9884@sp 1
9885@tex
9886@center @image{cons-4}
9887%%%% old method of including an image
9888% \input /usr/local/lib/tex/inputs/psfig.tex
9889% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9890% \catcode`\@=0 %
9891@end tex
9892@sp 1
9893@end ifset
9894@ifclear print-postscript-figures
9895@iftex
9896@sp 1
9897@smallexample
9898@group
9899bouquet flowers
9900 | |
9901 | ___ ___ ___ ___ | ___ ___ ___ ___
9902 --> | | | | | | --> | | | | | |
9903 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9904 | | | |
9905 | | | |
9906 --> lily --> rose --> violet --> buttercup
9907@end group
9908@end smallexample
9909@sp 1
9910@end iftex
9911@end ifclear
9912
9913@need 1200
9914@noindent
9915However, this does not change the value of the symbol
9916@code{flowers}, as you can see by evaluating the following,
9917
9918@smallexample
9919(eq (cdr (cdr bouquet)) flowers)
9920@end smallexample
9921
9922@noindent
9923which returns @code{t} for true.
9924
9925Until it is reset, @code{flowers} still has the value
9926@code{(violet buttercup)}; that is, it has the address of the cons
9927cell whose first address is of @code{violet}. Also, this does not
9928alter any of the pre-existing cons cells; they are all still there.
9929
9930Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9931of the next cons cell in the series; to get the @sc{car} of a list,
9932you get the address of the first element of the list; to @code{cons} a
9933new element on a list, you add a new cons cell to the front of the list.
9934That is all there is to it! The underlying structure of Lisp is
9935brilliantly simple!
9936
9937And what does the last address in a series of cons cells refer to? It
9938is the address of the empty list, of @code{nil}.
9939
9940In summary, when a Lisp variable is set to a value, it is provided with
9941the address of the list to which the variable refers.
9942
d6adf7e7 9943@node Symbols as Chest
8cda6f8f
GM
9944@section Symbols as a Chest of Drawers
9945@cindex Symbols as a Chest of Drawers
9946@cindex Chest of Drawers, metaphor for a symbol
9947@cindex Drawers, Chest of, metaphor for a symbol
9948
9949In an earlier section, I suggested that you might imagine a symbol as
9950being a chest of drawers. The function definition is put in one
9951drawer, the value in another, and so on. What is put in the drawer
9952holding the value can be changed without affecting the contents of the
9953drawer holding the function definition, and vice-verse.
9954
9955Actually, what is put in each drawer is the address of the value or
9956function definition. It is as if you found an old chest in the attic,
9957and in one of its drawers you found a map giving you directions to
9958where the buried treasure lies.
9959
9960(In addition to its name, symbol definition, and variable value, a
9961symbol has a `drawer' for a @dfn{property list} which can be used to
9962record other information. Property lists are not discussed here; see
9963@ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9964Reference Manual}.)
9965
9966@need 1500
9967Here is a fanciful representation:
9968
9969@c chest-of-drawers diagram
9970@ifnottex
9971@sp 1
9972@smallexample
9973@group
9974 Chest of Drawers Contents of Drawers
9975
9976 __ o0O0o __
9977 / \
9978 ---------------------
9979 | directions to | [map to]
9980 | symbol name | bouquet
9981 | |
9982 +---------------------+
9983 | directions to |
9984 | symbol definition | [none]
9985 | |
9986 +---------------------+
9987 | directions to | [map to]
9988 | variable value | (rose violet buttercup)
9989 | |
9990 +---------------------+
9991 | directions to |
9992 | property list | [not described here]
9993 | |
9994 +---------------------+
9995 |/ \|
9996@end group
9997@end smallexample
9998@sp 1
9999@end ifnottex
10000@ifset print-postscript-figures
10001@sp 1
10002@tex
10003@center @image{drawers}
10004%%%% old method of including an image
10005% \input /usr/local/lib/tex/inputs/psfig.tex
10006% \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
10007% \catcode`\@=0 %
10008@end tex
10009@sp 1
10010@end ifset
10011@ifclear print-postscript-figures
10012@iftex
10013@sp 1
10014@smallexample
10015@group
10016 Chest of Drawers Contents of Drawers
10017
10018 __ o0O0o __
10019 / \
10020 ---------------------
10021 | directions to | [map to]
10022 | symbol name | bouquet
10023 | |
10024 +---------------------+
10025 | directions to |
10026 | symbol definition | [none]
10027 | |
10028 +---------------------+
10029 | directions to | [map to]
10030 | variable value | (rose violet buttercup)
10031 | |
10032 +---------------------+
10033 | directions to |
10034 | property list | [not described here]
10035 | |
10036 +---------------------+
10037 |/ \|
10038@end group
10039@end smallexample
10040@sp 1
10041@end iftex
10042@end ifclear
10043
d6adf7e7 10044@node List Exercise
8cda6f8f
GM
10045@section Exercise
10046
10047Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
10048more flowers on to this list and set this new list to
10049@code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
10050What does the @code{more-flowers} list now contain?
10051
d6adf7e7 10052@node Yanking
8cda6f8f
GM
10053@chapter Yanking Text Back
10054@findex yank
10055@cindex Text retrieval
10056@cindex Retrieving text
10057@cindex Pasting text
10058
10059Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
10060you can bring it back with a `yank' command. The text that is cut out of
10061the buffer is put in the kill ring and the yank commands insert the
10062appropriate contents of the kill ring back into a buffer (not necessarily
10063the original buffer).
10064
10065A simple @kbd{C-y} (@code{yank}) command inserts the first item from
10066the kill ring into the current buffer. If the @kbd{C-y} command is
10067followed immediately by @kbd{M-y}, the first element is replaced by
10068the second element. Successive @kbd{M-y} commands replace the second
10069element with the third, fourth, or fifth element, and so on. When the
10070last element in the kill ring is reached, it is replaced by the first
10071element and the cycle is repeated. (Thus the kill ring is called a
10072`ring' rather than just a `list'. However, the actual data structure
10073that holds the text is a list.
10074@xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
10075list is handled as a ring.)
10076
10077@menu
10078* Kill Ring Overview::
10079* kill-ring-yank-pointer:: The kill ring is a list.
10080* yank nthcdr Exercises:: The @code{kill-ring-yank-pointer} variable.
10081@end menu
10082
d6adf7e7 10083@node Kill Ring Overview
8cda6f8f
GM
10084@section Kill Ring Overview
10085@cindex Kill ring overview
10086
10087The kill ring is a list of textual strings. This is what it looks like:
10088
10089@smallexample
10090("some text" "a different piece of text" "yet more text")
10091@end smallexample
10092
10093If this were the contents of my kill ring and I pressed @kbd{C-y}, the
10094string of characters saying @samp{some text} would be inserted in this
10095buffer where my cursor is located.
10096
10097The @code{yank} command is also used for duplicating text by copying it.
10098The copied text is not cut from the buffer, but a copy of it is put on the
10099kill ring and is inserted by yanking it back.
10100
10101Three functions are used for bringing text back from the kill ring:
10102@code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
10103which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
10104which is used by the two other functions.
10105
10106These functions refer to the kill ring through a variable called the
10107@code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
10108@code{yank} and @code{yank-pop} functions is:
10109
10110@smallexample
10111(insert (car kill-ring-yank-pointer))
10112@end smallexample
10113
10114@noindent
10115(Well, no more. In GNU Emacs 22, the function has been replaced by
10116@code{insert-for-yank} which calls @code{insert-for-yank-1}
10117repetitively for each @code{yank-handler} segment. In turn,
10118@code{insert-for-yank-1} strips text properties from the inserted text
10119according to @code{yank-excluded-properties}. Otherwise, it is just
10120like @code{insert}. We will stick with plain @code{insert} since it
10121is easier to understand.)
10122
10123To begin to understand how @code{yank} and @code{yank-pop} work, it is
10124first necessary to look at the @code{kill-ring-yank-pointer} variable.
10125
d6adf7e7 10126@node kill-ring-yank-pointer
8cda6f8f
GM
10127@section The @code{kill-ring-yank-pointer} Variable
10128
10129@code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
10130a variable. It points to something by being bound to the value of what
10131it points to, like any other Lisp variable.
10132
10133@need 1000
10134Thus, if the value of the kill ring is:
10135
10136@smallexample
10137("some text" "a different piece of text" "yet more text")
10138@end smallexample
10139
10140@need 1250
10141@noindent
10142and the @code{kill-ring-yank-pointer} points to the second clause, the
10143value of @code{kill-ring-yank-pointer} is:
10144
10145@smallexample
10146("a different piece of text" "yet more text")
10147@end smallexample
10148
10149As explained in the previous chapter (@pxref{List Implementation}), the
10150computer does not keep two different copies of the text being pointed to
10151by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
10152words ``a different piece of text'' and ``yet more text'' are not
10153duplicated. Instead, the two Lisp variables point to the same pieces of
10154text. Here is a diagram:
10155
10156@c cons-cell-diagram #5
10157@ifnottex
10158@smallexample
10159@group
10160kill-ring kill-ring-yank-pointer
10161 | |
10162 | ___ ___ | ___ ___ ___ ___
10163 ---> | | | --> | | | | | |
10164 |___|___|----> |___|___|--> |___|___|--> nil
10165 | | |
10166 | | |
10167 | | --> "yet more text"
10168 | |
10169 | --> "a different piece of text"
10170 |
10171 --> "some text"
10172@end group
10173@end smallexample
10174@sp 1
10175@end ifnottex
10176@ifset print-postscript-figures
10177@sp 1
10178@tex
10179@center @image{cons-5}
10180%%%% old method of including an image
10181% \input /usr/local/lib/tex/inputs/psfig.tex
10182% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
10183% \catcode`\@=0 %
10184@end tex
10185@sp 1
10186@end ifset
10187@ifclear print-postscript-figures
10188@iftex
10189@smallexample
10190@group
10191kill-ring kill-ring-yank-pointer
10192 | |
10193 | ___ ___ | ___ ___ ___ ___
10194 ---> | | | --> | | | | | |
10195 |___|___|----> |___|___|--> |___|___|--> nil
10196 | | |
10197 | | |
10198 | | --> "yet more text"
10199 | |
10200 | --> "a different piece of text
10201 |
10202 --> "some text"
10203@end group
10204@end smallexample
10205@sp 1
10206@end iftex
10207@end ifclear
10208
10209Both the variable @code{kill-ring} and the variable
10210@code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
10211usually described as if it were actually what it is composed of. The
10212@code{kill-ring} is spoken of as if it were the list rather than that it
10213points to the list. Conversely, the @code{kill-ring-yank-pointer} is
10214spoken of as pointing to a list.
10215
10216These two ways of talking about the same thing sound confusing at first but
10217make sense on reflection. The kill ring is generally thought of as the
10218complete structure of data that holds the information of what has recently
10219been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
10220on the other hand, serves to indicate---that is, to `point to'---that part
10221of the kill ring of which the first element (the @sc{car}) will be
10222inserted.
10223
10224@ignore
10225In GNU Emacs 22, the @code{kill-new} function calls
10226
10227@code{(setq kill-ring-yank-pointer kill-ring)}
10228
10229(defun rotate-yank-pointer (arg)
10230 "Rotate the yanking point in the kill ring.
10231With argument, rotate that many kills forward (or backward, if negative)."
10232 (interactive "p")
10233 (current-kill arg))
10234
10235(defun current-kill (n &optional do-not-move)
10236 "Rotate the yanking point by N places, and then return that kill.
10237If N is zero, `interprogram-paste-function' is set, and calling it
10238returns a string, then that string is added to the front of the
10239kill ring and returned as the latest kill.
10240If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
10241yanking point; just return the Nth kill forward."
10242 (let ((interprogram-paste (and (= n 0)
10243 interprogram-paste-function
10244 (funcall interprogram-paste-function))))
10245 (if interprogram-paste
10246 (progn
10247 ;; Disable the interprogram cut function when we add the new
10248 ;; text to the kill ring, so Emacs doesn't try to own the
10249 ;; selection, with identical text.
10250 (let ((interprogram-cut-function nil))
10251 (kill-new interprogram-paste))
10252 interprogram-paste)
10253 (or kill-ring (error "Kill ring is empty"))
10254 (let ((ARGth-kill-element
10255 (nthcdr (mod (- n (length kill-ring-yank-pointer))
10256 (length kill-ring))
10257 kill-ring)))
10258 (or do-not-move
10259 (setq kill-ring-yank-pointer ARGth-kill-element))
10260 (car ARGth-kill-element)))))
10261
10262@end ignore
10263
10264@need 1500
d6adf7e7 10265@node yank nthcdr Exercises
8cda6f8f
GM
10266@section Exercises with @code{yank} and @code{nthcdr}
10267
10268@itemize @bullet
10269@item
10270Using @kbd{C-h v} (@code{describe-variable}), look at the value of
10271your kill ring. Add several items to your kill ring; look at its
10272value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
10273around the kill ring. How many items were in your kill ring? Find
10274the value of @code{kill-ring-max}. Was your kill ring full, or could
10275you have kept more blocks of text within it?
10276
10277@item
10278Using @code{nthcdr} and @code{car}, construct a series of expressions
10279to return the first, second, third, and fourth elements of a list.
10280@end itemize
10281
d6adf7e7 10282@node Loops & Recursion
8cda6f8f
GM
10283@chapter Loops and Recursion
10284@cindex Loops and recursion
10285@cindex Recursion and loops
10286@cindex Repetition (loops)
10287
10288Emacs Lisp has two primary ways to cause an expression, or a series of
10289expressions, to be evaluated repeatedly: one uses a @code{while}
10290loop, and the other uses @dfn{recursion}.
10291
10292Repetition can be very valuable. For example, to move forward four
10293sentences, you need only write a program that will move forward one
10294sentence and then repeat the process four times. Since a computer does
10295not get bored or tired, such repetitive action does not have the
10296deleterious effects that excessive or the wrong kinds of repetition can
10297have on humans.
10298
10299People mostly write Emacs Lisp functions using @code{while} loops and
10300their kin; but you can use recursion, which provides a very powerful
10301way to think about and then to solve problems@footnote{You can write
10302recursive functions to be frugal or wasteful of mental or computer
10303resources; as it happens, methods that people find easy---that are
10304frugal of `mental resources'---sometimes use considerable computer
10305resources. Emacs was designed to run on machines that we now consider
10306limited and its default settings are conservative. You may want to
10307increase the values of @code{max-specpdl-size} and
10308@code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
1030915 and 30 times their default value.}.
10310
10311@menu
10312* while:: Causing a stretch of code to repeat.
10313* dolist dotimes::
10314* Recursion:: Causing a function to call itself.
10315* Looping exercise::
10316@end menu
10317
d6adf7e7 10318@node while
8cda6f8f
GM
10319@section @code{while}
10320@cindex Loops
10321@findex while
10322
10323The @code{while} special form tests whether the value returned by
10324evaluating its first argument is true or false. This is similar to what
10325the Lisp interpreter does with an @code{if}; what the interpreter does
10326next, however, is different.
10327
10328In a @code{while} expression, if the value returned by evaluating the
10329first argument is false, the Lisp interpreter skips the rest of the
10330expression (the @dfn{body} of the expression) and does not evaluate it.
10331However, if the value is true, the Lisp interpreter evaluates the body
10332of the expression and then again tests whether the first argument to
10333@code{while} is true or false. If the value returned by evaluating the
10334first argument is again true, the Lisp interpreter again evaluates the
10335body of the expression.
10336
10337@need 1200
10338The template for a @code{while} expression looks like this:
10339
10340@smallexample
10341@group
10342(while @var{true-or-false-test}
10343 @var{body}@dots{})
10344@end group
10345@end smallexample
10346
10347@menu
10348* Looping with while:: Repeat so long as test returns true.
10349* Loop Example:: A @code{while} loop that uses a list.
10350* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
10351* Incrementing Loop:: A loop with an incrementing counter.
10352* Incrementing Loop Details::
10353* Decrementing Loop:: A loop with a decrementing counter.
10354@end menu
10355
8cda6f8f 10356@ifnottex
d6adf7e7 10357@node Looping with while
8cda6f8f
GM
10358@unnumberedsubsec Looping with @code{while}
10359@end ifnottex
10360
10361So long as the true-or-false-test of the @code{while} expression
10362returns a true value when it is evaluated, the body is repeatedly
10363evaluated. This process is called a loop since the Lisp interpreter
10364repeats the same thing again and again, like an airplane doing a loop.
10365When the result of evaluating the true-or-false-test is false, the
10366Lisp interpreter does not evaluate the rest of the @code{while}
10367expression and `exits the loop'.
10368
10369Clearly, if the value returned by evaluating the first argument to
10370@code{while} is always true, the body following will be evaluated
10371again and again @dots{} and again @dots{} forever. Conversely, if the
10372value returned is never true, the expressions in the body will never
10373be evaluated. The craft of writing a @code{while} loop consists of
10374choosing a mechanism such that the true-or-false-test returns true
10375just the number of times that you want the subsequent expressions to
10376be evaluated, and then have the test return false.
10377
10378The value returned by evaluating a @code{while} is the value of the
10379true-or-false-test. An interesting consequence of this is that a
10380@code{while} loop that evaluates without error will return @code{nil}
10381or false regardless of whether it has looped 1 or 100 times or none at
10382all. A @code{while} expression that evaluates successfully never
10383returns a true value! What this means is that @code{while} is always
10384evaluated for its side effects, which is to say, the consequences of
10385evaluating the expressions within the body of the @code{while} loop.
10386This makes sense. It is not the mere act of looping that is desired,
10387but the consequences of what happens when the expressions in the loop
10388are repeatedly evaluated.
10389
d6adf7e7 10390@node Loop Example
8cda6f8f
GM
10391@subsection A @code{while} Loop and a List
10392
10393A common way to control a @code{while} loop is to test whether a list
10394has any elements. If it does, the loop is repeated; but if it does not,
10395the repetition is ended. Since this is an important technique, we will
10396create a short example to illustrate it.
10397
10398A simple way to test whether a list has elements is to evaluate the
10399list: if it has no elements, it is an empty list and will return the
10400empty list, @code{()}, which is a synonym for @code{nil} or false. On
10401the other hand, a list with elements will return those elements when it
10402is evaluated. Since Emacs Lisp considers as true any value that is not
10403@code{nil}, a list that returns elements will test true in a
10404@code{while} loop.
10405
10406@need 1200
10407For example, you can set the variable @code{empty-list} to @code{nil} by
10408evaluating the following @code{setq} expression:
10409
10410@smallexample
10411(setq empty-list ())
10412@end smallexample
10413
10414@noindent
10415After evaluating the @code{setq} expression, you can evaluate the
10416variable @code{empty-list} in the usual way, by placing the cursor after
10417the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
10418echo area:
10419
10420@smallexample
10421empty-list
10422@end smallexample
10423
10424On the other hand, if you set a variable to be a list with elements, the
10425list will appear when you evaluate the variable, as you can see by
10426evaluating the following two expressions:
10427
10428@smallexample
10429@group
10430(setq animals '(gazelle giraffe lion tiger))
10431
10432animals
10433@end group
10434@end smallexample
10435
10436Thus, to create a @code{while} loop that tests whether there are any
10437items in the list @code{animals}, the first part of the loop will be
10438written like this:
10439
10440@smallexample
10441@group
10442(while animals
10443 @dots{}
10444@end group
10445@end smallexample
10446
10447@noindent
10448When the @code{while} tests its first argument, the variable
10449@code{animals} is evaluated. It returns a list. So long as the list
10450has elements, the @code{while} considers the results of the test to be
10451true; but when the list is empty, it considers the results of the test
10452to be false.
10453
10454To prevent the @code{while} loop from running forever, some mechanism
10455needs to be provided to empty the list eventually. An oft-used
10456technique is to have one of the subsequent forms in the @code{while}
10457expression set the value of the list to be the @sc{cdr} of the list.
10458Each time the @code{cdr} function is evaluated, the list will be made
10459shorter, until eventually only the empty list will be left. At this
10460point, the test of the @code{while} loop will return false, and the
10461arguments to the @code{while} will no longer be evaluated.
10462
10463For example, the list of animals bound to the variable @code{animals}
10464can be set to be the @sc{cdr} of the original list with the
10465following expression:
10466
10467@smallexample
10468(setq animals (cdr animals))
10469@end smallexample
10470
10471@noindent
10472If you have evaluated the previous expressions and then evaluate this
10473expression, you will see @code{(giraffe lion tiger)} appear in the echo
10474area. If you evaluate the expression again, @code{(lion tiger)} will
10475appear in the echo area. If you evaluate it again and yet again,
10476@code{(tiger)} appears and then the empty list, shown by @code{nil}.
10477
10478A template for a @code{while} loop that uses the @code{cdr} function
10479repeatedly to cause the true-or-false-test eventually to test false
10480looks like this:
10481
10482@smallexample
10483@group
10484(while @var{test-whether-list-is-empty}
10485 @var{body}@dots{}
10486 @var{set-list-to-cdr-of-list})
10487@end group
10488@end smallexample
10489
10490This test and use of @code{cdr} can be put together in a function that
10491goes through a list and prints each element of the list on a line of its
10492own.
10493
d6adf7e7 10494@node print-elements-of-list
8cda6f8f
GM
10495@subsection An Example: @code{print-elements-of-list}
10496@findex print-elements-of-list
10497
10498The @code{print-elements-of-list} function illustrates a @code{while}
10499loop with a list.
10500
10501@cindex @file{*scratch*} buffer
10502The function requires several lines for its output. If you are
10503reading this in a recent instance of GNU Emacs,
10504@c GNU Emacs 21, GNU Emacs 22, or a later version,
10505you can evaluate the following expression inside of Info, as usual.
10506
10507If you are using an earlier version of Emacs, you need to copy the
10508necessary expressions to your @file{*scratch*} buffer and evaluate
10509them there. This is because the echo area had only one line in the
10510earlier versions.
10511
10512You can copy the expressions by marking the beginning of the region
10513with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
10514the end of the region and then copying the region using @kbd{M-w}
10515(@code{kill-ring-save}, which calls @code{copy-region-as-kill} and
10516then provides visual feedback). In the @file{*scratch*}
10517buffer, you can yank the expressions back by typing @kbd{C-y}
10518(@code{yank}).
10519
10520After you have copied the expressions to the @file{*scratch*} buffer,
10521evaluate each expression in turn. Be sure to evaluate the last
10522expression, @code{(print-elements-of-list animals)}, by typing
10523@kbd{C-u C-x C-e}, that is, by giving an argument to
10524@code{eval-last-sexp}. This will cause the result of the evaluation
10525to be printed in the @file{*scratch*} buffer instead of being printed
10526in the echo area. (Otherwise you will see something like this in your
10527echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
10528each @samp{^J} stands for a `newline'.)
10529
10530@need 1500
10531In a recent instance of GNU Emacs, you can evaluate these expressions
10532directly in the Info buffer, and the echo area will grow to show the
10533results.
10534
10535@smallexample
10536@group
10537(setq animals '(gazelle giraffe lion tiger))
10538
10539(defun print-elements-of-list (list)
10540 "Print each element of LIST on a line of its own."
10541 (while list
10542 (print (car list))
10543 (setq list (cdr list))))
10544
10545(print-elements-of-list animals)
10546@end group
10547@end smallexample
10548
10549@need 1200
10550@noindent
10551When you evaluate the three expressions in sequence, you will see
10552this:
10553
10554@smallexample
10555@group
10556gazelle
10557
10558giraffe
10559
10560lion
10561
10562tiger
10563nil
10564@end group
10565@end smallexample
10566
10567Each element of the list is printed on a line of its own (that is what
10568the function @code{print} does) and then the value returned by the
10569function is printed. Since the last expression in the function is the
10570@code{while} loop, and since @code{while} loops always return
10571@code{nil}, a @code{nil} is printed after the last element of the list.
10572
d6adf7e7 10573@node Incrementing Loop
8cda6f8f
GM
10574@subsection A Loop with an Incrementing Counter
10575
10576A loop is not useful unless it stops when it ought. Besides
10577controlling a loop with a list, a common way of stopping a loop is to
10578write the first argument as a test that returns false when the correct
10579number of repetitions are complete. This means that the loop must
10580have a counter---an expression that counts how many times the loop
10581repeats itself.
10582
8cda6f8f 10583@ifnottex
d6adf7e7 10584@node Incrementing Loop Details
8cda6f8f
GM
10585@unnumberedsubsec Details of an Incrementing Loop
10586@end ifnottex
10587
10588The test for a loop with an incrementing counter can be an expression
10589such as @code{(< count desired-number)} which returns @code{t} for
10590true if the value of @code{count} is less than the
10591@code{desired-number} of repetitions and @code{nil} for false if the
10592value of @code{count} is equal to or is greater than the
10593@code{desired-number}. The expression that increments the count can
10594be a simple @code{setq} such as @code{(setq count (1+ count))}, where
10595@code{1+} is a built-in function in Emacs Lisp that adds 1 to its
10596argument. (The expression @w{@code{(1+ count)}} has the same result
10597as @w{@code{(+ count 1)}}, but is easier for a human to read.)
10598
10599@need 1250
10600The template for a @code{while} loop controlled by an incrementing
10601counter looks like this:
10602
10603@smallexample
10604@group
10605@var{set-count-to-initial-value}
10606(while (< count desired-number) ; @r{true-or-false-test}
10607 @var{body}@dots{}
10608 (setq count (1+ count))) ; @r{incrementer}
10609@end group
10610@end smallexample
10611
10612@noindent
10613Note that you need to set the initial value of @code{count}; usually it
10614is set to 1.
10615
10616@menu
10617* Incrementing Example:: Counting pebbles in a triangle.
10618* Inc Example parts:: The parts of the function definition.
10619* Inc Example altogether:: Putting the function definition together.
10620@end menu
10621
d6adf7e7 10622@node Incrementing Example
8cda6f8f
GM
10623@unnumberedsubsubsec Example with incrementing counter
10624
10625Suppose you are playing on the beach and decide to make a triangle of
10626pebbles, putting one pebble in the first row, two in the second row,
10627three in the third row and so on, like this:
10628
10629@sp 1
10630@c pebble diagram
10631@ifnottex
10632@smallexample
10633@group
10634 *
10635 * *
10636 * * *
10637 * * * *
10638@end group
10639@end smallexample
10640@end ifnottex
10641@iftex
10642@smallexample
10643@group
10644 @bullet{}
10645 @bullet{} @bullet{}
10646 @bullet{} @bullet{} @bullet{}
10647 @bullet{} @bullet{} @bullet{} @bullet{}
10648@end group
10649@end smallexample
10650@end iftex
10651@sp 1
10652
10653@noindent
10654(About 2500 years ago, Pythagoras and others developed the beginnings of
10655number theory by considering questions such as this.)
10656
10657Suppose you want to know how many pebbles you will need to make a
10658triangle with 7 rows?
10659
10660Clearly, what you need to do is add up the numbers from 1 to 7. There
10661are two ways to do this; start with the smallest number, one, and add up
10662the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
10663number and add the list going down: 7, 6, 5, 4 and so on. Because both
10664mechanisms illustrate common ways of writing @code{while} loops, we will
10665create two examples, one counting up and the other counting down. In
10666this first example, we will start with 1 and add 2, 3, 4 and so on.
10667
10668If you are just adding up a short list of numbers, the easiest way to do
10669it is to add up all the numbers at once. However, if you do not know
10670ahead of time how many numbers your list will have, or if you want to be
10671prepared for a very long list, then you need to design your addition so
10672that what you do is repeat a simple process many times instead of doing
10673a more complex process once.
10674
10675For example, instead of adding up all the pebbles all at once, what you
10676can do is add the number of pebbles in the first row, 1, to the number
10677in the second row, 2, and then add the total of those two rows to the
10678third row, 3. Then you can add the number in the fourth row, 4, to the
10679total of the first three rows; and so on.
10680
10681The critical characteristic of the process is that each repetitive
10682action is simple. In this case, at each step we add only two numbers,
10683the number of pebbles in the row and the total already found. This
10684process of adding two numbers is repeated again and again until the last
10685row has been added to the total of all the preceding rows. In a more
10686complex loop the repetitive action might not be so simple, but it will
10687be simpler than doing everything all at once.
10688
d6adf7e7 10689@node Inc Example parts
8cda6f8f
GM
10690@unnumberedsubsubsec The parts of the function definition
10691
10692The preceding analysis gives us the bones of our function definition:
10693first, we will need a variable that we can call @code{total} that will
10694be the total number of pebbles. This will be the value returned by
10695the function.
10696
10697Second, we know that the function will require an argument: this
10698argument will be the total number of rows in the triangle. It can be
10699called @code{number-of-rows}.
10700
10701Finally, we need a variable to use as a counter. We could call this
10702variable @code{counter}, but a better name is @code{row-number}. That
10703is because what the counter does in this function is count rows, and a
10704program should be written to be as understandable as possible.
10705
10706When the Lisp interpreter first starts evaluating the expressions in the
10707function, the value of @code{total} should be set to zero, since we have
10708not added anything to it. Then the function should add the number of
10709pebbles in the first row to the total, and then add the number of
10710pebbles in the second to the total, and then add the number of
10711pebbles in the third row to the total, and so on, until there are no
10712more rows left to add.
10713
10714Both @code{total} and @code{row-number} are used only inside the
10715function, so they can be declared as local variables with @code{let}
10716and given initial values. Clearly, the initial value for @code{total}
10717should be 0. The initial value of @code{row-number} should be 1,
10718since we start with the first row. This means that the @code{let}
10719statement will look like this:
10720
10721@smallexample
10722@group
10723 (let ((total 0)
10724 (row-number 1))
10725 @var{body}@dots{})
10726@end group
10727@end smallexample
10728
10729After the internal variables are declared and bound to their initial
10730values, we can begin the @code{while} loop. The expression that serves
10731as the test should return a value of @code{t} for true so long as the
10732@code{row-number} is less than or equal to the @code{number-of-rows}.
10733(If the expression tests true only so long as the row number is less
10734than the number of rows in the triangle, the last row will never be
10735added to the total; hence the row number has to be either less than or
10736equal to the number of rows.)
10737
10738@need 1500
10739@findex <= @r{(less than or equal)}
10740Lisp provides the @code{<=} function that returns true if the value of
10741its first argument is less than or equal to the value of its second
10742argument and false otherwise. So the expression that the @code{while}
10743will evaluate as its test should look like this:
10744
10745@smallexample
10746(<= row-number number-of-rows)
10747@end smallexample
10748
10749The total number of pebbles can be found by repeatedly adding the number
10750of pebbles in a row to the total already found. Since the number of
10751pebbles in the row is equal to the row number, the total can be found by
10752adding the row number to the total. (Clearly, in a more complex
10753situation, the number of pebbles in the row might be related to the row
10754number in a more complicated way; if this were the case, the row number
10755would be replaced by the appropriate expression.)
10756
10757@smallexample
10758(setq total (+ total row-number))
10759@end smallexample
10760
10761@noindent
10762What this does is set the new value of @code{total} to be equal to the
10763sum of adding the number of pebbles in the row to the previous total.
10764
10765After setting the value of @code{total}, the conditions need to be
10766established for the next repetition of the loop, if there is one. This
10767is done by incrementing the value of the @code{row-number} variable,
10768which serves as a counter. After the @code{row-number} variable has
10769been incremented, the true-or-false-test at the beginning of the
10770@code{while} loop tests whether its value is still less than or equal to
10771the value of the @code{number-of-rows} and if it is, adds the new value
10772of the @code{row-number} variable to the @code{total} of the previous
10773repetition of the loop.
10774
10775@need 1200
10776The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10777@code{row-number} variable can be incremented with this expression:
10778
10779@smallexample
10780(setq row-number (1+ row-number))
10781@end smallexample
10782
d6adf7e7 10783@node Inc Example altogether
8cda6f8f
GM
10784@unnumberedsubsubsec Putting the function definition together
10785
10786We have created the parts for the function definition; now we need to
10787put them together.
10788
10789@need 800
10790First, the contents of the @code{while} expression:
10791
10792@smallexample
10793@group
10794(while (<= row-number number-of-rows) ; @r{true-or-false-test}
10795 (setq total (+ total row-number))
10796 (setq row-number (1+ row-number))) ; @r{incrementer}
10797@end group
10798@end smallexample
10799
10800Along with the @code{let} expression varlist, this very nearly
10801completes the body of the function definition. However, it requires
10802one final element, the need for which is somewhat subtle.
10803
10804The final touch is to place the variable @code{total} on a line by
10805itself after the @code{while} expression. Otherwise, the value returned
10806by the whole function is the value of the last expression that is
10807evaluated in the body of the @code{let}, and this is the value
10808returned by the @code{while}, which is always @code{nil}.
10809
10810This may not be evident at first sight. It almost looks as if the
10811incrementing expression is the last expression of the whole function.
10812But that expression is part of the body of the @code{while}; it is the
10813last element of the list that starts with the symbol @code{while}.
10814Moreover, the whole of the @code{while} loop is a list within the body
10815of the @code{let}.
10816
10817@need 1250
10818In outline, the function will look like this:
10819
10820@smallexample
10821@group
10822(defun @var{name-of-function} (@var{argument-list})
10823 "@var{documentation}@dots{}"
10824 (let (@var{varlist})
10825 (while (@var{true-or-false-test})
10826 @var{body-of-while}@dots{} )
10827 @dots{} )) ; @r{Need final expression here.}
10828@end group
10829@end smallexample
10830
10831The result of evaluating the @code{let} is what is going to be returned
10832by the @code{defun} since the @code{let} is not embedded within any
10833containing list, except for the @code{defun} as a whole. However, if
10834the @code{while} is the last element of the @code{let} expression, the
10835function will always return @code{nil}. This is not what we want!
10836Instead, what we want is the value of the variable @code{total}. This
10837is returned by simply placing the symbol as the last element of the list
10838starting with @code{let}. It gets evaluated after the preceding
10839elements of the list are evaluated, which means it gets evaluated after
10840it has been assigned the correct value for the total.
10841
10842It may be easier to see this by printing the list starting with
10843@code{let} all on one line. This format makes it evident that the
10844@var{varlist} and @code{while} expressions are the second and third
10845elements of the list starting with @code{let}, and the @code{total} is
10846the last element:
10847
10848@smallexample
10849@group
10850(let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10851@end group
10852@end smallexample
10853
10854@need 1200
10855Putting everything together, the @code{triangle} function definition
10856looks like this:
10857
10858@smallexample
10859@group
10860(defun triangle (number-of-rows) ; @r{Version with}
10861 ; @r{ incrementing counter.}
10862 "Add up the number of pebbles in a triangle.
10863The first row has one pebble, the second row two pebbles,
10864the third row three pebbles, and so on.
10865The argument is NUMBER-OF-ROWS."
10866@end group
10867@group
10868 (let ((total 0)
10869 (row-number 1))
10870 (while (<= row-number number-of-rows)
10871 (setq total (+ total row-number))
10872 (setq row-number (1+ row-number)))
10873 total))
10874@end group
10875@end smallexample
10876
10877@need 1200
10878After you have installed @code{triangle} by evaluating the function, you
10879can try it out. Here are two examples:
10880
10881@smallexample
10882@group
10883(triangle 4)
10884
10885(triangle 7)
10886@end group
10887@end smallexample
10888
10889@noindent
10890The sum of the first four numbers is 10 and the sum of the first seven
10891numbers is 28.
10892
d6adf7e7 10893@node Decrementing Loop
8cda6f8f
GM
10894@subsection Loop with a Decrementing Counter
10895
10896Another common way to write a @code{while} loop is to write the test
10897so that it determines whether a counter is greater than zero. So long
10898as the counter is greater than zero, the loop is repeated. But when
10899the counter is equal to or less than zero, the loop is stopped. For
10900this to work, the counter has to start out greater than zero and then
10901be made smaller and smaller by a form that is evaluated
10902repeatedly.
10903
10904The test will be an expression such as @code{(> counter 0)} which
10905returns @code{t} for true if the value of @code{counter} is greater
10906than zero, and @code{nil} for false if the value of @code{counter} is
10907equal to or less than zero. The expression that makes the number
10908smaller and smaller can be a simple @code{setq} such as @code{(setq
10909counter (1- counter))}, where @code{1-} is a built-in function in
10910Emacs Lisp that subtracts 1 from its argument.
10911
10912@need 1250
10913The template for a decrementing @code{while} loop looks like this:
10914
10915@smallexample
10916@group
10917(while (> counter 0) ; @r{true-or-false-test}
10918 @var{body}@dots{}
10919 (setq counter (1- counter))) ; @r{decrementer}
10920@end group
10921@end smallexample
10922
10923@menu
10924* Decrementing Example:: More pebbles on the beach.
10925* Dec Example parts:: The parts of the function definition.
10926* Dec Example altogether:: Putting the function definition together.
10927@end menu
10928
d6adf7e7 10929@node Decrementing Example
8cda6f8f
GM
10930@unnumberedsubsubsec Example with decrementing counter
10931
10932To illustrate a loop with a decrementing counter, we will rewrite the
10933@code{triangle} function so the counter decreases to zero.
10934
10935This is the reverse of the earlier version of the function. In this
10936case, to find out how many pebbles are needed to make a triangle with
109373 rows, add the number of pebbles in the third row, 3, to the number
10938in the preceding row, 2, and then add the total of those two rows to
10939the row that precedes them, which is 1.
10940
10941Likewise, to find the number of pebbles in a triangle with 7 rows, add
10942the number of pebbles in the seventh row, 7, to the number in the
10943preceding row, which is 6, and then add the total of those two rows to
10944the row that precedes them, which is 5, and so on. As in the previous
10945example, each addition only involves adding two numbers, the total of
10946the rows already added up and the number of pebbles in the row that is
10947being added to the total. This process of adding two numbers is
10948repeated again and again until there are no more pebbles to add.
10949
10950We know how many pebbles to start with: the number of pebbles in the
10951last row is equal to the number of rows. If the triangle has seven
10952rows, the number of pebbles in the last row is 7. Likewise, we know how
10953many pebbles are in the preceding row: it is one less than the number in
10954the row.
10955
d6adf7e7 10956@node Dec Example parts
8cda6f8f
GM
10957@unnumberedsubsubsec The parts of the function definition
10958
10959We start with three variables: the total number of rows in the
10960triangle; the number of pebbles in a row; and the total number of
10961pebbles, which is what we want to calculate. These variables can be
10962named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10963@code{total}, respectively.
10964
10965Both @code{total} and @code{number-of-pebbles-in-row} are used only
10966inside the function and are declared with @code{let}. The initial
10967value of @code{total} should, of course, be zero. However, the
10968initial value of @code{number-of-pebbles-in-row} should be equal to
10969the number of rows in the triangle, since the addition will start with
10970the longest row.
10971
10972@need 1250
10973This means that the beginning of the @code{let} expression will look
10974like this:
10975
10976@smallexample
10977@group
10978(let ((total 0)
10979 (number-of-pebbles-in-row number-of-rows))
10980 @var{body}@dots{})
10981@end group
10982@end smallexample
10983
10984The total number of pebbles can be found by repeatedly adding the number
10985of pebbles in a row to the total already found, that is, by repeatedly
10986evaluating the following expression:
10987
10988@smallexample
10989(setq total (+ total number-of-pebbles-in-row))
10990@end smallexample
10991
10992@noindent
10993After the @code{number-of-pebbles-in-row} is added to the @code{total},
10994the @code{number-of-pebbles-in-row} should be decremented by one, since
10995the next time the loop repeats, the preceding row will be
10996added to the total.
10997
10998The number of pebbles in a preceding row is one less than the number of
10999pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
11000used to compute the number of pebbles in the preceding row. This can be
11001done with the following expression:
11002
11003@smallexample
11004@group
11005(setq number-of-pebbles-in-row
11006 (1- number-of-pebbles-in-row))
11007@end group
11008@end smallexample
11009
11010Finally, we know that the @code{while} loop should stop making repeated
11011additions when there are no pebbles in a row. So the test for
11012the @code{while} loop is simply:
11013
11014@smallexample
11015(while (> number-of-pebbles-in-row 0)
11016@end smallexample
11017
d6adf7e7 11018@node Dec Example altogether
8cda6f8f
GM
11019@unnumberedsubsubsec Putting the function definition together
11020
11021We can put these expressions together to create a function definition
11022that works. However, on examination, we find that one of the local
11023variables is unneeded!
11024
11025@need 1250
11026The function definition looks like this:
11027
11028@smallexample
11029@group
11030;;; @r{First subtractive version.}
11031(defun triangle (number-of-rows)
11032 "Add up the number of pebbles in a triangle."
11033 (let ((total 0)
11034 (number-of-pebbles-in-row number-of-rows))
11035 (while (> number-of-pebbles-in-row 0)
11036 (setq total (+ total number-of-pebbles-in-row))
11037 (setq number-of-pebbles-in-row
11038 (1- number-of-pebbles-in-row)))
11039 total))
11040@end group
11041@end smallexample
11042
11043As written, this function works.
11044
11045However, we do not need @code{number-of-pebbles-in-row}.
11046
11047@cindex Argument as local variable
11048When the @code{triangle} function is evaluated, the symbol
11049@code{number-of-rows} will be bound to a number, giving it an initial
11050value. That number can be changed in the body of the function as if
11051it were a local variable, without any fear that such a change will
11052effect the value of the variable outside of the function. This is a
11053very useful characteristic of Lisp; it means that the variable
11054@code{number-of-rows} can be used anywhere in the function where
11055@code{number-of-pebbles-in-row} is used.
11056
11057@need 800
11058Here is a second version of the function written a bit more cleanly:
11059
11060@smallexample
11061@group
11062(defun triangle (number) ; @r{Second version.}
11063 "Return sum of numbers 1 through NUMBER inclusive."
11064 (let ((total 0))
11065 (while (> number 0)
11066 (setq total (+ total number))
11067 (setq number (1- number)))
11068 total))
11069@end group
11070@end smallexample
11071
11072In brief, a properly written @code{while} loop will consist of three parts:
11073
11074@enumerate
11075@item
11076A test that will return false after the loop has repeated itself the
11077correct number of times.
11078
11079@item
11080An expression the evaluation of which will return the value desired
11081after being repeatedly evaluated.
11082
11083@item
11084An expression to change the value passed to the true-or-false-test so
11085that the test returns false after the loop has repeated itself the right
11086number of times.
11087@end enumerate
11088
d6adf7e7 11089@node dolist dotimes
8cda6f8f
GM
11090@section Save your time: @code{dolist} and @code{dotimes}
11091
11092In addition to @code{while}, both @code{dolist} and @code{dotimes}
11093provide for looping. Sometimes these are quicker to write than the
11094equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
11095Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
11096
11097@code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
11098list': @code{dolist} automatically shortens the list each time it
11099loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
11100each shorter version of the list to the first of its arguments.
11101
11102@code{dotimes} loops a specific number of times: you specify the number.
11103
11104@menu
11105* dolist::
11106* dotimes::
11107@end menu
11108
d6adf7e7
GM
11109@node dolist
11110@unnumberedsubsec The @code{dolist} Macro
8cda6f8f
GM
11111@findex dolist
11112
11113Suppose, for example, you want to reverse a list, so that
11114``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
11115
11116@need 1250
11117In practice, you would use the @code{reverse} function, like this:
11118
11119@smallexample
11120@group
11121(setq animals '(gazelle giraffe lion tiger))
11122
11123(reverse animals)
11124@end group
11125@end smallexample
11126
11127@need 800
11128@noindent
11129Here is how you could reverse the list using a @code{while} loop:
11130
11131@smallexample
11132@group
11133(setq animals '(gazelle giraffe lion tiger))
11134
11135(defun reverse-list-with-while (list)
11136 "Using while, reverse the order of LIST."
11137 (let (value) ; make sure list starts empty
11138 (while list
11139 (setq value (cons (car list) value))
11140 (setq list (cdr list)))
11141 value))
11142
11143(reverse-list-with-while animals)
11144@end group
11145@end smallexample
11146
11147@need 800
11148@noindent
11149And here is how you could use the @code{dolist} macro:
11150
11151@smallexample
11152@group
11153(setq animals '(gazelle giraffe lion tiger))
11154
11155(defun reverse-list-with-dolist (list)
11156 "Using dolist, reverse the order of LIST."
11157 (let (value) ; make sure list starts empty
11158 (dolist (element list value)
11159 (setq value (cons element value)))))
11160
11161(reverse-list-with-dolist animals)
11162@end group
11163@end smallexample
11164
11165@need 1250
11166@noindent
11167In Info, you can place your cursor after the closing parenthesis of
11168each expression and type @kbd{C-x C-e}; in each case, you should see
11169
11170@smallexample
11171(tiger lion giraffe gazelle)
11172@end smallexample
11173
11174@noindent
11175in the echo area.
11176
11177For this example, the existing @code{reverse} function is obviously best.
11178The @code{while} loop is just like our first example (@pxref{Loop
11179Example, , A @code{while} Loop and a List}). The @code{while} first
11180checks whether the list has elements; if so, it constructs a new list
11181by adding the first element of the list to the existing list (which in
11182the first iteration of the loop is @code{nil}). Since the second
11183element is prepended in front of the first element, and the third
11184element is prepended in front of the second element, the list is reversed.
11185
11186In the expression using a @code{while} loop,
11187the @w{@code{(setq list (cdr list))}}
11188expression shortens the list, so the @code{while} loop eventually
11189stops. In addition, it provides the @code{cons} expression with a new
11190first element by creating a new and shorter list at each repetition of
11191the loop.
11192
11193The @code{dolist} expression does very much the same as the
11194@code{while} expression, except that the @code{dolist} macro does some
11195of the work you have to do when writing a @code{while} expression.
11196
11197Like a @code{while} loop, a @code{dolist} loops. What is different is
11198that it automatically shortens the list each time it loops --- it
11199`@sc{cdr}s down the list' on its own --- and it automatically binds
11200the @sc{car} of each shorter version of the list to the first of its
11201arguments.
11202
11203In the example, the @sc{car} of each shorter version of the list is
11204referred to using the symbol @samp{element}, the list itself is called
11205@samp{list}, and the value returned is called @samp{value}. The
11206remainder of the @code{dolist} expression is the body.
11207
11208The @code{dolist} expression binds the @sc{car} of each shorter
11209version of the list to @code{element} and then evaluates the body of
11210the expression; and repeats the loop. The result is returned in
11211@code{value}.
11212
d6adf7e7
GM
11213@node dotimes
11214@unnumberedsubsec The @code{dotimes} Macro
8cda6f8f
GM
11215@findex dotimes
11216
11217The @code{dotimes} macro is similar to @code{dolist}, except that it
11218loops a specific number of times.
11219
11220The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
11221and so forth each time around the loop, and the value of the third
11222argument is returned. You need to provide the value of the second
11223argument, which is how many times the macro loops.
11224
11225@need 1250
11226For example, the following binds the numbers from 0 up to, but not
11227including, the number 3 to the first argument, @var{number}, and then
11228constructs a list of the three numbers. (The first number is 0, the
11229second number is 1, and the third number is 2; this makes a total of
11230three numbers in all, starting with zero as the first number.)
11231
11232@smallexample
11233@group
11234(let (value) ; otherwise a value is a void variable
11235 (dotimes (number 3 value)
11236 (setq value (cons number value))))
11237
11238@result{} (2 1 0)
11239@end group
11240@end smallexample
11241
11242@noindent
11243@code{dotimes} returns @code{value}, so the way to use
11244@code{dotimes} is to operate on some expression @var{number} number of
11245times and then return the result, either as a list or an atom.
11246
11247@need 1250
11248Here is an example of a @code{defun} that uses @code{dotimes} to add
11249up the number of pebbles in a triangle.
11250
11251@smallexample
11252@group
11253(defun triangle-using-dotimes (number-of-rows)
11254 "Using dotimes, add up the number of pebbles in a triangle."
11255(let ((total 0)) ; otherwise a total is a void variable
11256 (dotimes (number number-of-rows total)
11257 (setq total (+ total (1+ number))))))
11258
11259(triangle-using-dotimes 4)
11260@end group
11261@end smallexample
11262
d6adf7e7 11263@node Recursion
8cda6f8f
GM
11264@section Recursion
11265@cindex Recursion
11266
11267A recursive function contains code that tells the Lisp interpreter to
11268call a program that runs exactly like itself, but with slightly
11269different arguments. The code runs exactly the same because it has
11270the same name. However, even though the program has the same name, it
11271is not the same entity. It is different. In the jargon, it is a
11272different `instance'.
11273
11274Eventually, if the program is written correctly, the `slightly
11275different arguments' will become sufficiently different from the first
11276arguments that the final instance will stop.
11277
11278@menu
11279* Building Robots:: Same model, different serial number ...
11280* Recursive Definition Parts:: Walk until you stop ...
11281* Recursion with list:: Using a list as the test whether to recurse.
11282* Recursive triangle function::
11283* Recursion with cond::
11284* Recursive Patterns:: Often used templates.
11285* No Deferment:: Don't store up work ...
11286* No deferment solution::
11287@end menu
11288
d6adf7e7 11289@node Building Robots
8cda6f8f
GM
11290@subsection Building Robots: Extending the Metaphor
11291@cindex Building robots
11292@cindex Robots, building
11293
11294It is sometimes helpful to think of a running program as a robot that
11295does a job. In doing its job, a recursive function calls on a second
11296robot to help it. The second robot is identical to the first in every
11297way, except that the second robot helps the first and has been
11298passed different arguments than the first.
11299
11300In a recursive function, the second robot may call a third; and the
11301third may call a fourth, and so on. Each of these is a different
11302entity; but all are clones.
11303
11304Since each robot has slightly different instructions---the arguments
11305will differ from one robot to the next---the last robot should know
11306when to stop.
11307
11308Let's expand on the metaphor in which a computer program is a robot.
11309
11310A function definition provides the blueprints for a robot. When you
11311install a function definition, that is, when you evaluate a
11312@code{defun} special form, you install the necessary equipment to
11313build robots. It is as if you were in a factory, setting up an
11314assembly line. Robots with the same name are built according to the
11315same blueprints. So they have, as it were, the same `model number',
11316but a different `serial number'.
11317
11318We often say that a recursive function `calls itself'. What we mean
11319is that the instructions in a recursive function cause the Lisp
11320interpreter to run a different function that has the same name and
11321does the same job as the first, but with different arguments.
11322
11323It is important that the arguments differ from one instance to the
11324next; otherwise, the process will never stop.
11325
d6adf7e7 11326@node Recursive Definition Parts
8cda6f8f
GM
11327@subsection The Parts of a Recursive Definition
11328@cindex Parts of a Recursive Definition
11329@cindex Recursive Definition Parts
11330
11331A recursive function typically contains a conditional expression which
11332has three parts:
11333
11334@enumerate
11335@item
11336A true-or-false-test that determines whether the function is called
11337again, here called the @dfn{do-again-test}.
11338
11339@item
11340The name of the function. When this name is called, a new instance of
11341the function---a new robot, as it were---is created and told what to do.
11342
11343@item
11344An expression that returns a different value each time the function is
11345called, here called the @dfn{next-step-expression}. Consequently, the
11346argument (or arguments) passed to the new instance of the function
11347will be different from that passed to the previous instance. This
11348causes the conditional expression, the @dfn{do-again-test}, to test
11349false after the correct number of repetitions.
11350@end enumerate
11351
11352Recursive functions can be much simpler than any other kind of
11353function. Indeed, when people first start to use them, they often look
11354so mysteriously simple as to be incomprehensible. Like riding a
11355bicycle, reading a recursive function definition takes a certain knack
11356which is hard at first but then seems simple.
11357
11358@need 1200
11359There are several different common recursive patterns. A very simple
11360pattern looks like this:
11361
11362@smallexample
11363@group
11364(defun @var{name-of-recursive-function} (@var{argument-list})
11365 "@var{documentation}@dots{}"
11366 (if @var{do-again-test}
11367 @var{body}@dots{}
11368 (@var{name-of-recursive-function}
11369 @var{next-step-expression})))
11370@end group
11371@end smallexample
11372
11373Each time a recursive function is evaluated, a new instance of it is
11374created and told what to do. The arguments tell the instance what to do.
11375
11376An argument is bound to the value of the next-step-expression. Each
11377instance runs with a different value of the next-step-expression.
11378
11379The value in the next-step-expression is used in the do-again-test.
11380
11381The value returned by the next-step-expression is passed to the new
11382instance of the function, which evaluates it (or some
11383transmogrification of it) to determine whether to continue or stop.
11384The next-step-expression is designed so that the do-again-test returns
11385false when the function should no longer be repeated.
11386
11387The do-again-test is sometimes called the @dfn{stop condition},
11388since it stops the repetitions when it tests false.
11389
d6adf7e7 11390@node Recursion with list
8cda6f8f
GM
11391@subsection Recursion with a List
11392
11393The example of a @code{while} loop that printed the elements of a list
11394of numbers can be written recursively. Here is the code, including
11395an expression to set the value of the variable @code{animals} to a list.
11396
8f4ea8e0
GM
11397If you are reading this in Info in Emacs, you can evaluate this
11398expression directly in Info. Otherwise, you must copy the example
11399to the @file{*scratch*} buffer and evaluate each expression there.
11400Use @kbd{C-u C-x C-e} to evaluate the
8cda6f8f
GM
11401@code{(print-elements-recursively animals)} expression so that the
11402results are printed in the buffer; otherwise the Lisp interpreter will
11403try to squeeze the results into the one line of the echo area.
11404
11405Also, place your cursor immediately after the last closing parenthesis
11406of the @code{print-elements-recursively} function, before the comment.
11407Otherwise, the Lisp interpreter will try to evaluate the comment.
11408
8cda6f8f
GM
11409@findex print-elements-recursively
11410@smallexample
11411@group
11412(setq animals '(gazelle giraffe lion tiger))
11413
11414(defun print-elements-recursively (list)
11415 "Print each element of LIST on a line of its own.
11416Uses recursion."
11417 (when list ; @r{do-again-test}
11418 (print (car list)) ; @r{body}
11419 (print-elements-recursively ; @r{recursive call}
11420 (cdr list)))) ; @r{next-step-expression}
11421
11422(print-elements-recursively animals)
11423@end group
11424@end smallexample
11425
11426The @code{print-elements-recursively} function first tests whether
11427there is any content in the list; if there is, the function prints the
11428first element of the list, the @sc{car} of the list. Then the
11429function `invokes itself', but gives itself as its argument, not the
11430whole list, but the second and subsequent elements of the list, the
11431@sc{cdr} of the list.
11432
11433Put another way, if the list is not empty, the function invokes
11434another instance of code that is similar to the initial code, but is a
11435different thread of execution, with different arguments than the first
11436instance.
11437
11438Put in yet another way, if the list is not empty, the first robot
2d7752a0 11439assembles a second robot and tells it what to do; the second robot is
8cda6f8f
GM
11440a different individual from the first, but is the same model.
11441
11442When the second evaluation occurs, the @code{when} expression is
11443evaluated and if true, prints the first element of the list it
11444receives as its argument (which is the second element of the original
11445list). Then the function `calls itself' with the @sc{cdr} of the list
11446it is invoked with, which (the second time around) is the @sc{cdr} of
11447the @sc{cdr} of the original list.
11448
11449Note that although we say that the function `calls itself', what we
11450mean is that the Lisp interpreter assembles and instructs a new
11451instance of the program. The new instance is a clone of the first,
11452but is a separate individual.
11453
11454Each time the function `invokes itself', it invokes itself on a
11455shorter version of the original list. It creates a new instance that
11456works on a shorter list.
11457
11458Eventually, the function invokes itself on an empty list. It creates
11459a new instance whose argument is @code{nil}. The conditional expression
11460tests the value of @code{list}. Since the value of @code{list} is
11461@code{nil}, the @code{when} expression tests false so the then-part is
11462not evaluated. The function as a whole then returns @code{nil}.
11463
11464@need 1200
a9097c6d
KB
11465When you evaluate the expression @code{(print-elements-recursively
11466animals)} in the @file{*scratch*} buffer, you see this result:
8cda6f8f
GM
11467
11468@smallexample
11469@group
11470gazelle
11471
11472giraffe
11473
11474lion
11475
11476tiger
11477nil
11478@end group
11479@end smallexample
11480
11481@need 2000
d6adf7e7 11482@node Recursive triangle function
8cda6f8f
GM
11483@subsection Recursion in Place of a Counter
11484@findex triangle-recursively
11485
11486@need 1200
11487The @code{triangle} function described in a previous section can also
11488be written recursively. It looks like this:
11489
11490@smallexample
11491@group
11492(defun triangle-recursively (number)
11493 "Return the sum of the numbers 1 through NUMBER inclusive.
11494Uses recursion."
11495 (if (= number 1) ; @r{do-again-test}
11496 1 ; @r{then-part}
11497 (+ number ; @r{else-part}
11498 (triangle-recursively ; @r{recursive call}
11499 (1- number))))) ; @r{next-step-expression}
11500
11501(triangle-recursively 7)
11502@end group
11503@end smallexample
11504
11505@noindent
11506You can install this function by evaluating it and then try it by
11507evaluating @code{(triangle-recursively 7)}. (Remember to put your
11508cursor immediately after the last parenthesis of the function
11509definition, before the comment.) The function evaluates to 28.
11510
11511To understand how this function works, let's consider what happens in the
11512various cases when the function is passed 1, 2, 3, or 4 as the value of
11513its argument.
11514
11515@menu
11516* Recursive Example arg of 1 or 2::
11517* Recursive Example arg of 3 or 4::
11518@end menu
11519
8cda6f8f 11520@ifnottex
d6adf7e7 11521@node Recursive Example arg of 1 or 2
8cda6f8f
GM
11522@unnumberedsubsubsec An argument of 1 or 2
11523@end ifnottex
11524
11525First, what happens if the value of the argument is 1?
11526
11527The function has an @code{if} expression after the documentation
11528string. It tests whether the value of @code{number} is equal to 1; if
11529so, Emacs evaluates the then-part of the @code{if} expression, which
11530returns the number 1 as the value of the function. (A triangle with
11531one row has one pebble in it.)
11532
11533Suppose, however, that the value of the argument is 2. In this case,
11534Emacs evaluates the else-part of the @code{if} expression.
11535
11536@need 1200
11537The else-part consists of an addition, the recursive call to
11538@code{triangle-recursively} and a decrementing action; and it looks like
11539this:
11540
11541@smallexample
11542(+ number (triangle-recursively (1- number)))
11543@end smallexample
11544
11545When Emacs evaluates this expression, the innermost expression is
11546evaluated first; then the other parts in sequence. Here are the steps
11547in detail:
11548
11549@table @i
11550@item Step 1 @w{ } Evaluate the innermost expression.
11551
11552The innermost expression is @code{(1- number)} so Emacs decrements the
11553value of @code{number} from 2 to 1.
11554
11555@item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
11556
11557The Lisp interpreter creates an individual instance of
11558@code{triangle-recursively}. It does not matter that this function is
11559contained within itself. Emacs passes the result Step 1 as the
11560argument used by this instance of the @code{triangle-recursively}
11561function
11562
11563In this case, Emacs evaluates @code{triangle-recursively} with an
11564argument of 1. This means that this evaluation of
11565@code{triangle-recursively} returns 1.
11566
11567@item Step 3 @w{ } Evaluate the value of @code{number}.
11568
11569The variable @code{number} is the second element of the list that
11570starts with @code{+}; its value is 2.
11571
11572@item Step 4 @w{ } Evaluate the @code{+} expression.
11573
11574The @code{+} expression receives two arguments, the first
11575from the evaluation of @code{number} (Step 3) and the second from the
11576evaluation of @code{triangle-recursively} (Step 2).
11577
11578The result of the addition is the sum of 2 plus 1, and the number 3 is
11579returned, which is correct. A triangle with two rows has three
11580pebbles in it.
11581@end table
11582
d6adf7e7 11583@node Recursive Example arg of 3 or 4
8cda6f8f
GM
11584@unnumberedsubsubsec An argument of 3 or 4
11585
11586Suppose that @code{triangle-recursively} is called with an argument of
115873.
11588
11589@table @i
11590@item Step 1 @w{ } Evaluate the do-again-test.
11591
11592The @code{if} expression is evaluated first. This is the do-again
11593test and returns false, so the else-part of the @code{if} expression
11594is evaluated. (Note that in this example, the do-again-test causes
11595the function to call itself when it tests false, not when it tests
11596true.)
11597
11598@item Step 2 @w{ } Evaluate the innermost expression of the else-part.
11599
11600The innermost expression of the else-part is evaluated, which decrements
116013 to 2. This is the next-step-expression.
11602
11603@item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
11604
11605The number 2 is passed to the @code{triangle-recursively} function.
11606
a9097c6d 11607We already know what happens when Emacs evaluates @code{triangle-recursively} with
8cda6f8f
GM
11608an argument of 2. After going through the sequence of actions described
11609earlier, it returns a value of 3. So that is what will happen here.
11610
11611@item Step 4 @w{ } Evaluate the addition.
11612
116133 will be passed as an argument to the addition and will be added to the
11614number with which the function was called, which is 3.
11615@end table
11616
11617@noindent
11618The value returned by the function as a whole will be 6.
11619
11620Now that we know what will happen when @code{triangle-recursively} is
11621called with an argument of 3, it is evident what will happen if it is
11622called with an argument of 4:
11623
11624@quotation
11625@need 800
11626In the recursive call, the evaluation of
11627
11628@smallexample
11629(triangle-recursively (1- 4))
11630@end smallexample
11631
11632@need 800
11633@noindent
11634will return the value of evaluating
11635
11636@smallexample
11637(triangle-recursively 3)
11638@end smallexample
11639
11640@noindent
11641which is 6 and this value will be added to 4 by the addition in the
11642third line.
11643@end quotation
11644
11645@noindent
11646The value returned by the function as a whole will be 10.
11647
11648Each time @code{triangle-recursively} is evaluated, it evaluates a
11649version of itself---a different instance of itself---with a smaller
11650argument, until the argument is small enough so that it does not
11651evaluate itself.
11652
11653Note that this particular design for a recursive function
11654requires that operations be deferred.
11655
11656Before @code{(triangle-recursively 7)} can calculate its answer, it
11657must call @code{(triangle-recursively 6)}; and before
11658@code{(triangle-recursively 6)} can calculate its answer, it must call
11659@code{(triangle-recursively 5)}; and so on. That is to say, the
11660calculation that @code{(triangle-recursively 7)} makes must be
11661deferred until @code{(triangle-recursively 6)} makes its calculation;
11662and @code{(triangle-recursively 6)} must defer until
11663@code{(triangle-recursively 5)} completes; and so on.
11664
11665If each of these instances of @code{triangle-recursively} are thought
11666of as different robots, the first robot must wait for the second to
11667complete its job, which must wait until the third completes, and so
11668on.
11669
11670There is a way around this kind of waiting, which we will discuss in
11671@ref{No Deferment, , Recursion without Deferments}.
11672
d6adf7e7 11673@node Recursion with cond
8cda6f8f
GM
11674@subsection Recursion Example Using @code{cond}
11675@findex cond
11676
11677The version of @code{triangle-recursively} described earlier is written
11678with the @code{if} special form. It can also be written using another
11679special form called @code{cond}. The name of the special form
11680@code{cond} is an abbreviation of the word @samp{conditional}.
11681
11682Although the @code{cond} special form is not used as often in the
11683Emacs Lisp sources as @code{if}, it is used often enough to justify
11684explaining it.
11685
11686@need 800
11687The template for a @code{cond} expression looks like this:
11688
11689@smallexample
11690@group
11691(cond
11692 @var{body}@dots{})
11693@end group
11694@end smallexample
11695
11696@noindent
11697where the @var{body} is a series of lists.
11698
11699@need 800
11700Written out more fully, the template looks like this:
11701
11702@smallexample
11703@group
11704(cond
11705 (@var{first-true-or-false-test} @var{first-consequent})
11706 (@var{second-true-or-false-test} @var{second-consequent})
11707 (@var{third-true-or-false-test} @var{third-consequent})
11708 @dots{})
11709@end group
11710@end smallexample
11711
11712When the Lisp interpreter evaluates the @code{cond} expression, it
11713evaluates the first element (the @sc{car} or true-or-false-test) of
11714the first expression in a series of expressions within the body of the
11715@code{cond}.
11716
11717If the true-or-false-test returns @code{nil} the rest of that
11718expression, the consequent, is skipped and the true-or-false-test of the
11719next expression is evaluated. When an expression is found whose
11720true-or-false-test returns a value that is not @code{nil}, the
11721consequent of that expression is evaluated. The consequent can be one
11722or more expressions. If the consequent consists of more than one
11723expression, the expressions are evaluated in sequence and the value of
11724the last one is returned. If the expression does not have a consequent,
11725the value of the true-or-false-test is returned.
11726
11727If none of the true-or-false-tests test true, the @code{cond} expression
11728returns @code{nil}.
11729
11730@need 1250
11731Written using @code{cond}, the @code{triangle} function looks like this:
11732
11733@smallexample
11734@group
11735(defun triangle-using-cond (number)
11736 (cond ((<= number 0) 0)
11737 ((= number 1) 1)
11738 ((> number 1)
11739 (+ number (triangle-using-cond (1- number))))))
11740@end group
11741@end smallexample
11742
11743@noindent
11744In this example, the @code{cond} returns 0 if the number is less than or
11745equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11746number (triangle-using-cond (1- number)))} if the number is greater than
117471.
11748
d6adf7e7 11749@node Recursive Patterns
8cda6f8f
GM
11750@subsection Recursive Patterns
11751@cindex Recursive Patterns
11752
11753Here are three common recursive patterns. Each involves a list.
11754Recursion does not need to involve lists, but Lisp is designed for lists
11755and this provides a sense of its primal capabilities.
11756
11757@menu
11758* Every::
11759* Accumulate::
11760* Keep::
11761@end menu
11762
d6adf7e7 11763@node Every
8cda6f8f
GM
11764@unnumberedsubsubsec Recursive Pattern: @emph{every}
11765@cindex Every, type of recursive pattern
11766@cindex Recursive pattern: every
11767
11768In the @code{every} recursive pattern, an action is performed on every
11769element of a list.
11770
11771@need 1500
11772The basic pattern is:
11773
11774@itemize @bullet
11775@item
11776If a list be empty, return @code{nil}.
11777@item
11778Else, act on the beginning of the list (the @sc{car} of the list)
11779 @itemize @minus
11780 @item
11781 through a recursive call by the function on the rest (the
11782 @sc{cdr}) of the list,
11783 @item
11784 and, optionally, combine the acted-on element, using @code{cons},
11785 with the results of acting on the rest.
11786 @end itemize
11787@end itemize
11788
11789@need 1500
11790Here is example:
11791
11792@smallexample
11793@group
11794(defun square-each (numbers-list)
11795 "Square each of a NUMBERS LIST, recursively."
11796 (if (not numbers-list) ; do-again-test
11797 nil
11798 (cons
11799 (* (car numbers-list) (car numbers-list))
11800 (square-each (cdr numbers-list))))) ; next-step-expression
11801@end group
11802
11803@group
11804(square-each '(1 2 3))
11805 @result{} (1 4 9)
11806@end group
11807@end smallexample
11808
11809@need 1200
11810@noindent
11811If @code{numbers-list} is empty, do nothing. But if it has content,
11812construct a list combining the square of the first number in the list
11813with the result of the recursive call.
11814
11815(The example follows the pattern exactly: @code{nil} is returned if
11816the numbers' list is empty. In practice, you would write the
11817conditional so it carries out the action when the numbers' list is not
11818empty.)
11819
11820The @code{print-elements-recursively} function (@pxref{Recursion with
11821list, , Recursion with a List}) is another example of an @code{every}
11822pattern, except in this case, rather than bring the results together
11823using @code{cons}, we print each element of output.
11824
11825@need 1250
11826The @code{print-elements-recursively} function looks like this:
11827
11828@smallexample
11829@group
11830(setq animals '(gazelle giraffe lion tiger))
11831@end group
11832
11833@group
11834(defun print-elements-recursively (list)
11835 "Print each element of LIST on a line of its own.
11836Uses recursion."
11837 (when list ; @r{do-again-test}
11838 (print (car list)) ; @r{body}
11839 (print-elements-recursively ; @r{recursive call}
11840 (cdr list)))) ; @r{next-step-expression}
11841
11842(print-elements-recursively animals)
11843@end group
11844@end smallexample
11845
11846@need 1500
11847The pattern for @code{print-elements-recursively} is:
11848
11849@itemize @bullet
11850@item
11851When the list is empty, do nothing.
11852@item
11853But when the list has at least one element,
11854 @itemize @minus
11855 @item
11856 act on the beginning of the list (the @sc{car} of the list),
11857 @item
11858 and make a recursive call on the rest (the @sc{cdr}) of the list.
11859 @end itemize
11860@end itemize
11861
d6adf7e7 11862@node Accumulate
8cda6f8f
GM
11863@unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11864@cindex Accumulate, type of recursive pattern
11865@cindex Recursive pattern: accumulate
11866
11867Another recursive pattern is called the @code{accumulate} pattern. In
11868the @code{accumulate} recursive pattern, an action is performed on
11869every element of a list and the result of that action is accumulated
11870with the results of performing the action on the other elements.
11871
11872This is very like the `every' pattern using @code{cons}, except that
11873@code{cons} is not used, but some other combiner.
11874
11875@need 1500
11876The pattern is:
11877
11878@itemize @bullet
11879@item
11880If a list be empty, return zero or some other constant.
11881@item
11882Else, act on the beginning of the list (the @sc{car} of the list),
11883 @itemize @minus
11884 @item
11885 and combine that acted-on element, using @code{+} or
11886 some other combining function, with
11887 @item
11888 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11889 @end itemize
11890@end itemize
11891
11892@need 1500
11893Here is an example:
11894
11895@smallexample
11896@group
11897(defun add-elements (numbers-list)
11898 "Add the elements of NUMBERS-LIST together."
11899 (if (not numbers-list)
11900 0
11901 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11902@end group
11903
11904@group
11905(add-elements '(1 2 3 4))
11906 @result{} 10
11907@end group
11908@end smallexample
11909
11910@xref{Files List, , Making a List of Files}, for an example of the
11911accumulate pattern.
11912
d6adf7e7 11913@node Keep
8cda6f8f
GM
11914@unnumberedsubsubsec Recursive Pattern: @emph{keep}
11915@cindex Keep, type of recursive pattern
11916@cindex Recursive pattern: keep
11917
11918A third recursive pattern is called the @code{keep} pattern.
11919In the @code{keep} recursive pattern, each element of a list is tested;
11920the element is acted on and the results are kept only if the element
11921meets a criterion.
11922
11923Again, this is very like the `every' pattern, except the element is
11924skipped unless it meets a criterion.
11925
11926@need 1500
11927The pattern has three parts:
11928
11929@itemize @bullet
11930@item
11931If a list be empty, return @code{nil}.
11932@item
11933Else, if the beginning of the list (the @sc{car} of the list) passes
11934 a test
11935 @itemize @minus
11936 @item
11937 act on that element and combine it, using @code{cons} with
11938 @item
11939 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11940 @end itemize
11941@item
11942Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11943the test
11944 @itemize @minus
11945 @item
11946 skip on that element,
11947 @item
11948 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11949 @end itemize
11950@end itemize
11951
11952@need 1500
11953Here is an example that uses @code{cond}:
11954
11955@smallexample
11956@group
11957(defun keep-three-letter-words (word-list)
11958 "Keep three letter words in WORD-LIST."
11959 (cond
11960 ;; First do-again-test: stop-condition
11961 ((not word-list) nil)
11962
11963 ;; Second do-again-test: when to act
11964 ((eq 3 (length (symbol-name (car word-list))))
11965 ;; combine acted-on element with recursive call on shorter list
11966 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11967
11968 ;; Third do-again-test: when to skip element;
11969 ;; recursively call shorter list with next-step expression
11970 (t (keep-three-letter-words (cdr word-list)))))
11971@end group
11972
11973@group
11974(keep-three-letter-words '(one two three four five six))
11975 @result{} (one two six)
11976@end group
11977@end smallexample
11978
11979It goes without saying that you need not use @code{nil} as the test for
11980when to stop; and you can, of course, combine these patterns.
11981
d6adf7e7 11982@node No Deferment
8cda6f8f
GM
11983@subsection Recursion without Deferments
11984@cindex Deferment in recursion
11985@cindex Recursion without Deferments
11986
11987Let's consider again what happens with the @code{triangle-recursively}
11988function. We will find that the intermediate calculations are
11989deferred until all can be done.
11990
11991@need 800
11992Here is the function definition:
11993
11994@smallexample
11995@group
11996(defun triangle-recursively (number)
11997 "Return the sum of the numbers 1 through NUMBER inclusive.
11998Uses recursion."
11999 (if (= number 1) ; @r{do-again-test}
12000 1 ; @r{then-part}
12001 (+ number ; @r{else-part}
12002 (triangle-recursively ; @r{recursive call}
12003 (1- number))))) ; @r{next-step-expression}
12004@end group
12005@end smallexample
12006
12007What happens when we call this function with a argument of 7?
12008
12009The first instance of the @code{triangle-recursively} function adds
12010the number 7 to the value returned by a second instance of
12011@code{triangle-recursively}, an instance that has been passed an
12012argument of 6. That is to say, the first calculation is:
12013
12014@smallexample
12015(+ 7 (triangle-recursively 6))
12016@end smallexample
12017
12018@noindent
12019The first instance of @code{triangle-recursively}---you may want to
12020think of it as a little robot---cannot complete its job. It must hand
12021off the calculation for @code{(triangle-recursively 6)} to a second
12022instance of the program, to a second robot. This second individual is
12023completely different from the first one; it is, in the jargon, a
12024`different instantiation'. Or, put another way, it is a different
12025robot. It is the same model as the first; it calculates triangle
12026numbers recursively; but it has a different serial number.
12027
12028And what does @code{(triangle-recursively 6)} return? It returns the
12029number 6 added to the value returned by evaluating
12030@code{triangle-recursively} with an argument of 5. Using the robot
12031metaphor, it asks yet another robot to help it.
12032
12033@need 800
12034Now the total is:
12035
12036@smallexample
12037(+ 7 6 (triangle-recursively 5))
12038@end smallexample
12039
12040@need 800
12041And what happens next?
12042
12043@smallexample
12044(+ 7 6 5 (triangle-recursively 4))
12045@end smallexample
12046
12047Each time @code{triangle-recursively} is called, except for the last
12048time, it creates another instance of the program---another robot---and
12049asks it to make a calculation.
12050
12051@need 800
12052Eventually, the full addition is set up and performed:
12053
12054@smallexample
12055(+ 7 6 5 4 3 2 1)
12056@end smallexample
12057
12058This design for the function defers the calculation of the first step
12059until the second can be done, and defers that until the third can be
12060done, and so on. Each deferment means the computer must remember what
12061is being waited on. This is not a problem when there are only a few
12062steps, as in this example. But it can be a problem when there are
12063more steps.
12064
d6adf7e7 12065@node No deferment solution
8cda6f8f
GM
12066@subsection No Deferment Solution
12067@cindex No deferment solution
12068@cindex Defermentless solution
12069@cindex Solution without deferment
12070
12071The solution to the problem of deferred operations is to write in a
12072manner that does not defer operations@footnote{The phrase @dfn{tail
12073recursive} is used to describe such a process, one that uses
12074`constant space'.}. This requires
12075writing to a different pattern, often one that involves writing two
12076function definitions, an `initialization' function and a `helper'
12077function.
12078
12079The `initialization' function sets up the job; the `helper' function
12080does the work.
12081
12082@need 1200
12083Here are the two function definitions for adding up numbers. They are
12084so simple, I find them hard to understand.
12085
12086@smallexample
12087@group
12088(defun triangle-initialization (number)
12089 "Return the sum of the numbers 1 through NUMBER inclusive.
12090This is the `initialization' component of a two function
12091duo that uses recursion."
12092 (triangle-recursive-helper 0 0 number))
12093@end group
12094@end smallexample
12095
12096@smallexample
12097@group
12098(defun triangle-recursive-helper (sum counter number)
12099 "Return SUM, using COUNTER, through NUMBER inclusive.
12100This is the `helper' component of a two function duo
12101that uses recursion."
12102 (if (> counter number)
12103 sum
12104 (triangle-recursive-helper (+ sum counter) ; @r{sum}
12105 (1+ counter) ; @r{counter}
12106 number))) ; @r{number}
12107@end group
12108@end smallexample
12109
12110@need 1250
12111Install both function definitions by evaluating them, then call
12112@code{triangle-initialization} with 2 rows:
12113
12114@smallexample
12115@group
12116(triangle-initialization 2)
12117 @result{} 3
12118@end group
12119@end smallexample
12120
12121The `initialization' function calls the first instance of the `helper'
12122function with three arguments: zero, zero, and a number which is the
12123number of rows in the triangle.
12124
12125The first two arguments passed to the `helper' function are
12126initialization values. These values are changed when
12127@code{triangle-recursive-helper} invokes new instances.@footnote{The
12128jargon is mildly confusing: @code{triangle-recursive-helper} uses a
12129process that is iterative in a procedure that is recursive. The
12130process is called iterative because the computer need only record the
12131three values, @code{sum}, @code{counter}, and @code{number}; the
12132procedure is recursive because the function `calls itself'. On the
12133other hand, both the process and the procedure used by
12134@code{triangle-recursively} are called recursive. The word
12135`recursive' has different meanings in the two contexts.}
12136
12137Let's see what happens when we have a triangle that has one row. (This
12138triangle will have one pebble in it!)
12139
12140@need 1200
12141@code{triangle-initialization} will call its helper with
12142the arguments @w{@code{0 0 1}}. That function will run the conditional
12143test whether @code{(> counter number)}:
12144
12145@smallexample
12146(> 0 1)
12147@end smallexample
12148
12149@need 1200
12150@noindent
12151and find that the result is false, so it will invoke
12152the else-part of the @code{if} clause:
12153
12154@smallexample
12155@group
12156 (triangle-recursive-helper
12157 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12158 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12159 number) ; @r{number stays the same}
12160@end group
12161@end smallexample
12162
12163@need 800
12164@noindent
12165which will first compute:
12166
12167@smallexample
12168@group
12169(triangle-recursive-helper (+ 0 0) ; @r{sum}
12170 (1+ 0) ; @r{counter}
12171 1) ; @r{number}
12172@exdent which is:
12173
12174(triangle-recursive-helper 0 1 1)
12175@end group
12176@end smallexample
12177
12178Again, @code{(> counter number)} will be false, so again, the Lisp
12179interpreter will evaluate @code{triangle-recursive-helper}, creating a
12180new instance with new arguments.
12181
12182@need 800
12183This new instance will be;
12184
12185@smallexample
12186@group
12187 (triangle-recursive-helper
12188 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
12189 (1+ counter) ; @r{increment counter} @result{} @r{counter}
12190 number) ; @r{number stays the same}
12191
12192@exdent which is:
12193
12194(triangle-recursive-helper 1 2 1)
12195@end group
12196@end smallexample
12197
12198In this case, the @code{(> counter number)} test will be true! So the
12199instance will return the value of the sum, which will be 1, as
12200expected.
12201
12202Now, let's pass @code{triangle-initialization} an argument
12203of 2, to find out how many pebbles there are in a triangle with two rows.
12204
12205That function calls @code{(triangle-recursive-helper 0 0 2)}.
12206
12207@need 800
12208In stages, the instances called will be:
12209
12210@smallexample
12211@group
12212 @r{sum counter number}
12213(triangle-recursive-helper 0 1 2)
12214
12215(triangle-recursive-helper 1 2 2)
12216
12217(triangle-recursive-helper 3 3 2)
12218@end group
12219@end smallexample
12220
12221When the last instance is called, the @code{(> counter number)} test
12222will be true, so the instance will return the value of @code{sum},
12223which will be 3.
12224
12225This kind of pattern helps when you are writing functions that can use
12226many resources in a computer.
12227
12228@need 1500
d6adf7e7 12229@node Looping exercise
8cda6f8f
GM
12230@section Looping Exercise
12231
12232@itemize @bullet
12233@item
12234Write a function similar to @code{triangle} in which each row has a
12235value which is the square of the row number. Use a @code{while} loop.
12236
12237@item
12238Write a function similar to @code{triangle} that multiplies instead of
12239adds the values.
12240
12241@item
12242Rewrite these two functions recursively. Rewrite these functions
12243using @code{cond}.
12244
12245@c comma in printed title causes problem in Info cross reference
12246@item
12247Write a function for Texinfo mode that creates an index entry at the
12248beginning of a paragraph for every @samp{@@dfn} within the paragraph.
12249(In a Texinfo file, @samp{@@dfn} marks a definition. This book is
12250written in Texinfo.)
12251
12252Many of the functions you will need are described in two of the
12253previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
12254Text}, and @ref{Yanking, , Yanking Text Back}. If you use
12255@code{forward-paragraph} to put the index entry at the beginning of
12256the paragraph, you will have to use @w{@kbd{C-h f}}
12257(@code{describe-function}) to find out how to make the command go
12258backwards.
12259
12260For more information, see
12261@ifinfo
12262@ref{Indicating, , Indicating Definitions, texinfo}.
12263@end ifinfo
12264@ifhtml
12265@ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
12266a Texinfo manual in the current directory. Or, if you are on the
12267Internet, see
12268@uref{http://www.gnu.org/software/texinfo/manual/texinfo/}
12269@end ifhtml
12270@iftex
12271``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
12272Documentation Format}.
12273@end iftex
12274@end itemize
12275
d6adf7e7 12276@node Regexp Search
8cda6f8f
GM
12277@chapter Regular Expression Searches
12278@cindex Searches, illustrating
12279@cindex Regular expression searches
12280@cindex Patterns, searching for
12281@cindex Motion by sentence and paragraph
12282@cindex Sentences, movement by
12283@cindex Paragraphs, movement by
12284
12285Regular expression searches are used extensively in GNU Emacs. The
12286two functions, @code{forward-sentence} and @code{forward-paragraph},
12287illustrate these searches well. They use regular expressions to find
12288where to move point. The phrase `regular expression' is often written
12289as `regexp'.
12290
12291Regular expression searches are described in @ref{Regexp Search, ,
12292Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
12293@ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
12294Manual}. In writing this chapter, I am presuming that you have at
12295least a mild acquaintance with them. The major point to remember is
12296that regular expressions permit you to search for patterns as well as
12297for literal strings of characters. For example, the code in
12298@code{forward-sentence} searches for the pattern of possible
12299characters that could mark the end of a sentence, and moves point to
12300that spot.
12301
12302Before looking at the code for the @code{forward-sentence} function, it
12303is worth considering what the pattern that marks the end of a sentence
12304must be. The pattern is discussed in the next section; following that
12305is a description of the regular expression search function,
12306@code{re-search-forward}. The @code{forward-sentence} function
12307is described in the section following. Finally, the
12308@code{forward-paragraph} function is described in the last section of
12309this chapter. @code{forward-paragraph} is a complex function that
12310introduces several new features.
12311
12312@menu
12313* sentence-end:: The regular expression for @code{sentence-end}.
12314* re-search-forward:: Very similar to @code{search-forward}.
12315* forward-sentence:: A straightforward example of regexp search.
12316* forward-paragraph:: A somewhat complex example.
12317* etags:: How to create your own @file{TAGS} table.
12318* Regexp Review::
12319* re-search Exercises::
12320@end menu
12321
d6adf7e7 12322@node sentence-end
8cda6f8f
GM
12323@section The Regular Expression for @code{sentence-end}
12324@findex sentence-end
12325
12326The symbol @code{sentence-end} is bound to the pattern that marks the
12327end of a sentence. What should this regular expression be?
12328
12329Clearly, a sentence may be ended by a period, a question mark, or an
12330exclamation mark. Indeed, in English, only clauses that end with one
12331of those three characters should be considered the end of a sentence.
12332This means that the pattern should include the character set:
12333
12334@smallexample
12335[.?!]
12336@end smallexample
12337
12338However, we do not want @code{forward-sentence} merely to jump to a
12339period, a question mark, or an exclamation mark, because such a character
12340might be used in the middle of a sentence. A period, for example, is
12341used after abbreviations. So other information is needed.
12342
12343According to convention, you type two spaces after every sentence, but
12344only one space after a period, a question mark, or an exclamation mark in
12345the body of a sentence. So a period, a question mark, or an exclamation
12346mark followed by two spaces is a good indicator of an end of sentence.
12347However, in a file, the two spaces may instead be a tab or the end of a
12348line. This means that the regular expression should include these three
12349items as alternatives.
12350
12351@need 800
12352This group of alternatives will look like this:
12353
12354@smallexample
12355@group
12356\\($\\| \\| \\)
12357 ^ ^^
12358 TAB SPC
12359@end group
12360@end smallexample
12361
12362@noindent
12363Here, @samp{$} indicates the end of the line, and I have pointed out
12364where the tab and two spaces are inserted in the expression. Both are
12365inserted by putting the actual characters into the expression.
12366
12367Two backslashes, @samp{\\}, are required before the parentheses and
12368vertical bars: the first backslash quotes the following backslash in
12369Emacs; and the second indicates that the following character, the
12370parenthesis or the vertical bar, is special.
12371
12372@need 1000
12373Also, a sentence may be followed by one or more carriage returns, like
12374this:
12375
12376@smallexample
12377@group
12378[
12379]*
12380@end group
12381@end smallexample
12382
12383@noindent
12384Like tabs and spaces, a carriage return is inserted into a regular
12385expression by inserting it literally. The asterisk indicates that the
12386@key{RET} is repeated zero or more times.
12387
12388But a sentence end does not consist only of a period, a question mark or
12389an exclamation mark followed by appropriate space: a closing quotation
12390mark or a closing brace of some kind may precede the space. Indeed more
12391than one such mark or brace may precede the space. These require a
12392expression that looks like this:
12393
12394@smallexample
12395[]\"')@}]*
12396@end smallexample
12397
12398In this expression, the first @samp{]} is the first character in the
12399expression; the second character is @samp{"}, which is preceded by a
12400@samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
12401three characters are @samp{'}, @samp{)}, and @samp{@}}.
12402
12403All this suggests what the regular expression pattern for matching the
12404end of a sentence should be; and, indeed, if we evaluate
12405@code{sentence-end} we find that it returns the following value:
12406
12407@smallexample
12408@group
12409sentence-end
12410 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
12411]*"
12412@end group
12413@end smallexample
12414
12415@noindent
12416(Well, not in GNU Emacs 22; that is because of an effort to make the
12417process simpler and to handle more glyphs and languages. When the
12418value of @code{sentence-end} is @code{nil}, then use the value defined
12419by the function @code{sentence-end}. (Here is a use of the difference
12420between a value and a function in Emacs Lisp.) The function returns a
12421value constructed from the variables @code{sentence-end-base},
12422@code{sentence-end-double-space}, @code{sentence-end-without-period},
12423and @code{sentence-end-without-space}. The critical variable is
12424@code{sentence-end-base}; its global value is similar to the one
12425described above but it also contains two additional quotation marks.
12426These have differing degrees of curliness. The
12427@code{sentence-end-without-period} variable, when true, tells Emacs
12428that a sentence may end without a period, such as text in Thai.)
12429
12430@ignore
12431@noindent
12432(Note that here the @key{TAB}, two spaces, and @key{RET} are shown
12433literally in the pattern.)
12434
12435This regular expression can be deciphered as follows:
12436
12437@table @code
12438@item [.?!]
12439The first part of the pattern is the three characters, a period, a question
12440mark and an exclamation mark, within square brackets. The pattern must
12441begin with one or other of these characters.
12442
12443@item []\"')@}]*
12444The second part of the pattern is the group of closing braces and
12445quotation marks, which can appear zero or more times. These may follow
12446the period, question mark or exclamation mark. In a regular expression,
12447the backslash, @samp{\}, followed by the double quotation mark,
12448@samp{"}, indicates the class of string-quote characters. Usually, the
12449double quotation mark is the only character in this class. The
12450asterisk, @samp{*}, indicates that the items in the previous group (the
12451group surrounded by square brackets, @samp{[]}) may be repeated zero or
12452more times.
12453
12454@item \\($\\| \\| \\)
12455The third part of the pattern is one or other of: either the end of a
12456line, or two blank spaces, or a tab. The double back-slashes are used
12457to prevent Emacs from reading the parentheses and vertical bars as part
12458of the search pattern; the parentheses are used to mark the group and
12459the vertical bars are used to indicated that the patterns to either side
12460of them are alternatives. The dollar sign is used to indicate the end
12461of a line and both the two spaces and the tab are each inserted as is to
12462indicate what they are.
12463
12464@item [@key{RET}]*
12465Finally, the last part of the pattern indicates that the end of the line
12466or the whitespace following the period, question mark or exclamation
12467mark may, but need not, be followed by one or more carriage returns. In
12468the pattern, the carriage return is inserted as an actual carriage
12469return between square brackets but here it is shown as @key{RET}.
12470@end table
12471@end ignore
12472
d6adf7e7 12473@node re-search-forward
8cda6f8f
GM
12474@section The @code{re-search-forward} Function
12475@findex re-search-forward
12476
12477The @code{re-search-forward} function is very like the
12478@code{search-forward} function. (@xref{search-forward, , The
12479@code{search-forward} Function}.)
12480
12481@code{re-search-forward} searches for a regular expression. If the
12482search is successful, it leaves point immediately after the last
12483character in the target. If the search is backwards, it leaves point
12484just before the first character in the target. You may tell
12485@code{re-search-forward} to return @code{t} for true. (Moving point
12486is therefore a `side effect'.)
12487
12488Like @code{search-forward}, the @code{re-search-forward} function takes
12489four arguments:
12490
12491@enumerate
12492@item
12493The first argument is the regular expression that the function searches
7b4b1301 12494for. The regular expression will be a string between quotation marks.
8cda6f8f
GM
12495
12496@item
12497The optional second argument limits how far the function will search; it is a
12498bound, which is specified as a position in the buffer.
12499
12500@item
12501The optional third argument specifies how the function responds to
12502failure: @code{nil} as the third argument causes the function to
12503signal an error (and print a message) when the search fails; any other
12504value causes it to return @code{nil} if the search fails and @code{t}
12505if the search succeeds.
12506
12507@item
12508The optional fourth argument is the repeat count. A negative repeat
12509count causes @code{re-search-forward} to search backwards.
12510@end enumerate
12511
12512@need 800
12513The template for @code{re-search-forward} looks like this:
12514
12515@smallexample
12516@group
12517(re-search-forward "@var{regular-expression}"
12518 @var{limit-of-search}
12519 @var{what-to-do-if-search-fails}
12520 @var{repeat-count})
12521@end group
12522@end smallexample
12523
12524The second, third, and fourth arguments are optional. However, if you
12525want to pass a value to either or both of the last two arguments, you
12526must also pass a value to all the preceding arguments. Otherwise, the
12527Lisp interpreter will mistake which argument you are passing the value
12528to.
12529
12530@need 1200
12531In the @code{forward-sentence} function, the regular expression will be
12532the value of the variable @code{sentence-end}. In simple form, that is:
12533
12534@smallexample
12535@group
12536"[.?!][]\"')@}]*\\($\\| \\| \\)[
12537]*"
12538@end group
12539@end smallexample
12540
12541@noindent
12542The limit of the search will be the end of the paragraph (since a
12543sentence cannot go beyond a paragraph). If the search fails, the
12544function will return @code{nil}; and the repeat count will be provided
12545by the argument to the @code{forward-sentence} function.
12546
d6adf7e7 12547@node forward-sentence
8cda6f8f
GM
12548@section @code{forward-sentence}
12549@findex forward-sentence
12550
12551The command to move the cursor forward a sentence is a straightforward
12552illustration of how to use regular expression searches in Emacs Lisp.
12553Indeed, the function looks longer and more complicated than it is; this
12554is because the function is designed to go backwards as well as forwards;
12555and, optionally, over more than one sentence. The function is usually
12556bound to the key command @kbd{M-e}.
12557
12558@menu
12559* Complete forward-sentence::
12560* fwd-sentence while loops:: Two @code{while} loops.
12561* fwd-sentence re-search:: A regular expression search.
12562@end menu
12563
8cda6f8f 12564@ifnottex
d6adf7e7 12565@node Complete forward-sentence
8cda6f8f
GM
12566@unnumberedsubsec Complete @code{forward-sentence} function definition
12567@end ifnottex
12568
12569@need 1250
12570Here is the code for @code{forward-sentence}:
12571
12572@c in GNU Emacs 22
12573@smallexample
12574@group
12575(defun forward-sentence (&optional arg)
12576 "Move forward to next `sentence-end'. With argument, repeat.
12577With negative argument, move backward repeatedly to `sentence-beginning'.
12578
12579The variable `sentence-end' is a regular expression that matches ends of
12580sentences. Also, every paragraph boundary terminates sentences as well."
12581@end group
12582@group
12583 (interactive "p")
12584 (or arg (setq arg 1))
12585 (let ((opoint (point))
12586 (sentence-end (sentence-end)))
12587 (while (< arg 0)
12588 (let ((pos (point))
12589 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12590 (if (and (re-search-backward sentence-end par-beg t)
12591 (or (< (match-end 0) pos)
12592 (re-search-backward sentence-end par-beg t)))
12593 (goto-char (match-end 0))
12594 (goto-char par-beg)))
12595 (setq arg (1+ arg)))
12596@end group
12597@group
12598 (while (> arg 0)
12599 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12600 (if (re-search-forward sentence-end par-end t)
12601 (skip-chars-backward " \t\n")
12602 (goto-char par-end)))
12603 (setq arg (1- arg)))
12604 (constrain-to-field nil opoint t)))
12605@end group
12606@end smallexample
12607
12608@ignore
12609GNU Emacs 21
12610@smallexample
12611@group
12612(defun forward-sentence (&optional arg)
12613 "Move forward to next sentence-end. With argument, repeat.
12614With negative argument, move backward repeatedly to sentence-beginning.
12615Sentence ends are identified by the value of sentence-end
12616treated as a regular expression. Also, every paragraph boundary
12617terminates sentences as well."
12618@end group
12619@group
12620 (interactive "p")
12621 (or arg (setq arg 1))
12622 (while (< arg 0)
12623 (let ((par-beg
12624 (save-excursion (start-of-paragraph-text) (point))))
12625 (if (re-search-backward
12626 (concat sentence-end "[^ \t\n]") par-beg t)
12627 (goto-char (1- (match-end 0)))
12628 (goto-char par-beg)))
12629 (setq arg (1+ arg)))
12630 (while (> arg 0)
12631 (let ((par-end
12632 (save-excursion (end-of-paragraph-text) (point))))
12633 (if (re-search-forward sentence-end par-end t)
12634 (skip-chars-backward " \t\n")
12635 (goto-char par-end)))
12636 (setq arg (1- arg))))
12637@end group
12638@end smallexample
12639@end ignore
12640
12641The function looks long at first sight and it is best to look at its
12642skeleton first, and then its muscle. The way to see the skeleton is to
12643look at the expressions that start in the left-most columns:
12644
12645@smallexample
12646@group
12647(defun forward-sentence (&optional arg)
12648 "@var{documentation}@dots{}"
12649 (interactive "p")
12650 (or arg (setq arg 1))
12651 (let ((opoint (point)) (sentence-end (sentence-end)))
12652 (while (< arg 0)
12653 (let ((pos (point))
12654 (par-beg (save-excursion (start-of-paragraph-text) (point))))
12655 @var{rest-of-body-of-while-loop-when-going-backwards}
12656 (while (> arg 0)
12657 (let ((par-end (save-excursion (end-of-paragraph-text) (point))))
12658 @var{rest-of-body-of-while-loop-when-going-forwards}
12659 @var{handle-forms-and-equivalent}
12660@end group
12661@end smallexample
12662
12663This looks much simpler! The function definition consists of
12664documentation, an @code{interactive} expression, an @code{or}
12665expression, a @code{let} expression, and @code{while} loops.
12666
12667Let's look at each of these parts in turn.
12668
12669We note that the documentation is thorough and understandable.
12670
12671The function has an @code{interactive "p"} declaration. This means
12672that the processed prefix argument, if any, is passed to the
12673function as its argument. (This will be a number.) If the function
12674is not passed an argument (it is optional) then the argument
12675@code{arg} will be bound to 1.
12676
12677When @code{forward-sentence} is called non-interactively without an
12678argument, @code{arg} is bound to @code{nil}. The @code{or} expression
12679handles this. What it does is either leave the value of @code{arg} as
12680it is, but only if @code{arg} is bound to a value; or it sets the
12681value of @code{arg} to 1, in the case when @code{arg} is bound to
12682@code{nil}.
12683
12684Next is a @code{let}. That specifies the values of two local
12685variables, @code{point} and @code{sentence-end}. The local value of
12686point, from before the search, is used in the
12687@code{constrain-to-field} function which handles forms and
12688equivalents. The @code{sentence-end} variable is set by the
12689@code{sentence-end} function.
12690
d6adf7e7 12691@node fwd-sentence while loops
8cda6f8f
GM
12692@unnumberedsubsec The @code{while} loops
12693
12694Two @code{while} loops follow. The first @code{while} has a
12695true-or-false-test that tests true if the prefix argument for
12696@code{forward-sentence} is a negative number. This is for going
12697backwards. The body of this loop is similar to the body of the second
12698@code{while} clause, but it is not exactly the same. We will skip
12699this @code{while} loop and concentrate on the second @code{while}
12700loop.
12701
12702@need 1500
12703The second @code{while} loop is for moving point forward. Its skeleton
12704looks like this:
12705
12706@smallexample
12707@group
12708(while (> arg 0) ; @r{true-or-false-test}
12709 (let @var{varlist}
12710 (if (@var{true-or-false-test})
12711 @var{then-part}
12712 @var{else-part}
12713 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
12714@end group
12715@end smallexample
12716
12717The @code{while} loop is of the decrementing kind.
12718(@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
12719has a true-or-false-test that tests true so long as the counter (in
12720this case, the variable @code{arg}) is greater than zero; and it has a
12721decrementer that subtracts 1 from the value of the counter every time
12722the loop repeats.
12723
12724If no prefix argument is given to @code{forward-sentence}, which is
12725the most common way the command is used, this @code{while} loop will
12726run once, since the value of @code{arg} will be 1.
12727
12728The body of the @code{while} loop consists of a @code{let} expression,
12729which creates and binds a local variable, and has, as its body, an
12730@code{if} expression.
12731
12732@need 1250
12733The body of the @code{while} loop looks like this:
12734
12735@smallexample
12736@group
12737(let ((par-end
12738 (save-excursion (end-of-paragraph-text) (point))))
12739 (if (re-search-forward sentence-end par-end t)
12740 (skip-chars-backward " \t\n")
12741 (goto-char par-end)))
12742@end group
12743@end smallexample
12744
12745The @code{let} expression creates and binds the local variable
12746@code{par-end}. As we shall see, this local variable is designed to
12747provide a bound or limit to the regular expression search. If the
12748search fails to find a proper sentence ending in the paragraph, it will
12749stop on reaching the end of the paragraph.
12750
12751But first, let us examine how @code{par-end} is bound to the value of
12752the end of the paragraph. What happens is that the @code{let} sets the
12753value of @code{par-end} to the value returned when the Lisp interpreter
12754evaluates the expression
12755
12756@smallexample
12757@group
12758(save-excursion (end-of-paragraph-text) (point))
12759@end group
12760@end smallexample
12761
12762@noindent
12763In this expression, @code{(end-of-paragraph-text)} moves point to the
12764end of the paragraph, @code{(point)} returns the value of point, and then
12765@code{save-excursion} restores point to its original position. Thus,
12766the @code{let} binds @code{par-end} to the value returned by the
12767@code{save-excursion} expression, which is the position of the end of
12768the paragraph. (The @code{end-of-paragraph-text} function uses
12769@code{forward-paragraph}, which we will discuss shortly.)
12770
12771@need 1200
12772Emacs next evaluates the body of the @code{let}, which is an @code{if}
12773expression that looks like this:
12774
12775@smallexample
12776@group
12777(if (re-search-forward sentence-end par-end t) ; @r{if-part}
12778 (skip-chars-backward " \t\n") ; @r{then-part}
12779 (goto-char par-end))) ; @r{else-part}
12780@end group
12781@end smallexample
12782
12783The @code{if} tests whether its first argument is true and if so,
12784evaluates its then-part; otherwise, the Emacs Lisp interpreter
12785evaluates the else-part. The true-or-false-test of the @code{if}
12786expression is the regular expression search.
12787
12788It may seem odd to have what looks like the `real work' of
12789the @code{forward-sentence} function buried here, but this is a common
12790way this kind of operation is carried out in Lisp.
12791
d6adf7e7 12792@node fwd-sentence re-search
8cda6f8f
GM
12793@unnumberedsubsec The regular expression search
12794
12795The @code{re-search-forward} function searches for the end of the
12796sentence, that is, for the pattern defined by the @code{sentence-end}
12797regular expression. If the pattern is found---if the end of the sentence is
12798found---then the @code{re-search-forward} function does two things:
12799
12800@enumerate
12801@item
12802The @code{re-search-forward} function carries out a side effect, which
12803is to move point to the end of the occurrence found.
12804
12805@item
12806The @code{re-search-forward} function returns a value of true. This is
12807the value received by the @code{if}, and means that the search was
12808successful.
12809@end enumerate
12810
12811@noindent
12812The side effect, the movement of point, is completed before the
12813@code{if} function is handed the value returned by the successful
12814conclusion of the search.
12815
12816When the @code{if} function receives the value of true from a successful
12817call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12818which is the expression @code{(skip-chars-backward " \t\n")}. This
12819expression moves backwards over any blank spaces, tabs or carriage
12820returns until a printed character is found and then leaves point after
12821the character. Since point has already been moved to the end of the
12822pattern that marks the end of the sentence, this action leaves point
12823right after the closing printed character of the sentence, which is
12824usually a period.
12825
12826On the other hand, if the @code{re-search-forward} function fails to
12827find a pattern marking the end of the sentence, the function returns
12828false. The false then causes the @code{if} to evaluate its third
12829argument, which is @code{(goto-char par-end)}: it moves point to the
12830end of the paragraph.
12831
12832(And if the text is in a form or equivalent, and point may not move
12833fully, then the @code{constrain-to-field} function comes into play.)
12834
12835Regular expression searches are exceptionally useful and the pattern
12836illustrated by @code{re-search-forward}, in which the search is the
12837test of an @code{if} expression, is handy. You will see or write code
12838incorporating this pattern often.
12839
d6adf7e7 12840@node forward-paragraph
8cda6f8f
GM
12841@section @code{forward-paragraph}: a Goldmine of Functions
12842@findex forward-paragraph
12843
12844@ignore
12845@c in GNU Emacs 22
12846(defun forward-paragraph (&optional arg)
12847 "Move forward to end of paragraph.
12848With argument ARG, do it ARG times;
12849a negative argument ARG = -N means move backward N paragraphs.
12850
12851A line which `paragraph-start' matches either separates paragraphs
12852\(if `paragraph-separate' matches it also) or is the first line of a paragraph.
12853A paragraph end is the beginning of a line which is not part of the paragraph
12854to which the end of the previous line belongs, or the end of the buffer.
12855Returns the count of paragraphs left to move."
12856 (interactive "p")
12857 (or arg (setq arg 1))
12858 (let* ((opoint (point))
12859 (fill-prefix-regexp
12860 (and fill-prefix (not (equal fill-prefix ""))
12861 (not paragraph-ignore-fill-prefix)
12862 (regexp-quote fill-prefix)))
12863 ;; Remove ^ from paragraph-start and paragraph-sep if they are there.
12864 ;; These regexps shouldn't be anchored, because we look for them
12865 ;; starting at the left-margin. This allows paragraph commands to
12866 ;; work normally with indented text.
12867 ;; This hack will not find problem cases like "whatever\\|^something".
12868 (parstart (if (and (not (equal "" paragraph-start))
12869 (equal ?^ (aref paragraph-start 0)))
12870 (substring paragraph-start 1)
12871 paragraph-start))
12872 (parsep (if (and (not (equal "" paragraph-separate))
12873 (equal ?^ (aref paragraph-separate 0)))
12874 (substring paragraph-separate 1)
12875 paragraph-separate))
12876 (parsep
12877 (if fill-prefix-regexp
12878 (concat parsep "\\|"
12879 fill-prefix-regexp "[ \t]*$")
12880 parsep))
12881 ;; This is used for searching.
12882 (sp-parstart (concat "^[ \t]*\\(?:" parstart "\\|" parsep "\\)"))
12883 start found-start)
12884 (while (and (< arg 0) (not (bobp)))
12885 (if (and (not (looking-at parsep))
12886 (re-search-backward "^\n" (max (1- (point)) (point-min)) t)
12887 (looking-at parsep))
12888 (setq arg (1+ arg))
12889 (setq start (point))
12890 ;; Move back over paragraph-separating lines.
12891 (forward-char -1) (beginning-of-line)
12892 (while (and (not (bobp))
12893 (progn (move-to-left-margin)
12894 (looking-at parsep)))
12895 (forward-line -1))
12896 (if (bobp)
12897 nil
12898 (setq arg (1+ arg))
12899 ;; Go to end of the previous (non-separating) line.
12900 (end-of-line)
12901 ;; Search back for line that starts or separates paragraphs.
12902 (if (if fill-prefix-regexp
12903 ;; There is a fill prefix; it overrides parstart.
12904 (let (multiple-lines)
12905 (while (and (progn (beginning-of-line) (not (bobp)))
12906 (progn (move-to-left-margin)
12907 (not (looking-at parsep)))
12908 (looking-at fill-prefix-regexp))
12909 (unless (= (point) start)
12910 (setq multiple-lines t))
12911 (forward-line -1))
12912 (move-to-left-margin)
12913 ;; This deleted code caused a long hanging-indent line
12914 ;; not to be filled together with the following lines.
12915 ;; ;; Don't move back over a line before the paragraph
12916 ;; ;; which doesn't start with fill-prefix
12917 ;; ;; unless that is the only line we've moved over.
12918 ;; (and (not (looking-at fill-prefix-regexp))
12919 ;; multiple-lines
12920 ;; (forward-line 1))
12921 (not (bobp)))
12922 (while (and (re-search-backward sp-parstart nil 1)
12923 (setq found-start t)
12924 ;; Found a candidate, but need to check if it is a
12925 ;; REAL parstart.
12926 (progn (setq start (point))
12927 (move-to-left-margin)
12928 (not (looking-at parsep)))
12929 (not (and (looking-at parstart)
12930 (or (not use-hard-newlines)
12931 (bobp)
12932 (get-text-property
12933 (1- start) 'hard)))))
12934 (setq found-start nil)
12935 (goto-char start))
12936 found-start)
12937 ;; Found one.
12938 (progn
12939 ;; Move forward over paragraph separators.
12940 ;; We know this cannot reach the place we started
12941 ;; because we know we moved back over a non-separator.
12942 (while (and (not (eobp))
12943 (progn (move-to-left-margin)
12944 (looking-at parsep)))
12945 (forward-line 1))
12946 ;; If line before paragraph is just margin, back up to there.
12947 (end-of-line 0)
12948 (if (> (current-column) (current-left-margin))
12949 (forward-char 1)
12950 (skip-chars-backward " \t")
12951 (if (not (bolp))
12952 (forward-line 1))))
12953 ;; No starter or separator line => use buffer beg.
12954 (goto-char (point-min))))))
12955
12956 (while (and (> arg 0) (not (eobp)))
12957 ;; Move forward over separator lines...
12958 (while (and (not (eobp))
12959 (progn (move-to-left-margin) (not (eobp)))
12960 (looking-at parsep))
12961 (forward-line 1))
12962 (unless (eobp) (setq arg (1- arg)))
12963 ;; ... and one more line.
12964 (forward-line 1)
12965 (if fill-prefix-regexp
12966 ;; There is a fill prefix; it overrides parstart.
12967 (while (and (not (eobp))
12968 (progn (move-to-left-margin) (not (eobp)))
12969 (not (looking-at parsep))
12970 (looking-at fill-prefix-regexp))
12971 (forward-line 1))
12972 (while (and (re-search-forward sp-parstart nil 1)
12973 (progn (setq start (match-beginning 0))
12974 (goto-char start)
12975 (not (eobp)))
12976 (progn (move-to-left-margin)
12977 (not (looking-at parsep)))
12978 (or (not (looking-at parstart))
12979 (and use-hard-newlines
12980 (not (get-text-property (1- start) 'hard)))))
12981 (forward-char 1))
12982 (if (< (point) (point-max))
12983 (goto-char start))))
12984 (constrain-to-field nil opoint t)
12985 ;; Return the number of steps that could not be done.
12986 arg))
12987@end ignore
12988
12989The @code{forward-paragraph} function moves point forward to the end
12990of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12991number of functions that are important in themselves, including
12992@code{let*}, @code{match-beginning}, and @code{looking-at}.
12993
12994The function definition for @code{forward-paragraph} is considerably
12995longer than the function definition for @code{forward-sentence}
12996because it works with a paragraph, each line of which may begin with a
12997fill prefix.
12998
12999A fill prefix consists of a string of characters that are repeated at
13000the beginning of each line. For example, in Lisp code, it is a
13001convention to start each line of a paragraph-long comment with
13002@samp{;;; }. In Text mode, four blank spaces make up another common
13003fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
13004emacs, The GNU Emacs Manual}, for more information about fill
13005prefixes.)
13006
13007The existence of a fill prefix means that in addition to being able to
13008find the end of a paragraph whose lines begin on the left-most
13009column, the @code{forward-paragraph} function must be able to find the
13010end of a paragraph when all or many of the lines in the buffer begin
13011with the fill prefix.
13012
13013Moreover, it is sometimes practical to ignore a fill prefix that
13014exists, especially when blank lines separate paragraphs.
13015This is an added complication.
13016
13017@menu
13018* forward-paragraph in brief:: Key parts of the function definition.
13019* fwd-para let:: The @code{let*} expression.
13020* fwd-para while:: The forward motion @code{while} loop.
13021@end menu
13022
8cda6f8f 13023@ifnottex
d6adf7e7 13024@node forward-paragraph in brief
8cda6f8f
GM
13025@unnumberedsubsec Shortened @code{forward-paragraph} function definition
13026@end ifnottex
13027
13028Rather than print all of the @code{forward-paragraph} function, we
13029will only print parts of it. Read without preparation, the function
13030can be daunting!
13031
13032@need 800
13033In outline, the function looks like this:
13034
13035@smallexample
13036@group
13037(defun forward-paragraph (&optional arg)
13038 "@var{documentation}@dots{}"
13039 (interactive "p")
13040 (or arg (setq arg 1))
13041 (let*
13042 @var{varlist}
13043 (while (and (< arg 0) (not (bobp))) ; @r{backward-moving-code}
13044 @dots{}
13045 (while (and (> arg 0) (not (eobp))) ; @r{forward-moving-code}
13046 @dots{}
13047@end group
13048@end smallexample
13049
13050The first parts of the function are routine: the function's argument
13051list consists of one optional argument. Documentation follows.
13052
13053The lower case @samp{p} in the @code{interactive} declaration means
13054that the processed prefix argument, if any, is passed to the function.
13055This will be a number, and is the repeat count of how many paragraphs
13056point will move. The @code{or} expression in the next line handles
13057the common case when no argument is passed to the function, which occurs
13058if the function is called from other code rather than interactively.
13059This case was described earlier. (@xref{forward-sentence, The
13060@code{forward-sentence} function}.) Now we reach the end of the
13061familiar part of this function.
13062
d6adf7e7 13063@node fwd-para let
8cda6f8f
GM
13064@unnumberedsubsec The @code{let*} expression
13065
13066The next line of the @code{forward-paragraph} function begins a
13067@code{let*} expression. This is a different than @code{let}. The
13068symbol is @code{let*} not @code{let}.
13069
13070The @code{let*} special form is like @code{let} except that Emacs sets
13071each variable in sequence, one after another, and variables in the
13072latter part of the varlist can make use of the values to which Emacs
13073set variables in the earlier part of the varlist.
13074
13075@ignore
13076( refappend save-excursion, , code save-excursion in code append-to-buffer .)
13077@end ignore
13078
13079(@ref{append save-excursion, , @code{save-excursion} in @code{append-to-buffer}}.)
13080
13081In the @code{let*} expression in this function, Emacs binds a total of
13082seven variables: @code{opoint}, @code{fill-prefix-regexp},
13083@code{parstart}, @code{parsep}, @code{sp-parstart}, @code{start}, and
13084@code{found-start}.
13085
13086The variable @code{parsep} appears twice, first, to remove instances
13087of @samp{^}, and second, to handle fill prefixes.
13088
13089The variable @code{opoint} is just the value of @code{point}. As you
13090can guess, it is used in a @code{constrain-to-field} expression, just
13091as in @code{forward-sentence}.
13092
13093The variable @code{fill-prefix-regexp} is set to the value returned by
13094evaluating the following list:
13095
13096@smallexample
13097@group
13098(and fill-prefix
13099 (not (equal fill-prefix ""))
13100 (not paragraph-ignore-fill-prefix)
13101 (regexp-quote fill-prefix))
13102@end group
13103@end smallexample
13104
13105@noindent
13106This is an expression whose first element is the @code{and} special form.
13107
13108As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
13109function}), the @code{and} special form evaluates each of its
13110arguments until one of the arguments returns a value of @code{nil}, in
13111which case the @code{and} expression returns @code{nil}; however, if
13112none of the arguments returns a value of @code{nil}, the value
13113resulting from evaluating the last argument is returned. (Since such
13114a value is not @code{nil}, it is considered true in Lisp.) In other
13115words, an @code{and} expression returns a true value only if all its
13116arguments are true.
13117@findex and
13118
13119In this case, the variable @code{fill-prefix-regexp} is bound to a
13120non-@code{nil} value only if the following four expressions produce a
13121true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
13122@code{fill-prefix-regexp} is bound to @code{nil}.
13123
13124@table @code
13125@item fill-prefix
13126When this variable is evaluated, the value of the fill prefix, if any,
13127is returned. If there is no fill prefix, this variable returns
13128@code{nil}.
13129
13130@item (not (equal fill-prefix "")
13131This expression checks whether an existing fill prefix is an empty
13132string, that is, a string with no characters in it. An empty string is
13133not a useful fill prefix.
13134
13135@item (not paragraph-ignore-fill-prefix)
13136This expression returns @code{nil} if the variable
13137@code{paragraph-ignore-fill-prefix} has been turned on by being set to a
13138true value such as @code{t}.
13139
13140@item (regexp-quote fill-prefix)
13141This is the last argument to the @code{and} special form. If all the
13142arguments to the @code{and} are true, the value resulting from
13143evaluating this expression will be returned by the @code{and} expression
13144and bound to the variable @code{fill-prefix-regexp},
13145@end table
13146
13147@findex regexp-quote
13148@noindent
13149The result of evaluating this @code{and} expression successfully is that
13150@code{fill-prefix-regexp} will be bound to the value of
13151@code{fill-prefix} as modified by the @code{regexp-quote} function.
13152What @code{regexp-quote} does is read a string and return a regular
13153expression that will exactly match the string and match nothing else.
13154This means that @code{fill-prefix-regexp} will be set to a value that
13155will exactly match the fill prefix if the fill prefix exists.
13156Otherwise, the variable will be set to @code{nil}.
13157
13158The next two local variables in the @code{let*} expression are
13159designed to remove instances of @samp{^} from @code{parstart} and
13160@code{parsep}, the local variables which indicate the paragraph start
13161and the paragraph separator. The next expression sets @code{parsep}
13162again. That is to handle fill prefixes.
13163
13164This is the setting that requires the definition call @code{let*}
13165rather than @code{let}. The true-or-false-test for the @code{if}
13166depends on whether the variable @code{fill-prefix-regexp} evaluates to
13167@code{nil} or some other value.
13168
13169If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
13170the else-part of the @code{if} expression and binds @code{parsep} to
13171its local value. (@code{parsep} is a regular expression that matches
13172what separates paragraphs.)
13173
13174But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
13175the then-part of the @code{if} expression and binds @code{parsep} to a
13176regular expression that includes the @code{fill-prefix-regexp} as part
13177of the pattern.
13178
13179Specifically, @code{parsep} is set to the original value of the
13180paragraph separate regular expression concatenated with an alternative
13181expression that consists of the @code{fill-prefix-regexp} followed by
13182optional whitespace to the end of the line. The whitespace is defined
13183by @w{@code{"[ \t]*$"}}.) The @samp{\\|} defines this portion of the
13184regexp as an alternative to @code{parsep}.
13185
13186According to a comment in the code, the next local variable,
13187@code{sp-parstart}, is used for searching, and then the final two,
13188@code{start} and @code{found-start}, are set to @code{nil}.
13189
13190Now we get into the body of the @code{let*}. The first part of the body
13191of the @code{let*} deals with the case when the function is given a
13192negative argument and is therefore moving backwards. We will skip this
13193section.
13194
d6adf7e7 13195@node fwd-para while
8cda6f8f
GM
13196@unnumberedsubsec The forward motion @code{while} loop
13197
13198The second part of the body of the @code{let*} deals with forward
13199motion. It is a @code{while} loop that repeats itself so long as the
13200value of @code{arg} is greater than zero. In the most common use of
13201the function, the value of the argument is 1, so the body of the
13202@code{while} loop is evaluated exactly once, and the cursor moves
13203forward one paragraph.
13204
13205@ignore
13206(while (and (> arg 0) (not (eobp)))
13207
13208 ;; Move forward over separator lines...
13209 (while (and (not (eobp))
13210 (progn (move-to-left-margin) (not (eobp)))
13211 (looking-at parsep))
13212 (forward-line 1))
13213 (unless (eobp) (setq arg (1- arg)))
13214 ;; ... and one more line.
13215 (forward-line 1)
13216
13217 (if fill-prefix-regexp
13218 ;; There is a fill prefix; it overrides parstart.
13219 (while (and (not (eobp))
13220 (progn (move-to-left-margin) (not (eobp)))
13221 (not (looking-at parsep))
13222 (looking-at fill-prefix-regexp))
13223 (forward-line 1))
13224
13225 (while (and (re-search-forward sp-parstart nil 1)
13226 (progn (setq start (match-beginning 0))
13227 (goto-char start)
13228 (not (eobp)))
13229 (progn (move-to-left-margin)
13230 (not (looking-at parsep)))
13231 (or (not (looking-at parstart))
13232 (and use-hard-newlines
13233 (not (get-text-property (1- start) 'hard)))))
13234 (forward-char 1))
13235
13236 (if (< (point) (point-max))
13237 (goto-char start))))
13238@end ignore
13239
13240This part handles three situations: when point is between paragraphs,
13241when there is a fill prefix and when there is no fill prefix.
13242
13243@need 800
13244The @code{while} loop looks like this:
13245
13246@smallexample
13247@group
13248;; @r{going forwards and not at the end of the buffer}
13249(while (and (> arg 0) (not (eobp)))
13250
13251 ;; @r{between paragraphs}
13252 ;; Move forward over separator lines...
13253 (while (and (not (eobp))
13254 (progn (move-to-left-margin) (not (eobp)))
13255 (looking-at parsep))
13256 (forward-line 1))
13257 ;; @r{This decrements the loop}
13258 (unless (eobp) (setq arg (1- arg)))
13259 ;; ... and one more line.
13260 (forward-line 1)
13261@end group
13262
13263@group
13264 (if fill-prefix-regexp
13265 ;; There is a fill prefix; it overrides parstart;
13266 ;; we go forward line by line
13267 (while (and (not (eobp))
13268 (progn (move-to-left-margin) (not (eobp)))
13269 (not (looking-at parsep))
13270 (looking-at fill-prefix-regexp))
13271 (forward-line 1))
13272@end group
13273
13274@group
13275 ;; There is no fill prefix;
13276 ;; we go forward character by character
13277 (while (and (re-search-forward sp-parstart nil 1)
13278 (progn (setq start (match-beginning 0))
13279 (goto-char start)
13280 (not (eobp)))
13281 (progn (move-to-left-margin)
13282 (not (looking-at parsep)))
13283 (or (not (looking-at parstart))
13284 (and use-hard-newlines
13285 (not (get-text-property (1- start) 'hard)))))
13286 (forward-char 1))
13287@end group
13288
13289@group
13290 ;; and if there is no fill prefix and if we are not at the end,
13291 ;; go to whatever was found in the regular expression search
13292 ;; for sp-parstart
13293 (if (< (point) (point-max))
13294 (goto-char start))))
13295@end group
13296@end smallexample
13297
13298@findex eobp
13299We can see that this is a decrementing counter @code{while} loop,
13300using the expression @code{(setq arg (1- arg))} as the decrementer.
13301That expression is not far from the @code{while}, but is hidden in
13302another Lisp macro, an @code{unless} macro. Unless we are at the end
13303of the buffer --- that is what the @code{eobp} function determines; it
13304is an abbreviation of @samp{End Of Buffer P} --- we decrease the value
13305of @code{arg} by one.
13306
13307(If we are at the end of the buffer, we cannot go forward any more and
13308the next loop of the @code{while} expression will test false since the
13309test is an @code{and} with @code{(not (eobp))}. The @code{not}
13310function means exactly as you expect; it is another name for
13311@code{null}, a function that returns true when its argument is false.)
13312
13313Interestingly, the loop count is not decremented until we leave the
13314space between paragraphs, unless we come to the end of buffer or stop
13315seeing the local value of the paragraph separator.
13316
13317That second @code{while} also has a @code{(move-to-left-margin)}
13318expression. The function is self-explanatory. It is inside a
13319@code{progn} expression and not the last element of its body, so it is
13320only invoked for its side effect, which is to move point to the left
13321margin of the current line.
13322
13323@findex looking-at
13324The @code{looking-at} function is also self-explanatory; it returns
13325true if the text after point matches the regular expression given as
13326its argument.
13327
13328The rest of the body of the loop looks difficult at first, but makes
13329sense as you come to understand it.
13330
13331@need 800
13332First consider what happens if there is a fill prefix:
13333
13334@smallexample
13335@group
13336 (if fill-prefix-regexp
13337 ;; There is a fill prefix; it overrides parstart;
13338 ;; we go forward line by line
13339 (while (and (not (eobp))
13340 (progn (move-to-left-margin) (not (eobp)))
13341 (not (looking-at parsep))
13342 (looking-at fill-prefix-regexp))
13343 (forward-line 1))
13344@end group
13345@end smallexample
13346
13347@noindent
13348This expression moves point forward line by line so long
13349as four conditions are true:
13350
13351@enumerate
13352@item
13353Point is not at the end of the buffer.
13354
13355@item
13356We can move to the left margin of the text and are
13357not at the end of the buffer.
13358
13359@item
13360The text following point does not separate paragraphs.
13361
13362@item
13363The pattern following point is the fill prefix regular expression.
13364@end enumerate
13365
13366The last condition may be puzzling, until you remember that point was
13367moved to the beginning of the line early in the @code{forward-paragraph}
13368function. This means that if the text has a fill prefix, the
13369@code{looking-at} function will see it.
13370
13371@need 1250
13372Consider what happens when there is no fill prefix.
13373
13374@smallexample
13375@group
13376 (while (and (re-search-forward sp-parstart nil 1)
13377 (progn (setq start (match-beginning 0))
13378 (goto-char start)
13379 (not (eobp)))
13380 (progn (move-to-left-margin)
13381 (not (looking-at parsep)))
13382 (or (not (looking-at parstart))
13383 (and use-hard-newlines
13384 (not (get-text-property (1- start) 'hard)))))
13385 (forward-char 1))
13386@end group
13387@end smallexample
13388
13389@noindent
13390This @code{while} loop has us searching forward for
13391@code{sp-parstart}, which is the combination of possible whitespace
13392with a the local value of the start of a paragraph or of a paragraph
13393separator. (The latter two are within an expression starting
13394@code{\(?:} so that they are not referenced by the
13395@code{match-beginning} function.)
13396
13397@need 800
13398The two expressions,
13399
13400@smallexample
13401@group
13402(setq start (match-beginning 0))
13403(goto-char start)
13404@end group
13405@end smallexample
13406
13407@noindent
13408mean go to the start of the text matched by the regular expression
13409search.
13410
13411The @code{(match-beginning 0)} expression is new. It returns a number
13412specifying the location of the start of the text that was matched by
13413the last search.
13414
13415The @code{match-beginning} function is used here because of a
13416characteristic of a forward search: a successful forward search,
13417regardless of whether it is a plain search or a regular expression
13418search, moves point to the end of the text that is found. In this
13419case, a successful search moves point to the end of the pattern for
13420@code{sp-parstart}.
13421
13422However, we want to put point at the end of the current paragraph, not
13423somewhere else. Indeed, since the search possibly includes the
13424paragraph separator, point may end up at the beginning of the next one
13425unless we use an expression that includes @code{match-beginning}.
13426
13427@findex match-beginning
13428When given an argument of 0, @code{match-beginning} returns the
13429position that is the start of the text matched by the most recent
13430search. In this case, the most recent search looks for
13431@code{sp-parstart}. The @code{(match-beginning 0)} expression returns
13432the beginning position of that pattern, rather than the end position
13433of that pattern.
13434
13435(Incidentally, when passed a positive number as an argument, the
13436@code{match-beginning} function returns the location of point at that
13437parenthesized expression in the last search unless that parenthesized
13438expression begins with @code{\(?:}. I don't know why @code{\(?:}
13439appears here since the argument is 0.)
13440
13441@need 1250
13442The last expression when there is no fill prefix is
13443
13444@smallexample
13445@group
13446(if (< (point) (point-max))
13447 (goto-char start))))
13448@end group
13449@end smallexample
13450
13451@noindent
13452This says that if there is no fill prefix and if we are not at the
13453end, point should move to the beginning of whatever was found by the
13454regular expression search for @code{sp-parstart}.
13455
13456The full definition for the @code{forward-paragraph} function not only
13457includes code for going forwards, but also code for going backwards.
13458
13459If you are reading this inside of GNU Emacs and you want to see the
13460whole function, you can type @kbd{C-h f} (@code{describe-function})
13461and the name of the function. This gives you the function
13462documentation and the name of the library containing the function's
13463source. Place point over the name of the library and press the RET
13464key; you will be taken directly to the source. (Be sure to install
13465your sources! Without them, you are like a person who tries to drive
13466a car with his eyes shut!)
13467
d6adf7e7 13468@node etags
8cda6f8f
GM
13469@section Create Your Own @file{TAGS} File
13470@findex etags
13471@cindex @file{TAGS} file, create own
13472
13473Besides @kbd{C-h f} (@code{describe-function}), another way to see the
13474source of a function is to type @kbd{M-.} (@code{find-tag}) and the
13475name of the function when prompted for it. This is a good habit to
13476get into. The @kbd{M-.} (@code{find-tag}) command takes you directly
13477to the source for a function, variable, or node. The function depends
13478on tags tables to tell it where to go.
13479
13480If the @code{find-tag} function first asks you for the name of a
13481@file{TAGS} table, give it the name of a @file{TAGS} file such as
13482@file{/usr/local/src/emacs/src/TAGS}. (The exact path to your
13483@file{TAGS} file depends on how your copy of Emacs was installed. I
13484just told you the location that provides both my C and my Emacs Lisp
13485sources.)
13486
13487You can also create your own @file{TAGS} file for directories that
13488lack one.
13489
13490You often need to build and install tags tables yourself. They are
13491not built automatically. A tags table is called a @file{TAGS} file;
13492the name is in upper case letters.
13493
13494You can create a @file{TAGS} file by calling the @code{etags} program
13495that comes as a part of the Emacs distribution. Usually, @code{etags}
13496is compiled and installed when Emacs is built. (@code{etags} is not
13497an Emacs Lisp function or a part of Emacs; it is a C program.)
13498
13499@need 1250
13500To create a @file{TAGS} file, first switch to the directory in which
13501you want to create the file. In Emacs you can do this with the
13502@kbd{M-x cd} command, or by visiting a file in the directory, or by
13503listing the directory with @kbd{C-x d} (@code{dired}). Then run the
13504compile command, with @w{@code{etags *.el}} as the command to execute
13505
13506@smallexample
13507M-x compile RET etags *.el RET
13508@end smallexample
13509
13510@noindent
13511to create a @file{TAGS} file for Emacs Lisp.
13512
13513For example, if you have a large number of files in your
13514@file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
13515of which I load 12---you can create a @file{TAGS} file for the Emacs
13516Lisp files in that directory.
13517
13518@need 1250
13519The @code{etags} program takes all the usual shell `wildcards'. For
13520example, if you have two directories for which you want a single
13521@file{TAGS} file, type @w{@code{etags *.el ../elisp/*.el}}, where
13522@file{../elisp/} is the second directory:
13523
13524@smallexample
13525M-x compile RET etags *.el ../elisp/*.el RET
13526@end smallexample
13527
13528@need 1250
13529Type
13530
13531@smallexample
13532M-x compile RET etags --help RET
13533@end smallexample
13534
13535@noindent
13536to see a list of the options accepted by @code{etags} as well as a
13537list of supported languages.
13538
13539The @code{etags} program handles more than 20 languages, including
13540Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, HTML, Java,
7877f373 13541LaTeX, Pascal, Perl, PostScript, Python, TeX, Texinfo, makefiles, and
8cda6f8f
GM
13542most assemblers. The program has no switches for specifying the
13543language; it recognizes the language in an input file according to its
13544file name and contents.
13545
13546@file{etags} is very helpful when you are writing code yourself and
13547want to refer back to functions you have already written. Just run
13548@code{etags} again at intervals as you write new functions, so they
13549become part of the @file{TAGS} file.
13550
13551If you think an appropriate @file{TAGS} file already exists for what
13552you want, but do not know where it is, you can use the @code{locate}
13553program to attempt to find it.
13554
13555Type @w{@kbd{M-x locate @key{RET} TAGS @key{RET}}} and Emacs will list
13556for you the full path names of all your @file{TAGS} files. On my
13557system, this command lists 34 @file{TAGS} files. On the other hand, a
13558`plain vanilla' system I recently installed did not contain any
13559@file{TAGS} files.
13560
13561If the tags table you want has been created, you can use the @code{M-x
13562visit-tags-table} command to specify it. Otherwise, you will need to
13563create the tag table yourself and then use @code{M-x
13564visit-tags-table}.
13565
13566@subsubheading Building Tags in the Emacs sources
13567@cindex Building Tags in the Emacs sources
13568@cindex Tags in the Emacs sources
13569@findex make tags
13570
13571The GNU Emacs sources come with a @file{Makefile} that contains a
13572sophisticated @code{etags} command that creates, collects, and merges
13573tags tables from all over the Emacs sources and puts the information
13574into one @file{TAGS} file in the @file{src/} directory. (The
13575@file{src/} directory is below the top level of your Emacs directory.)
13576
13577@need 1250
13578To build this @file{TAGS} file, go to the top level of your Emacs
13579source directory and run the compile command @code{make tags}:
13580
13581@smallexample
13582M-x compile RET make tags RET
13583@end smallexample
13584
13585@noindent
13586(The @code{make tags} command works well with the GNU Emacs sources,
13587as well as with some other source packages.)
13588
13589For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
13590Manual}.
13591
d6adf7e7 13592@node Regexp Review
8cda6f8f
GM
13593@section Review
13594
13595Here is a brief summary of some recently introduced functions.
13596
13597@table @code
13598@item while
13599Repeatedly evaluate the body of the expression so long as the first
13600element of the body tests true. Then return @code{nil}. (The
13601expression is evaluated only for its side effects.)
13602
13603@need 1250
13604For example:
13605
13606@smallexample
13607@group
13608(let ((foo 2))
13609 (while (> foo 0)
13610 (insert (format "foo is %d.\n" foo))
13611 (setq foo (1- foo))))
13612
13613 @result{} foo is 2.
13614 foo is 1.
13615 nil
13616@end group
13617@end smallexample
13618
13619@noindent
13620(The @code{insert} function inserts its arguments at point; the
13621@code{format} function returns a string formatted from its arguments
13622the way @code{message} formats its arguments; @code{\n} produces a new
13623line.)
13624
13625@item re-search-forward
13626Search for a pattern, and if the pattern is found, move point to rest
13627just after it.
13628
13629@noindent
13630Takes four arguments, like @code{search-forward}:
13631
13632@enumerate
13633@item
13634A regular expression that specifies the pattern to search for.
13635(Remember to put quotation marks around this argument!)
13636
13637@item
13638Optionally, the limit of the search.
13639
13640@item
13641Optionally, what to do if the search fails, return @code{nil} or an
13642error message.
13643
13644@item
13645Optionally, how many times to repeat the search; if negative, the
13646search goes backwards.
13647@end enumerate
13648
13649@item let*
13650Bind some variables locally to particular values,
13651and then evaluate the remaining arguments, returning the value of the
13652last one. While binding the local variables, use the local values of
13653variables bound earlier, if any.
13654
13655@need 1250
13656For example:
13657
13658@smallexample
13659@group
13660(let* ((foo 7)
13661 (bar (* 3 foo)))
13662 (message "`bar' is %d." bar))
13663 @result{} `bar' is 21.
13664@end group
13665@end smallexample
13666
13667@item match-beginning
13668Return the position of the start of the text found by the last regular
13669expression search.
13670
13671@item looking-at
13672Return @code{t} for true if the text after point matches the argument,
13673which should be a regular expression.
13674
13675@item eobp
13676Return @code{t} for true if point is at the end of the accessible part
13677of a buffer. The end of the accessible part is the end of the buffer
13678if the buffer is not narrowed; it is the end of the narrowed part if
13679the buffer is narrowed.
13680@end table
13681
13682@need 1500
d6adf7e7 13683@node re-search Exercises
8cda6f8f
GM
13684@section Exercises with @code{re-search-forward}
13685
13686@itemize @bullet
13687@item
13688Write a function to search for a regular expression that matches two
13689or more blank lines in sequence.
13690
13691@item
13692Write a function to search for duplicated words, such as `the the'.
13693@xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
13694Manual}, for information on how to write a regexp (a regular
13695expression) to match a string that is composed of two identical
13696halves. You can devise several regexps; some are better than others.
13697The function I use is described in an appendix, along with several
13698regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
13699@end itemize
13700
d6adf7e7 13701@node Counting Words
8cda6f8f
GM
13702@chapter Counting: Repetition and Regexps
13703@cindex Repetition for word counting
13704@cindex Regular expressions for word counting
13705
13706Repetition and regular expression searches are powerful tools that you
13707often use when you write code in Emacs Lisp. This chapter illustrates
13708the use of regular expression searches through the construction of
13709word count commands using @code{while} loops and recursion.
13710
13711@menu
13712* Why Count Words::
ea4f7750 13713* @value{COUNT-WORDS}:: Use a regexp, but find a problem.
8cda6f8f
GM
13714* recursive-count-words:: Start with case of no words in region.
13715* Counting Exercise::
13716@end menu
13717
8cda6f8f 13718@ifnottex
d6adf7e7 13719@node Why Count Words
8cda6f8f
GM
13720@unnumberedsec Counting words
13721@end ifnottex
13722
ea4f7750
GM
13723The standard Emacs distribution contains functions for counting the
13724number of lines and words within a region.
8cda6f8f
GM
13725
13726Certain types of writing ask you to count words. Thus, if you write
13727an essay, you may be limited to 800 words; if you write a novel, you
ea4f7750
GM
13728may discipline yourself to write 1000 words a day. It seems odd, but
13729for a long time, Emacs lacked a word count command. Perhaps people used
13730Emacs mostly for code or types of documentation that did not require
13731word counts; or perhaps they restricted themselves to the operating
13732system word count command, @code{wc}. Alternatively, people may have
13733followed the publishers' convention and computed a word count by
13734dividing the number of characters in a document by five.
13735
13736There are many ways to implement a command to count words. Here are
13737some examples, which you may wish to compare with the standard Emacs
13738command, @code{count-words-region}.
13739
d6adf7e7 13740@node @value{COUNT-WORDS}
ea4f7750
GM
13741@section The @code{@value{COUNT-WORDS}} Function
13742@findex @value{COUNT-WORDS}
8cda6f8f
GM
13743
13744A word count command could count words in a line, paragraph, region,
13745or buffer. What should the command cover? You could design the
13746command to count the number of words in a complete buffer. However,
13747the Emacs tradition encourages flexibility---you may want to count
13748words in just a section, rather than all of a buffer. So it makes
13749more sense to design the command to count the number of words in a
ea4f7750 13750region. Once you have a command to count words in a region, you can,
8cda6f8f
GM
13751if you wish, count words in a whole buffer by marking it with
13752@w{@kbd{C-x h}} (@code{mark-whole-buffer}).
13753
13754Clearly, counting words is a repetitive act: starting from the
13755beginning of the region, you count the first word, then the second
13756word, then the third word, and so on, until you reach the end of the
13757region. This means that word counting is ideally suited to recursion
13758or to a @code{while} loop.
13759
13760@menu
ea4f7750
GM
13761* Design @value{COUNT-WORDS}:: The definition using a @code{while} loop.
13762* Whitespace Bug:: The Whitespace Bug in @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
13763@end menu
13764
8cda6f8f 13765@ifnottex
d6adf7e7 13766@node Design @value{COUNT-WORDS}
ea4f7750 13767@unnumberedsubsec Designing @code{@value{COUNT-WORDS}}
8cda6f8f
GM
13768@end ifnottex
13769
13770First, we will implement the word count command with a @code{while}
13771loop, then with recursion. The command will, of course, be
13772interactive.
13773
13774@need 800
13775The template for an interactive function definition is, as always:
13776
13777@smallexample
13778@group
13779(defun @var{name-of-function} (@var{argument-list})
13780 "@var{documentation}@dots{}"
13781 (@var{interactive-expression}@dots{})
13782 @var{body}@dots{})
13783@end group
13784@end smallexample
13785
13786What we need to do is fill in the slots.
13787
13788The name of the function should be self-explanatory and similar to the
13789existing @code{count-lines-region} name. This makes the name easier
ea4f7750
GM
13790to remember. @code{count-words-region} is the obvious choice. Since
13791that name is now used for the standard Emacs command to count words, we
13792will name our implementation @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
13793
13794The function counts words within a region. This means that the
13795argument list must contain symbols that are bound to the two
13796positions, the beginning and end of the region. These two positions
13797can be called @samp{beginning} and @samp{end} respectively. The first
13798line of the documentation should be a single sentence, since that is
13799all that is printed as documentation by a command such as
13800@code{apropos}. The interactive expression will be of the form
13801@samp{(interactive "r")}, since that will cause Emacs to pass the
13802beginning and end of the region to the function's argument list. All
13803this is routine.
13804
13805The body of the function needs to be written to do three tasks:
13806first, to set up conditions under which the @code{while} loop can
13807count words, second, to run the @code{while} loop, and third, to send
13808a message to the user.
13809
ea4f7750 13810When a user calls @code{@value{COUNT-WORDS}}, point may be at the
8cda6f8f
GM
13811beginning or the end of the region. However, the counting process
13812must start at the beginning of the region. This means we will want
13813to put point there if it is not already there. Executing
13814@code{(goto-char beginning)} ensures this. Of course, we will want to
13815return point to its expected position when the function finishes its
13816work. For this reason, the body must be enclosed in a
13817@code{save-excursion} expression.
13818
13819The central part of the body of the function consists of a
13820@code{while} loop in which one expression jumps point forward word by
13821word, and another expression counts those jumps. The true-or-false-test
13822of the @code{while} loop should test true so long as point should jump
13823forward, and false when point is at the end of the region.
13824
13825We could use @code{(forward-word 1)} as the expression for moving point
13826forward word by word, but it is easier to see what Emacs identifies as a
13827`word' if we use a regular expression search.
13828
13829A regular expression search that finds the pattern for which it is
13830searching leaves point after the last character matched. This means
13831that a succession of successful word searches will move point forward
13832word by word.
13833
13834As a practical matter, we want the regular expression search to jump
13835over whitespace and punctuation between words as well as over the
13836words themselves. A regexp that refuses to jump over interword
13837whitespace would never jump more than one word! This means that
13838the regexp should include the whitespace and punctuation that follows
13839a word, if any, as well as the word itself. (A word may end a buffer
13840and not have any following whitespace or punctuation, so that part of
13841the regexp must be optional.)
13842
13843Thus, what we want for the regexp is a pattern defining one or more
13844word constituent characters followed, optionally, by one or more
13845characters that are not word constituents. The regular expression for
13846this is:
13847
13848@smallexample
13849\w+\W*
13850@end smallexample
13851
13852@noindent
13853The buffer's syntax table determines which characters are and are not
0fd2c9a3
GM
13854word constituents. For more information about syntax,
13855@pxref{Syntax Tables, , Syntax Tables, elisp, The GNU Emacs Lisp
13856Reference Manual}.
8cda6f8f
GM
13857
13858@need 800
13859The search expression looks like this:
13860
13861@smallexample
13862(re-search-forward "\\w+\\W*")
13863@end smallexample
13864
13865@noindent
13866(Note that paired backslashes precede the @samp{w} and @samp{W}. A
13867single backslash has special meaning to the Emacs Lisp interpreter.
13868It indicates that the following character is interpreted differently
13869than usual. For example, the two characters, @samp{\n}, stand for
13870@samp{newline}, rather than for a backslash followed by @samp{n}. Two
13871backslashes in a row stand for an ordinary, `unspecial' backslash, so
13872Emacs Lisp interpreter ends of seeing a single backslash followed by a
13873letter. So it discovers the letter is special.)
13874
13875We need a counter to count how many words there are; this variable
13876must first be set to 0 and then incremented each time Emacs goes
13877around the @code{while} loop. The incrementing expression is simply:
13878
13879@smallexample
13880(setq count (1+ count))
13881@end smallexample
13882
13883Finally, we want to tell the user how many words there are in the
13884region. The @code{message} function is intended for presenting this
13885kind of information to the user. The message has to be phrased so
13886that it reads properly regardless of how many words there are in the
13887region: we don't want to say that ``there are 1 words in the region''.
13888The conflict between singular and plural is ungrammatical. We can
13889solve this problem by using a conditional expression that evaluates
13890different messages depending on the number of words in the region.
13891There are three possibilities: no words in the region, one word in the
13892region, and more than one word. This means that the @code{cond}
13893special form is appropriate.
13894
13895@need 1500
13896All this leads to the following function definition:
13897
13898@smallexample
13899@group
13900;;; @r{First version; has bugs!}
ea4f7750 13901(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
13902 "Print number of words in the region.
13903Words are defined as at least one word-constituent
13904character followed by at least one character that
13905is not a word-constituent. The buffer's syntax
13906table determines which characters these are."
13907 (interactive "r")
13908 (message "Counting words in region ... ")
13909@end group
13910
13911@group
13912;;; @r{1. Set up appropriate conditions.}
13913 (save-excursion
13914 (goto-char beginning)
13915 (let ((count 0))
13916@end group
13917
13918@group
13919;;; @r{2. Run the} while @r{loop.}
13920 (while (< (point) end)
13921 (re-search-forward "\\w+\\W*")
13922 (setq count (1+ count)))
13923@end group
13924
13925@group
13926;;; @r{3. Send a message to the user.}
13927 (cond ((zerop count)
13928 (message
13929 "The region does NOT have any words."))
13930 ((= 1 count)
13931 (message
13932 "The region has 1 word."))
13933 (t
13934 (message
13935 "The region has %d words." count))))))
13936@end group
13937@end smallexample
13938
13939@noindent
13940As written, the function works, but not in all circumstances.
13941
d6adf7e7 13942@node Whitespace Bug
ea4f7750 13943@subsection The Whitespace Bug in @code{@value{COUNT-WORDS}}
8cda6f8f 13944
ea4f7750 13945The @code{@value{COUNT-WORDS}} command described in the preceding
8cda6f8f
GM
13946section has two bugs, or rather, one bug with two manifestations.
13947First, if you mark a region containing only whitespace in the middle
ea4f7750 13948of some text, the @code{@value{COUNT-WORDS}} command tells you that the
8cda6f8f
GM
13949region contains one word! Second, if you mark a region containing
13950only whitespace at the end of the buffer or the accessible portion of
13951a narrowed buffer, the command displays an error message that looks
13952like this:
13953
13954@smallexample
13955Search failed: "\\w+\\W*"
13956@end smallexample
13957
13958If you are reading this in Info in GNU Emacs, you can test for these
13959bugs yourself.
13960
13961First, evaluate the function in the usual manner to install it.
13962@ifinfo
13963Here is a copy of the definition. Place your cursor after the closing
13964parenthesis and type @kbd{C-x C-e} to install it.
13965
13966@smallexample
13967@group
13968;; @r{First version; has bugs!}
ea4f7750 13969(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
13970 "Print number of words in the region.
13971Words are defined as at least one word-constituent character followed
13972by at least one character that is not a word-constituent. The buffer's
13973syntax table determines which characters these are."
13974@end group
13975@group
13976 (interactive "r")
13977 (message "Counting words in region ... ")
13978@end group
13979
13980@group
13981;;; @r{1. Set up appropriate conditions.}
13982 (save-excursion
13983 (goto-char beginning)
13984 (let ((count 0))
13985@end group
13986
13987@group
13988;;; @r{2. Run the} while @r{loop.}
13989 (while (< (point) end)
13990 (re-search-forward "\\w+\\W*")
13991 (setq count (1+ count)))
13992@end group
13993
13994@group
13995;;; @r{3. Send a message to the user.}
13996 (cond ((zerop count)
13997 (message "The region does NOT have any words."))
13998 ((= 1 count) (message "The region has 1 word."))
13999 (t (message "The region has %d words." count))))))
14000@end group
14001@end smallexample
14002@end ifinfo
14003
14004@need 1000
14005If you wish, you can also install this keybinding by evaluating it:
14006
14007@smallexample
ea4f7750 14008(global-set-key "\C-c=" '@value{COUNT-WORDS})
8cda6f8f
GM
14009@end smallexample
14010
14011To conduct the first test, set mark and point to the beginning and end
14012of the following line and then type @kbd{C-c =} (or @kbd{M-x
ea4f7750 14013@value{COUNT-WORDS}} if you have not bound @kbd{C-c =}):
8cda6f8f
GM
14014
14015@smallexample
14016 one two three
14017@end smallexample
14018
14019@noindent
14020Emacs will tell you, correctly, that the region has three words.
14021
14022Repeat the test, but place mark at the beginning of the line and place
14023point just @emph{before} the word @samp{one}. Again type the command
ea4f7750 14024@kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}). Emacs should tell you
8cda6f8f
GM
14025that the region has no words, since it is composed only of the
14026whitespace at the beginning of the line. But instead Emacs tells you
14027that the region has one word!
14028
14029For the third test, copy the sample line to the end of the
14030@file{*scratch*} buffer and then type several spaces at the end of the
14031line. Place mark right after the word @samp{three} and point at the
14032end of line. (The end of the line will be the end of the buffer.)
ea4f7750 14033Type @kbd{C-c =} (or @kbd{M-x @value{COUNT-WORDS}}) as you did before.
8cda6f8f
GM
14034Again, Emacs should tell you that the region has no words, since it is
14035composed only of the whitespace at the end of the line. Instead,
14036Emacs displays an error message saying @samp{Search failed}.
14037
14038The two bugs stem from the same problem.
14039
14040Consider the first manifestation of the bug, in which the command
14041tells you that the whitespace at the beginning of the line contains
ea4f7750 14042one word. What happens is this: The @code{M-x @value{COUNT-WORDS}}
8cda6f8f
GM
14043command moves point to the beginning of the region. The @code{while}
14044tests whether the value of point is smaller than the value of
14045@code{end}, which it is. Consequently, the regular expression search
14046looks for and finds the first word. It leaves point after the word.
14047@code{count} is set to one. The @code{while} loop repeats; but this
14048time the value of point is larger than the value of @code{end}, the
14049loop is exited; and the function displays a message saying the number
14050of words in the region is one. In brief, the regular expression
14051search looks for and finds the word even though it is outside
14052the marked region.
14053
14054In the second manifestation of the bug, the region is whitespace at
14055the end of the buffer. Emacs says @samp{Search failed}. What happens
14056is that the true-or-false-test in the @code{while} loop tests true, so
14057the search expression is executed. But since there are no more words
14058in the buffer, the search fails.
14059
14060In both manifestations of the bug, the search extends or attempts to
14061extend outside of the region.
14062
14063The solution is to limit the search to the region---this is a fairly
14064simple action, but as you may have come to expect, it is not quite as
14065simple as you might think.
14066
14067As we have seen, the @code{re-search-forward} function takes a search
14068pattern as its first argument. But in addition to this first,
14069mandatory argument, it accepts three optional arguments. The optional
14070second argument bounds the search. The optional third argument, if
14071@code{t}, causes the function to return @code{nil} rather than signal
14072an error if the search fails. The optional fourth argument is a
14073repeat count. (In Emacs, you can see a function's documentation by
14074typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
14075
ea4f7750 14076In the @code{@value{COUNT-WORDS}} definition, the value of the end of
8cda6f8f
GM
14077the region is held by the variable @code{end} which is passed as an
14078argument to the function. Thus, we can add @code{end} as an argument
14079to the regular expression search expression:
14080
14081@smallexample
14082(re-search-forward "\\w+\\W*" end)
14083@end smallexample
14084
ea4f7750 14085However, if you make only this change to the @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14086definition and then test the new version of the definition on a
14087stretch of whitespace, you will receive an error message saying
14088@samp{Search failed}.
14089
14090What happens is this: the search is limited to the region, and fails
14091as you expect because there are no word-constituent characters in the
14092region. Since it fails, we receive an error message. But we do not
14093want to receive an error message in this case; we want to receive the
14094message that "The region does NOT have any words."
14095
14096The solution to this problem is to provide @code{re-search-forward}
14097with a third argument of @code{t}, which causes the function to return
14098@code{nil} rather than signal an error if the search fails.
14099
14100However, if you make this change and try it, you will see the message
14101``Counting words in region ... '' and @dots{} you will keep on seeing
14102that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
14103
14104Here is what happens: the search is limited to the region, as before,
14105and it fails because there are no word-constituent characters in the
14106region, as expected. Consequently, the @code{re-search-forward}
14107expression returns @code{nil}. It does nothing else. In particular,
14108it does not move point, which it does as a side effect if it finds the
14109search target. After the @code{re-search-forward} expression returns
14110@code{nil}, the next expression in the @code{while} loop is evaluated.
14111This expression increments the count. Then the loop repeats. The
14112true-or-false-test tests true because the value of point is still less
14113than the value of end, since the @code{re-search-forward} expression
14114did not move point. @dots{} and the cycle repeats @dots{}
14115
ea4f7750 14116The @code{@value{COUNT-WORDS}} definition requires yet another
8cda6f8f
GM
14117modification, to cause the true-or-false-test of the @code{while} loop
14118to test false if the search fails. Put another way, there are two
14119conditions that must be satisfied in the true-or-false-test before the
14120word count variable is incremented: point must still be within the
14121region and the search expression must have found a word to count.
14122
14123Since both the first condition and the second condition must be true
14124together, the two expressions, the region test and the search
14125expression, can be joined with an @code{and} special form and embedded in
14126the @code{while} loop as the true-or-false-test, like this:
14127
14128@smallexample
14129(and (< (point) end) (re-search-forward "\\w+\\W*" end t))
14130@end smallexample
14131
14132@c colon in printed section title causes problem in Info cross reference
14133@c also trouble with an overfull hbox
14134@iftex
14135@noindent
14136(For information about @code{and}, see
14137@ref{kill-new function, , The @code{kill-new} function}.)
14138@end iftex
14139@ifinfo
14140@noindent
14141(@xref{kill-new function, , The @code{kill-new} function}, for
14142information about @code{and}.)
14143@end ifinfo
14144
14145The @code{re-search-forward} expression returns @code{t} if the search
14146succeeds and as a side effect moves point. Consequently, as words are
14147found, point is moved through the region. When the search expression
14148fails to find another word, or when point reaches the end of the
14149region, the true-or-false-test tests false, the @code{while} loop
ea4f7750 14150exits, and the @code{@value{COUNT-WORDS}} function displays one or
8cda6f8f
GM
14151other of its messages.
14152
ea4f7750 14153After incorporating these final changes, the @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14154works without bugs (or at least, without bugs that I have found!).
14155Here is what it looks like:
14156
14157@smallexample
14158@group
14159;;; @r{Final version:} @code{while}
ea4f7750 14160(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14161 "Print number of words in the region."
14162 (interactive "r")
14163 (message "Counting words in region ... ")
14164@end group
14165
14166@group
14167;;; @r{1. Set up appropriate conditions.}
14168 (save-excursion
14169 (let ((count 0))
14170 (goto-char beginning)
14171@end group
14172
14173@group
14174;;; @r{2. Run the} while @r{loop.}
14175 (while (and (< (point) end)
14176 (re-search-forward "\\w+\\W*" end t))
14177 (setq count (1+ count)))
14178@end group
14179
14180@group
14181;;; @r{3. Send a message to the user.}
14182 (cond ((zerop count)
14183 (message
14184 "The region does NOT have any words."))
14185 ((= 1 count)
14186 (message
14187 "The region has 1 word."))
14188 (t
14189 (message
14190 "The region has %d words." count))))))
14191@end group
14192@end smallexample
14193
d6adf7e7 14194@node recursive-count-words
8cda6f8f
GM
14195@section Count Words Recursively
14196@cindex Count words recursively
14197@cindex Recursively counting words
14198@cindex Words, counted recursively
14199
14200You can write the function for counting words recursively as well as
14201with a @code{while} loop. Let's see how this is done.
14202
ea4f7750 14203First, we need to recognize that the @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14204function has three jobs: it sets up the appropriate conditions for
14205counting to occur; it counts the words in the region; and it sends a
14206message to the user telling how many words there are.
14207
14208If we write a single recursive function to do everything, we will
14209receive a message for every recursive call. If the region contains 13
14210words, we will receive thirteen messages, one right after the other.
14211We don't want this! Instead, we must write two functions to do the
14212job, one of which (the recursive function) will be used inside of the
14213other. One function will set up the conditions and display the
14214message; the other will return the word count.
14215
14216Let us start with the function that causes the message to be displayed.
ea4f7750 14217We can continue to call this @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
14218
14219This is the function that the user will call. It will be interactive.
14220Indeed, it will be similar to our previous versions of this
14221function, except that it will call @code{recursive-count-words} to
14222determine how many words are in the region.
14223
14224@need 1250
14225We can readily construct a template for this function, based on our
14226previous versions:
14227
14228@smallexample
14229@group
14230;; @r{Recursive version; uses regular expression search}
ea4f7750 14231(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14232 "@var{documentation}@dots{}"
14233 (@var{interactive-expression}@dots{})
14234@end group
14235@group
14236
14237;;; @r{1. Set up appropriate conditions.}
14238 (@var{explanatory message})
14239 (@var{set-up functions}@dots{}
14240@end group
14241@group
14242
14243;;; @r{2. Count the words.}
14244 @var{recursive call}
14245@end group
14246@group
14247
14248;;; @r{3. Send a message to the user.}
14249 @var{message providing word count}))
14250@end group
14251@end smallexample
14252
14253The definition looks straightforward, except that somehow the count
14254returned by the recursive call must be passed to the message
14255displaying the word count. A little thought suggests that this can be
14256done by making use of a @code{let} expression: we can bind a variable
14257in the varlist of a @code{let} expression to the number of words in
14258the region, as returned by the recursive call; and then the
14259@code{cond} expression, using binding, can display the value to the
14260user.
14261
14262Often, one thinks of the binding within a @code{let} expression as
14263somehow secondary to the `primary' work of a function. But in this
14264case, what you might consider the `primary' job of the function,
14265counting words, is done within the @code{let} expression.
14266
14267@need 1250
14268Using @code{let}, the function definition looks like this:
14269
14270@smallexample
14271@group
ea4f7750 14272(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14273 "Print number of words in the region."
14274 (interactive "r")
14275@end group
14276
14277@group
14278;;; @r{1. Set up appropriate conditions.}
14279 (message "Counting words in region ... ")
14280 (save-excursion
14281 (goto-char beginning)
14282@end group
14283
14284@group
14285;;; @r{2. Count the words.}
14286 (let ((count (recursive-count-words end)))
14287@end group
14288
14289@group
14290;;; @r{3. Send a message to the user.}
14291 (cond ((zerop count)
14292 (message
14293 "The region does NOT have any words."))
14294 ((= 1 count)
14295 (message
14296 "The region has 1 word."))
14297 (t
14298 (message
14299 "The region has %d words." count))))))
14300@end group
14301@end smallexample
14302
14303Next, we need to write the recursive counting function.
14304
14305A recursive function has at least three parts: the `do-again-test', the
14306`next-step-expression', and the recursive call.
14307
14308The do-again-test determines whether the function will or will not be
14309called again. Since we are counting words in a region and can use a
14310function that moves point forward for every word, the do-again-test
14311can check whether point is still within the region. The do-again-test
14312should find the value of point and determine whether point is before,
14313at, or after the value of the end of the region. We can use the
14314@code{point} function to locate point. Clearly, we must pass the
14315value of the end of the region to the recursive counting function as an
14316argument.
14317
14318In addition, the do-again-test should also test whether the search finds a
14319word. If it does not, the function should not call itself again.
14320
14321The next-step-expression changes a value so that when the recursive
14322function is supposed to stop calling itself, it stops. More
14323precisely, the next-step-expression changes a value so that at the
14324right time, the do-again-test stops the recursive function from
14325calling itself again. In this case, the next-step-expression can be
14326the expression that moves point forward, word by word.
14327
14328The third part of a recursive function is the recursive call.
14329
14330Somewhere, also, we also need a part that does the `work' of the
14331function, a part that does the counting. A vital part!
14332
14333@need 1250
14334But already, we have an outline of the recursive counting function:
14335
14336@smallexample
14337@group
14338(defun recursive-count-words (region-end)
14339 "@var{documentation}@dots{}"
14340 @var{do-again-test}
14341 @var{next-step-expression}
14342 @var{recursive call})
14343@end group
14344@end smallexample
14345
14346Now we need to fill in the slots. Let's start with the simplest cases
14347first: if point is at or beyond the end of the region, there cannot
14348be any words in the region, so the function should return zero.
14349Likewise, if the search fails, there are no words to count, so the
14350function should return zero.
14351
14352On the other hand, if point is within the region and the search
14353succeeds, the function should call itself again.
14354
14355@need 800
14356Thus, the do-again-test should look like this:
14357
14358@smallexample
14359@group
14360(and (< (point) region-end)
14361 (re-search-forward "\\w+\\W*" region-end t))
14362@end group
14363@end smallexample
14364
14365Note that the search expression is part of the do-again-test---the
14366function returns @code{t} if its search succeeds and @code{nil} if it
14367fails. (@xref{Whitespace Bug, , The Whitespace Bug in
ea4f7750 14368@code{@value{COUNT-WORDS}}}, for an explanation of how
8cda6f8f
GM
14369@code{re-search-forward} works.)
14370
14371The do-again-test is the true-or-false test of an @code{if} clause.
14372Clearly, if the do-again-test succeeds, the then-part of the @code{if}
14373clause should call the function again; but if it fails, the else-part
14374should return zero since either point is outside the region or the
14375search failed because there were no words to find.
14376
14377But before considering the recursive call, we need to consider the
14378next-step-expression. What is it? Interestingly, it is the search
14379part of the do-again-test.
14380
14381In addition to returning @code{t} or @code{nil} for the
14382do-again-test, @code{re-search-forward} moves point forward as a side
14383effect of a successful search. This is the action that changes the
14384value of point so that the recursive function stops calling itself
14385when point completes its movement through the region. Consequently,
14386the @code{re-search-forward} expression is the next-step-expression.
14387
14388@need 1200
14389In outline, then, the body of the @code{recursive-count-words}
14390function looks like this:
14391
14392@smallexample
14393@group
14394(if @var{do-again-test-and-next-step-combined}
14395 ;; @r{then}
14396 @var{recursive-call-returning-count}
14397 ;; @r{else}
14398 @var{return-zero})
14399@end group
14400@end smallexample
14401
14402How to incorporate the mechanism that counts?
14403
14404If you are not used to writing recursive functions, a question like
14405this can be troublesome. But it can and should be approached
14406systematically.
14407
14408We know that the counting mechanism should be associated in some way
14409with the recursive call. Indeed, since the next-step-expression moves
14410point forward by one word, and since a recursive call is made for
14411each word, the counting mechanism must be an expression that adds one
14412to the value returned by a call to @code{recursive-count-words}.
14413
14414@need 800
14415Consider several cases:
14416
14417@itemize @bullet
14418@item
14419If there are two words in the region, the function should return
14420a value resulting from adding one to the value returned when it counts
14421the first word, plus the number returned when it counts the remaining
14422words in the region, which in this case is one.
14423
14424@item
14425If there is one word in the region, the function should return
14426a value resulting from adding one to the value returned when it counts
14427that word, plus the number returned when it counts the remaining
14428words in the region, which in this case is zero.
14429
14430@item
14431If there are no words in the region, the function should return zero.
14432@end itemize
14433
14434From the sketch we can see that the else-part of the @code{if} returns
14435zero for the case of no words. This means that the then-part of the
14436@code{if} must return a value resulting from adding one to the value
14437returned from a count of the remaining words.
14438
14439@need 1200
14440The expression will look like this, where @code{1+} is a function that
14441adds one to its argument.
14442
14443@smallexample
14444(1+ (recursive-count-words region-end))
14445@end smallexample
14446
14447@need 1200
14448The whole @code{recursive-count-words} function will then look like
14449this:
14450
14451@smallexample
14452@group
14453(defun recursive-count-words (region-end)
14454 "@var{documentation}@dots{}"
14455
14456;;; @r{1. do-again-test}
14457 (if (and (< (point) region-end)
14458 (re-search-forward "\\w+\\W*" region-end t))
14459@end group
14460
14461@group
14462;;; @r{2. then-part: the recursive call}
14463 (1+ (recursive-count-words region-end))
14464
14465;;; @r{3. else-part}
14466 0))
14467@end group
14468@end smallexample
14469
14470@need 1250
14471Let's examine how this works:
14472
14473If there are no words in the region, the else part of the @code{if}
14474expression is evaluated and consequently the function returns zero.
14475
14476If there is one word in the region, the value of point is less than
14477the value of @code{region-end} and the search succeeds. In this case,
14478the true-or-false-test of the @code{if} expression tests true, and the
14479then-part of the @code{if} expression is evaluated. The counting
14480expression is evaluated. This expression returns a value (which will
14481be the value returned by the whole function) that is the sum of one
14482added to the value returned by a recursive call.
14483
14484Meanwhile, the next-step-expression has caused point to jump over the
14485first (and in this case only) word in the region. This means that
14486when @code{(recursive-count-words region-end)} is evaluated a second
14487time, as a result of the recursive call, the value of point will be
14488equal to or greater than the value of region end. So this time,
14489@code{recursive-count-words} will return zero. The zero will be added
14490to one, and the original evaluation of @code{recursive-count-words}
14491will return one plus zero, which is one, which is the correct amount.
14492
14493Clearly, if there are two words in the region, the first call to
14494@code{recursive-count-words} returns one added to the value returned
14495by calling @code{recursive-count-words} on a region containing the
14496remaining word---that is, it adds one to one, producing two, which is
14497the correct amount.
14498
14499Similarly, if there are three words in the region, the first call to
14500@code{recursive-count-words} returns one added to the value returned
14501by calling @code{recursive-count-words} on a region containing the
14502remaining two words---and so on and so on.
14503
14504@need 1250
14505@noindent
14506With full documentation the two functions look like this:
14507
14508@need 1250
14509@noindent
14510The recursive function:
14511
14512@findex recursive-count-words
14513@smallexample
14514@group
14515(defun recursive-count-words (region-end)
14516 "Number of words between point and REGION-END."
14517@end group
14518
14519@group
14520;;; @r{1. do-again-test}
14521 (if (and (< (point) region-end)
14522 (re-search-forward "\\w+\\W*" region-end t))
14523@end group
14524
14525@group
14526;;; @r{2. then-part: the recursive call}
14527 (1+ (recursive-count-words region-end))
14528
14529;;; @r{3. else-part}
14530 0))
14531@end group
14532@end smallexample
14533
14534@need 800
14535@noindent
14536The wrapper:
14537
14538@smallexample
14539@group
14540;;; @r{Recursive version}
ea4f7750 14541(defun @value{COUNT-WORDS} (beginning end)
8cda6f8f
GM
14542 "Print number of words in the region.
14543@end group
14544
14545@group
14546Words are defined as at least one word-constituent
14547character followed by at least one character that is
14548not a word-constituent. The buffer's syntax table
14549determines which characters these are."
14550@end group
14551@group
14552 (interactive "r")
14553 (message "Counting words in region ... ")
14554 (save-excursion
14555 (goto-char beginning)
14556 (let ((count (recursive-count-words end)))
14557@end group
14558@group
14559 (cond ((zerop count)
14560 (message
14561 "The region does NOT have any words."))
14562@end group
14563@group
14564 ((= 1 count)
14565 (message "The region has 1 word."))
14566 (t
14567 (message
14568 "The region has %d words." count))))))
14569@end group
14570@end smallexample
14571
d6adf7e7 14572@node Counting Exercise
8cda6f8f
GM
14573@section Exercise: Counting Punctuation
14574
14575Using a @code{while} loop, write a function to count the number of
14576punctuation marks in a region---period, comma, semicolon, colon,
14577exclamation mark, and question mark. Do the same using recursion.
14578
d6adf7e7 14579@node Words in a defun
8cda6f8f
GM
14580@chapter Counting Words in a @code{defun}
14581@cindex Counting words in a @code{defun}
14582@cindex Word counting in a @code{defun}
14583
14584Our next project is to count the number of words in a function
14585definition. Clearly, this can be done using some variant of
ea4f7750 14586@code{@value{COUNT-WORDS}}. @xref{Counting Words, , Counting Words:
8cda6f8f
GM
14587Repetition and Regexps}. If we are just going to count the words in
14588one definition, it is easy enough to mark the definition with the
14589@kbd{C-M-h} (@code{mark-defun}) command, and then call
ea4f7750 14590@code{@value{COUNT-WORDS}}.
8cda6f8f
GM
14591
14592However, I am more ambitious: I want to count the words and symbols in
14593every definition in the Emacs sources and then print a graph that
14594shows how many functions there are of each length: how many contain 40
14595to 49 words or symbols, how many contain 50 to 59 words or symbols,
14596and so on. I have often been curious how long a typical function is,
14597and this will tell.
14598
14599@menu
14600* Divide and Conquer::
14601* Words and Symbols:: What to count?
14602* Syntax:: What constitutes a word or symbol?
ea4f7750 14603* count-words-in-defun:: Very like @code{@value{COUNT-WORDS}}.
8cda6f8f
GM
14604* Several defuns:: Counting several defuns in a file.
14605* Find a File:: Do you want to look at a file?
14606* lengths-list-file:: A list of the lengths of many definitions.
14607* Several files:: Counting in definitions in different files.
14608* Several files recursively:: Recursively counting in different files.
14609* Prepare the data:: Prepare the data for display in a graph.
14610@end menu
14611
8cda6f8f 14612@ifnottex
d6adf7e7 14613@node Divide and Conquer
8cda6f8f
GM
14614@unnumberedsec Divide and Conquer
14615@end ifnottex
14616
14617Described in one phrase, the histogram project is daunting; but
14618divided into numerous small steps, each of which we can take one at a
14619time, the project becomes less fearsome. Let us consider what the
14620steps must be:
14621
14622@itemize @bullet
14623@item
14624First, write a function to count the words in one definition. This
14625includes the problem of handling symbols as well as words.
14626
14627@item
14628Second, write a function to list the numbers of words in each function
14629in a file. This function can use the @code{count-words-in-defun}
14630function.
14631
14632@item
14633Third, write a function to list the numbers of words in each function
14634in each of several files. This entails automatically finding the
14635various files, switching to them, and counting the words in the
14636definitions within them.
14637
14638@item
14639Fourth, write a function to convert the list of numbers that we
14640created in step three to a form that will be suitable for printing as
14641a graph.
14642
14643@item
14644Fifth, write a function to print the results as a graph.
14645@end itemize
14646
14647This is quite a project! But if we take each step slowly, it will not
14648be difficult.
14649
d6adf7e7 14650@node Words and Symbols
8cda6f8f
GM
14651@section What to Count?
14652@cindex Words and symbols in defun
14653
14654When we first start thinking about how to count the words in a
14655function definition, the first question is (or ought to be) what are
14656we going to count? When we speak of `words' with respect to a Lisp
14657function definition, we are actually speaking, in large part, of
14658`symbols'. For example, the following @code{multiply-by-seven}
14659function contains the five symbols @code{defun},
14660@code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
14661addition, in the documentation string, it contains the four words
14662@samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
14663symbol @samp{number} is repeated, so the definition contains a total
14664of ten words and symbols.
14665
14666@smallexample
14667@group
14668(defun multiply-by-seven (number)
14669 "Multiply NUMBER by seven."
14670 (* 7 number))
14671@end group
14672@end smallexample
14673
14674@noindent
14675However, if we mark the @code{multiply-by-seven} definition with
14676@kbd{C-M-h} (@code{mark-defun}), and then call
ea4f7750
GM
14677@code{@value{COUNT-WORDS}} on it, we will find that
14678@code{@value{COUNT-WORDS}} claims the definition has eleven words, not
8cda6f8f
GM
14679ten! Something is wrong!
14680
ea4f7750 14681The problem is twofold: @code{@value{COUNT-WORDS}} does not count the
8cda6f8f
GM
14682@samp{*} as a word, and it counts the single symbol,
14683@code{multiply-by-seven}, as containing three words. The hyphens are
14684treated as if they were interword spaces rather than intraword
14685connectors: @samp{multiply-by-seven} is counted as if it were written
14686@samp{multiply by seven}.
14687
14688The cause of this confusion is the regular expression search within
ea4f7750
GM
14689the @code{@value{COUNT-WORDS}} definition that moves point forward word
14690by word. In the canonical version of @code{@value{COUNT-WORDS}}, the
8cda6f8f
GM
14691regexp is:
14692
14693@smallexample
14694"\\w+\\W*"
14695@end smallexample
14696
14697@noindent
14698This regular expression is a pattern defining one or more word
14699constituent characters possibly followed by one or more characters
14700that are not word constituents. What is meant by `word constituent
14701characters' brings us to the issue of syntax, which is worth a section
14702of its own.
14703
d6adf7e7 14704@node Syntax
8cda6f8f
GM
14705@section What Constitutes a Word or Symbol?
14706@cindex Syntax categories and tables
14707
14708Emacs treats different characters as belonging to different
14709@dfn{syntax categories}. For example, the regular expression,
14710@samp{\\w+}, is a pattern specifying one or more @emph{word
14711constituent} characters. Word constituent characters are members of
14712one syntax category. Other syntax categories include the class of
14713punctuation characters, such as the period and the comma, and the
14714class of whitespace characters, such as the blank space and the tab
0fd2c9a3 14715character. (For more information, @pxref{Syntax Tables, , Syntax
8cda6f8f
GM
14716Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
14717
14718Syntax tables specify which characters belong to which categories.
14719Usually, a hyphen is not specified as a `word constituent character'.
14720Instead, it is specified as being in the `class of characters that are
14721part of symbol names but not words.' This means that the
ea4f7750
GM
14722@code{@value{COUNT-WORDS}} function treats it in the same way it treats
14723an interword white space, which is why @code{@value{COUNT-WORDS}}
8cda6f8f
GM
14724counts @samp{multiply-by-seven} as three words.
14725
14726There are two ways to cause Emacs to count @samp{multiply-by-seven} as
14727one symbol: modify the syntax table or modify the regular expression.
14728
14729We could redefine a hyphen as a word constituent character by
14730modifying the syntax table that Emacs keeps for each mode. This
14731action would serve our purpose, except that a hyphen is merely the
14732most common character within symbols that is not typically a word
14733constituent character; there are others, too.
14734
52af8e0a 14735Alternatively, we can redefine the regexp used in the
ea4f7750 14736@code{@value{COUNT-WORDS}} definition so as to include symbols. This
8cda6f8f
GM
14737procedure has the merit of clarity, but the task is a little tricky.
14738
14739@need 1200
14740The first part is simple enough: the pattern must match ``at least one
14741character that is a word or symbol constituent''. Thus:
14742
14743@smallexample
14744"\\(\\w\\|\\s_\\)+"
14745@end smallexample
14746
14747@noindent
14748The @samp{\\(} is the first part of the grouping construct that
14749includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
14750by the @samp{\\|}. The @samp{\\w} matches any word-constituent
14751character and the @samp{\\s_} matches any character that is part of a
14752symbol name but not a word-constituent character. The @samp{+}
14753following the group indicates that the word or symbol constituent
14754characters must be matched at least once.
14755
14756However, the second part of the regexp is more difficult to design.
14757What we want is to follow the first part with ``optionally one or more
14758characters that are not constituents of a word or symbol''. At first,
14759I thought I could define this with the following:
14760
14761@smallexample
14762"\\(\\W\\|\\S_\\)*"
14763@end smallexample
14764
14765@noindent
14766The upper case @samp{W} and @samp{S} match characters that are
14767@emph{not} word or symbol constituents. Unfortunately, this
14768expression matches any character that is either not a word constituent
14769or not a symbol constituent. This matches any character!
14770
14771I then noticed that every word or symbol in my test region was
14772followed by white space (blank space, tab, or newline). So I tried
14773placing a pattern to match one or more blank spaces after the pattern
14774for one or more word or symbol constituents. This failed, too. Words
14775and symbols are often separated by whitespace, but in actual code
14776parentheses may follow symbols and punctuation may follow words. So
14777finally, I designed a pattern in which the word or symbol constituents
14778are followed optionally by characters that are not white space and
14779then followed optionally by white space.
14780
14781@need 800
14782Here is the full regular expression:
14783
14784@smallexample
14785"\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14786@end smallexample
14787
d6adf7e7 14788@node count-words-in-defun
8cda6f8f
GM
14789@section The @code{count-words-in-defun} Function
14790@cindex Counting words in a @code{defun}
14791
14792We have seen that there are several ways to write a
ea4f7750 14793@code{count-words-region} function. To write a
8cda6f8f
GM
14794@code{count-words-in-defun}, we need merely adapt one of these
14795versions.
14796
14797The version that uses a @code{while} loop is easy to understand, so I
14798am going to adapt that. Because @code{count-words-in-defun} will be
14799part of a more complex program, it need not be interactive and it need
14800not display a message but just return the count. These considerations
14801simplify the definition a little.
14802
14803On the other hand, @code{count-words-in-defun} will be used within a
14804buffer that contains function definitions. Consequently, it is
14805reasonable to ask that the function determine whether it is called
14806when point is within a function definition, and if it is, to return
14807the count for that definition. This adds complexity to the
14808definition, but saves us from needing to pass arguments to the
14809function.
14810
14811@need 1250
14812These considerations lead us to prepare the following template:
14813
14814@smallexample
14815@group
14816(defun count-words-in-defun ()
14817 "@var{documentation}@dots{}"
14818 (@var{set up}@dots{}
14819 (@var{while loop}@dots{})
14820 @var{return count})
14821@end group
14822@end smallexample
14823
14824@noindent
14825As usual, our job is to fill in the slots.
14826
14827First, the set up.
14828
14829We are presuming that this function will be called within a buffer
14830containing function definitions. Point will either be within a
14831function definition or not. For @code{count-words-in-defun} to work,
14832point must move to the beginning of the definition, a counter must
14833start at zero, and the counting loop must stop when point reaches the
14834end of the definition.
14835
14836The @code{beginning-of-defun} function searches backwards for an
14837opening delimiter such as a @samp{(} at the beginning of a line, and
14838moves point to that position, or else to the limit of the search. In
14839practice, this means that @code{beginning-of-defun} moves point to the
14840beginning of an enclosing or preceding function definition, or else to
14841the beginning of the buffer. We can use @code{beginning-of-defun} to
14842place point where we wish to start.
14843
14844The @code{while} loop requires a counter to keep track of the words or
14845symbols being counted. A @code{let} expression can be used to create
14846a local variable for this purpose, and bind it to an initial value of zero.
14847
14848The @code{end-of-defun} function works like @code{beginning-of-defun}
14849except that it moves point to the end of the definition.
14850@code{end-of-defun} can be used as part of an expression that
14851determines the position of the end of the definition.
14852
14853The set up for @code{count-words-in-defun} takes shape rapidly: first
14854we move point to the beginning of the definition, then we create a
14855local variable to hold the count, and finally, we record the position
14856of the end of the definition so the @code{while} loop will know when to stop
14857looping.
14858
14859@need 1250
14860The code looks like this:
14861
14862@smallexample
14863@group
14864(beginning-of-defun)
14865(let ((count 0)
14866 (end (save-excursion (end-of-defun) (point))))
14867@end group
14868@end smallexample
14869
14870@noindent
14871The code is simple. The only slight complication is likely to concern
14872@code{end}: it is bound to the position of the end of the definition
14873by a @code{save-excursion} expression that returns the value of point
14874after @code{end-of-defun} temporarily moves it to the end of the
14875definition.
14876
14877The second part of the @code{count-words-in-defun}, after the set up,
14878is the @code{while} loop.
14879
14880The loop must contain an expression that jumps point forward word by
14881word and symbol by symbol, and another expression that counts the
14882jumps. The true-or-false-test for the @code{while} loop should test
14883true so long as point should jump forward, and false when point is at
14884the end of the definition. We have already redefined the regular
0fd2c9a3 14885expression for this, so the loop is straightforward:
8cda6f8f
GM
14886
14887@smallexample
14888@group
14889(while (and (< (point) end)
14890 (re-search-forward
1ef17681 14891 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t))
8cda6f8f
GM
14892 (setq count (1+ count)))
14893@end group
14894@end smallexample
14895
14896The third part of the function definition returns the count of words
14897and symbols. This part is the last expression within the body of the
14898@code{let} expression, and can be, very simply, the local variable
14899@code{count}, which when evaluated returns the count.
14900
14901@need 1250
14902Put together, the @code{count-words-in-defun} definition looks like this:
14903
14904@findex count-words-in-defun
14905@smallexample
14906@group
14907(defun count-words-in-defun ()
14908 "Return the number of words and symbols in a defun."
14909 (beginning-of-defun)
14910 (let ((count 0)
14911 (end (save-excursion (end-of-defun) (point))))
14912@end group
14913@group
14914 (while
14915 (and (< (point) end)
14916 (re-search-forward
14917 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14918 end t))
14919 (setq count (1+ count)))
14920 count))
14921@end group
14922@end smallexample
14923
14924How to test this? The function is not interactive, but it is easy to
14925put a wrapper around the function to make it interactive; we can use
14926almost the same code as for the recursive version of
ea4f7750 14927@code{@value{COUNT-WORDS}}:
8cda6f8f
GM
14928
14929@smallexample
14930@group
14931;;; @r{Interactive version.}
14932(defun count-words-defun ()
14933 "Number of words and symbols in a function definition."
14934 (interactive)
14935 (message
14936 "Counting words and symbols in function definition ... ")
14937@end group
14938@group
14939 (let ((count (count-words-in-defun)))
14940 (cond
14941 ((zerop count)
14942 (message
14943 "The definition does NOT have any words or symbols."))
14944@end group
14945@group
14946 ((= 1 count)
14947 (message
14948 "The definition has 1 word or symbol."))
14949 (t
14950 (message
14951 "The definition has %d words or symbols." count)))))
14952@end group
14953@end smallexample
14954
14955@need 800
14956@noindent
14957Let's re-use @kbd{C-c =} as a convenient keybinding:
14958
14959@smallexample
14960(global-set-key "\C-c=" 'count-words-defun)
14961@end smallexample
14962
14963Now we can try out @code{count-words-defun}: install both
14964@code{count-words-in-defun} and @code{count-words-defun}, and set the
14965keybinding, and then place the cursor within the following definition:
14966
14967@smallexample
14968@group
14969(defun multiply-by-seven (number)
14970 "Multiply NUMBER by seven."
14971 (* 7 number))
14972 @result{} 10
14973@end group
14974@end smallexample
14975
14976@noindent
14977Success! The definition has 10 words and symbols.
14978
14979The next problem is to count the numbers of words and symbols in
14980several definitions within a single file.
14981
d6adf7e7 14982@node Several defuns
8cda6f8f
GM
14983@section Count Several @code{defuns} Within a File
14984
14985A file such as @file{simple.el} may have a hundred or more function
14986definitions within it. Our long term goal is to collect statistics on
14987many files, but as a first step, our immediate goal is to collect
14988statistics on one file.
14989
14990The information will be a series of numbers, each number being the
14991length of a function definition. We can store the numbers in a list.
14992
14993We know that we will want to incorporate the information regarding one
14994file with information about many other files; this means that the
14995function for counting definition lengths within one file need only
14996return the list of lengths. It need not and should not display any
14997messages.
14998
14999The word count commands contain one expression to jump point forward
15000word by word and another expression to count the jumps. The function
15001to return the lengths of definitions can be designed to work the same
15002way, with one expression to jump point forward definition by
15003definition and another expression to construct the lengths' list.
15004
15005This statement of the problem makes it elementary to write the
15006function definition. Clearly, we will start the count at the
15007beginning of the file, so the first command will be @code{(goto-char
15008(point-min))}. Next, we start the @code{while} loop; and the
15009true-or-false test of the loop can be a regular expression search for
15010the next function definition---so long as the search succeeds, point
15011is moved forward and then the body of the loop is evaluated. The body
15012needs an expression that constructs the lengths' list. @code{cons},
15013the list construction command, can be used to create the list. That
15014is almost all there is to it.
15015
15016@need 800
15017Here is what this fragment of code looks like:
15018
15019@smallexample
15020@group
15021(goto-char (point-min))
15022(while (re-search-forward "^(defun" nil t)
15023 (setq lengths-list
15024 (cons (count-words-in-defun) lengths-list)))
15025@end group
15026@end smallexample
15027
15028What we have left out is the mechanism for finding the file that
15029contains the function definitions.
15030
15031In previous examples, we either used this, the Info file, or we
15032switched back and forth to some other buffer, such as the
15033@file{*scratch*} buffer.
15034
15035Finding a file is a new process that we have not yet discussed.
15036
d6adf7e7 15037@node Find a File
8cda6f8f
GM
15038@section Find a File
15039@cindex Find a File
15040
15041To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
15042command. This command is almost, but not quite right for the lengths
15043problem.
15044
15045@need 1200
15046Let's look at the source for @code{find-file}:
15047
15048@smallexample
15049@group
15050(defun find-file (filename)
15051 "Edit file FILENAME.
15052Switch to a buffer visiting file FILENAME,
15053creating one if none already exists."
15054 (interactive "FFind file: ")
15055 (switch-to-buffer (find-file-noselect filename)))
15056@end group
15057@end smallexample
15058
15059@noindent
15060(The most recent version of the @code{find-file} function definition
15061permits you to specify optional wildcards to visit multiple files; that
15062makes the definition more complex and we will not discuss it here,
15063since it is not relevant. You can see its source using either
15064@kbd{M-.} (@code{find-tag}) or @kbd{C-h f} (@code{describe-function}).)
15065
15066@ignore
15067In Emacs 22
15068(defun find-file (filename &optional wildcards)
15069 "Edit file FILENAME.
15070Switch to a buffer visiting file FILENAME,
15071creating one if none already exists.
15072Interactively, the default if you just type RET is the current directory,
15073but the visited file name is available through the minibuffer history:
15074type M-n to pull it into the minibuffer.
15075
15076Interactively, or if WILDCARDS is non-nil in a call from Lisp,
15077expand wildcards (if any) and visit multiple files. You can
15078suppress wildcard expansion by setting `find-file-wildcards' to nil.
15079
15080To visit a file without any kind of conversion and without
15081automatically choosing a major mode, use \\[find-file-literally]."
15082 (interactive (find-file-read-args "Find file: " nil))
15083 (let ((value (find-file-noselect filename nil nil wildcards)))
15084 (if (listp value)
15085 (mapcar 'switch-to-buffer (nreverse value))
15086 (switch-to-buffer value))))
15087@end ignore
15088
15089The definition I am showing possesses short but complete documentation
15090and an interactive specification that prompts you for a file name when
15091you use the command interactively. The body of the definition
15092contains two functions, @code{find-file-noselect} and
15093@code{switch-to-buffer}.
15094
15095According to its documentation as shown by @kbd{C-h f} (the
15096@code{describe-function} command), the @code{find-file-noselect}
15097function reads the named file into a buffer and returns the buffer.
15098(Its most recent version includes an optional wildcards argument,
15099too, as well as another to read a file literally and an other you
15100suppress warning messages. These optional arguments are irrelevant.)
15101
15102However, the @code{find-file-noselect} function does not select the
15103buffer in which it puts the file. Emacs does not switch its attention
15104(or yours if you are using @code{find-file-noselect}) to the selected
15105buffer. That is what @code{switch-to-buffer} does: it switches the
15106buffer to which Emacs attention is directed; and it switches the
15107buffer displayed in the window to the new buffer. We have discussed
15108buffer switching elsewhere. (@xref{Switching Buffers}.)
15109
15110In this histogram project, we do not need to display each file on the
15111screen as the program determines the length of each definition within
15112it. Instead of employing @code{switch-to-buffer}, we can work with
15113@code{set-buffer}, which redirects the attention of the computer
15114program to a different buffer but does not redisplay it on the screen.
15115So instead of calling on @code{find-file} to do the job, we must write
15116our own expression.
15117
15118The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
15119
d6adf7e7 15120@node lengths-list-file
8cda6f8f
GM
15121@section @code{lengths-list-file} in Detail
15122
15123The core of the @code{lengths-list-file} function is a @code{while}
15124loop containing a function to move point forward `defun by defun' and
15125a function to count the number of words and symbols in each defun.
15126This core must be surrounded by functions that do various other tasks,
15127including finding the file, and ensuring that point starts out at the
15128beginning of the file. The function definition looks like this:
15129@findex lengths-list-file
15130
15131@smallexample
15132@group
15133(defun lengths-list-file (filename)
15134 "Return list of definitions' lengths within FILE.
15135The returned list is a list of numbers.
15136Each number is the number of words or
15137symbols in one function definition."
15138@end group
15139@group
15140 (message "Working on `%s' ... " filename)
15141 (save-excursion
15142 (let ((buffer (find-file-noselect filename))
15143 (lengths-list))
15144 (set-buffer buffer)
15145 (setq buffer-read-only t)
15146 (widen)
15147 (goto-char (point-min))
15148 (while (re-search-forward "^(defun" nil t)
15149 (setq lengths-list
15150 (cons (count-words-in-defun) lengths-list)))
15151 (kill-buffer buffer)
15152 lengths-list)))
15153@end group
15154@end smallexample
15155
15156@noindent
15157The function is passed one argument, the name of the file on which it
15158will work. It has four lines of documentation, but no interactive
15159specification. Since people worry that a computer is broken if they
15160don't see anything going on, the first line of the body is a
15161message.
15162
44e97401 15163The next line contains a @code{save-excursion} that returns Emacs's
8cda6f8f
GM
15164attention to the current buffer when the function completes. This is
15165useful in case you embed this function in another function that
15166presumes point is restored to the original buffer.
15167
15168In the varlist of the @code{let} expression, Emacs finds the file and
15169binds the local variable @code{buffer} to the buffer containing the
15170file. At the same time, Emacs creates @code{lengths-list} as a local
15171variable.
15172
15173Next, Emacs switches its attention to the buffer.
15174
15175In the following line, Emacs makes the buffer read-only. Ideally,
15176this line is not necessary. None of the functions for counting words
15177and symbols in a function definition should change the buffer.
15178Besides, the buffer is not going to be saved, even if it were changed.
15179This line is entirely the consequence of great, perhaps excessive,
15180caution. The reason for the caution is that this function and those
15181it calls work on the sources for Emacs and it is inconvenient if they
15182are inadvertently modified. It goes without saying that I did not
15183realize a need for this line until an experiment went awry and started
15184to modify my Emacs source files @dots{}
15185
15186Next comes a call to widen the buffer if it is narrowed. This
15187function is usually not needed---Emacs creates a fresh buffer if none
15188already exists; but if a buffer visiting the file already exists Emacs
15189returns that one. In this case, the buffer may be narrowed and must
15190be widened. If we wanted to be fully `user-friendly', we would
15191arrange to save the restriction and the location of point, but we
15192won't.
15193
15194The @code{(goto-char (point-min))} expression moves point to the
15195beginning of the buffer.
15196
15197Then comes a @code{while} loop in which the `work' of the function is
15198carried out. In the loop, Emacs determines the length of each
15199definition and constructs a lengths' list containing the information.
15200
15201Emacs kills the buffer after working through it. This is to save
15202space inside of Emacs. My version of GNU Emacs 19 contained over 300
15203source files of interest; GNU Emacs 22 contains over a thousand source
15204files. Another function will apply @code{lengths-list-file} to each
15205of the files.
15206
15207Finally, the last expression within the @code{let} expression is the
15208@code{lengths-list} variable; its value is returned as the value of
15209the whole function.
15210
15211You can try this function by installing it in the usual fashion. Then
15212place your cursor after the following expression and type @kbd{C-x
15213C-e} (@code{eval-last-sexp}).
15214
15215@c !!! 22.1.1 lisp sources location here
15216@smallexample
15217(lengths-list-file
15218 "/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el")
15219@end smallexample
15220
15221@noindent
15222(You may need to change the pathname of the file; the one here is for
15223GNU Emacs version 22.1.1. To change the expression, copy it to
15224the @file{*scratch*} buffer and edit it.
15225
15226@need 1200
15227@noindent
15228(Also, to see the full length of the list, rather than a truncated
15229version, you may have to evaluate the following:
15230
15231@smallexample
15232(custom-set-variables '(eval-expression-print-length nil))
15233@end smallexample
15234
15235@noindent
15236(@xref{defcustom, , Specifying Variables using @code{defcustom}}.
15237Then evaluate the @code{lengths-list-file} expression.)
15238
15239@need 1200
15240The lengths' list for @file{debug.el} takes less than a second to
15241produce and looks like this in GNU Emacs 22:
15242
15243@smallexample
15244(83 113 105 144 289 22 30 97 48 89 25 52 52 88 28 29 77 49 43 290 232 587)
15245@end smallexample
15246
15247@need 1500
15248(Using my old machine, the version 19 lengths' list for @file{debug.el}
15249took seven seconds to produce and looked like this:
15250
15251@smallexample
15252(75 41 80 62 20 45 44 68 45 12 34 235)
15253@end smallexample
15254
15255(The newer version of @file{debug.el} contains more defuns than the
15256earlier one; and my new machine is much faster than the old one.)
15257
15258Note that the length of the last definition in the file is first in
15259the list.
15260
d6adf7e7 15261@node Several files
8cda6f8f
GM
15262@section Count Words in @code{defuns} in Different Files
15263
15264In the previous section, we created a function that returns a list of
15265the lengths of each definition in a file. Now, we want to define a
15266function to return a master list of the lengths of the definitions in
15267a list of files.
15268
15269Working on each of a list of files is a repetitious act, so we can use
15270either a @code{while} loop or recursion.
15271
15272@menu
15273* lengths-list-many-files:: Return a list of the lengths of defuns.
15274* append:: Attach one list to another.
15275@end menu
15276
8cda6f8f 15277@ifnottex
d6adf7e7 15278@node lengths-list-many-files
8cda6f8f
GM
15279@unnumberedsubsec Determine the lengths of @code{defuns}
15280@end ifnottex
15281
15282The design using a @code{while} loop is routine. The argument passed
15283the function is a list of files. As we saw earlier (@pxref{Loop
15284Example}), you can write a @code{while} loop so that the body of the
15285loop is evaluated if such a list contains elements, but to exit the
15286loop if the list is empty. For this design to work, the body of the
15287loop must contain an expression that shortens the list each time the
15288body is evaluated, so that eventually the list is empty. The usual
15289technique is to set the value of the list to the value of the @sc{cdr}
15290of the list each time the body is evaluated.
15291
15292@need 800
15293The template looks like this:
15294
15295@smallexample
15296@group
15297(while @var{test-whether-list-is-empty}
15298 @var{body}@dots{}
15299 @var{set-list-to-cdr-of-list})
15300@end group
15301@end smallexample
15302
15303Also, we remember that a @code{while} loop returns @code{nil} (the
15304result of evaluating the true-or-false-test), not the result of any
15305evaluation within its body. (The evaluations within the body of the
15306loop are done for their side effects.) However, the expression that
15307sets the lengths' list is part of the body---and that is the value
15308that we want returned by the function as a whole. To do this, we
15309enclose the @code{while} loop within a @code{let} expression, and
15310arrange that the last element of the @code{let} expression contains
15311the value of the lengths' list. (@xref{Incrementing Example, , Loop
15312Example with an Incrementing Counter}.)
15313
15314@findex lengths-list-many-files
15315@need 1250
15316These considerations lead us directly to the function itself:
15317
15318@smallexample
15319@group
15320;;; @r{Use @code{while} loop.}
15321(defun lengths-list-many-files (list-of-files)
15322 "Return list of lengths of defuns in LIST-OF-FILES."
15323@end group
15324@group
15325 (let (lengths-list)
15326
15327;;; @r{true-or-false-test}
15328 (while list-of-files
15329 (setq lengths-list
15330 (append
15331 lengths-list
15332
15333;;; @r{Generate a lengths' list.}
15334 (lengths-list-file
15335 (expand-file-name (car list-of-files)))))
15336@end group
15337
15338@group
15339;;; @r{Make files' list shorter.}
15340 (setq list-of-files (cdr list-of-files)))
15341
15342;;; @r{Return final value of lengths' list.}
15343 lengths-list))
15344@end group
15345@end smallexample
15346
15347@code{expand-file-name} is a built-in function that converts a file
15348name to the absolute, long, path name form. The function employs the
15349name of the directory in which the function is called.
15350
15351@c !!! 22.1.1 lisp sources location here
15352@need 1500
15353Thus, if @code{expand-file-name} is called on @code{debug.el} when
15354Emacs is visiting the
15355@file{/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/} directory,
15356
15357@smallexample
15358debug.el
15359@end smallexample
15360
15361@need 800
15362@noindent
15363becomes
15364
15365@c !!! 22.1.1 lisp sources location here
15366@smallexample
15367/usr/local/share/emacs/22.1.1/lisp/emacs-lisp/debug.el
15368@end smallexample
15369
15370The only other new element of this function definition is the as yet
15371unstudied function @code{append}, which merits a short section for
15372itself.
15373
d6adf7e7 15374@node append
8cda6f8f
GM
15375@subsection The @code{append} Function
15376
15377@need 800
15378The @code{append} function attaches one list to another. Thus,
15379
15380@smallexample
15381(append '(1 2 3 4) '(5 6 7 8))
15382@end smallexample
15383
15384@need 800
15385@noindent
15386produces the list
15387
15388@smallexample
15389(1 2 3 4 5 6 7 8)
15390@end smallexample
15391
15392This is exactly how we want to attach two lengths' lists produced by
15393@code{lengths-list-file} to each other. The results contrast with
15394@code{cons},
15395
15396@smallexample
15397(cons '(1 2 3 4) '(5 6 7 8))
15398@end smallexample
15399
15400@need 1250
15401@noindent
15402which constructs a new list in which the first argument to @code{cons}
15403becomes the first element of the new list:
15404
15405@smallexample
15406((1 2 3 4) 5 6 7 8)
15407@end smallexample
15408
d6adf7e7 15409@node Several files recursively
8cda6f8f
GM
15410@section Recursively Count Words in Different Files
15411
15412Besides a @code{while} loop, you can work on each of a list of files
15413with recursion. A recursive version of @code{lengths-list-many-files}
15414is short and simple.
15415
15416The recursive function has the usual parts: the `do-again-test', the
15417`next-step-expression', and the recursive call. The `do-again-test'
15418determines whether the function should call itself again, which it
15419will do if the @code{list-of-files} contains any remaining elements;
15420the `next-step-expression' resets the @code{list-of-files} to the
15421@sc{cdr} of itself, so eventually the list will be empty; and the
15422recursive call calls itself on the shorter list. The complete
15423function is shorter than this description!
15424@findex recursive-lengths-list-many-files
15425
15426@smallexample
15427@group
15428(defun recursive-lengths-list-many-files (list-of-files)
15429 "Return list of lengths of each defun in LIST-OF-FILES."
15430 (if list-of-files ; @r{do-again-test}
15431 (append
15432 (lengths-list-file
15433 (expand-file-name (car list-of-files)))
15434 (recursive-lengths-list-many-files
15435 (cdr list-of-files)))))
15436@end group
15437@end smallexample
15438
15439@noindent
15440In a sentence, the function returns the lengths' list for the first of
15441the @code{list-of-files} appended to the result of calling itself on
15442the rest of the @code{list-of-files}.
15443
15444Here is a test of @code{recursive-lengths-list-many-files}, along with
15445the results of running @code{lengths-list-file} on each of the files
15446individually.
15447
15448Install @code{recursive-lengths-list-many-files} and
15449@code{lengths-list-file}, if necessary, and then evaluate the
15450following expressions. You may need to change the files' pathnames;
15451those here work when this Info file and the Emacs sources are located
15452in their customary places. To change the expressions, copy them to
15453the @file{*scratch*} buffer, edit them, and then evaluate them.
15454
15455The results are shown after the @samp{@result{}}. (These results are
15456for files from Emacs version 22.1.1; files from other versions of
15457Emacs may produce different results.)
15458
15459@c !!! 22.1.1 lisp sources location here
15460@smallexample
15461@group
15462(cd "/usr/local/share/emacs/22.1.1/")
15463
15464(lengths-list-file "./lisp/macros.el")
15465 @result{} (283 263 480 90)
15466@end group
15467
15468@group
15469(lengths-list-file "./lisp/mail/mailalias.el")
15470 @result{} (38 32 29 95 178 180 321 218 324)
15471@end group
15472
15473@group
15474(lengths-list-file "./lisp/makesum.el")
15475 @result{} (85 181)
15476@end group
15477
15478@group
15479 (recursive-lengths-list-many-files
15480 '("./lisp/macros.el"
15481 "./lisp/mail/mailalias.el"
15482 "./lisp/makesum.el"))
15483 @result{} (283 263 480 90 38 32 29 95 178 180 321 218 324 85 181)
15484@end group
15485@end smallexample
15486
15487The @code{recursive-lengths-list-many-files} function produces the
15488output we want.
15489
15490The next step is to prepare the data in the list for display in a graph.
15491
d6adf7e7 15492@node Prepare the data
8cda6f8f
GM
15493@section Prepare the Data for Display in a Graph
15494
15495The @code{recursive-lengths-list-many-files} function returns a list
15496of numbers. Each number records the length of a function definition.
15497What we need to do now is transform this data into a list of numbers
15498suitable for generating a graph. The new list will tell how many
15499functions definitions contain less than 10 words and
15500symbols, how many contain between 10 and 19 words and symbols, how
15501many contain between 20 and 29 words and symbols, and so on.
15502
15503In brief, we need to go through the lengths' list produced by the
15504@code{recursive-lengths-list-many-files} function and count the number
15505of defuns within each range of lengths, and produce a list of those
15506numbers.
15507
15508@menu
15509* Data for Display in Detail::
15510* Sorting:: Sorting lists.
15511* Files List:: Making a list of files.
15512* Counting function definitions::
15513@end menu
15514
8cda6f8f 15515@ifnottex
d6adf7e7 15516@node Data for Display in Detail
8cda6f8f
GM
15517@unnumberedsubsec The Data for Display in Detail
15518@end ifnottex
15519
15520Based on what we have done before, we can readily foresee that it
15521should not be too hard to write a function that `@sc{cdr}s' down the
15522lengths' list, looks at each element, determines which length range it
15523is in, and increments a counter for that range.
15524
15525However, before beginning to write such a function, we should consider
15526the advantages of sorting the lengths' list first, so the numbers are
15527ordered from smallest to largest. First, sorting will make it easier
15528to count the numbers in each range, since two adjacent numbers will
15529either be in the same length range or in adjacent ranges. Second, by
15530inspecting a sorted list, we can discover the highest and lowest
15531number, and thereby determine the largest and smallest length range
15532that we will need.
15533
d6adf7e7 15534@node Sorting
8cda6f8f
GM
15535@subsection Sorting Lists
15536@findex sort
15537
15538Emacs contains a function to sort lists, called (as you might guess)
15539@code{sort}. The @code{sort} function takes two arguments, the list
15540to be sorted, and a predicate that determines whether the first of
15541two list elements is ``less'' than the second.
15542
15543As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
15544Type Object as an Argument}), a predicate is a function that
15545determines whether some property is true or false. The @code{sort}
15546function will reorder a list according to whatever property the
15547predicate uses; this means that @code{sort} can be used to sort
15548non-numeric lists by non-numeric criteria---it can, for example,
15549alphabetize a list.
15550
15551@need 1250
15552The @code{<} function is used when sorting a numeric list. For example,
15553
15554@smallexample
15555(sort '(4 8 21 17 33 7 21 7) '<)
15556@end smallexample
15557
15558@need 800
15559@noindent
15560produces this:
15561
15562@smallexample
15563(4 7 7 8 17 21 21 33)
15564@end smallexample
15565
15566@noindent
15567(Note that in this example, both the arguments are quoted so that the
15568symbols are not evaluated before being passed to @code{sort} as
15569arguments.)
15570
15571Sorting the list returned by the
15572@code{recursive-lengths-list-many-files} function is straightforward;
15573it uses the @code{<} function:
15574
15575@ignore
155762006 Oct 29
15577In GNU Emacs 22, eval
15578(progn
15579 (cd "/usr/local/share/emacs/22.0.50/")
15580 (sort
15581 (recursive-lengths-list-many-files
15582 '("./lisp/macros.el"
15583 "./lisp/mail/mailalias.el"
15584 "./lisp/makesum.el"))
15585 '<))
15586
15587@end ignore
15588
15589@smallexample
15590@group
15591(sort
15592 (recursive-lengths-list-many-files
15593 '("./lisp/macros.el"
15594 "./lisp/mailalias.el"
15595 "./lisp/makesum.el"))
15596 '<)
15597@end group
15598@end smallexample
15599
15600@need 800
15601@noindent
15602which produces:
15603
15604@smallexample
15605(29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)
15606@end smallexample
15607
15608@noindent
15609(Note that in this example, the first argument to @code{sort} is not
15610quoted, since the expression must be evaluated so as to produce the
15611list that is passed to @code{sort}.)
15612
d6adf7e7 15613@node Files List
8cda6f8f
GM
15614@subsection Making a List of Files
15615
15616The @code{recursive-lengths-list-many-files} function requires a list
15617of files as its argument. For our test examples, we constructed such
15618a list by hand; but the Emacs Lisp source directory is too large for
15619us to do for that. Instead, we will write a function to do the job
15620for us. In this function, we will use both a @code{while} loop and a
15621recursive call.
15622
15623@findex directory-files
15624We did not have to write a function like this for older versions of
15625GNU Emacs, since they placed all the @samp{.el} files in one
15626directory. Instead, we were able to use the @code{directory-files}
15627function, which lists the names of files that match a specified
15628pattern within a single directory.
15629
15630However, recent versions of Emacs place Emacs Lisp files in
15631sub-directories of the top level @file{lisp} directory. This
15632re-arrangement eases navigation. For example, all the mail related
15633files are in a @file{lisp} sub-directory called @file{mail}. But at
15634the same time, this arrangement forces us to create a file listing
15635function that descends into the sub-directories.
15636
15637@findex files-in-below-directory
15638We can create this function, called @code{files-in-below-directory},
15639using familiar functions such as @code{car}, @code{nthcdr}, and
15640@code{substring} in conjunction with an existing function called
15641@code{directory-files-and-attributes}. This latter function not only
15642lists all the filenames in a directory, including the names
15643of sub-directories, but also their attributes.
15644
15645To restate our goal: to create a function that will enable us
15646to feed filenames to @code{recursive-lengths-list-many-files}
15647as a list that looks like this (but with more elements):
15648
15649@smallexample
15650@group
15651("./lisp/macros.el"
15652 "./lisp/mail/rmail.el"
15653 "./lisp/makesum.el")
15654@end group
15655@end smallexample
15656
15657The @code{directory-files-and-attributes} function returns a list of
15658lists. Each of the lists within the main list consists of 13
15659elements. The first element is a string that contains the name of the
15660file -- which, in GNU/Linux, may be a `directory file', that is to
15661say, a file with the special attributes of a directory. The second
15662element of the list is @code{t} for a directory, a string
15663for symbolic link (the string is the name linked to), or @code{nil}.
15664
15665For example, the first @samp{.el} file in the @file{lisp/} directory
15666is @file{abbrev.el}. Its name is
15667@file{/usr/local/share/emacs/22.1.1/lisp/abbrev.el} and it is not a
15668directory or a symbolic link.
15669
15670@need 1000
15671This is how @code{directory-files-and-attributes} lists that file and
15672its attributes:
15673
15674@smallexample
15675@group
15676("abbrev.el"
15677nil
156781
156791000
15680100
15681@end group
15682@group
72ec96fb
PE
15683(20615 27034 579989 697000)
15684(17905 55681 0 0)
15685(20615 26327 734791 805000)
1568613188
15687"-rw-r--r--"
8cda6f8f
GM
15688@end group
15689@group
97976f9f 15690t
8cda6f8f
GM
156912971624
15692773)
15693@end group
15694@end smallexample
15695
15696@need 1200
15697On the other hand, @file{mail/} is a directory within the @file{lisp/}
15698directory. The beginning of its listing looks like this:
15699
15700@smallexample
15701@group
15702("mail"
15703t
15704@dots{}
15705)
15706@end group
15707@end smallexample
15708
15709(To learn about the different attributes, look at the documentation of
15710@code{file-attributes}. Bear in mind that the @code{file-attributes}
15711function does not list the filename, so its first element is
15712@code{directory-files-and-attributes}'s second element.)
15713
15714We will want our new function, @code{files-in-below-directory}, to
15715list the @samp{.el} files in the directory it is told to check, and in
15716any directories below that directory.
15717
15718This gives us a hint on how to construct
15719@code{files-in-below-directory}: within a directory, the function
15720should add @samp{.el} filenames to a list; and if, within a directory,
15721the function comes upon a sub-directory, it should go into that
15722sub-directory and repeat its actions.
15723
15724However, we should note that every directory contains a name that
15725refers to itself, called @file{.}, (``dot'') and a name that refers to
15726its parent directory, called @file{..} (``double dot''). (In
15727@file{/}, the root directory, @file{..} refers to itself, since
15728@file{/} has no parent.) Clearly, we do not want our
15729@code{files-in-below-directory} function to enter those directories,
15730since they always lead us, directly or indirectly, to the current
15731directory.
15732
15733Consequently, our @code{files-in-below-directory} function must do
15734several tasks:
15735
15736@itemize @bullet
15737@item
15738Check to see whether it is looking at a filename that ends in
15739@samp{.el}; and if so, add its name to a list.
15740
15741@item
15742Check to see whether it is looking at a filename that is the name of a
15743directory; and if so,
15744
15745@itemize @minus
15746@item
15747Check to see whether it is looking at @file{.} or @file{..}; and if
15748so skip it.
15749
15750@item
15751Or else, go into that directory and repeat the process.
15752@end itemize
15753@end itemize
15754
15755Let's write a function definition to do these tasks. We will use a
15756@code{while} loop to move from one filename to another within a
15757directory, checking what needs to be done; and we will use a recursive
15758call to repeat the actions on each sub-directory. The recursive
15759pattern is `accumulate'
15760(@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
15761using @code{append} as the combiner.
15762
15763@ignore
15764(directory-files "/usr/local/src/emacs/lisp/" t "\\.el$")
15765(shell-command "find /usr/local/src/emacs/lisp/ -name '*.el'")
15766
15767(directory-files "/usr/local/share/emacs/22.1.1/lisp/" t "\\.el$")
15768(shell-command "find /usr/local/share/emacs/22.1.1/lisp/ -name '*.el'")
15769@end ignore
15770
15771@c /usr/local/share/emacs/22.1.1/lisp/
15772
15773@need 800
15774Here is the function:
15775
15776@smallexample
15777@group
15778(defun files-in-below-directory (directory)
15779 "List the .el files in DIRECTORY and in its sub-directories."
15780 ;; Although the function will be used non-interactively,
15781 ;; it will be easier to test if we make it interactive.
15782 ;; The directory will have a name such as
15783 ;; "/usr/local/share/emacs/22.1.1/lisp/"
15784 (interactive "DDirectory name: ")
15785@end group
15786@group
15787 (let (el-files-list
15788 (current-directory-list
15789 (directory-files-and-attributes directory t)))
15790 ;; while we are in the current directory
15791 (while current-directory-list
15792@end group
15793@group
15794 (cond
15795 ;; check to see whether filename ends in `.el'
15796 ;; and if so, append its name to a list.
15797 ((equal ".el" (substring (car (car current-directory-list)) -3))
15798 (setq el-files-list
15799 (cons (car (car current-directory-list)) el-files-list)))
15800@end group
15801@group
15802 ;; check whether filename is that of a directory
15803 ((eq t (car (cdr (car current-directory-list))))
15804 ;; decide whether to skip or recurse
15805 (if
15806 (equal "."
15807 (substring (car (car current-directory-list)) -1))
15808 ;; then do nothing since filename is that of
15809 ;; current directory or parent, "." or ".."
15810 ()
15811@end group
15812@group
15813 ;; else descend into the directory and repeat the process
15814 (setq el-files-list
15815 (append
15816 (files-in-below-directory
15817 (car (car current-directory-list)))
15818 el-files-list)))))
15819 ;; move to the next filename in the list; this also
15820 ;; shortens the list so the while loop eventually comes to an end
15821 (setq current-directory-list (cdr current-directory-list)))
15822 ;; return the filenames
15823 el-files-list))
15824@end group
15825@end smallexample
15826
15827@c (files-in-below-directory "/usr/local/src/emacs/lisp/")
15828@c (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15829
15830The @code{files-in-below-directory} @code{directory-files} function
15831takes one argument, the name of a directory.
15832
15833@need 1250
15834Thus, on my system,
15835
15836@c (length (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15837
15838@c !!! 22.1.1 lisp sources location here
15839@smallexample
15840@group
15841(length
15842 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/"))
15843@end group
15844@end smallexample
15845
15846@noindent
15847tells me that in and below my Lisp sources directory are 1031
15848@samp{.el} files.
15849
15850@code{files-in-below-directory} returns a list in reverse alphabetical
15851order. An expression to sort the list in alphabetical order looks
15852like this:
15853
15854@smallexample
15855@group
15856(sort
15857 (files-in-below-directory "/usr/local/share/emacs/22.1.1/lisp/")
15858 'string-lessp)
15859@end group
15860@end smallexample
15861
15862@ignore
15863(defun test ()
15864 "Test how long it takes to find lengths of all sorted elisp defuns."
15865 (insert "\n" (current-time-string) "\n")
15866 (sit-for 0)
15867 (sort
15868 (recursive-lengths-list-many-files
15869 (files-in-below-directory "/usr/local/src/emacs/lisp/"))
15870 '<)
15871 (insert (format "%s" (current-time-string))))
15872@end ignore
15873
d6adf7e7 15874@node Counting function definitions
8cda6f8f
GM
15875@subsection Counting function definitions
15876
15877Our immediate goal is to generate a list that tells us how many
15878function definitions contain fewer than 10 words and symbols, how many
15879contain between 10 and 19 words and symbols, how many contain between
1588020 and 29 words and symbols, and so on.
15881
15882With a sorted list of numbers, this is easy: count how many elements
15883of the list are smaller than 10, then, after moving past the numbers
15884just counted, count how many are smaller than 20, then, after moving
15885past the numbers just counted, count how many are smaller than 30, and
15886so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
15887larger than the top of that range. We can call the list of such
15888numbers the @code{top-of-ranges} list.
15889
15890@need 1200
15891If we wished, we could generate this list automatically, but it is
15892simpler to write a list manually. Here it is:
15893@vindex top-of-ranges
15894
15895@smallexample
15896@group
15897(defvar top-of-ranges
15898 '(10 20 30 40 50
15899 60 70 80 90 100
15900 110 120 130 140 150
15901 160 170 180 190 200
15902 210 220 230 240 250
15903 260 270 280 290 300)
15904 "List specifying ranges for `defuns-per-range'.")
15905@end group
15906@end smallexample
15907
15908To change the ranges, we edit this list.
15909
15910Next, we need to write the function that creates the list of the
15911number of definitions within each range. Clearly, this function must
15912take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15913as arguments.
15914
15915The @code{defuns-per-range} function must do two things again and
15916again: it must count the number of definitions within a range
15917specified by the current top-of-range value; and it must shift to the
15918next higher value in the @code{top-of-ranges} list after counting the
15919number of definitions in the current range. Since each of these
15920actions is repetitive, we can use @code{while} loops for the job.
15921One loop counts the number of definitions in the range defined by the
15922current top-of-range value, and the other loop selects each of the
15923top-of-range values in turn.
15924
15925Several entries of the @code{sorted-lengths} list are counted for each
15926range; this means that the loop for the @code{sorted-lengths} list
15927will be inside the loop for the @code{top-of-ranges} list, like a
15928small gear inside a big gear.
15929
15930The inner loop counts the number of definitions within the range. It
15931is a simple counting loop of the type we have seen before.
15932(@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15933The true-or-false test of the loop tests whether the value from the
15934@code{sorted-lengths} list is smaller than the current value of the
15935top of the range. If it is, the function increments the counter and
15936tests the next value from the @code{sorted-lengths} list.
15937
15938@need 1250
15939The inner loop looks like this:
15940
15941@smallexample
15942@group
15943(while @var{length-element-smaller-than-top-of-range}
15944 (setq number-within-range (1+ number-within-range))
15945 (setq sorted-lengths (cdr sorted-lengths)))
15946@end group
15947@end smallexample
15948
15949The outer loop must start with the lowest value of the
15950@code{top-of-ranges} list, and then be set to each of the succeeding
15951higher values in turn. This can be done with a loop like this:
15952
15953@smallexample
15954@group
15955(while top-of-ranges
15956 @var{body-of-loop}@dots{}
15957 (setq top-of-ranges (cdr top-of-ranges)))
15958@end group
15959@end smallexample
15960
15961@need 1200
15962Put together, the two loops look like this:
15963
15964@smallexample
15965@group
15966(while top-of-ranges
15967
15968 ;; @r{Count the number of elements within the current range.}
15969 (while @var{length-element-smaller-than-top-of-range}
15970 (setq number-within-range (1+ number-within-range))
15971 (setq sorted-lengths (cdr sorted-lengths)))
15972
15973 ;; @r{Move to next range.}
15974 (setq top-of-ranges (cdr top-of-ranges)))
15975@end group
15976@end smallexample
15977
15978In addition, in each circuit of the outer loop, Emacs should record
15979the number of definitions within that range (the value of
15980@code{number-within-range}) in a list. We can use @code{cons} for
15981this purpose. (@xref{cons, , @code{cons}}.)
15982
15983The @code{cons} function works fine, except that the list it
15984constructs will contain the number of definitions for the highest
15985range at its beginning and the number of definitions for the lowest
15986range at its end. This is because @code{cons} attaches new elements
15987of the list to the beginning of the list, and since the two loops are
15988working their way through the lengths' list from the lower end first,
15989the @code{defuns-per-range-list} will end up largest number first.
15990But we will want to print our graph with smallest values first and the
15991larger later. The solution is to reverse the order of the
15992@code{defuns-per-range-list}. We can do this using the
15993@code{nreverse} function, which reverses the order of a list.
15994@findex nreverse
15995
15996@need 800
15997For example,
15998
15999@smallexample
16000(nreverse '(1 2 3 4))
16001@end smallexample
16002
16003@need 800
16004@noindent
16005produces:
16006
16007@smallexample
16008(4 3 2 1)
16009@end smallexample
16010
16011Note that the @code{nreverse} function is ``destructive''---that is,
16012it changes the list to which it is applied; this contrasts with the
16013@code{car} and @code{cdr} functions, which are non-destructive. In
16014this case, we do not want the original @code{defuns-per-range-list},
16015so it does not matter that it is destroyed. (The @code{reverse}
16016function provides a reversed copy of a list, leaving the original list
16017as is.)
16018@findex reverse
16019
16020@need 1250
16021Put all together, the @code{defuns-per-range} looks like this:
16022
16023@smallexample
16024@group
16025(defun defuns-per-range (sorted-lengths top-of-ranges)
16026 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
16027 (let ((top-of-range (car top-of-ranges))
16028 (number-within-range 0)
16029 defuns-per-range-list)
16030@end group
16031
16032@group
16033 ;; @r{Outer loop.}
16034 (while top-of-ranges
16035@end group
16036
16037@group
16038 ;; @r{Inner loop.}
16039 (while (and
16040 ;; @r{Need number for numeric test.}
16041 (car sorted-lengths)
16042 (< (car sorted-lengths) top-of-range))
16043@end group
16044
16045@group
16046 ;; @r{Count number of definitions within current range.}
16047 (setq number-within-range (1+ number-within-range))
16048 (setq sorted-lengths (cdr sorted-lengths)))
16049
16050 ;; @r{Exit inner loop but remain within outer loop.}
16051@end group
16052
16053@group
16054 (setq defuns-per-range-list
16055 (cons number-within-range defuns-per-range-list))
16056 (setq number-within-range 0) ; @r{Reset count to zero.}
16057@end group
16058
16059@group
16060 ;; @r{Move to next range.}
16061 (setq top-of-ranges (cdr top-of-ranges))
16062 ;; @r{Specify next top of range value.}
16063 (setq top-of-range (car top-of-ranges)))
16064@end group
16065
16066@group
16067 ;; @r{Exit outer loop and count the number of defuns larger than}
16068 ;; @r{ the largest top-of-range value.}
16069 (setq defuns-per-range-list
16070 (cons
16071 (length sorted-lengths)
16072 defuns-per-range-list))
16073@end group
16074
16075@group
16076 ;; @r{Return a list of the number of definitions within each range,}
16077 ;; @r{ smallest to largest.}
16078 (nreverse defuns-per-range-list)))
16079@end group
16080@end smallexample
16081
16082@need 1200
16083@noindent
16084The function is straightforward except for one subtle feature. The
16085true-or-false test of the inner loop looks like this:
16086
16087@smallexample
16088@group
16089(and (car sorted-lengths)
16090 (< (car sorted-lengths) top-of-range))
16091@end group
16092@end smallexample
16093
16094@need 800
16095@noindent
16096instead of like this:
16097
16098@smallexample
16099(< (car sorted-lengths) top-of-range)
16100@end smallexample
16101
16102The purpose of the test is to determine whether the first item in the
16103@code{sorted-lengths} list is less than the value of the top of the
16104range.
16105
16106The simple version of the test works fine unless the
16107@code{sorted-lengths} list has a @code{nil} value. In that case, the
16108@code{(car sorted-lengths)} expression function returns
16109@code{nil}. The @code{<} function cannot compare a number to
16110@code{nil}, which is an empty list, so Emacs signals an error and
16111stops the function from attempting to continue to execute.
16112
16113The @code{sorted-lengths} list always becomes @code{nil} when the
16114counter reaches the end of the list. This means that any attempt to
16115use the @code{defuns-per-range} function with the simple version of
16116the test will fail.
16117
16118We solve the problem by using the @code{(car sorted-lengths)}
16119expression in conjunction with the @code{and} expression. The
16120@code{(car sorted-lengths)} expression returns a non-@code{nil}
16121value so long as the list has at least one number within it, but
16122returns @code{nil} if the list is empty. The @code{and} expression
16123first evaluates the @code{(car sorted-lengths)} expression, and
16124if it is @code{nil}, returns false @emph{without} evaluating the
16125@code{<} expression. But if the @code{(car sorted-lengths)}
16126expression returns a non-@code{nil} value, the @code{and} expression
16127evaluates the @code{<} expression, and returns that value as the value
16128of the @code{and} expression.
16129
16130@c colon in printed section title causes problem in Info cross reference
16131This way, we avoid an error.
16132@iftex
16133@noindent
16134(For information about @code{and}, see
16135@ref{kill-new function, , The @code{kill-new} function}.)
16136@end iftex
16137@ifinfo
16138@noindent
16139(@xref{kill-new function, , The @code{kill-new} function}, for
16140information about @code{and}.)
16141@end ifinfo
16142
16143Here is a short test of the @code{defuns-per-range} function. First,
16144evaluate the expression that binds (a shortened)
16145@code{top-of-ranges} list to the list of values, then evaluate the
16146expression for binding the @code{sorted-lengths} list, and then
16147evaluate the @code{defuns-per-range} function.
16148
16149@smallexample
16150@group
16151;; @r{(Shorter list than we will use later.)}
16152(setq top-of-ranges
16153 '(110 120 130 140 150
16154 160 170 180 190 200))
16155
16156(setq sorted-lengths
16157 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
16158
16159(defuns-per-range sorted-lengths top-of-ranges)
16160@end group
16161@end smallexample
16162
16163@need 800
16164@noindent
16165The list returned looks like this:
16166
16167@smallexample
16168(2 2 2 0 0 1 0 2 0 0 4)
16169@end smallexample
16170
16171@noindent
16172Indeed, there are two elements of the @code{sorted-lengths} list
16173smaller than 110, two elements between 110 and 119, two elements
16174between 120 and 129, and so on. There are four elements with a value
16175of 200 or larger.
16176
16177@c The next step is to turn this numbers' list into a graph.
d6adf7e7 16178@node Readying a Graph
8cda6f8f
GM
16179@chapter Readying a Graph
16180@cindex Readying a graph
16181@cindex Graph prototype
16182@cindex Prototype graph
16183@cindex Body of graph
16184
16185Our goal is to construct a graph showing the numbers of function
16186definitions of various lengths in the Emacs lisp sources.
16187
16188As a practical matter, if you were creating a graph, you would
16189probably use a program such as @code{gnuplot} to do the job.
16190(@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
16191however, we create one from scratch, and in the process we will
16192re-acquaint ourselves with some of what we learned before and learn
16193more.
16194
16195In this chapter, we will first write a simple graph printing function.
16196This first definition will be a @dfn{prototype}, a rapidly written
16197function that enables us to reconnoiter this unknown graph-making
16198territory. We will discover dragons, or find that they are myth.
16199After scouting the terrain, we will feel more confident and enhance
16200the function to label the axes automatically.
16201
16202@menu
16203* Columns of a graph::
16204* graph-body-print:: How to print the body of a graph.
16205* recursive-graph-body-print::
16206* Printed Axes::
16207* Line Graph Exercise::
16208@end menu
16209
8cda6f8f 16210@ifnottex
d6adf7e7 16211@node Columns of a graph
8cda6f8f
GM
16212@unnumberedsec Printing the Columns of a Graph
16213@end ifnottex
16214
16215Since Emacs is designed to be flexible and work with all kinds of
16216terminals, including character-only terminals, the graph will need to
16217be made from one of the `typewriter' symbols. An asterisk will do; as
16218we enhance the graph-printing function, we can make the choice of
16219symbol a user option.
16220
16221We can call this function @code{graph-body-print}; it will take a
16222@code{numbers-list} as its only argument. At this stage, we will not
16223label the graph, but only print its body.
16224
16225The @code{graph-body-print} function inserts a vertical column of
16226asterisks for each element in the @code{numbers-list}. The height of
16227each line is determined by the value of that element of the
16228@code{numbers-list}.
16229
16230Inserting columns is a repetitive act; that means that this function can
16231be written either with a @code{while} loop or recursively.
16232
16233Our first challenge is to discover how to print a column of asterisks.
16234Usually, in Emacs, we print characters onto a screen horizontally,
16235line by line, by typing. We have two routes we can follow: write our
16236own column-insertion function or discover whether one exists in Emacs.
16237
16238To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
16239command. This command is like the @kbd{C-h a} (@code{command-apropos})
16240command, except that the latter finds only those functions that are
16241commands. The @kbd{M-x apropos} command lists all symbols that match
16242a regular expression, including functions that are not interactive.
16243@findex apropos
16244
16245What we want to look for is some command that prints or inserts
16246columns. Very likely, the name of the function will contain either
16247the word `print' or the word `insert' or the word `column'.
16248Therefore, we can simply type @kbd{M-x apropos RET
16249print\|insert\|column RET} and look at the result. On my system, this
16250command once too takes quite some time, and then produced a list of 79
16251functions and variables. Now it does not take much time at all and
16252produces a list of 211 functions and variables. Scanning down the
16253list, the only function that looks as if it might do the job is
16254@code{insert-rectangle}.
16255
16256@need 1200
16257Indeed, this is the function we want; its documentation says:
16258
16259@smallexample
16260@group
16261insert-rectangle:
16262Insert text of RECTANGLE with upper left corner at point.
16263RECTANGLE's first line is inserted at point,
16264its second line is inserted at a point vertically under point, etc.
16265RECTANGLE should be a list of strings.
16266After this command, the mark is at the upper left corner
16267and point is at the lower right corner.
16268@end group
16269@end smallexample
16270
16271We can run a quick test, to make sure it does what we expect of it.
16272
16273Here is the result of placing the cursor after the
16274@code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
16275(@code{eval-last-sexp}). The function inserts the strings
16276@samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
16277point. Also the function returns @code{nil}.
16278
16279@smallexample
16280@group
16281(insert-rectangle '("first" "second" "third"))first
16282 second
16283 thirdnil
16284@end group
16285@end smallexample
16286
16287@noindent
16288Of course, we won't be inserting the text of the
16289@code{insert-rectangle} expression itself into the buffer in which we
16290are making the graph, but will call the function from our program. We
16291shall, however, have to make sure that point is in the buffer at the
16292place where the @code{insert-rectangle} function will insert its
16293column of strings.
16294
16295If you are reading this in Info, you can see how this works by
16296switching to another buffer, such as the @file{*scratch*} buffer,
16297placing point somewhere in the buffer, typing @kbd{M-:}, typing the
16298@code{insert-rectangle} expression into the minibuffer at the prompt,
16299and then typing @key{RET}. This causes Emacs to evaluate the
16300expression in the minibuffer, but to use as the value of point the
16301position of point in the @file{*scratch*} buffer. (@kbd{M-:} is the
16302keybinding for @code{eval-expression}. Also, @code{nil} does not
16303appear in the @file{*scratch*} buffer since the expression is
16304evaluated in the minibuffer.)
16305
16306We find when we do this that point ends up at the end of the last
16307inserted line---that is to say, this function moves point as a
16308side-effect. If we were to repeat the command, with point at this
16309position, the next insertion would be below and to the right of the
16310previous insertion. We don't want this! If we are going to make a
16311bar graph, the columns need to be beside each other.
16312
16313So we discover that each cycle of the column-inserting @code{while}
16314loop must reposition point to the place we want it, and that place
16315will be at the top, not the bottom, of the column. Moreover, we
16316remember that when we print a graph, we do not expect all the columns
16317to be the same height. This means that the top of each column may be
16318at a different height from the previous one. We cannot simply
16319reposition point to the same line each time, but moved over to the
16320right---or perhaps we can@dots{}
16321
16322We are planning to make the columns of the bar graph out of asterisks.
16323The number of asterisks in the column is the number specified by the
16324current element of the @code{numbers-list}. We need to construct a
16325list of asterisks of the right length for each call to
16326@code{insert-rectangle}. If this list consists solely of the requisite
16327number of asterisks, then we will have position point the right number
16328of lines above the base for the graph to print correctly. This could
16329be difficult.
16330
16331Alternatively, if we can figure out some way to pass
16332@code{insert-rectangle} a list of the same length each time, then we
16333can place point on the same line each time, but move it over one
16334column to the right for each new column. If we do this, however, some
16335of the entries in the list passed to @code{insert-rectangle} must be
16336blanks rather than asterisks. For example, if the maximum height of
16337the graph is 5, but the height of the column is 3, then
16338@code{insert-rectangle} requires an argument that looks like this:
16339
16340@smallexample
16341(" " " " "*" "*" "*")
16342@end smallexample
16343
16344This last proposal is not so difficult, so long as we can determine
16345the column height. There are two ways for us to specify the column
16346height: we can arbitrarily state what it will be, which would work
16347fine for graphs of that height; or we can search through the list of
16348numbers and use the maximum height of the list as the maximum height
16349of the graph. If the latter operation were difficult, then the former
16350procedure would be easiest, but there is a function built into Emacs
16351that determines the maximum of its arguments. We can use that
16352function. The function is called @code{max} and it returns the
16353largest of all its arguments, which must be numbers. Thus, for
16354example,
16355
16356@smallexample
16357(max 3 4 6 5 7 3)
16358@end smallexample
16359
16360@noindent
16361returns 7. (A corresponding function called @code{min} returns the
16362smallest of all its arguments.)
16363@findex max
16364@findex min
16365
16366However, we cannot simply call @code{max} on the @code{numbers-list};
16367the @code{max} function expects numbers as its argument, not a list of
16368numbers. Thus, the following expression,
16369
16370@smallexample
16371(max '(3 4 6 5 7 3))
16372@end smallexample
16373
16374@need 800
16375@noindent
16376produces the following error message;
16377
16378@smallexample
16379Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
16380@end smallexample
16381
16382@findex apply
16383We need a function that passes a list of arguments to a function.
16384This function is @code{apply}. This function `applies' its first
16385argument (a function) to its remaining arguments, the last of which
16386may be a list.
16387
16388@need 1250
16389For example,
16390
16391@smallexample
16392(apply 'max 3 4 7 3 '(4 8 5))
16393@end smallexample
16394
16395@noindent
16396returns 8.
16397
16398(Incidentally, I don't know how you would learn of this function
16399without a book such as this. It is possible to discover other
16400functions, like @code{search-forward} or @code{insert-rectangle}, by
16401guessing at a part of their names and then using @code{apropos}. Even
16402though its base in metaphor is clear---`apply' its first argument to
16403the rest---I doubt a novice would come up with that particular word
16404when using @code{apropos} or other aid. Of course, I could be wrong;
16405after all, the function was first named by someone who had to invent
16406it.)
16407
16408The second and subsequent arguments to @code{apply} are optional, so
16409we can use @code{apply} to call a function and pass the elements of a
16410list to it, like this, which also returns 8:
16411
16412@smallexample
16413(apply 'max '(4 8 5))
16414@end smallexample
16415
16416This latter way is how we will use @code{apply}. The
16417@code{recursive-lengths-list-many-files} function returns a numbers'
16418list to which we can apply @code{max} (we could also apply @code{max} to
16419the sorted numbers' list; it does not matter whether the list is
16420sorted or not.)
16421
16422@need 800
16423Hence, the operation for finding the maximum height of the graph is this:
16424
16425@smallexample
16426(setq max-graph-height (apply 'max numbers-list))
16427@end smallexample
16428
16429Now we can return to the question of how to create a list of strings
16430for a column of the graph. Told the maximum height of the graph
16431and the number of asterisks that should appear in the column, the
16432function should return a list of strings for the
16433@code{insert-rectangle} command to insert.
16434
16435Each column is made up of asterisks or blanks. Since the function is
16436passed the value of the height of the column and the number of
16437asterisks in the column, the number of blanks can be found by
16438subtracting the number of asterisks from the height of the column.
16439Given the number of blanks and the number of asterisks, two
16440@code{while} loops can be used to construct the list:
16441
16442@smallexample
16443@group
16444;;; @r{First version.}
16445(defun column-of-graph (max-graph-height actual-height)
16446 "Return list of strings that is one column of a graph."
16447 (let ((insert-list nil)
16448 (number-of-top-blanks
16449 (- max-graph-height actual-height)))
16450@end group
16451
16452@group
16453 ;; @r{Fill in asterisks.}
16454 (while (> actual-height 0)
16455 (setq insert-list (cons "*" insert-list))
16456 (setq actual-height (1- actual-height)))
16457@end group
16458
16459@group
16460 ;; @r{Fill in blanks.}
16461 (while (> number-of-top-blanks 0)
16462 (setq insert-list (cons " " insert-list))
16463 (setq number-of-top-blanks
16464 (1- number-of-top-blanks)))
16465@end group
16466
16467@group
16468 ;; @r{Return whole list.}
16469 insert-list))
16470@end group
16471@end smallexample
16472
16473If you install this function and then evaluate the following
16474expression you will see that it returns the list as desired:
16475
16476@smallexample
16477(column-of-graph 5 3)
16478@end smallexample
16479
16480@need 800
16481@noindent
16482returns
16483
16484@smallexample
16485(" " " " "*" "*" "*")
16486@end smallexample
16487
16488As written, @code{column-of-graph} contains a major flaw: the symbols
16489used for the blank and for the marked entries in the column are
16490`hard-coded' as a space and asterisk. This is fine for a prototype,
16491but you, or another user, may wish to use other symbols. For example,
16492in testing the graph function, you many want to use a period in place
16493of the space, to make sure the point is being repositioned properly
16494each time the @code{insert-rectangle} function is called; or you might
16495want to substitute a @samp{+} sign or other symbol for the asterisk.
16496You might even want to make a graph-column that is more than one
16497display column wide. The program should be more flexible. The way to
16498do that is to replace the blank and the asterisk with two variables
16499that we can call @code{graph-blank} and @code{graph-symbol} and define
16500those variables separately.
16501
16502Also, the documentation is not well written. These considerations
16503lead us to the second version of the function:
16504
16505@smallexample
16506@group
16507(defvar graph-symbol "*"
16508 "String used as symbol in graph, usually an asterisk.")
16509@end group
16510
16511@group
16512(defvar graph-blank " "
16513 "String used as blank in graph, usually a blank space.
16514graph-blank must be the same number of columns wide
16515as graph-symbol.")
16516@end group
16517@end smallexample
16518
16519@noindent
16520(For an explanation of @code{defvar}, see
16521@ref{defvar, , Initializing a Variable with @code{defvar}}.)
16522
16523@smallexample
16524@group
16525;;; @r{Second version.}
16526(defun column-of-graph (max-graph-height actual-height)
16527 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
16528
16529@end group
16530@group
16531The graph-symbols are contiguous entries at the end
16532of the list.
16533The list will be inserted as one column of a graph.
16534The strings are either graph-blank or graph-symbol."
16535@end group
16536
16537@group
16538 (let ((insert-list nil)
16539 (number-of-top-blanks
16540 (- max-graph-height actual-height)))
16541@end group
16542
16543@group
16544 ;; @r{Fill in @code{graph-symbols}.}
16545 (while (> actual-height 0)
16546 (setq insert-list (cons graph-symbol insert-list))
16547 (setq actual-height (1- actual-height)))
16548@end group
16549
16550@group
16551 ;; @r{Fill in @code{graph-blanks}.}
16552 (while (> number-of-top-blanks 0)
16553 (setq insert-list (cons graph-blank insert-list))
16554 (setq number-of-top-blanks
16555 (1- number-of-top-blanks)))
16556
16557 ;; @r{Return whole list.}
16558 insert-list))
16559@end group
16560@end smallexample
16561
16562If we wished, we could rewrite @code{column-of-graph} a third time to
16563provide optionally for a line graph as well as for a bar graph. This
16564would not be hard to do. One way to think of a line graph is that it
16565is no more than a bar graph in which the part of each bar that is
16566below the top is blank. To construct a column for a line graph, the
16567function first constructs a list of blanks that is one shorter than
16568the value, then it uses @code{cons} to attach a graph symbol to the
16569list; then it uses @code{cons} again to attach the `top blanks' to
16570the list.
16571
16572It is easy to see how to write such a function, but since we don't
16573need it, we will not do it. But the job could be done, and if it were
16574done, it would be done with @code{column-of-graph}. Even more
16575important, it is worth noting that few changes would have to be made
16576anywhere else. The enhancement, if we ever wish to make it, is
16577simple.
16578
16579Now, finally, we come to our first actual graph printing function.
16580This prints the body of a graph, not the labels for the vertical and
16581horizontal axes, so we can call this @code{graph-body-print}.
16582
d6adf7e7 16583@node graph-body-print
8cda6f8f
GM
16584@section The @code{graph-body-print} Function
16585@findex graph-body-print
16586
16587After our preparation in the preceding section, the
16588@code{graph-body-print} function is straightforward. The function
16589will print column after column of asterisks and blanks, using the
16590elements of a numbers' list to specify the number of asterisks in each
16591column. This is a repetitive act, which means we can use a
16592decrementing @code{while} loop or recursive function for the job. In
16593this section, we will write the definition using a @code{while} loop.
16594
16595The @code{column-of-graph} function requires the height of the graph
16596as an argument, so we should determine and record that as a local variable.
16597
16598This leads us to the following template for the @code{while} loop
16599version of this function:
16600
16601@smallexample
16602@group
16603(defun graph-body-print (numbers-list)
16604 "@var{documentation}@dots{}"
16605 (let ((height @dots{}
16606 @dots{}))
16607@end group
16608
16609@group
16610 (while numbers-list
16611 @var{insert-columns-and-reposition-point}
16612 (setq numbers-list (cdr numbers-list)))))
16613@end group
16614@end smallexample
16615
16616@noindent
16617We need to fill in the slots of the template.
16618
16619Clearly, we can use the @code{(apply 'max numbers-list)} expression to
16620determine the height of the graph.
16621
16622The @code{while} loop will cycle through the @code{numbers-list} one
16623element at a time. As it is shortened by the @code{(setq numbers-list
16624(cdr numbers-list))} expression, the @sc{car} of each instance of the
16625list is the value of the argument for @code{column-of-graph}.
16626
16627At each cycle of the @code{while} loop, the @code{insert-rectangle}
16628function inserts the list returned by @code{column-of-graph}. Since
16629the @code{insert-rectangle} function moves point to the lower right of
16630the inserted rectangle, we need to save the location of point at the
16631time the rectangle is inserted, move back to that position after the
16632rectangle is inserted, and then move horizontally to the next place
16633from which @code{insert-rectangle} is called.
16634
16635If the inserted columns are one character wide, as they will be if
16636single blanks and asterisks are used, the repositioning command is
16637simply @code{(forward-char 1)}; however, the width of a column may be
16638greater than one. This means that the repositioning command should be
16639written @code{(forward-char symbol-width)}. The @code{symbol-width}
16640itself is the length of a @code{graph-blank} and can be found using
16641the expression @code{(length graph-blank)}. The best place to bind
16642the @code{symbol-width} variable to the value of the width of graph
16643column is in the varlist of the @code{let} expression.
16644
16645@need 1250
16646These considerations lead to the following function definition:
16647
16648@smallexample
16649@group
16650(defun graph-body-print (numbers-list)
16651 "Print a bar graph of the NUMBERS-LIST.
16652The numbers-list consists of the Y-axis values."
16653
16654 (let ((height (apply 'max numbers-list))
16655 (symbol-width (length graph-blank))
16656 from-position)
16657@end group
16658
16659@group
16660 (while numbers-list
16661 (setq from-position (point))
16662 (insert-rectangle
16663 (column-of-graph height (car numbers-list)))
16664 (goto-char from-position)
16665 (forward-char symbol-width)
16666@end group
16667@group
16668 ;; @r{Draw graph column by column.}
16669 (sit-for 0)
16670 (setq numbers-list (cdr numbers-list)))
16671@end group
16672@group
16673 ;; @r{Place point for X axis labels.}
16674 (forward-line height)
16675 (insert "\n")
16676))
16677@end group
16678@end smallexample
16679
16680@noindent
16681The one unexpected expression in this function is the
16682@w{@code{(sit-for 0)}} expression in the @code{while} loop. This
16683expression makes the graph printing operation more interesting to
16684watch than it would be otherwise. The expression causes Emacs to
16685`sit' or do nothing for a zero length of time and then redraw the
16686screen. Placed here, it causes Emacs to redraw the screen column by
16687column. Without it, Emacs would not redraw the screen until the
16688function exits.
16689
16690We can test @code{graph-body-print} with a short list of numbers.
16691
16692@enumerate
16693@item
16694Install @code{graph-symbol}, @code{graph-blank},
16695@code{column-of-graph}, which are in
16696@iftex
16697@ref{Readying a Graph, , Readying a Graph},
16698@end iftex
16699@ifinfo
16700@ref{Columns of a graph},
16701@end ifinfo
16702and @code{graph-body-print}.
16703
16704@need 800
16705@item
16706Copy the following expression:
16707
16708@smallexample
16709(graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
16710@end smallexample
16711
16712@item
16713Switch to the @file{*scratch*} buffer and place the cursor where you
16714want the graph to start.
16715
16716@item
16717Type @kbd{M-:} (@code{eval-expression}).
16718
16719@item
16720Yank the @code{graph-body-print} expression into the minibuffer
16721with @kbd{C-y} (@code{yank)}.
16722
16723@item
16724Press @key{RET} to evaluate the @code{graph-body-print} expression.
16725@end enumerate
16726
16727@need 800
16728Emacs will print a graph like this:
16729
16730@smallexample
16731@group
16732 *
16733 * **
16734 * ****
16735 *** ****
16736 ********* *
16737 ************
16738 *************
16739@end group
16740@end smallexample
16741
d6adf7e7 16742@node recursive-graph-body-print
8cda6f8f
GM
16743@section The @code{recursive-graph-body-print} Function
16744@findex recursive-graph-body-print
16745
16746The @code{graph-body-print} function may also be written recursively.
16747The recursive solution is divided into two parts: an outside `wrapper'
16748that uses a @code{let} expression to determine the values of several
16749variables that need only be found once, such as the maximum height of
16750the graph, and an inside function that is called recursively to print
16751the graph.
16752
16753@need 1250
16754The `wrapper' is uncomplicated:
16755
16756@smallexample
16757@group
16758(defun recursive-graph-body-print (numbers-list)
16759 "Print a bar graph of the NUMBERS-LIST.
16760The numbers-list consists of the Y-axis values."
16761 (let ((height (apply 'max numbers-list))
16762 (symbol-width (length graph-blank))
16763 from-position)
16764 (recursive-graph-body-print-internal
16765 numbers-list
16766 height
16767 symbol-width)))
16768@end group
16769@end smallexample
16770
16771The recursive function is a little more difficult. It has four parts:
16772the `do-again-test', the printing code, the recursive call, and the
16773`next-step-expression'. The `do-again-test' is a @code{when}
16774expression that determines whether the @code{numbers-list} contains
16775any remaining elements; if it does, the function prints one column of
16776the graph using the printing code and calls itself again. The
16777function calls itself again according to the value produced by the
16778`next-step-expression' which causes the call to act on a shorter
16779version of the @code{numbers-list}.
16780
16781@smallexample
16782@group
16783(defun recursive-graph-body-print-internal
16784 (numbers-list height symbol-width)
16785 "Print a bar graph.
16786Used within recursive-graph-body-print function."
16787@end group
16788
16789@group
16790 (when numbers-list
16791 (setq from-position (point))
16792 (insert-rectangle
16793 (column-of-graph height (car numbers-list)))
16794@end group
16795@group
16796 (goto-char from-position)
16797 (forward-char symbol-width)
16798 (sit-for 0) ; @r{Draw graph column by column.}
16799 (recursive-graph-body-print-internal
16800 (cdr numbers-list) height symbol-width)))
16801@end group
16802@end smallexample
16803
16804@need 1250
16805After installation, this expression can be tested; here is a sample:
16806
16807@smallexample
16808(recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
16809@end smallexample
16810
16811@need 800
16812Here is what @code{recursive-graph-body-print} produces:
16813
16814@smallexample
16815@group
16816 *
16817 ** *
16818 **** *
16819 **** ***
16820 * *********
16821 ************
16822 *************
16823@end group
16824@end smallexample
16825
16826Either of these two functions, @code{graph-body-print} or
16827@code{recursive-graph-body-print}, create the body of a graph.
16828
d6adf7e7 16829@node Printed Axes
8cda6f8f
GM
16830@section Need for Printed Axes
16831
16832A graph needs printed axes, so you can orient yourself. For a do-once
44e97401 16833project, it may be reasonable to draw the axes by hand using Emacs's
8cda6f8f
GM
16834Picture mode; but a graph drawing function may be used more than once.
16835
16836For this reason, I have written enhancements to the basic
16837@code{print-graph-body} function that automatically print labels for
16838the horizontal and vertical axes. Since the label printing functions
16839do not contain much new material, I have placed their description in
09e80d9f 16840an appendix. @xref{Full Graph, , A Graph with Labeled Axes}.
8cda6f8f 16841
d6adf7e7 16842@node Line Graph Exercise
8cda6f8f
GM
16843@section Exercise
16844
16845Write a line graph version of the graph printing functions.
16846
d6adf7e7 16847@node Emacs Initialization
8cda6f8f
GM
16848@chapter Your @file{.emacs} File
16849@cindex @file{.emacs} file
16850@cindex Customizing your @file{.emacs} file
16851@cindex Initialization file
16852
16853``You don't have to like Emacs to like it'' -- this seemingly
16854paradoxical statement is the secret of GNU Emacs. The plain, `out of
16855the box' Emacs is a generic tool. Most people who use it, customize
16856it to suit themselves.
16857
16858GNU Emacs is mostly written in Emacs Lisp; this means that by writing
16859expressions in Emacs Lisp you can change or extend Emacs.
16860
16861@menu
16862* Default Configuration::
16863* Site-wide Init:: You can write site-wide init files.
16864* defcustom:: Emacs will write code for you.
16865* Beginning a .emacs File:: How to write a @code{.emacs file}.
16866* Text and Auto-fill:: Automatically wrap lines.
16867* Mail Aliases:: Use abbreviations for email addresses.
16868* Indent Tabs Mode:: Don't use tabs with @TeX{}
16869* Keybindings:: Create some personal keybindings.
16870* Keymaps:: More about key binding.
16871* Loading Files:: Load (i.e., evaluate) files automatically.
16872* Autoload:: Make functions available.
16873* Simple Extension:: Define a function; bind it to a key.
16874* X11 Colors:: Colors in X.
16875* Miscellaneous::
16876* Mode Line:: How to customize your mode line.
16877@end menu
16878
8cda6f8f 16879@ifnottex
d6adf7e7 16880@node Default Configuration
44e97401 16881@unnumberedsec Emacs's Default Configuration
8cda6f8f
GM
16882@end ifnottex
16883
44e97401 16884There are those who appreciate Emacs's default configuration. After
8cda6f8f
GM
16885all, Emacs starts you in C mode when you edit a C file, starts you in
16886Fortran mode when you edit a Fortran file, and starts you in
16887Fundamental mode when you edit an unadorned file. This all makes
16888sense, if you do not know who is going to use Emacs. Who knows what a
16889person hopes to do with an unadorned file? Fundamental mode is the
16890right default for such a file, just as C mode is the right default for
16891editing C code. (Enough programming languages have syntaxes
16892that enable them to share or nearly share features, so C mode is
6bd6c2fa 16893now provided by CC mode, the `C Collection'.)
8cda6f8f
GM
16894
16895But when you do know who is going to use Emacs---you,
16896yourself---then it makes sense to customize Emacs.
16897
16898For example, I seldom want Fundamental mode when I edit an
16899otherwise undistinguished file; I want Text mode. This is why I
16900customize Emacs: so it suits me.
16901
16902You can customize and extend Emacs by writing or adapting a
16903@file{~/.emacs} file. This is your personal initialization file; its
16904contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16905may also add @file{.el} to @file{~/.emacs} and call it a
16906@file{~/.emacs.el} file. In the past, you were forbidden to type the
16907extra keystrokes that the name @file{~/.emacs.el} requires, but now
16908you may. The new format is consistent with the Emacs Lisp file
16909naming conventions; the old format saves typing.}
16910
16911A @file{~/.emacs} file contains Emacs Lisp code. You can write this
44e97401 16912code yourself; or you can use Emacs's @code{customize} feature to write
8cda6f8f
GM
16913the code for you. You can combine your own expressions and
16914auto-written Customize expressions in your @file{.emacs} file.
16915
16916(I myself prefer to write my own expressions, except for those,
16917particularly fonts, that I find easier to manipulate using the
16918@code{customize} command. I combine the two methods.)
16919
16920Most of this chapter is about writing expressions yourself. It
16921describes a simple @file{.emacs} file; for more information, see
16922@ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16923@ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16924Manual}.
16925
d6adf7e7 16926@node Site-wide Init
8cda6f8f
GM
16927@section Site-wide Initialization Files
16928
16929@cindex @file{default.el} init file
16930@cindex @file{site-init.el} init file
16931@cindex @file{site-load.el} init file
16932In addition to your personal initialization file, Emacs automatically
16933loads various site-wide initialization files, if they exist. These
16934have the same form as your @file{.emacs} file, but are loaded by
16935everyone.
16936
16937Two site-wide initialization files, @file{site-load.el} and
16938@file{site-init.el}, are loaded into Emacs and then `dumped' if a
16939`dumped' version of Emacs is created, as is most common. (Dumped
16940copies of Emacs load more quickly. However, once a file is loaded and
16941dumped, a change to it does not lead to a change in Emacs unless you
16942load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16943Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16944@file{INSTALL} file.)
16945
16946Three other site-wide initialization files are loaded automatically
16947each time you start Emacs, if they exist. These are
16948@file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16949file, and @file{default.el}, and the terminal type file, which are both
16950loaded @emph{after} your @file{.emacs} file.
16951
16952Settings and definitions in your @file{.emacs} file will overwrite
16953conflicting settings and definitions in a @file{site-start.el} file,
16954if it exists; but the settings and definitions in a @file{default.el}
16955or terminal type file will overwrite those in your @file{.emacs} file.
16956(You can prevent interference from a terminal type file by setting
16957@code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16958Simple Extension}.)
16959
16960@c Rewritten to avoid overfull hbox.
16961The @file{INSTALL} file that comes in the distribution contains
16962descriptions of the @file{site-init.el} and @file{site-load.el} files.
16963
16964The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16965control loading. These files are in the @file{lisp} directory of the
16966Emacs distribution and are worth perusing.
16967
16968The @file{loaddefs.el} file contains a good many suggestions as to
16969what to put into your own @file{.emacs} file, or into a site-wide
16970initialization file.
16971
d6adf7e7 16972@node defcustom
8cda6f8f
GM
16973@section Specifying Variables using @code{defcustom}
16974@findex defcustom
16975
16976You can specify variables using @code{defcustom} so that you and
44e97401 16977others can then use Emacs's @code{customize} feature to set their
8cda6f8f
GM
16978values. (You cannot use @code{customize} to write function
16979definitions; but you can write @code{defuns} in your @file{.emacs}
16980file. Indeed, you can write any Lisp expression in your @file{.emacs}
16981file.)
16982
16983The @code{customize} feature depends on the @code{defcustom} special
16984form. Although you can use @code{defvar} or @code{setq} for variables
16985that users set, the @code{defcustom} special form is designed for the
16986job.
16987
16988You can use your knowledge of @code{defvar} for writing the
16989first three arguments for @code{defcustom}. The first argument to
16990@code{defcustom} is the name of the variable. The second argument is
16991the variable's initial value, if any; and this value is set only if
16992the value has not already been set. The third argument is the
16993documentation.
16994
16995The fourth and subsequent arguments to @code{defcustom} specify types
16996and options; these are not featured in @code{defvar}. (These
16997arguments are optional.)
16998
16999Each of these arguments consists of a keyword followed by a value.
17000Each keyword starts with the colon character @samp{:}.
17001
17002@need 1250
17003For example, the customizable user option variable
17004@code{text-mode-hook} looks like this:
17005
17006@smallexample
17007@group
17008(defcustom text-mode-hook nil
17009 "Normal hook run when entering Text mode and many related modes."
17010 :type 'hook
17011 :options '(turn-on-auto-fill flyspell-mode)
17012 :group 'data)
17013@end group
17014@end smallexample
17015
17016@noindent
17017The name of the variable is @code{text-mode-hook}; it has no default
17018value; and its documentation string tells you what it does.
17019
17020The @code{:type} keyword tells Emacs the kind of data to which
17021@code{text-mode-hook} should be set and how to display the value in a
17022Customization buffer.
17023
17024The @code{:options} keyword specifies a suggested list of values for
17025the variable. Usually, @code{:options} applies to a hook.
17026The list is only a suggestion; it is not exclusive; a person who sets
17027the variable may set it to other values; the list shown following the
17028@code{:options} keyword is intended to offer convenient choices to a
17029user.
17030
17031Finally, the @code{:group} keyword tells the Emacs Customization
17032command in which group the variable is located. This tells where to
17033find it.
17034
17035The @code{defcustom} function recognizes more than a dozen keywords.
17036For more information, see @ref{Customization, , Writing Customization
17037Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
17038
17039Consider @code{text-mode-hook} as an example.
17040
17041There are two ways to customize this variable. You can use the
17042customization command or write the appropriate expressions yourself.
17043
17044@need 800
17045Using the customization command, you can type:
17046
17047@smallexample
17048M-x customize
17049@end smallexample
17050
17051@noindent
17052and find that the group for editing files of data is called `data'.
17053Enter that group. Text Mode Hook is the first member. You can click
17054on its various options, such as @code{turn-on-auto-fill}, to set the
17055values. After you click on the button to
17056
17057@smallexample
17058Save for Future Sessions
17059@end smallexample
17060
17061@noindent
17062Emacs will write an expression into your @file{.emacs} file.
17063It will look like this:
17064
17065@smallexample
17066@group
17067(custom-set-variables
17068 ;; custom-set-variables was added by Custom.
17069 ;; If you edit it by hand, you could mess it up, so be careful.
17070 ;; Your init file should contain only one such instance.
17071 ;; If there is more than one, they won't work right.
17072 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
17073@end group
17074@end smallexample
17075
17076@noindent
17077(The @code{text-mode-hook-identify} function tells
17078@code{toggle-text-mode-auto-fill} which buffers are in Text mode.
17079It comes on automatically.)
17080
17081The @code{custom-set-variables} function works somewhat differently
17082than a @code{setq}. While I have never learned the differences, I
17083modify the @code{custom-set-variables} expressions in my @file{.emacs}
17084file by hand: I make the changes in what appears to me to be a
17085reasonable manner and have not had any problems. Others prefer to use
17086the Customization command and let Emacs do the work for them.
17087
17088Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
17089This function sets the various font faces. Over time, I have set a
17090considerable number of faces. Some of the time, I re-set them using
17091@code{customize}; other times, I simply edit the
17092@code{custom-set-faces} expression in my @file{.emacs} file itself.
17093
17094The second way to customize your @code{text-mode-hook} is to set it
17095yourself in your @file{.emacs} file using code that has nothing to do
17096with the @code{custom-set-@dots{}} functions.
17097
17098@need 800
17099When you do this, and later use @code{customize}, you will see a
17100message that says
17101
17102@smallexample
17103CHANGED outside Customize; operating on it here may be unreliable.
17104@end smallexample
17105
17106@need 800
17107This message is only a warning. If you click on the button to
17108
17109@smallexample
17110Save for Future Sessions
17111@end smallexample
17112
17113@noindent
17114Emacs will write a @code{custom-set-@dots{}} expression near the end
17115of your @file{.emacs} file that will be evaluated after your
17116hand-written expression. It will, therefore, overrule your
17117hand-written expression. No harm will be done. When you do this,
17118however, be careful to remember which expression is active; if you
17119forget, you may confuse yourself.
17120
17121So long as you remember where the values are set, you will have no
17122trouble. In any event, the values are always set in your
17123initialization file, which is usually called @file{.emacs}.
17124
17125I myself use @code{customize} for hardly anything. Mostly, I write
17126expressions myself.
17127
17128@findex defsubst
17129@findex defconst
17130Incidentally, to be more complete concerning defines: @code{defsubst}
17131defines an inline function. The syntax is just like that of
17132@code{defun}. @code{defconst} defines a symbol as a constant. The
17133intent is that neither programs nor users should ever change a value
17134set by @code{defconst}. (You can change it; the value set is a
17135variable; but please do not.)
17136
d6adf7e7 17137@node Beginning a .emacs File
8cda6f8f
GM
17138@section Beginning a @file{.emacs} File
17139@cindex @file{.emacs} file, beginning of
17140
17141When you start Emacs, it loads your @file{.emacs} file unless you tell
17142it not to by specifying @samp{-q} on the command line. (The
17143@code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
17144
17145A @file{.emacs} file contains Lisp expressions. Often, these are no
17146more than expressions to set values; sometimes they are function
17147definitions.
17148
17149@xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
17150Manual}, for a short description of initialization files.
17151
17152This chapter goes over some of the same ground, but is a walk among
17153extracts from a complete, long-used @file{.emacs} file---my own.
17154
17155The first part of the file consists of comments: reminders to myself.
17156By now, of course, I remember these things, but when I started, I did
17157not.
17158
17159@need 1200
17160@smallexample
17161@group
17162;;;; Bob's .emacs file
17163; Robert J. Chassell
17164; 26 September 1985
17165@end group
17166@end smallexample
17167
17168@noindent
17169Look at that date! I started this file a long time ago. I have been
17170adding to it ever since.
17171
17172@smallexample
17173@group
17174; Each section in this file is introduced by a
17175; line beginning with four semicolons; and each
17176; entry is introduced by a line beginning with
17177; three semicolons.
17178@end group
17179@end smallexample
17180
17181@noindent
17182This describes the usual conventions for comments in Emacs Lisp.
17183Everything on a line that follows a semicolon is a comment. Two,
17184three, and four semicolons are used as subsection and section markers.
17185(@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference Manual}, for
17186more about comments.)
17187
17188@smallexample
17189@group
17190;;;; The Help Key
17191; Control-h is the help key;
17192; after typing control-h, type a letter to
17193; indicate the subject about which you want help.
17194; For an explanation of the help facility,
17195; type control-h two times in a row.
17196@end group
17197@end smallexample
17198
17199@noindent
17200Just remember: type @kbd{C-h} two times for help.
17201
17202@smallexample
17203@group
17204; To find out about any mode, type control-h m
17205; while in that mode. For example, to find out
17206; about mail mode, enter mail mode and then type
17207; control-h m.
17208@end group
17209@end smallexample
17210
17211@noindent
17212`Mode help', as I call this, is very helpful. Usually, it tells you
17213all you need to know.
17214
17215Of course, you don't need to include comments like these in your
17216@file{.emacs} file. I included them in mine because I kept forgetting
17217about Mode help or the conventions for comments---but I was able to
17218remember to look here to remind myself.
17219
d6adf7e7 17220@node Text and Auto-fill
8cda6f8f
GM
17221@section Text and Auto Fill Mode
17222
17223Now we come to the part that `turns on' Text mode and
17224Auto Fill mode.
17225
17226@smallexample
17227@group
17228;;; Text mode and Auto Fill mode
cd61af01
SM
17229;; The next two lines put Emacs into Text mode
17230;; and Auto Fill mode, and are for writers who
17231;; want to start writing prose rather than code.
17232(setq-default major-mode 'text-mode)
8cda6f8f
GM
17233(add-hook 'text-mode-hook 'turn-on-auto-fill)
17234@end group
17235@end smallexample
17236
17237Here is the first part of this @file{.emacs} file that does something
17238besides remind a forgetful human!
17239
17240The first of the two lines in parentheses tells Emacs to turn on Text
17241mode when you find a file, @emph{unless} that file should go into some
17242other mode, such as C mode.
17243
17244@cindex Per-buffer, local variables list
17245@cindex Local variables list, per-buffer,
17246@cindex Automatic mode selection
17247@cindex Mode selection, automatic
17248When Emacs reads a file, it looks at the extension to the file name,
17249if any. (The extension is the part that comes after a @samp{.}.) If
17250the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
17251on C mode. Also, Emacs looks at first nonblank line of the file; if
17252the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
17253possesses a list of extensions and specifications that it uses
17254automatically. In addition, Emacs looks near the last page for a
17255per-buffer, ``local variables list'', if any.
17256
17257@ifinfo
17258@xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
17259Emacs Manual}.
17260
17261@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17262Manual}.
17263@end ifinfo
17264@iftex
17265See sections ``How Major Modes are Chosen'' and ``Local Variables in
17266Files'' in @cite{The GNU Emacs Manual}.
17267@end iftex
17268
17269Now, back to the @file{.emacs} file.
17270
17271@need 800
17272Here is the line again; how does it work?
17273
17274@cindex Text Mode turned on
17275@smallexample
4e3b4528 17276(setq major-mode 'text-mode)
8cda6f8f
GM
17277@end smallexample
17278
17279@noindent
17280This line is a short, but complete Emacs Lisp expression.
17281
17282We are already familiar with @code{setq}. It sets the following variable,
4e3b4528
SM
17283@code{major-mode}, to the subsequent value, which is @code{text-mode}.
17284The single quote mark before @code{text-mode} tells Emacs to deal directly
17285with the @code{text-mode} symbol, not with whatever it might stand for.
17286@xref{set & setq, , Setting the Value of a Variable},
17287for a reminder of how @code{setq} works.
17288The main point is that there is no difference between the procedure you
17289use to set a value in your @file{.emacs} file and the procedure you use
17290anywhere else in Emacs.
8cda6f8f
GM
17291
17292@need 800
17293Here is the next line:
17294
17295@cindex Auto Fill mode turned on
17296@findex add-hook
17297@smallexample
17298(add-hook 'text-mode-hook 'turn-on-auto-fill)
17299@end smallexample
17300
17301@noindent
17302In this line, the @code{add-hook} command adds
17303@code{turn-on-auto-fill} to the variable.
17304
17305@code{turn-on-auto-fill} is the name of a program, that, you guessed
17306it!, turns on Auto Fill mode.
17307
17308Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
17309onto Text mode. So every time Emacs turns on Text mode, Emacs also
17310turns on Auto Fill mode.
17311
17312In brief, the first line causes Emacs to enter Text mode when you edit a
17313file, unless the file name extension, a first non-blank line, or local
17314variables to tell Emacs otherwise.
17315
17316Text mode among other actions, sets the syntax table to work
17317conveniently for writers. In Text mode, Emacs considers an apostrophe
17318as part of a word like a letter; but Emacs does not consider a period
17319or a space as part of a word. Thus, @kbd{M-f} moves you over
17320@samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
17321the @samp{t} of @samp{it's}.
17322
17323The second line causes Emacs to turn on Auto Fill mode when it turns
17324on Text mode. In Auto Fill mode, Emacs automatically breaks a line
17325that is too wide and brings the excessively wide part of the line down
17326to the next line. Emacs breaks lines between words, not within them.
17327
17328When Auto Fill mode is turned off, lines continue to the right as you
17329type them. Depending on how you set the value of
17330@code{truncate-lines}, the words you type either disappear off the
17331right side of the screen, or else are shown, in a rather ugly and
17332unreadable manner, as a continuation line on the screen.
17333
17334@need 1250
17335In addition, in this part of my @file{.emacs} file, I tell the Emacs
17336fill commands to insert two spaces after a colon:
17337
17338@smallexample
17339(setq colon-double-space t)
17340@end smallexample
17341
d6adf7e7 17342@node Mail Aliases
8cda6f8f
GM
17343@section Mail Aliases
17344
17345Here is a @code{setq} that `turns on' mail aliases, along with more
17346reminders.
17347
17348@smallexample
17349@group
17350;;; Mail mode
17351; To enter mail mode, type `C-x m'
17352; To enter RMAIL (for reading mail),
17353; type `M-x rmail'
17354(setq mail-aliases t)
17355@end group
17356@end smallexample
17357
17358@cindex Mail aliases
17359@noindent
17360This @code{setq} command sets the value of the variable
17361@code{mail-aliases} to @code{t}. Since @code{t} means true, the line
17362says, in effect, ``Yes, use mail aliases.''
17363
17364Mail aliases are convenient short names for long email addresses or
17365for lists of email addresses. The file where you keep your `aliases'
17366is @file{~/.mailrc}. You write an alias like this:
17367
17368@smallexample
17369alias geo george@@foobar.wiz.edu
17370@end smallexample
17371
17372@noindent
17373When you write a message to George, address it to @samp{geo}; the
17374mailer will automatically expand @samp{geo} to the full address.
17375
d6adf7e7 17376@node Indent Tabs Mode
8cda6f8f
GM
17377@section Indent Tabs Mode
17378@cindex Tabs, preventing
17379@findex indent-tabs-mode
17380
17381By default, Emacs inserts tabs in place of multiple spaces when it
17382formats a region. (For example, you might indent many lines of text
17383all at once with the @code{indent-region} command.) Tabs look fine on
17384a terminal or with ordinary printing, but they produce badly indented
17385output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
17386
17387@need 1250
17388The following turns off Indent Tabs mode:
17389
17390@smallexample
17391@group
17392;;; Prevent Extraneous Tabs
17393(setq-default indent-tabs-mode nil)
17394@end group
17395@end smallexample
17396
17397Note that this line uses @code{setq-default} rather than the
17398@code{setq} command that we have seen before. The @code{setq-default}
17399command sets values only in buffers that do not have their own local
17400values for the variable.
17401
17402@ifinfo
17403@xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
17404
17405@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
17406Manual}.
17407@end ifinfo
17408@iftex
17409See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
17410Files'' in @cite{The GNU Emacs Manual}.
17411@end iftex
17412
17413@need 1700
d6adf7e7 17414@node Keybindings
8cda6f8f
GM
17415@section Some Keybindings
17416
17417Now for some personal keybindings:
17418
17419@smallexample
17420@group
17421;;; Compare windows
17422(global-set-key "\C-cw" 'compare-windows)
17423@end group
17424@end smallexample
17425
17426@findex compare-windows
17427@code{compare-windows} is a nifty command that compares the text in
17428your current window with text in the next window. It makes the
17429comparison by starting at point in each window, moving over text in
17430each window as far as they match. I use this command all the time.
17431
17432This also shows how to set a key globally, for all modes.
17433
17434@cindex Setting a key globally
17435@cindex Global set key
17436@cindex Key setting globally
17437@findex global-set-key
17438The command is @code{global-set-key}. It is followed by the
17439keybinding. In a @file{.emacs} file, the keybinding is written as
17440shown: @code{\C-c} stands for `control-c', which means `press the
17441control key and the @key{c} key at the same time'. The @code{w} means
17442`press the @key{w} key'. The keybinding is surrounded by double
17443quotation marks. In documentation, you would write this as
17444@w{@kbd{C-c w}}. (If you were binding a @key{META} key, such as
17445@kbd{M-c}, rather than a @key{CTRL} key, you would write
17446@w{@code{\M-c}} in your @file{.emacs} file. @xref{Init Rebinding, ,
17447Rebinding Keys in Your Init File, emacs, The GNU Emacs Manual}, for
17448details.)
17449
17450The command invoked by the keys is @code{compare-windows}. Note that
17451@code{compare-windows} is preceded by a single quote; otherwise, Emacs
17452would first try to evaluate the symbol to determine its value.
17453
17454These three things, the double quotation marks, the backslash before
17455the @samp{C}, and the single quote mark are necessary parts of
17456keybinding that I tend to forget. Fortunately, I have come to
17457remember that I should look at my existing @file{.emacs} file, and
17458adapt what is there.
17459
17460As for the keybinding itself: @kbd{C-c w}. This combines the prefix
17461key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
17462set of keys, @kbd{C-c} followed by a single character, is strictly
17463reserved for individuals' own use. (I call these `own' keys, since
17464these are for my own use.) You should always be able to create such a
17465keybinding for your own use without stomping on someone else's
17466keybinding. If you ever write an extension to Emacs, please avoid
17467taking any of these keys for public use. Create a key like @kbd{C-c
17468C-w} instead. Otherwise, we will run out of `own' keys.
17469
17470@need 1250
17471Here is another keybinding, with a comment:
17472
17473@smallexample
17474@group
17475;;; Keybinding for `occur'
17476; I use occur a lot, so let's bind it to a key:
17477(global-set-key "\C-co" 'occur)
17478@end group
17479@end smallexample
17480
17481@findex occur
17482The @code{occur} command shows all the lines in the current buffer
17483that contain a match for a regular expression. Matching lines are
17484shown in a buffer called @file{*Occur*}. That buffer serves as a menu
17485to jump to occurrences.
17486
17487@findex global-unset-key
17488@cindex Unbinding key
17489@cindex Key unbinding
17490@need 1250
17491Here is how to unbind a key, so it does not
17492work:
17493
17494@smallexample
17495@group
17496;;; Unbind `C-x f'
17497(global-unset-key "\C-xf")
17498@end group
17499@end smallexample
17500
17501There is a reason for this unbinding: I found I inadvertently typed
17502@w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
17503file, as I intended, I accidentally set the width for filled text,
17504almost always to a width I did not want. Since I hardly ever reset my
17505default width, I simply unbound the key.
17506
17507@findex list-buffers, @r{rebound}
17508@findex buffer-menu, @r{bound to key}
17509@need 1250
17510The following rebinds an existing key:
17511
17512@smallexample
17513@group
17514;;; Rebind `C-x C-b' for `buffer-menu'
17515(global-set-key "\C-x\C-b" 'buffer-menu)
17516@end group
17517@end smallexample
17518
17519By default, @kbd{C-x C-b} runs the
17520@code{list-buffers} command. This command lists
17521your buffers in @emph{another} window. Since I
17522almost always want to do something in that
17523window, I prefer the @code{buffer-menu}
17524command, which not only lists the buffers,
17525but moves point into that window.
17526
d6adf7e7 17527@node Keymaps
8cda6f8f
GM
17528@section Keymaps
17529@cindex Keymaps
17530@cindex Rebinding keys
17531
17532Emacs uses @dfn{keymaps} to record which keys call which commands.
17533When you use @code{global-set-key} to set the keybinding for a single
17534command in all parts of Emacs, you are specifying the keybinding in
17535@code{current-global-map}.
17536
17537Specific modes, such as C mode or Text mode, have their own keymaps;
17538the mode-specific keymaps override the global map that is shared by
17539all buffers.
17540
17541The @code{global-set-key} function binds, or rebinds, the global
17542keymap. For example, the following binds the key @kbd{C-x C-b} to the
17543function @code{buffer-menu}:
17544
17545@smallexample
17546(global-set-key "\C-x\C-b" 'buffer-menu)
17547@end smallexample
17548
17549Mode-specific keymaps are bound using the @code{define-key} function,
17550which takes a specific keymap as an argument, as well as the key and
17551the command. For example, my @file{.emacs} file contains the
17552following expression to bind the @code{texinfo-insert-@@group} command
17553to @kbd{C-c C-c g}:
17554
17555@smallexample
17556@group
17557(define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
17558@end group
17559@end smallexample
17560
17561@noindent
17562The @code{texinfo-insert-@@group} function itself is a little extension
17563to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
17564use this command all the time and prefer to type the three strokes
17565@kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
17566(@samp{@@group} and its matching @samp{@@end group} are commands that
17567keep all enclosed text together on one page; many multi-line examples
17568in this book are surrounded by @samp{@@group @dots{} @@end group}.)
17569
17570@need 1250
17571Here is the @code{texinfo-insert-@@group} function definition:
17572
17573@smallexample
17574@group
17575(defun texinfo-insert-@@group ()
17576 "Insert the string @@group in a Texinfo buffer."
17577 (interactive)
17578 (beginning-of-line)
17579 (insert "@@group\n"))
17580@end group
17581@end smallexample
17582
17583(Of course, I could have used Abbrev mode to save typing, rather than
17584write a function to insert a word; but I prefer key strokes consistent
17585with other Texinfo mode key bindings.)
17586
17587You will see numerous @code{define-key} expressions in
17588@file{loaddefs.el} as well as in the various mode libraries, such as
17589@file{cc-mode.el} and @file{lisp-mode.el}.
17590
17591@xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
17592Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
17593Reference Manual}, for more information about keymaps.
17594
d6adf7e7 17595@node Loading Files
8cda6f8f
GM
17596@section Loading Files
17597@cindex Loading files
17598@c findex load
17599
17600Many people in the GNU Emacs community have written extensions to
17601Emacs. As time goes by, these extensions are often included in new
17602releases. For example, the Calendar and Diary packages are now part
17603of the standard GNU Emacs, as is Calc.
17604
17605You can use a @code{load} command to evaluate a complete file and
17606thereby install all the functions and variables in the file into Emacs.
17607For example:
17608
17609@c (auto-compression-mode t)
17610
17611@smallexample
17612(load "~/emacs/slowsplit")
17613@end smallexample
17614
1df7defd 17615This evaluates, i.e., loads, the @file{slowsplit.el} file or if it
8cda6f8f
GM
17616exists, the faster, byte compiled @file{slowsplit.elc} file from the
17617@file{emacs} sub-directory of your home directory. The file contains
17618the function @code{split-window-quietly}, which John Robinson wrote in
176191989.
17620
17621The @code{split-window-quietly} function splits a window with the
17622minimum of redisplay. I installed it in 1989 because it worked well
17623with the slow 1200 baud terminals I was then using. Nowadays, I only
17624occasionally come across such a slow connection, but I continue to use
17625the function because I like the way it leaves the bottom half of a
17626buffer in the lower of the new windows and the top half in the upper
17627window.
17628
17629@need 1250
17630To replace the key binding for the default
17631@code{split-window-vertically}, you must also unset that key and bind
17632the keys to @code{split-window-quietly}, like this:
17633
17634@smallexample
17635@group
17636(global-unset-key "\C-x2")
17637(global-set-key "\C-x2" 'split-window-quietly)
17638@end group
17639@end smallexample
17640
17641@vindex load-path
17642If you load many extensions, as I do, then instead of specifying the
17643exact location of the extension file, as shown above, you can specify
44e97401 17644that directory as part of Emacs's @code{load-path}. Then, when Emacs
8cda6f8f
GM
17645loads a file, it will search that directory as well as its default
17646list of directories. (The default list is specified in @file{paths.h}
17647when Emacs is built.)
17648
17649@need 1250
17650The following command adds your @file{~/emacs} directory to the
17651existing load path:
17652
17653@smallexample
17654@group
17655;;; Emacs Load Path
17656(setq load-path (cons "~/emacs" load-path))
17657@end group
17658@end smallexample
17659
17660Incidentally, @code{load-library} is an interactive interface to the
17661@code{load} function. The complete function looks like this:
17662
17663@findex load-library
17664@smallexample
17665@group
17666(defun load-library (library)
17667 "Load the library named LIBRARY.
17668This is an interface to the function `load'."
17669 (interactive
17670 (list (completing-read "Load library: "
e0e10d9d 17671 (apply-partially 'locate-file-completion-table
f51f97dd
SM
17672 load-path
17673 (get-load-suffixes)))))
8cda6f8f
GM
17674 (load library))
17675@end group
17676@end smallexample
17677
17678The name of the function, @code{load-library}, comes from the use of
17679`library' as a conventional synonym for `file'. The source for the
17680@code{load-library} command is in the @file{files.el} library.
17681
17682Another interactive command that does a slightly different job is
17683@code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
17684Emacs, emacs, The GNU Emacs Manual}, for information on the
17685distinction between @code{load-library} and this command.
17686
d6adf7e7 17687@node Autoload
8cda6f8f
GM
17688@section Autoloading
17689@findex autoload
17690
17691Instead of installing a function by loading the file that contains it,
17692or by evaluating the function definition, you can make the function
17693available but not actually install it until it is first called. This
17694is called @dfn{autoloading}.
17695
17696When you execute an autoloaded function, Emacs automatically evaluates
17697the file that contains the definition, and then calls the function.
17698
17699Emacs starts quicker with autoloaded functions, since their libraries
17700are not loaded right away; but you need to wait a moment when you
17701first use such a function, while its containing file is evaluated.
17702
17703Rarely used functions are frequently autoloaded. The
17704@file{loaddefs.el} library contains hundreds of autoloaded functions,
17705from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
17706come to use a `rare' function frequently. When you do, you should
17707load that function's file with a @code{load} expression in your
17708@file{.emacs} file.
17709
17710In my @file{.emacs} file, I load 14 libraries that contain functions
17711that would otherwise be autoloaded. (Actually, it would have been
17712better to include these files in my `dumped' Emacs, but I forgot.
17713@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17714Reference Manual}, and the @file{INSTALL} file for more about
17715dumping.)
17716
17717You may also want to include autoloaded expressions in your @file{.emacs}
17718file. @code{autoload} is a built-in function that takes up to five
17719arguments, the final three of which are optional. The first argument
17720is the name of the function to be autoloaded; the second is the name
17721of the file to be loaded. The third argument is documentation for the
17722function, and the fourth tells whether the function can be called
17723interactively. The fifth argument tells what type of
17724object---@code{autoload} can handle a keymap or macro as well as a
17725function (the default is a function).
17726
17727@need 800
17728Here is a typical example:
17729
17730@smallexample
17731@group
17732(autoload 'html-helper-mode
17733 "html-helper-mode" "Edit HTML documents" t)
17734@end group
17735@end smallexample
17736
17737@noindent
17738(@code{html-helper-mode} is an older alternative to @code{html-mode},
17739which is a standard part of the distribution.)
17740
17741@noindent
17742This expression autoloads the @code{html-helper-mode} function. It
17743takes it from the @file{html-helper-mode.el} file (or from the byte
a9097c6d
KB
17744compiled version @file{html-helper-mode.elc}, if that exists.) The
17745file must be located in a directory specified by @code{load-path}.
17746The documentation says that this is a mode to help you edit documents
8cda6f8f
GM
17747written in the HyperText Markup Language. You can call this mode
17748interactively by typing @kbd{M-x html-helper-mode}. (You need to
17749duplicate the function's regular documentation in the autoload
17750expression because the regular function is not yet loaded, so its
17751documentation is not available.)
17752
17753@xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
17754Manual}, for more information.
17755
d6adf7e7 17756@node Simple Extension
8cda6f8f
GM
17757@section A Simple Extension: @code{line-to-top-of-window}
17758@findex line-to-top-of-window
17759@cindex Simple extension in @file{.emacs} file
17760
17761Here is a simple extension to Emacs that moves the line point is on to
17762the top of the window. I use this all the time, to make text easier
17763to read.
17764
17765You can put the following code into a separate file and then load it
17766from your @file{.emacs} file, or you can include it within your
17767@file{.emacs} file.
17768
17769@need 1250
17770Here is the definition:
17771
17772@smallexample
17773@group
17774;;; Line to top of window;
17775;;; replace three keystroke sequence C-u 0 C-l
17776(defun line-to-top-of-window ()
17777 "Move the line point is on to top of window."
17778 (interactive)
17779 (recenter 0))
17780@end group
17781@end smallexample
17782
17783@need 1250
17784Now for the keybinding.
17785
17786Nowadays, function keys as well as mouse button events and
17787non-@sc{ascii} characters are written within square brackets, without
17788quotation marks. (In Emacs version 18 and before, you had to write
17789different function key bindings for each different make of terminal.)
17790
17791I bind @code{line-to-top-of-window} to my @key{F6} function key like
17792this:
17793
17794@smallexample
17795(global-set-key [f6] 'line-to-top-of-window)
17796@end smallexample
17797
17798For more information, see @ref{Init Rebinding, , Rebinding Keys in
17799Your Init File, emacs, The GNU Emacs Manual}.
17800
17801@cindex Conditional 'twixt two versions of Emacs
17802@cindex Version of Emacs, choosing
17803@cindex Emacs version, choosing
6dd28193 17804If you run two versions of GNU Emacs, such as versions 22 and 23, and
8cda6f8f
GM
17805use one @file{.emacs} file, you can select which code to evaluate with
17806the following conditional:
17807
17808@smallexample
17809@group
17810(cond
6dd28193 17811 ((= 22 emacs-major-version)
8cda6f8f 17812 ;; evaluate version 22 code
6dd28193
CY
17813 ( @dots{} ))
17814 ((= 23 emacs-major-version)
17815 ;; evaluate version 23 code
8cda6f8f
GM
17816 ( @dots{} )))
17817@end group
17818@end smallexample
17819
8f4ea8e0 17820For example, recent versions blink
8cda6f8f
GM
17821their cursors by default. I hate such blinking, as well as other
17822features, so I placed the following in my @file{.emacs}
17823file@footnote{When I start instances of Emacs that do not load my
17824@file{.emacs} file or any site file, I also turn off blinking:
17825
17826@smallexample
17827emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
17828
17829@exdent Or nowadays, using an even more sophisticated set of options,
17830
17831emacs -Q - D
17832@end smallexample
17833}:
17834
17835@smallexample
17836@group
6dd28193
CY
17837(when (>= emacs-major-version 21)
17838 (blink-cursor-mode 0)
17839 ;; Insert newline when you press `C-n' (next-line)
17840 ;; at the end of the buffer
17841 (setq next-line-add-newlines t)
8cda6f8f
GM
17842@end group
17843@group
6dd28193
CY
17844 ;; Turn on image viewing
17845 (auto-image-file-mode t)
8cda6f8f
GM
17846@end group
17847@group
6dd28193
CY
17848 ;; Turn on menu bar (this bar has text)
17849 ;; (Use numeric argument to turn on)
17850 (menu-bar-mode 1)
8cda6f8f
GM
17851@end group
17852@group
6dd28193
CY
17853 ;; Turn off tool bar (this bar has icons)
17854 ;; (Use numeric argument to turn on)
17855 (tool-bar-mode nil)
8cda6f8f 17856@end group
8cda6f8f 17857@group
6dd28193
CY
17858 ;; Turn off tooltip mode for tool bar
17859 ;; (This mode causes icon explanations to pop up)
17860 ;; (Use numeric argument to turn on)
17861 (tooltip-mode nil)
17862 ;; If tooltips turned on, make tips appear promptly
17863 (setq tooltip-delay 0.1) ; default is 0.7 second
17864 )
8cda6f8f
GM
17865@end group
17866@end smallexample
17867
d6adf7e7 17868@node X11 Colors
8cda6f8f
GM
17869@section X11 Colors
17870
17871You can specify colors when you use Emacs with the MIT X Windowing
17872system.
17873
17874I dislike the default colors and specify my own.
17875
17876@need 1250
17877Here are the expressions in my @file{.emacs}
17878file that set values:
17879
17880@smallexample
17881@group
17882;; Set cursor color
17883(set-cursor-color "white")
17884
17885;; Set mouse color
17886(set-mouse-color "white")
17887
17888;; Set foreground and background
17889(set-foreground-color "white")
17890(set-background-color "darkblue")
17891@end group
17892
17893@group
17894;;; Set highlighting colors for isearch and drag
17895(set-face-foreground 'highlight "white")
17896(set-face-background 'highlight "blue")
17897@end group
17898
17899@group
17900(set-face-foreground 'region "cyan")
17901(set-face-background 'region "blue")
17902@end group
17903
17904@group
17905(set-face-foreground 'secondary-selection "skyblue")
17906(set-face-background 'secondary-selection "darkblue")
17907@end group
17908
17909@group
17910;; Set calendar highlighting colors
17911(setq calendar-load-hook
d1069532
SM
17912 (lambda ()
17913 (set-face-foreground 'diary-face "skyblue")
17914 (set-face-background 'holiday-face "slate blue")
17915 (set-face-foreground 'holiday-face "white")))
8cda6f8f
GM
17916@end group
17917@end smallexample
17918
17919The various shades of blue soothe my eye and prevent me from seeing
17920the screen flicker.
17921
17922Alternatively, I could have set my specifications in various X
17923initialization files. For example, I could set the foreground,
17924background, cursor, and pointer (i.e., mouse) colors in my
17925@file{~/.Xresources} file like this:
17926
17927@smallexample
17928@group
17929Emacs*foreground: white
17930Emacs*background: darkblue
17931Emacs*cursorColor: white
17932Emacs*pointerColor: white
17933@end group
17934@end smallexample
17935
17936In any event, since it is not part of Emacs, I set the root color of
17937my X window in my @file{~/.xinitrc} file, like this@footnote{I also
17938run more modern window managers, such as Enlightenment, Gnome, or KDE;
17939in those cases, I often specify an image rather than a plain color.}:
17940
17941@smallexample
17942xsetroot -solid Navy -fg white &
17943@end smallexample
17944
17945@need 1700
d6adf7e7 17946@node Miscellaneous
8cda6f8f
GM
17947@section Miscellaneous Settings for a @file{.emacs} File
17948
17949@need 1250
17950Here are a few miscellaneous settings:
17951@sp 1
17952
17953@itemize @minus
17954@item
17955Set the shape and color of the mouse cursor:
17956
17957@smallexample
17958@group
17959; Cursor shapes are defined in
17960; `/usr/include/X11/cursorfont.h';
17961; for example, the `target' cursor is number 128;
17962; the `top_left_arrow' cursor is number 132.
17963@end group
17964
17965@group
17966(let ((mpointer (x-get-resource "*mpointer"
17967 "*emacs*mpointer")))
17968 ;; If you have not set your mouse pointer
17969 ;; then set it, otherwise leave as is:
17970 (if (eq mpointer nil)
17971 (setq mpointer "132")) ; top_left_arrow
17972@end group
17973@group
17974 (setq x-pointer-shape (string-to-int mpointer))
17975 (set-mouse-color "white"))
17976@end group
17977@end smallexample
17978
17979@item
17980Or you can set the values of a variety of features in an alist, like
17981this:
17982
17983@smallexample
17984@group
17985(setq-default
17986 default-frame-alist
17987 '((cursor-color . "white")
17988 (mouse-color . "white")
17989 (foreground-color . "white")
17990 (background-color . "DodgerBlue4")
17991 ;; (cursor-type . bar)
17992 (cursor-type . box)
17993@end group
17994@group
17995 (tool-bar-lines . 0)
17996 (menu-bar-lines . 1)
17997 (width . 80)
17998 (height . 58)
17999 (font .
18000 "-Misc-Fixed-Medium-R-Normal--20-200-75-75-C-100-ISO8859-1")
18001 ))
18002@end group
18003@end smallexample
18004
18005@item
18006Convert @kbd{@key{CTRL}-h} into @key{DEL} and @key{DEL}
18007into @kbd{@key{CTRL}-h}.@*
18008(Some older keyboards needed this, although I have not seen the
18009problem recently.)
18010
18011@smallexample
18012@group
18013;; Translate `C-h' to <DEL>.
18014; (keyboard-translate ?\C-h ?\C-?)
18015
18016;; Translate <DEL> to `C-h'.
18017(keyboard-translate ?\C-? ?\C-h)
18018@end group
18019@end smallexample
18020
18021@item Turn off a blinking cursor!
18022
18023@smallexample
18024@group
18025(if (fboundp 'blink-cursor-mode)
18026 (blink-cursor-mode -1))
18027@end group
18028@end smallexample
18029
18030@noindent
18031or start GNU Emacs with the command @code{emacs -nbc}.
18032
18033@need 1250
18034@item When using `grep'@*
18035@samp{-i}@w{ } Ignore case distinctions@*
18036@samp{-n}@w{ } Prefix each line of output with line number@*
18037@samp{-H}@w{ } Print the filename for each match.@*
18038@samp{-e}@w{ } Protect patterns beginning with a hyphen character, @samp{-}
18039
18040@smallexample
18041(setq grep-command "grep -i -nH -e ")
18042@end smallexample
18043
18044@ignore
18045@c Evidently, no longer needed in GNU Emacs 22
18046
18047item Automatically uncompress compressed files when visiting them
18048
18049smallexample
18050(load "uncompress")
18051end smallexample
18052
18053@end ignore
18054
18055@item Find an existing buffer, even if it has a different name@*
18056This avoids problems with symbolic links.
18057
18058@smallexample
18059(setq find-file-existing-other-name t)
18060@end smallexample
18061
18062@item Set your language environment and default input method
18063
18064@smallexample
18065@group
18066(set-language-environment "latin-1")
18067;; Remember you can enable or disable multilingual text input
18068;; with the @code{toggle-input-method'} (@kbd{C-\}) command
18069(setq default-input-method "latin-1-prefix")
18070@end group
18071@end smallexample
18072
18073If you want to write with Chinese `GB' characters, set this instead:
18074
18075@smallexample
18076@group
18077(set-language-environment "Chinese-GB")
18078(setq default-input-method "chinese-tonepy")
18079@end group
18080@end smallexample
18081@end itemize
18082
18083@subsubheading Fixing Unpleasant Key Bindings
18084@cindex Key bindings, fixing
18085@cindex Bindings, key, fixing unpleasant
18086
18087Some systems bind keys unpleasantly. Sometimes, for example, the
18088@key{CTRL} key appears in an awkward spot rather than at the far left
18089of the home row.
18090
18091Usually, when people fix these sorts of keybindings, they do not
18092change their @file{~/.emacs} file. Instead, they bind the proper keys
18093on their consoles with the @code{loadkeys} or @code{install-keymap}
18094commands in their boot script and then include @code{xmodmap} commands
18095in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
18096
18097@need 1250
18098@noindent
18099For a boot script:
18100
18101@smallexample
18102@group
18103loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
18104@exdent or
18105install-keymap emacs2
18106@end group
18107@end smallexample
18108
18109@need 1250
18110@noindent
18111For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
18112Lock} key is at the far left of the home row:
18113
18114@smallexample
18115@group
18116# Bind the key labeled `Caps Lock' to `Control'
18117# (Such a broken user interface suggests that keyboard manufacturers
18118# think that computers are typewriters from 1885.)
18119
18120xmodmap -e "clear Lock"
18121xmodmap -e "add Control = Caps_Lock"
18122@end group
18123@end smallexample
18124
18125@need 1250
18126@noindent
18127In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
18128key to a @key{META} key:
18129
18130@smallexample
18131@group
18132# Some ill designed keyboards have a key labeled ALT and no Meta
18133xmodmap -e "keysym Alt_L = Meta_L Alt_L"
18134@end group
18135@end smallexample
18136
18137@need 1700
d6adf7e7 18138@node Mode Line
8cda6f8f 18139@section A Modified Mode Line
cd61af01 18140@vindex mode-line-format
8cda6f8f
GM
18141@cindex Mode line format
18142
18143Finally, a feature I really like: a modified mode line.
18144
18145When I work over a network, I forget which machine I am using. Also,
18146I tend to I lose track of where I am, and which line point is on.
18147
18148So I reset my mode line to look like this:
18149
18150@smallexample
18151-:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
18152@end smallexample
18153
18154I am visiting a file called @file{foo.texi}, on my machine
18155@file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
18156Texinfo mode, and am at the top of the buffer.
18157
18158@need 1200
18159My @file{.emacs} file has a section that looks like this:
18160
18161@smallexample
18162@group
18163;; Set a Mode Line that tells me which machine, which directory,
18164;; and which line I am on, plus the other customary information.
cd61af01 18165(setq-default mode-line-format
8cda6f8f
GM
18166 (quote
18167 (#("-" 0 1
18168 (help-echo
18169 "mouse-1: select window, mouse-2: delete others ..."))
18170 mode-line-mule-info
18171 mode-line-modified
18172 mode-line-frame-identification
18173 " "
18174@end group
18175@group
18176 mode-line-buffer-identification
18177 " "
18178 (:eval (substring
18179 (system-name) 0 (string-match "\\..+" (system-name))))
18180 ":"
18181 default-directory
18182 #(" " 0 1
18183 (help-echo
18184 "mouse-1: select window, mouse-2: delete others ..."))
18185 (line-number-mode " Line %l ")
18186 global-mode-string
18187@end group
18188@group
18189 #(" %[(" 0 6
18190 (help-echo
18191 "mouse-1: select window, mouse-2: delete others ..."))
18192 (:eval (mode-line-mode-name))
18193 mode-line-process
18194 minor-mode-alist
18195 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
18196 ")%] "
18197 (-3 . "%P")
18198 ;; "-%-"
18199 )))
18200@end group
18201@end smallexample
18202
18203@noindent
18204Here, I redefine the default mode line. Most of the parts are from
18205the original; but I make a few changes. I set the @emph{default} mode
18206line format so as to permit various modes, such as Info, to override
18207it.
18208
18209Many elements in the list are self-explanatory:
18210@code{mode-line-modified} is a variable that tells whether the buffer
18211has been modified, @code{mode-name} tells the name of the mode, and so
18212on. However, the format looks complicated because of two features we
18213have not discussed.
18214
18215@cindex Properties, in mode line example
18216The first string in the mode line is a dash or hyphen, @samp{-}. In
18217the old days, it would have been specified simply as @code{"-"}. But
18218nowadays, Emacs can add properties to a string, such as highlighting
18219or, as in this case, a help feature. If you place your mouse cursor
18220over the hyphen, some help information appears (By default, you must
18221wait seven-tenths of a second before the information appears. You can
18222change that timing by changing the value of @code{tooltip-delay}.)
18223
18224@need 1000
18225The new string format has a special syntax:
18226
18227@smallexample
18228#("-" 0 1 (help-echo "mouse-1: select window, ..."))
18229@end smallexample
18230
18231@noindent
18232The @code{#(} begins a list. The first element of the list is the
18233string itself, just one @samp{-}. The second and third
18234elements specify the range over which the fourth element applies. A
18235range starts @emph{after} a character, so a zero means the range
18236starts just before the first character; a 1 means that the range ends
18237just after the first character. The third element is the property for
18238the range. It consists of a property list, a
18239property name, in this case, @samp{help-echo}, followed by a value, in this
18240case, a string. The second, third, and fourth elements of this new
18241string format can be repeated.
18242
18243@xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
18244Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
18245elisp, The GNU Emacs Lisp Reference Manual}, for more information.
18246
18247@code{mode-line-buffer-identification}
18248displays the current buffer name. It is a list
18249beginning @code{(#("%12b" 0 4 @dots{}}.
18250The @code{#(} begins the list.
18251
18252The @samp{"%12b"} displays the current buffer name, using the
18253@code{buffer-name} function with which we are familiar; the `12'
18254specifies the maximum number of characters that will be displayed.
18255When a name has fewer characters, whitespace is added to fill out to
18256this number. (Buffer names can and often should be longer than 12
18257characters; this length works well in a typical 80 column wide
18258window.)
18259
18260@code{:eval} says to evaluate the following form and use the result as
18261a string to display. In this case, the expression displays the first
18262component of the full system name. The end of the first component is
18263a @samp{.} (`period'), so I use the @code{string-match} function to
18264tell me the length of the first component. The substring from the
18265zeroth character to that length is the name of the machine.
18266
18267@need 1250
18268This is the expression:
18269
18270@smallexample
18271@group
18272(:eval (substring
18273 (system-name) 0 (string-match "\\..+" (system-name))))
18274@end group
18275@end smallexample
18276
18277@samp{%[} and @samp{%]} cause a pair of square brackets
18278to appear for each recursive editing level. @samp{%n} says `Narrow'
18279when narrowing is in effect. @samp{%P} tells you the percentage of
18280the buffer that is above the bottom of the window, or `Top', `Bottom',
18281or `All'. (A lower case @samp{p} tell you the percentage above the
18282@emph{top} of the window.) @samp{%-} inserts enough dashes to fill
18283out the line.
18284
18285Remember, ``You don't have to like Emacs to like it'' --- your own
18286Emacs can have different colors, different commands, and different
18287keys than a default Emacs.
18288
18289On the other hand, if you want to bring up a plain `out of the box'
18290Emacs, with no customization, type:
18291
18292@smallexample
18293emacs -q
18294@end smallexample
18295
18296@noindent
18297This will start an Emacs that does @emph{not} load your
18298@file{~/.emacs} initialization file. A plain, default Emacs. Nothing
18299more.
18300
d6adf7e7 18301@node Debugging
8cda6f8f
GM
18302@chapter Debugging
18303@cindex debugging
18304
18305GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
18306first is built into the internals of Emacs and is always with you;
18307the second requires that you instrument a function before you can use it.
18308
18309Both debuggers are described extensively in @ref{Debugging, ,
18310Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
18311In this chapter, I will walk through a short example of each.
18312
18313@menu
18314* debug:: How to use the built-in debugger.
18315* debug-on-entry:: Start debugging when you call a function.
18316* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
18317* edebug:: How to use Edebug, a source level debugger.
18318* Debugging Exercises::
18319@end menu
18320
d6adf7e7 18321@node debug
8cda6f8f
GM
18322@section @code{debug}
18323@findex debug
18324
18325Suppose you have written a function definition that is intended to
18326return the sum of the numbers 1 through a given number. (This is the
18327@code{triangle} function discussed earlier. @xref{Decrementing
18328Example, , Example with Decrementing Counter}, for a discussion.)
18329@c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
18330
18331However, your function definition has a bug. You have mistyped
18332@samp{1=} for @samp{1-}. Here is the broken definition:
18333
18334@findex triangle-bugged
18335@smallexample
18336@group
18337(defun triangle-bugged (number)
18338 "Return sum of numbers 1 through NUMBER inclusive."
18339 (let ((total 0))
18340 (while (> number 0)
18341 (setq total (+ total number))
18342 (setq number (1= number))) ; @r{Error here.}
18343 total))
18344@end group
18345@end smallexample
18346
18347If you are reading this in Info, you can evaluate this definition in
18348the normal fashion. You will see @code{triangle-bugged} appear in the
18349echo area.
18350
18351@need 1250
18352Now evaluate the @code{triangle-bugged} function with an
18353argument of 4:
18354
18355@smallexample
18356(triangle-bugged 4)
18357@end smallexample
18358
18359@noindent
18360In a recent GNU Emacs, you will create and enter a @file{*Backtrace*}
18361buffer that says:
18362
18363@noindent
18364@smallexample
18365@group
18366---------- Buffer: *Backtrace* ----------
18367Debugger entered--Lisp error: (void-function 1=)
18368 (1= number)
18369 (setq number (1= number))
18370 (while (> number 0) (setq total (+ total number))
18371 (setq number (1= number)))
18372 (let ((total 0)) (while (> number 0) (setq total ...)
18373 (setq number ...)) total)
18374 triangle-bugged(4)
18375@end group
18376@group
18377 eval((triangle-bugged 4))
18378 eval-last-sexp-1(nil)
18379 eval-last-sexp(nil)
18380 call-interactively(eval-last-sexp)
18381---------- Buffer: *Backtrace* ----------
18382@end group
18383@end smallexample
18384
18385@noindent
18386(I have reformatted this example slightly; the debugger does not fold
18387long lines. As usual, you can quit the debugger by typing @kbd{q} in
18388the @file{*Backtrace*} buffer.)
18389
18390In practice, for a bug as simple as this, the `Lisp error' line will
18391tell you what you need to know to correct the definition. The
18392function @code{1=} is `void'.
18393
18394@ignore
18395@need 800
18396In GNU Emacs 20 and before, you will see:
18397
18398@smallexample
18399Symbol's function definition is void:@: 1=
18400@end smallexample
18401
18402@noindent
18403which has the same meaning as the @file{*Backtrace*} buffer line in
18404version 21.
18405@end ignore
18406
18407However, suppose you are not quite certain what is going on?
18408You can read the complete backtrace.
18409
18410In this case, you need to run a recent GNU Emacs, which automatically
18411starts the debugger that puts you in the @file{*Backtrace*} buffer; or
18412else, you need to start the debugger manually as described below.
18413
18414Read the @file{*Backtrace*} buffer from the bottom up; it tells you
18415what Emacs did that led to the error. Emacs made an interactive call
18416to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
18417of the @code{triangle-bugged} expression. Each line above tells you
18418what the Lisp interpreter evaluated next.
18419
18420@need 1250
18421The third line from the top of the buffer is
18422
18423@smallexample
18424(setq number (1= number))
18425@end smallexample
18426
18427@noindent
18428Emacs tried to evaluate this expression; in order to do so, it tried
18429to evaluate the inner expression shown on the second line from the
18430top:
18431
18432@smallexample
18433(1= number)
18434@end smallexample
18435
18436@need 1250
18437@noindent
18438This is where the error occurred; as the top line says:
18439
18440@smallexample
18441Debugger entered--Lisp error: (void-function 1=)
18442@end smallexample
18443
18444@noindent
18445You can correct the mistake, re-evaluate the function definition, and
18446then run your test again.
18447
d6adf7e7 18448@node debug-on-entry
8cda6f8f
GM
18449@section @code{debug-on-entry}
18450@findex debug-on-entry
18451
18452A recent GNU Emacs starts the debugger automatically when your
18453function has an error.
18454
18455@ignore
18456GNU Emacs version 20 and before did not; it simply
18457presented you with an error message. You had to start the debugger
18458manually.
18459@end ignore
18460
18461Incidentally, you can start the debugger manually for all versions of
18462Emacs; the advantage is that the debugger runs even if you do not have
18463a bug in your code. Sometimes your code will be free of bugs!
18464
18465You can enter the debugger when you call the function by calling
18466@code{debug-on-entry}.
18467
18468@need 1250
18469@noindent
18470Type:
18471
18472@smallexample
18473M-x debug-on-entry RET triangle-bugged RET
18474@end smallexample
18475
18476@need 1250
18477@noindent
18478Now, evaluate the following:
18479
18480@smallexample
18481(triangle-bugged 5)
18482@end smallexample
18483
18484@noindent
18485All versions of Emacs will create a @file{*Backtrace*} buffer and tell
18486you that it is beginning to evaluate the @code{triangle-bugged}
18487function:
18488
18489@smallexample
18490@group
18491---------- Buffer: *Backtrace* ----------
18492Debugger entered--entering a function:
18493* triangle-bugged(5)
18494 eval((triangle-bugged 5))
18495@end group
18496@group
18497 eval-last-sexp-1(nil)
18498 eval-last-sexp(nil)
18499 call-interactively(eval-last-sexp)
18500---------- Buffer: *Backtrace* ----------
18501@end group
18502@end smallexample
18503
18504In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
18505the first expression in @code{triangle-bugged}; the buffer will look
18506like this:
18507
18508@smallexample
18509@group
18510---------- Buffer: *Backtrace* ----------
18511Debugger entered--beginning evaluation of function call form:
18512* (let ((total 0)) (while (> number 0) (setq total ...)
18513 (setq number ...)) total)
18514* triangle-bugged(5)
18515 eval((triangle-bugged 5))
18516@end group
18517@group
18518 eval-last-sexp-1(nil)
18519 eval-last-sexp(nil)
18520 call-interactively(eval-last-sexp)
18521---------- Buffer: *Backtrace* ----------
18522@end group
18523@end smallexample
18524
18525@noindent
18526Now, type @kbd{d} again, eight times, slowly. Each time you type
18527@kbd{d}, Emacs will evaluate another expression in the function
18528definition.
18529
18530@need 1750
18531Eventually, the buffer will look like this:
18532
18533@smallexample
18534@group
18535---------- Buffer: *Backtrace* ----------
18536Debugger entered--beginning evaluation of function call form:
18537* (setq number (1= number))
18538* (while (> number 0) (setq total (+ total number))
18539 (setq number (1= number)))
18540@group
18541@end group
18542* (let ((total 0)) (while (> number 0) (setq total ...)
18543 (setq number ...)) total)
18544* triangle-bugged(5)
18545 eval((triangle-bugged 5))
18546@group
18547@end group
18548 eval-last-sexp-1(nil)
18549 eval-last-sexp(nil)
18550 call-interactively(eval-last-sexp)
18551---------- Buffer: *Backtrace* ----------
18552@end group
18553@end smallexample
18554
18555@need 1500
18556@noindent
18557Finally, after you type @kbd{d} two more times, Emacs will reach the
18558error, and the top two lines of the @file{*Backtrace*} buffer will look
18559like this:
18560
18561@smallexample
18562@group
18563---------- Buffer: *Backtrace* ----------
18564Debugger entered--Lisp error: (void-function 1=)
18565* (1= number)
18566@dots{}
18567---------- Buffer: *Backtrace* ----------
18568@end group
18569@end smallexample
18570
18571By typing @kbd{d}, you were able to step through the function.
18572
18573You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
18574quits the trace, but does not cancel @code{debug-on-entry}.
18575
18576@findex cancel-debug-on-entry
18577To cancel the effect of @code{debug-on-entry}, call
18578@code{cancel-debug-on-entry} and the name of the function, like this:
18579
18580@smallexample
18581M-x cancel-debug-on-entry RET triangle-bugged RET
18582@end smallexample
18583
18584@noindent
18585(If you are reading this in Info, cancel @code{debug-on-entry} now.)
18586
d6adf7e7 18587@node debug-on-quit
8cda6f8f
GM
18588@section @code{debug-on-quit} and @code{(debug)}
18589
18590In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
18591there are two other ways to start @code{debug}.
18592
18593@findex debug-on-quit
18594You can start @code{debug} whenever you type @kbd{C-g}
18595(@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
18596@code{t}. This is useful for debugging infinite loops.
18597
18598@need 1500
18599@cindex @code{(debug)} in code
18600Or, you can insert a line that says @code{(debug)} into your code
18601where you want the debugger to start, like this:
18602
18603@smallexample
18604@group
18605(defun triangle-bugged (number)
18606 "Return sum of numbers 1 through NUMBER inclusive."
18607 (let ((total 0))
18608 (while (> number 0)
18609 (setq total (+ total number))
18610 (debug) ; @r{Start debugger.}
18611 (setq number (1= number))) ; @r{Error here.}
18612 total))
18613@end group
18614@end smallexample
18615
18616The @code{debug} function is described in detail in @ref{Debugger, ,
18617The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
18618
d6adf7e7 18619@node edebug
8cda6f8f
GM
18620@section The @code{edebug} Source Level Debugger
18621@cindex Source level debugger
18622@findex edebug
18623
18624Edebug is a source level debugger. Edebug normally displays the
18625source of the code you are debugging, with an arrow at the left that
18626shows which line you are currently executing.
18627
18628You can walk through the execution of a function, line by line, or run
18629quickly until reaching a @dfn{breakpoint} where execution stops.
18630
18631Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18632Lisp Reference Manual}.
18633
18634@need 1250
18635Here is a bugged function definition for @code{triangle-recursively}.
18636@xref{Recursive triangle function, , Recursion in place of a counter},
18637for a review of it.
18638
18639@smallexample
18640@group
18641(defun triangle-recursively-bugged (number)
18642 "Return sum of numbers 1 through NUMBER inclusive.
18643Uses recursion."
18644 (if (= number 1)
18645 1
18646 (+ number
18647 (triangle-recursively-bugged
18648 (1= number))))) ; @r{Error here.}
18649@end group
18650@end smallexample
18651
18652@noindent
18653Normally, you would install this definition by positioning your cursor
18654after the function's closing parenthesis and typing @kbd{C-x C-e}
18655(@code{eval-last-sexp}) or else by positioning your cursor within the
18656definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
18657the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
a1539cd7 18658Interaction mode.)
8cda6f8f
GM
18659
18660@need 1500
18661However, to prepare this function definition for Edebug, you must
18662first @dfn{instrument} the code using a different command. You can do
18663this by positioning your cursor within or just after the definition
18664and typing
18665
18666@smallexample
18667M-x edebug-defun RET
18668@end smallexample
18669
18670@noindent
18671This will cause Emacs to load Edebug automatically if it is not
18672already loaded, and properly instrument the function.
18673
18674After instrumenting the function, place your cursor after the
18675following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
18676
18677@smallexample
18678(triangle-recursively-bugged 3)
18679@end smallexample
18680
18681@noindent
18682You will be jumped back to the source for
18683@code{triangle-recursively-bugged} and the cursor positioned at the
18684beginning of the @code{if} line of the function. Also, you will see
18685an arrowhead at the left hand side of that line. The arrowhead marks
18686the line where the function is executing. (In the following examples,
18687we show the arrowhead with @samp{=>}; in a windowing system, you may
18688see the arrowhead as a solid triangle in the window `fringe'.)
18689
18690@smallexample
18691=>@point{}(if (= number 1)
18692@end smallexample
18693
18694@noindent
18695@iftex
18696In the example, the location of point is displayed with a star,
18697@samp{@point{}} (in Info, it is displayed as @samp{-!-}).
18698@end iftex
18699@ifnottex
18700In the example, the location of point is displayed as @samp{@point{}}
18701(in a printed book, it is displayed with a five pointed star).
18702@end ifnottex
18703
18704If you now press @key{SPC}, point will move to the next expression to
18705be executed; the line will look like this:
18706
18707@smallexample
18708=>(if @point{}(= number 1)
18709@end smallexample
18710
18711@noindent
18712As you continue to press @key{SPC}, point will move from expression to
18713expression. At the same time, whenever an expression returns a value,
18714that value will be displayed in the echo area. For example, after you
18715move point past @code{number}, you will see the following:
18716
18717@smallexample
18718Result: 3 (#o3, #x3, ?\C-c)
18719@end smallexample
18720
18721@noindent
18722This means the value of @code{number} is 3, which is octal three,
18723hexadecimal three, and @sc{ascii} `control-c' (the third letter of the
18724alphabet, in case you need to know this information).
18725
18726You can continue moving through the code until you reach the line with
18727the error. Before evaluation, that line looks like this:
18728
18729@smallexample
18730=> @point{}(1= number))))) ; @r{Error here.}
18731@end smallexample
18732
18733@need 1250
18734@noindent
18735When you press @key{SPC} once again, you will produce an error message
18736that says:
18737
18738@smallexample
18739Symbol's function definition is void:@: 1=
18740@end smallexample
18741
18742@noindent
18743This is the bug.
18744
18745Press @kbd{q} to quit Edebug.
18746
18747To remove instrumentation from a function definition, simply
18748re-evaluate it with a command that does not instrument it.
18749For example, you could place your cursor after the definition's
18750closing parenthesis and type @kbd{C-x C-e}.
18751
18752Edebug does a great deal more than walk with you through a function.
18753You can set it so it races through on its own, stopping only at an
18754error or at specified stopping points; you can cause it to display the
18755changing values of various expressions; you can find out how many
18756times a function is called, and more.
18757
18758Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
18759Lisp Reference Manual}.
18760
18761@need 1500
d6adf7e7 18762@node Debugging Exercises
8cda6f8f
GM
18763@section Debugging Exercises
18764
18765@itemize @bullet
18766@item
ea4f7750 18767Install the @code{@value{COUNT-WORDS}} function and then cause it to
8cda6f8f
GM
18768enter the built-in debugger when you call it. Run the command on a
18769region containing two words. You will need to press @kbd{d} a
18770remarkable number of times. On your system, is a `hook' called after
18771the command finishes? (For information on hooks, see @ref{Command
18772Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
18773Manual}.)
18774
18775@item
ea4f7750 18776Copy @code{@value{COUNT-WORDS}} into the @file{*scratch*} buffer,
8cda6f8f
GM
18777instrument the function for Edebug, and walk through its execution.
18778The function does not need to have a bug, although you can introduce
18779one if you wish. If the function lacks a bug, the walk-through
18780completes without problems.
18781
18782@item
18783While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
1df7defd 18784(The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.,
8cda6f8f
GM
18785@kbd{@key{CTRL}-x} followed by an upper case @kbd{X}; use this prefix
18786for commands made outside of the Edebug debugging buffer.)
18787
18788@item
18789In the Edebug debugging buffer, use the @kbd{p}
18790(@code{edebug-bounce-point}) command to see where in the region the
ea4f7750 18791@code{@value{COUNT-WORDS}} is working.
8cda6f8f
GM
18792
18793@item
18794Move point to some spot further down the function and then type the
18795@kbd{h} (@code{edebug-goto-here}) command to jump to that location.
18796
18797@item
18798Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
18799walk through the function on its own; use an upper case @kbd{T} for
18800@code{edebug-Trace-fast-mode}.
18801
18802@item
18803Set a breakpoint, then run Edebug in Trace mode until it reaches the
18804stopping point.
18805@end itemize
18806
d6adf7e7 18807@node Conclusion
8cda6f8f
GM
18808@chapter Conclusion
18809
18810We have now reached the end of this Introduction. You have now
18811learned enough about programming in Emacs Lisp to set values, to write
18812simple @file{.emacs} files for yourself and your friends, and write
18813simple customizations and extensions to Emacs.
18814
18815This is a place to stop. Or, if you wish, you can now go onward, and
18816teach yourself.
18817
18818You have learned some of the basic nuts and bolts of programming. But
18819only some. There are a great many more brackets and hinges that are
18820easy to use that we have not touched.
18821
18822A path you can follow right now lies among the sources to GNU Emacs
18823and in
18824@ifnotinfo
18825@cite{The GNU Emacs Lisp Reference Manual}.
18826@end ifnotinfo
18827@ifinfo
18828@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
18829Emacs Lisp Reference Manual}.
18830@end ifinfo
18831
18832The Emacs Lisp sources are an adventure. When you read the sources and
18833come across a function or expression that is unfamiliar, you need to
18834figure out or find out what it does.
18835
18836Go to the Reference Manual. It is a thorough, complete, and fairly
18837easy-to-read description of Emacs Lisp. It is written not only for
18838experts, but for people who know what you know. (The @cite{Reference
18839Manual} comes with the standard GNU Emacs distribution. Like this
18840introduction, it comes as a Texinfo source file, so you can read it
18841on-line and as a typeset, printed book.)
18842
18843Go to the other on-line help that is part of GNU Emacs: the on-line
88c26f5c 18844documentation for all functions and variables, and @code{find-tag},
8cda6f8f
GM
18845the program that takes you to sources.
18846
18847Here is an example of how I explore the sources. Because of its name,
18848@file{simple.el} is the file I looked at first, a long time ago. As
18849it happens some of the functions in @file{simple.el} are complicated,
18850or at least look complicated at first sight. The @code{open-line}
18851function, for example, looks complicated.
18852
18853You may want to walk through this function slowly, as we did with the
18854@code{forward-sentence} function. (@xref{forward-sentence, The
18855@code{forward-sentence} function}.) Or you may want to skip that
18856function and look at another, such as @code{split-line}. You don't
18857need to read all the functions. According to
18858@code{count-words-in-defun}, the @code{split-line} function contains
18859102 words and symbols.
18860
18861Even though it is short, @code{split-line} contains expressions
18862we have not studied: @code{skip-chars-forward}, @code{indent-to},
18863@code{current-column} and @code{insert-and-inherit}.
18864
18865Consider the @code{skip-chars-forward} function. (It is part of the
18866function definition for @code{back-to-indentation}, which is shown in
18867@ref{Review, , Review}.)
18868
18869In GNU Emacs, you can find out more about @code{skip-chars-forward} by
18870typing @kbd{C-h f} (@code{describe-function}) and the name of the
18871function. This gives you the function documentation.
18872
18873You may be able to guess what is done by a well named function such as
18874@code{indent-to}; or you can look it up, too. Incidentally, the
18875@code{describe-function} function itself is in @file{help.el}; it is
18876one of those long, but decipherable functions. You can look up
18877@code{describe-function} using the @kbd{C-h f} command!
18878
18879In this instance, since the code is Lisp, the @file{*Help*} buffer
18880contains the name of the library containing the function's source.
18881You can put point over the name of the library and press the RET key,
18882which in this situation is bound to @code{help-follow}, and be taken
18883directly to the source, in the same way as @kbd{M-.}
18884(@code{find-tag}).
18885
18886The definition for @code{describe-function} illustrates how to
18887customize the @code{interactive} expression without using the standard
18888character codes; and it shows how to create a temporary buffer.
18889
18890(The @code{indent-to} function is written in C rather than Emacs Lisp;
18891it is a `built-in' function. @code{help-follow} takes you to its
18892source as does @code{find-tag}, when properly set up.)
18893
18894You can look at a function's source using @code{find-tag}, which is
18895bound to @kbd{M-.} Finally, you can find out what the Reference
18896Manual has to say by visiting the manual in Info, and typing @kbd{i}
18897(@code{Info-index}) and the name of the function, or by looking up the
18898function in the index to a printed copy of the manual.
18899
18900Similarly, you can find out what is meant by
18901@code{insert-and-inherit}.
18902
18903Other interesting source files include @file{paragraphs.el},
18904@file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
18905file includes short, easily understood functions as well as longer
18906ones. The @file{loaddefs.el} file contains the many standard
18907autoloads and many keymaps. I have never looked at it all; only at
18908parts. @file{loadup.el} is the file that loads the standard parts of
18909Emacs; it tells you a great deal about how Emacs is built.
18910(@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
18911Reference Manual}, for more about building.)
18912
18913As I said, you have learned some nuts and bolts; however, and very
18914importantly, we have hardly touched major aspects of programming; I
18915have said nothing about how to sort information, except to use the
18916predefined @code{sort} function; I have said nothing about how to store
18917information, except to use variables and lists; I have said nothing
18918about how to write programs that write programs. These are topics for
18919another, and different kind of book, a different kind of learning.
18920
18921What you have done is learn enough for much practical work with GNU
18922Emacs. What you have done is get started. This is the end of a
18923beginning.
18924
18925@c ================ Appendix ================
18926
d6adf7e7 18927@node the-the
8cda6f8f
GM
18928@appendix The @code{the-the} Function
18929@findex the-the
18930@cindex Duplicated words function
18931@cindex Words, duplicated
18932
18933Sometimes when you you write text, you duplicate words---as with ``you
18934you'' near the beginning of this sentence. I find that most
18935frequently, I duplicate ``the''; hence, I call the function for
18936detecting duplicated words, @code{the-the}.
18937
18938@need 1250
18939As a first step, you could use the following regular expression to
18940search for duplicates:
18941
18942@smallexample
18943\\(\\w+[ \t\n]+\\)\\1
18944@end smallexample
18945
18946@noindent
18947This regexp matches one or more word-constituent characters followed
18948by one or more spaces, tabs, or newlines. However, it does not detect
18949duplicated words on different lines, since the ending of the first
18950word, the end of the line, is different from the ending of the second
18951word, a space. (For more information about regular expressions, see
18952@ref{Regexp Search, , Regular Expression Searches}, as well as
18953@ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18954Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18955The GNU Emacs Lisp Reference Manual}.)
18956
18957You might try searching just for duplicated word-constituent
18958characters but that does not work since the pattern detects doubles
18959such as the two occurrences of `th' in `with the'.
18960
18961Another possible regexp searches for word-constituent characters
18962followed by non-word-constituent characters, reduplicated. Here,
18963@w{@samp{\\w+}} matches one or more word-constituent characters and
18964@w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18965
18966@smallexample
18967\\(\\(\\w+\\)\\W*\\)\\1
18968@end smallexample
18969
18970@noindent
18971Again, not useful.
18972
18973Here is the pattern that I use. It is not perfect, but good enough.
18974@w{@samp{\\b}} matches the empty string, provided it is at the beginning
18975or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18976any characters that are @emph{not} an @@-sign, space, newline, or tab.
18977
18978@smallexample
18979\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18980@end smallexample
18981
18982One can write more complicated expressions, but I found that this
18983expression is good enough, so I use it.
18984
18985Here is the @code{the-the} function, as I include it in my
18986@file{.emacs} file, along with a handy global key binding:
18987
18988@smallexample
18989@group
18990(defun the-the ()
18991 "Search forward for for a duplicated word."
18992 (interactive)
18993 (message "Searching for for duplicated words ...")
18994 (push-mark)
18995@end group
18996@group
18997 ;; This regexp is not perfect
18998 ;; but is fairly good over all:
18999 (if (re-search-forward
19000 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
19001 (message "Found duplicated word.")
19002 (message "End of buffer")))
19003@end group
19004
19005@group
19006;; Bind `the-the' to C-c \
19007(global-set-key "\C-c\\" 'the-the)
19008@end group
19009@end smallexample
19010
19011@sp 1
19012Here is test text:
19013
19014@smallexample
19015@group
19016one two two three four five
19017five six seven
19018@end group
19019@end smallexample
19020
19021You can substitute the other regular expressions shown above in the
19022function definition and try each of them on this list.
19023
d6adf7e7 19024@node Kill Ring
8cda6f8f
GM
19025@appendix Handling the Kill Ring
19026@cindex Kill ring handling
19027@cindex Handling the kill ring
19028@cindex Ring, making a list like a
19029
19030The kill ring is a list that is transformed into a ring by the
19031workings of the @code{current-kill} function. The @code{yank} and
19032@code{yank-pop} commands use the @code{current-kill} function.
19033
19034This appendix describes the @code{current-kill} function as well as
19035both the @code{yank} and the @code{yank-pop} commands, but first,
19036consider the workings of the kill ring.
19037
19038@menu
19039* What the Kill Ring Does::
19040* current-kill::
19041* yank:: Paste a copy of a clipped element.
19042* yank-pop:: Insert element pointed to.
19043* ring file::
19044@end menu
19045
8cda6f8f 19046@ifnottex
d6adf7e7 19047@node What the Kill Ring Does
8cda6f8f
GM
19048@unnumberedsec What the Kill Ring Does
19049@end ifnottex
19050
19051@need 1250
19052The kill ring has a default maximum length of sixty items; this number
19053is too large for an explanation. Instead, set it to four. Please
19054evaluate the following:
19055
19056@smallexample
19057@group
19058(setq old-kill-ring-max kill-ring-max)
19059(setq kill-ring-max 4)
19060@end group
19061@end smallexample
19062
19063@noindent
19064Then, please copy each line of the following indented example into the
19065kill ring. You may kill each line with @kbd{C-k} or mark it and copy
19066it with @kbd{M-w}.
19067
19068@noindent
19069(In a read-only buffer, such as the @file{*info*} buffer, the kill
19070command, @kbd{C-k} (@code{kill-line}), will not remove the text,
19071merely copy it to the kill ring. However, your machine may beep at
19072you. Alternatively, for silence, you may copy the region of each line
19073with the @kbd{M-w} (@code{kill-ring-save}) command. You must mark
19074each line for this command to succeed, but it does not matter at which
19075end you put point or mark.)
19076
19077@need 1250
19078@noindent
19079Please invoke the calls in order, so that five elements attempt to
19080fill the kill ring:
19081
19082@smallexample
19083@group
19084first some text
19085second piece of text
19086third line
19087fourth line of text
19088fifth bit of text
19089@end group
19090@end smallexample
19091
19092@need 1250
19093@noindent
19094Then find the value of @code{kill-ring} by evaluating
19095
19096@smallexample
19097kill-ring
19098@end smallexample
19099
19100@need 800
19101@noindent
19102It is:
19103
19104@smallexample
19105@group
19106("fifth bit of text" "fourth line of text"
19107"third line" "second piece of text")
19108@end group
19109@end smallexample
19110
19111@noindent
19112The first element, @samp{first some text}, was dropped.
19113
19114@need 1250
19115To return to the old value for the length of the kill ring, evaluate:
19116
19117@smallexample
19118(setq kill-ring-max old-kill-ring-max)
19119@end smallexample
19120
d6adf7e7 19121@node current-kill
8cda6f8f
GM
19122@appendixsec The @code{current-kill} Function
19123@findex current-kill
19124
19125The @code{current-kill} function changes the element in the kill ring
19126to which @code{kill-ring-yank-pointer} points. (Also, the
19127@code{kill-new} function sets @code{kill-ring-yank-pointer} to point
867d4bb3 19128to the latest element of the kill ring. The @code{kill-new}
8cda6f8f
GM
19129function is used directly or indirectly by @code{kill-append},
19130@code{copy-region-as-kill}, @code{kill-ring-save}, @code{kill-line},
19131and @code{kill-region}.)
19132
19133@menu
19134* Code for current-kill::
19135* Understanding current-kill::
19136@end menu
19137
8cda6f8f 19138@ifnottex
d6adf7e7 19139@node Code for current-kill
8cda6f8f
GM
19140@unnumberedsubsec The code for @code{current-kill}
19141@end ifnottex
19142
19143
19144@need 1500
19145The @code{current-kill} function is used by @code{yank} and by
19146@code{yank-pop}. Here is the code for @code{current-kill}:
19147
19148@smallexample
19149@group
19150(defun current-kill (n &optional do-not-move)
19151 "Rotate the yanking point by N places, and then return that kill.
19152If N is zero, `interprogram-paste-function' is set, and calling it
19153returns a string, then that string is added to the front of the
19154kill ring and returned as the latest kill.
19155@end group
19156@group
19157If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
19158yanking point; just return the Nth kill forward."
19159 (let ((interprogram-paste (and (= n 0)
19160 interprogram-paste-function
19161 (funcall interprogram-paste-function))))
19162@end group
19163@group
19164 (if interprogram-paste
19165 (progn
19166 ;; Disable the interprogram cut function when we add the new
19167 ;; text to the kill ring, so Emacs doesn't try to own the
19168 ;; selection, with identical text.
19169 (let ((interprogram-cut-function nil))
19170 (kill-new interprogram-paste))
19171 interprogram-paste)
19172@end group
19173@group
19174 (or kill-ring (error "Kill ring is empty"))
19175 (let ((ARGth-kill-element
19176 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19177 (length kill-ring))
19178 kill-ring)))
19179 (or do-not-move
19180 (setq kill-ring-yank-pointer ARGth-kill-element))
19181 (car ARGth-kill-element)))))
19182@end group
19183@end smallexample
19184
19185Remember also that the @code{kill-new} function sets
867d4bb3 19186@code{kill-ring-yank-pointer} to the latest element of the kill
8cda6f8f
GM
19187ring, which means that all the functions that call it set the value
19188indirectly: @code{kill-append}, @code{copy-region-as-kill},
19189@code{kill-ring-save}, @code{kill-line}, and @code{kill-region}.
19190
19191@need 1500
19192Here is the line in @code{kill-new}, which is explained in
19193@ref{kill-new function, , The @code{kill-new} function}.
19194
19195@smallexample
19196(setq kill-ring-yank-pointer kill-ring)
19197@end smallexample
19198
8cda6f8f 19199@ifnottex
d6adf7e7 19200@node Understanding current-kill
8cda6f8f
GM
19201@unnumberedsubsec @code{current-kill} in Outline
19202@end ifnottex
19203
19204The @code{current-kill} function looks complex, but as usual, it can
19205be understood by taking it apart piece by piece. First look at it in
19206skeletal form:
19207
19208@smallexample
19209@group
19210(defun current-kill (n &optional do-not-move)
19211 "Rotate the yanking point by N places, and then return that kill."
19212 (let @var{varlist}
19213 @var{body}@dots{})
19214@end group
19215@end smallexample
19216
19217This function takes two arguments, one of which is optional. It has a
19218documentation string. It is @emph{not} interactive.
19219
19220@menu
19221* Body of current-kill::
19222* Digression concerning error:: How to mislead humans, but not computers.
19223* Determining the Element::
19224@end menu
19225
8cda6f8f 19226@ifnottex
d6adf7e7 19227@node Body of current-kill
8cda6f8f
GM
19228@unnumberedsubsubsec The Body of @code{current-kill}
19229@end ifnottex
19230
19231The body of the function definition is a @code{let} expression, which
19232itself has a body as well as a @var{varlist}.
19233
19234The @code{let} expression declares a variable that will be only usable
19235within the bounds of this function. This variable is called
19236@code{interprogram-paste} and is for copying to another program. It
19237is not for copying within this instance of GNU Emacs. Most window
19238systems provide a facility for interprogram pasting. Sadly, that
19239facility usually provides only for the last element. Most windowing
19240systems have not adopted a ring of many possibilities, even though
19241Emacs has provided it for decades.
19242
19243The @code{if} expression has two parts, one if there exists
19244@code{interprogram-paste} and one if not.
19245
19246@need 2000
19247Let us consider the `if not' or else-part of the @code{current-kill}
867d4bb3 19248function. (The then-part uses the @code{kill-new} function, which
8cda6f8f
GM
19249we have already described. @xref{kill-new function, , The
19250@code{kill-new} function}.)
19251
19252@smallexample
19253@group
19254(or kill-ring (error "Kill ring is empty"))
19255(let ((ARGth-kill-element
19256 (nthcdr (mod (- n (length kill-ring-yank-pointer))
19257 (length kill-ring))
19258 kill-ring)))
19259 (or do-not-move
19260 (setq kill-ring-yank-pointer ARGth-kill-element))
19261 (car ARGth-kill-element))
19262@end group
19263@end smallexample
19264
19265@noindent
19266The code first checks whether the kill ring has content; otherwise it
19267signals an error.
19268
19269@need 1000
19270Note that the @code{or} expression is very similar to testing length
19271with an @code{if}:
19272
19273@findex zerop
19274@findex error
19275@smallexample
19276@group
19277(if (zerop (length kill-ring)) ; @r{if-part}
19278 (error "Kill ring is empty")) ; @r{then-part}
19279 ;; No else-part
19280@end group
19281@end smallexample
19282
19283@noindent
19284If there is not anything in the kill ring, its length must be zero and
19285an error message sent to the user: @samp{Kill ring is empty}. The
19286@code{current-kill} function uses an @code{or} expression which is
19287simpler. But an @code{if} expression reminds us what goes on.
19288
19289This @code{if} expression uses the function @code{zerop} which returns
19290true if the value it is testing is zero. When @code{zerop} tests
19291true, the then-part of the @code{if} is evaluated. The then-part is a
19292list starting with the function @code{error}, which is a function that
19293is similar to the @code{message} function
19294(@pxref{message, , The @code{message} Function}) in that
19295it prints a one-line message in the echo area. However, in addition
19296to printing a message, @code{error} also stops evaluation of the
19297function within which it is embedded. This means that the rest of the
19298function will not be evaluated if the length of the kill ring is zero.
19299
19300Then the @code{current-kill} function selects the element to return.
19301The selection depends on the number of places that @code{current-kill}
19302rotates and on where @code{kill-ring-yank-pointer} points.
19303
19304Next, either the optional @code{do-not-move} argument is true or the
19305current value of @code{kill-ring-yank-pointer} is set to point to the
19306list. Finally, another expression returns the first element of the
19307list even if the @code{do-not-move} argument is true.
19308
8cda6f8f 19309@ifnottex
d6adf7e7 19310@node Digression concerning error
8cda6f8f
GM
19311@unnumberedsubsubsec Digression about the word `error'
19312@end ifnottex
19313
19314In my opinion, it is slightly misleading, at least to humans, to use
19315the term `error' as the name of the @code{error} function. A better
19316term would be `cancel'. Strictly speaking, of course, you cannot
19317point to, much less rotate a pointer to a list that has no length, so
19318from the point of view of the computer, the word `error' is correct.
19319But a human expects to attempt this sort of thing, if only to find out
19320whether the kill ring is full or empty. This is an act of
19321exploration.
19322
19323From the human point of view, the act of exploration and discovery is
09e80d9f 19324not necessarily an error, and therefore should not be labeled as one,
8cda6f8f
GM
19325even in the bowels of a computer. As it is, the code in Emacs implies
19326that a human who is acting virtuously, by exploring his or her
19327environment, is making an error. This is bad. Even though the computer
19328takes the same steps as it does when there is an `error', a term such as
19329`cancel' would have a clearer connotation.
19330
8cda6f8f 19331@ifnottex
d6adf7e7 19332@node Determining the Element
8cda6f8f
GM
19333@unnumberedsubsubsec Determining the Element
19334@end ifnottex
19335
19336Among other actions, the else-part of the @code{if} expression sets
19337the value of @code{kill-ring-yank-pointer} to
19338@code{ARGth-kill-element} when the kill ring has something in it and
19339the value of @code{do-not-move} is @code{nil}.
19340
19341@need 800
19342The code looks like this:
19343
19344@smallexample
19345@group
19346(nthcdr (mod (- n (length kill-ring-yank-pointer))
19347 (length kill-ring))
19348 kill-ring)))
19349@end group
19350@end smallexample
19351
19352This needs some examination. Unless it is not supposed to move the
19353pointer, the @code{current-kill} function changes where
19354@code{kill-ring-yank-pointer} points.
19355That is what the
19356@w{@code{(setq kill-ring-yank-pointer ARGth-kill-element))}}
19357expression does. Also, clearly, @code{ARGth-kill-element} is being
19358set to be equal to some @sc{cdr} of the kill ring, using the
19359@code{nthcdr} function that is described in an earlier section.
19360(@xref{copy-region-as-kill}.) How does it do this?
19361
19362As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
19363works by repeatedly taking the @sc{cdr} of a list---it takes the
19364@sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
19365
19366@need 800
19367The two following expressions produce the same result:
19368
19369@smallexample
19370@group
19371(setq kill-ring-yank-pointer (cdr kill-ring))
19372
19373(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
19374@end group
19375@end smallexample
19376
19377However, the @code{nthcdr} expression is more complicated. It uses
19378the @code{mod} function to determine which @sc{cdr} to select.
19379
19380(You will remember to look at inner functions first; indeed, we will
19381have to go inside the @code{mod}.)
19382
19383The @code{mod} function returns the value of its first argument modulo
19384the second; that is to say, it returns the remainder after dividing
19385the first argument by the second. The value returned has the same
19386sign as the second argument.
19387
19388@need 800
19389Thus,
19390
19391@smallexample
19392@group
19393(mod 12 4)
19394 @result{} 0 ;; @r{because there is no remainder}
19395(mod 13 4)
19396 @result{} 1
19397@end group
19398@end smallexample
19399
19400@need 1250
19401In this case, the first argument is often smaller than the second.
19402That is fine.
19403
19404@smallexample
19405@group
19406(mod 0 4)
19407 @result{} 0
19408(mod 1 4)
19409 @result{} 1
19410@end group
19411@end smallexample
19412
19413We can guess what the @code{-} function does. It is like @code{+} but
19414subtracts instead of adds; the @code{-} function subtracts its second
19415argument from its first. Also, we already know what the @code{length}
19416function does (@pxref{length}). It returns the length of a list.
19417
19418And @code{n} is the name of the required argument to the
19419@code{current-kill} function.
19420
19421@need 1250
19422So when the first argument to @code{nthcdr} is zero, the @code{nthcdr}
19423expression returns the whole list, as you can see by evaluating the
19424following:
19425
19426@smallexample
19427@group
19428;; kill-ring-yank-pointer @r{and} kill-ring @r{have a length of four}
19429;; @r{and} (mod (- 0 4) 4) @result{} 0
19430(nthcdr (mod (- 0 4) 4)
19431 '("fourth line of text"
19432 "third line"
19433 "second piece of text"
19434 "first some text"))
19435@end group
19436@end smallexample
19437
19438@need 1250
19439When the first argument to the @code{current-kill} function is one,
19440the @code{nthcdr} expression returns the list without its first
19441element.
19442
19443@smallexample
19444@group
19445(nthcdr (mod (- 1 4) 4)
19446 '("fourth line of text"
19447 "third line"
19448 "second piece of text"
19449 "first some text"))
19450@end group
19451@end smallexample
19452
19453@cindex @samp{global variable} defined
19454@cindex @samp{variable, global}, defined
19455Incidentally, both @code{kill-ring} and @code{kill-ring-yank-pointer}
19456are @dfn{global variables}. That means that any expression in Emacs
19457Lisp can access them. They are not like the local variables set by
19458@code{let} or like the symbols in an argument list.
19459Local variables can only be accessed
19460within the @code{let} that defines them or the function that specifies
19461them in an argument list (and within expressions called by them).
19462
19463@ignore
19464@c texi2dvi fails when the name of the section is within ifnottex ...
19465(@xref{Prevent confusion, , @code{let} Prevents Confusion}, and
19466@ref{defun, , The @code{defun} Special Form}.)
19467@end ignore
19468
d6adf7e7 19469@node yank
8cda6f8f
GM
19470@appendixsec @code{yank}
19471@findex yank
19472
19473After learning about @code{current-kill}, the code for the
19474@code{yank} function is almost easy.
19475
19476The @code{yank} function does not use the
19477@code{kill-ring-yank-pointer} variable directly. It calls
19478@code{insert-for-yank} which calls @code{current-kill} which sets the
19479@code{kill-ring-yank-pointer} variable.
19480
19481@need 1250
19482The code looks like this:
19483
19484@c in GNU Emacs 22
19485@smallexample
19486@group
19487(defun yank (&optional arg)
19488 "Reinsert (\"paste\") the last stretch of killed text.
19489More precisely, reinsert the stretch of killed text most recently
19490killed OR yanked. Put point at end, and set mark at beginning.
19491With just \\[universal-argument] as argument, same but put point at
19492beginning (and mark at end). With argument N, reinsert the Nth most
19493recently killed stretch of killed text.
19494
19495When this command inserts killed text into the buffer, it honors
19496`yank-excluded-properties' and `yank-handler' as described in the
19497doc string for `insert-for-yank-1', which see.
19498
19499See also the command \\[yank-pop]."
19500@end group
19501@group
19502 (interactive "*P")
19503 (setq yank-window-start (window-start))
19504 ;; If we don't get all the way thru, make last-command indicate that
19505 ;; for the following command.
19506 (setq this-command t)
19507 (push-mark (point))
19508@end group
19509@group
19510 (insert-for-yank (current-kill (cond
19511 ((listp arg) 0)
19512 ((eq arg '-) -2)
19513 (t (1- arg)))))
19514 (if (consp arg)
19515 ;; This is like exchange-point-and-mark,
19516 ;; but doesn't activate the mark.
19517 ;; It is cleaner to avoid activation, even though the command
19518 ;; loop would deactivate the mark because we inserted text.
19519 (goto-char (prog1 (mark t)
19520 (set-marker (mark-marker) (point) (current-buffer)))))
19521@end group
19522@group
19523 ;; If we do get all the way thru, make this-command indicate that.
19524 (if (eq this-command t)
19525 (setq this-command 'yank))
19526 nil)
19527@end group
19528@end smallexample
19529
19530The key expression is @code{insert-for-yank}, which inserts the string
19531returned by @code{current-kill}, but removes some text properties from
19532it.
19533
19534However, before getting to that expression, the function sets the value
19535of @code{yank-window-start} to the position returned by the
19536@code{(window-start)} expression, the position at which the display
19537currently starts. The @code{yank} function also sets
19538@code{this-command} and pushes the mark.
19539
19540After it yanks the appropriate element, if the optional argument is a
19541@sc{cons} rather than a number or nothing, it puts point at beginning
19542of the yanked text and mark at its end.
19543
19544(The @code{prog1} function is like @code{progn} but returns the value
19545of its first argument rather than the value of its last argument. Its
19546first argument is forced to return the buffer's mark as an integer.
19547You can see the documentation for these functions by placing point
19548over them in this buffer and then typing @kbd{C-h f}
19549(@code{describe-function}) followed by a @kbd{RET}; the default is the
19550function.)
19551
19552The last part of the function tells what to do when it succeeds.
19553
d6adf7e7 19554@node yank-pop
8cda6f8f
GM
19555@appendixsec @code{yank-pop}
19556@findex yank-pop
19557
19558After understanding @code{yank} and @code{current-kill}, you know how
19559to approach the @code{yank-pop} function. Leaving out the
19560documentation to save space, it looks like this:
19561
19562@c GNU Emacs 22
19563@smallexample
19564@group
19565(defun yank-pop (&optional arg)
19566 "@dots{}"
19567 (interactive "*p")
19568 (if (not (eq last-command 'yank))
19569 (error "Previous command was not a yank"))
19570@end group
19571@group
19572 (setq this-command 'yank)
19573 (unless arg (setq arg 1))
19574 (let ((inhibit-read-only t)
19575 (before (< (point) (mark t))))
19576@end group
19577@group
19578 (if before
19579 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
19580 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
19581 (setq yank-undo-function nil)
19582@end group
19583@group
19584 (set-marker (mark-marker) (point) (current-buffer))
19585 (insert-for-yank (current-kill arg))
19586 ;; Set the window start back where it was in the yank command,
19587 ;; if possible.
19588 (set-window-start (selected-window) yank-window-start t)
19589@end group
19590@group
19591 (if before
19592 ;; This is like exchange-point-and-mark,
19593 ;; but doesn't activate the mark.
19594 ;; It is cleaner to avoid activation, even though the command
19595 ;; loop would deactivate the mark because we inserted text.
19596 (goto-char (prog1 (mark t)
19597 (set-marker (mark-marker)
19598 (point)
19599 (current-buffer))))))
19600 nil)
19601@end group
19602@end smallexample
19603
19604The function is interactive with a small @samp{p} so the prefix
19605argument is processed and passed to the function. The command can
19606only be used after a previous yank; otherwise an error message is
19607sent. This check uses the variable @code{last-command} which is set
19608by @code{yank} and is discussed elsewhere.
19609(@xref{copy-region-as-kill}.)
19610
19611The @code{let} clause sets the variable @code{before} to true or false
19612depending whether point is before or after mark and then the region
19613between point and mark is deleted. This is the region that was just
19614inserted by the previous yank and it is this text that will be
19615replaced.
19616
19617@code{funcall} calls its first argument as a function, passing
19618remaining arguments to it. The first argument is whatever the
19619@code{or} expression returns. The two remaining arguments are the
19620positions of point and mark set by the preceding @code{yank} command.
19621
19622There is more, but that is the hardest part.
19623
d6adf7e7 19624@node ring file
8cda6f8f
GM
19625@appendixsec The @file{ring.el} File
19626@cindex @file{ring.el} file
19627
19628Interestingly, GNU Emacs posses a file called @file{ring.el} that
19629provides many of the features we just discussed. But functions such
19630as @code{kill-ring-yank-pointer} do not use this library, possibly
19631because they were written earlier.
19632
d6adf7e7 19633@node Full Graph
09e80d9f 19634@appendix A Graph with Labeled Axes
8cda6f8f
GM
19635
19636Printed axes help you understand a graph. They convey scale. In an
19637earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
19638wrote the code to print the body of a graph. Here we write the code
09e80d9f 19639for printing and labeling vertical and horizontal axes, along with the
8cda6f8f
GM
19640body itself.
19641
19642@menu
09e80d9f 19643* Labeled Example::
8cda6f8f
GM
19644* print-graph Varlist:: @code{let} expression in @code{print-graph}.
19645* print-Y-axis:: Print a label for the vertical axis.
19646* print-X-axis:: Print a horizontal label.
19647* Print Whole Graph:: The function to print a complete graph.
19648@end menu
19649
8cda6f8f 19650@ifnottex
d6adf7e7 19651@node Labeled Example
09e80d9f 19652@unnumberedsec Labeled Example Graph
8cda6f8f
GM
19653@end ifnottex
19654
19655Since insertions fill a buffer to the right and below point, the new
19656graph printing function should first print the Y or vertical axis,
19657then the body of the graph, and finally the X or horizontal axis.
19658This sequence lays out for us the contents of the function:
19659
19660@enumerate
19661@item
19662Set up code.
19663
19664@item
19665Print Y axis.
19666
19667@item
19668Print body of graph.
19669
19670@item
19671Print X axis.
19672@end enumerate
19673
19674@need 800
19675Here is an example of how a finished graph should look:
19676
19677@smallexample
19678@group
19679 10 -
19680 *
19681 * *
19682 * **
19683 * ***
19684 5 - * *******
19685 * *** *******
19686 *************
19687 ***************
19688 1 - ****************
19689 | | | |
19690 1 5 10 15
19691@end group
19692@end smallexample
19693
19694@noindent
09e80d9f 19695In this graph, both the vertical and the horizontal axes are labeled
8cda6f8f 19696with numbers. However, in some graphs, the horizontal axis is time
09e80d9f 19697and would be better labeled with months, like this:
8cda6f8f
GM
19698
19699@smallexample
19700@group
19701 5 - *
19702 * ** *
19703 *******
19704 ********** **
19705 1 - **************
19706 | ^ |
19707 Jan June Jan
19708@end group
19709@end smallexample
19710
19711Indeed, with a little thought, we can easily come up with a variety of
09e80d9f 19712vertical and horizontal labeling schemes. Our task could become
8cda6f8f 19713complicated. But complications breed confusion. Rather than permit
09e80d9f 19714this, it is better choose a simple labeling scheme for our first
8cda6f8f
GM
19715effort, and to modify or replace it later.
19716
19717@need 1200
19718These considerations suggest the following outline for the
19719@code{print-graph} function:
19720
19721@smallexample
19722@group
19723(defun print-graph (numbers-list)
19724 "@var{documentation}@dots{}"
19725 (let ((height @dots{}
19726 @dots{}))
19727@end group
19728@group
19729 (print-Y-axis height @dots{} )
19730 (graph-body-print numbers-list)
19731 (print-X-axis @dots{} )))
19732@end group
19733@end smallexample
19734
19735We can work on each part of the @code{print-graph} function definition
19736in turn.
19737
d6adf7e7 19738@node print-graph Varlist
8cda6f8f
GM
19739@appendixsec The @code{print-graph} Varlist
19740@cindex @code{print-graph} varlist
19741
19742In writing the @code{print-graph} function, the first task is to write
19743the varlist in the @code{let} expression. (We will leave aside for the
19744moment any thoughts about making the function interactive or about the
19745contents of its documentation string.)
19746
19747The varlist should set several values. Clearly, the top of the label
19748for the vertical axis must be at least the height of the graph, which
19749means that we must obtain this information here. Note that the
19750@code{print-graph-body} function also requires this information. There
19751is no reason to calculate the height of the graph in two different
19752places, so we should change @code{print-graph-body} from the way we
19753defined it earlier to take advantage of the calculation.
19754
19755Similarly, both the function for printing the X axis labels and the
19756@code{print-graph-body} function need to learn the value of the width of
19757each symbol. We can perform the calculation here and change the
19758definition for @code{print-graph-body} from the way we defined it in the
19759previous chapter.
19760
19761The length of the label for the horizontal axis must be at least as long
19762as the graph. However, this information is used only in the function
19763that prints the horizontal axis, so it does not need to be calculated here.
19764
19765These thoughts lead us directly to the following form for the varlist
19766in the @code{let} for @code{print-graph}:
19767
19768@smallexample
19769@group
19770(let ((height (apply 'max numbers-list)) ; @r{First version.}
19771 (symbol-width (length graph-blank)))
19772@end group
19773@end smallexample
19774
19775@noindent
19776As we shall see, this expression is not quite right.
19777
19778@need 2000
d6adf7e7 19779@node print-Y-axis
8cda6f8f
GM
19780@appendixsec The @code{print-Y-axis} Function
19781@cindex Axis, print vertical
19782@cindex Y axis printing
19783@cindex Vertical axis printing
19784@cindex Print vertical axis
19785
19786The job of the @code{print-Y-axis} function is to print a label for
19787the vertical axis that looks like this:
19788
19789@smallexample
19790@group
19791 10 -
19792
19793
19794
19795
19796 5 -
19797
19798
19799
19800 1 -
19801@end group
19802@end smallexample
19803
19804@noindent
19805The function should be passed the height of the graph, and then should
19806construct and insert the appropriate numbers and marks.
19807
19808@menu
19809* print-Y-axis in Detail::
19810* Height of label:: What height for the Y axis?
19811* Compute a Remainder:: How to compute the remainder of a division.
19812* Y Axis Element:: Construct a line for the Y axis.
19813* Y-axis-column:: Generate a list of Y axis labels.
19814* print-Y-axis Penultimate:: A not quite final version.
19815@end menu
19816
8cda6f8f 19817@ifnottex
d6adf7e7 19818@node print-Y-axis in Detail
8cda6f8f
GM
19819@unnumberedsubsec The @code{print-Y-axis} Function in Detail
19820@end ifnottex
19821
19822It is easy enough to see in the figure what the Y axis label should
19823look like; but to say in words, and then to write a function
19824definition to do the job is another matter. It is not quite true to
19825say that we want a number and a tic every five lines: there are only
19826three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19827but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19828and 9). It is better to say that we want a number and a tic mark on
19829the base line (number 1) and then that we want a number and a tic on
19830the fifth line from the bottom and on every line that is a multiple of
19831five.
19832
8cda6f8f 19833@ifnottex
d6adf7e7 19834@node Height of label
8cda6f8f
GM
19835@unnumberedsubsec What height should the label be?
19836@end ifnottex
19837
19838The next issue is what height the label should be? Suppose the maximum
19839height of tallest column of the graph is seven. Should the highest
19840label on the Y axis be @samp{5 -}, and should the graph stick up above
19841the label? Or should the highest label be @samp{7 -}, and mark the peak
19842of the graph? Or should the highest label be @code{10 -}, which is a
19843multiple of five, and be higher than the topmost value of the graph?
19844
19845The latter form is preferred. Most graphs are drawn within rectangles
19846whose sides are an integral number of steps long---5, 10, 15, and so
19847on for a step distance of five. But as soon as we decide to use a
19848step height for the vertical axis, we discover that the simple
19849expression in the varlist for computing the height is wrong. The
19850expression is @code{(apply 'max numbers-list)}. This returns the
19851precise height, not the maximum height plus whatever is necessary to
19852round up to the nearest multiple of five. A more complex expression
19853is required.
19854
19855As usual in cases like this, a complex problem becomes simpler if it is
19856divided into several smaller problems.
19857
19858First, consider the case when the highest value of the graph is an
19859integral multiple of five---when it is 5, 10, 15, or some higher
19860multiple of five. We can use this value as the Y axis height.
19861
19862A fairly simply way to determine whether a number is a multiple of
19863five is to divide it by five and see if the division results in a
19864remainder. If there is no remainder, the number is a multiple of
19865five. Thus, seven divided by five has a remainder of two, and seven
19866is not an integral multiple of five. Put in slightly different
19867language, more reminiscent of the classroom, five goes into seven
19868once, with a remainder of two. However, five goes into ten twice,
19869with no remainder: ten is an integral multiple of five.
19870
d6adf7e7 19871@node Compute a Remainder
8cda6f8f
GM
19872@appendixsubsec Side Trip: Compute a Remainder
19873
19874@findex % @r{(remainder function)}
19875@cindex Remainder function, @code{%}
19876In Lisp, the function for computing a remainder is @code{%}. The
19877function returns the remainder of its first argument divided by its
19878second argument. As it happens, @code{%} is a function in Emacs Lisp
19879that you cannot discover using @code{apropos}: you find nothing if you
19880type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
19881learn of the existence of @code{%} is to read about it in a book such
19882as this or in the Emacs Lisp sources.
19883
19884You can try the @code{%} function by evaluating the following two
19885expressions:
19886
19887@smallexample
19888@group
19889(% 7 5)
19890
19891(% 10 5)
19892@end group
19893@end smallexample
19894
19895@noindent
19896The first expression returns 2 and the second expression returns 0.
19897
19898To test whether the returned value is zero or some other number, we
19899can use the @code{zerop} function. This function returns @code{t} if
19900its argument, which must be a number, is zero.
19901
19902@smallexample
19903@group
19904(zerop (% 7 5))
19905 @result{} nil
19906
19907(zerop (% 10 5))
19908 @result{} t
19909@end group
19910@end smallexample
19911
19912Thus, the following expression will return @code{t} if the height
19913of the graph is evenly divisible by five:
19914
19915@smallexample
19916(zerop (% height 5))
19917@end smallexample
19918
19919@noindent
19920(The value of @code{height}, of course, can be found from @code{(apply
19921'max numbers-list)}.)
19922
19923On the other hand, if the value of @code{height} is not a multiple of
19924five, we want to reset the value to the next higher multiple of five.
19925This is straightforward arithmetic using functions with which we are
19926already familiar. First, we divide the value of @code{height} by five
19927to determine how many times five goes into the number. Thus, five
19928goes into twelve twice. If we add one to this quotient and multiply by
19929five, we will obtain the value of the next multiple of five that is
19930larger than the height. Five goes into twelve twice. Add one to two,
19931and multiply by five; the result is fifteen, which is the next multiple
19932of five that is higher than twelve. The Lisp expression for this is:
19933
19934@smallexample
19935(* (1+ (/ height 5)) 5)
19936@end smallexample
19937
19938@noindent
19939For example, if you evaluate the following, the result is 15:
19940
19941@smallexample
19942(* (1+ (/ 12 5)) 5)
19943@end smallexample
19944
19945All through this discussion, we have been using `five' as the value
19946for spacing labels on the Y axis; but we may want to use some other
19947value. For generality, we should replace `five' with a variable to
19948which we can assign a value. The best name I can think of for this
19949variable is @code{Y-axis-label-spacing}.
19950
19951@need 1250
19952Using this term, and an @code{if} expression, we produce the
19953following:
19954
19955@smallexample
19956@group
19957(if (zerop (% height Y-axis-label-spacing))
19958 height
19959 ;; @r{else}
19960 (* (1+ (/ height Y-axis-label-spacing))
19961 Y-axis-label-spacing))
19962@end group
19963@end smallexample
19964
19965@noindent
19966This expression returns the value of @code{height} itself if the height
19967is an even multiple of the value of the @code{Y-axis-label-spacing} or
19968else it computes and returns a value of @code{height} that is equal to
19969the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19970
19971We can now include this expression in the @code{let} expression of the
19972@code{print-graph} function (after first setting the value of
19973@code{Y-axis-label-spacing}):
19974@vindex Y-axis-label-spacing
19975
19976@smallexample
19977@group
19978(defvar Y-axis-label-spacing 5
19979 "Number of lines from one Y axis label to next.")
19980@end group
19981
19982@group
19983@dots{}
19984(let* ((height (apply 'max numbers-list))
19985 (height-of-top-line
19986 (if (zerop (% height Y-axis-label-spacing))
19987 height
19988@end group
19989@group
19990 ;; @r{else}
19991 (* (1+ (/ height Y-axis-label-spacing))
19992 Y-axis-label-spacing)))
19993 (symbol-width (length graph-blank))))
19994@dots{}
19995@end group
19996@end smallexample
19997
19998@noindent
19999(Note use of the @code{let*} function: the initial value of height is
20000computed once by the @code{(apply 'max numbers-list)} expression and
20001then the resulting value of @code{height} is used to compute its
20002final value. @xref{fwd-para let, , The @code{let*} expression}, for
20003more about @code{let*}.)
20004
d6adf7e7 20005@node Y Axis Element
8cda6f8f
GM
20006@appendixsubsec Construct a Y Axis Element
20007
20008When we print the vertical axis, we want to insert strings such as
20009@w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
20010Moreover, we want the numbers and dashes to line up, so shorter
20011numbers must be padded with leading spaces. If some of the strings
20012use two digit numbers, the strings with single digit numbers must
20013include a leading blank space before the number.
20014
20015@findex number-to-string
20016To figure out the length of the number, the @code{length} function is
20017used. But the @code{length} function works only with a string, not with
20018a number. So the number has to be converted from being a number to
20019being a string. This is done with the @code{number-to-string} function.
20020For example,
20021
20022@smallexample
20023@group
20024(length (number-to-string 35))
20025 @result{} 2
20026
20027(length (number-to-string 100))
20028 @result{} 3
20029@end group
20030@end smallexample
20031
20032@noindent
20033(@code{number-to-string} is also called @code{int-to-string}; you will
20034see this alternative name in various sources.)
20035
20036In addition, in each label, each number is followed by a string such
20037as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
20038This variable is defined with @code{defvar}:
20039
20040@vindex Y-axis-tic
20041@smallexample
20042@group
20043(defvar Y-axis-tic " - "
20044 "String that follows number in a Y axis label.")
20045@end group
20046@end smallexample
20047
20048The length of the Y label is the sum of the length of the Y axis tic
20049mark and the length of the number of the top of the graph.
20050
20051@smallexample
20052(length (concat (number-to-string height) Y-axis-tic)))
20053@end smallexample
20054
20055This value will be calculated by the @code{print-graph} function in
20056its varlist as @code{full-Y-label-width} and passed on. (Note that we
20057did not think to include this in the varlist when we first proposed it.)
20058
20059To make a complete vertical axis label, a tic mark is concatenated
20060with a number; and the two together may be preceded by one or more
20061spaces depending on how long the number is. The label consists of
20062three parts: the (optional) leading spaces, the number, and the tic
20063mark. The function is passed the value of the number for the specific
20064row, and the value of the width of the top line, which is calculated
20065(just once) by @code{print-graph}.
20066
20067@smallexample
20068@group
20069(defun Y-axis-element (number full-Y-label-width)
20070 "Construct a NUMBERed label element.
20071A numbered element looks like this ` 5 - ',
20072and is padded as needed so all line up with
20073the element for the largest number."
20074@end group
20075@group
20076 (let* ((leading-spaces
20077 (- full-Y-label-width
20078 (length
20079 (concat (number-to-string number)
20080 Y-axis-tic)))))
20081@end group
20082@group
20083 (concat
20084 (make-string leading-spaces ? )
20085 (number-to-string number)
20086 Y-axis-tic)))
20087@end group
20088@end smallexample
20089
20090The @code{Y-axis-element} function concatenates together the leading
20091spaces, if any; the number, as a string; and the tic mark.
20092
20093To figure out how many leading spaces the label will need, the
20094function subtracts the actual length of the label---the length of the
20095number plus the length of the tic mark---from the desired label width.
20096
20097@findex make-string
20098Blank spaces are inserted using the @code{make-string} function. This
20099function takes two arguments: the first tells it how long the string
20100will be and the second is a symbol for the character to insert, in a
20101special format. The format is a question mark followed by a blank
20102space, like this, @samp{? }. @xref{Character Type, , Character Type,
20103elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
20104syntax for characters. (Of course, you might want to replace the
20105blank space by some other character @dots{} You know what to do.)
20106
20107The @code{number-to-string} function is used in the concatenation
20108expression, to convert the number to a string that is concatenated
20109with the leading spaces and the tic mark.
20110
d6adf7e7 20111@node Y-axis-column
8cda6f8f
GM
20112@appendixsubsec Create a Y Axis Column
20113
20114The preceding functions provide all the tools needed to construct a
20115function that generates a list of numbered and blank strings to insert
20116as the label for the vertical axis:
20117
20118@findex Y-axis-column
20119@smallexample
20120@group
20121(defun Y-axis-column (height width-of-label)
20122 "Construct list of Y axis labels and blank strings.
20123For HEIGHT of line above base and WIDTH-OF-LABEL."
20124 (let (Y-axis)
20125@group
20126@end group
20127 (while (> height 1)
20128 (if (zerop (% height Y-axis-label-spacing))
20129 ;; @r{Insert label.}
20130 (setq Y-axis
20131 (cons
20132 (Y-axis-element height width-of-label)
20133 Y-axis))
20134@group
20135@end group
20136 ;; @r{Else, insert blanks.}
20137 (setq Y-axis
20138 (cons
20139 (make-string width-of-label ? )
20140 Y-axis)))
20141 (setq height (1- height)))
20142 ;; @r{Insert base line.}
20143 (setq Y-axis
20144 (cons (Y-axis-element 1 width-of-label) Y-axis))
20145 (nreverse Y-axis)))
20146@end group
20147@end smallexample
20148
20149In this function, we start with the value of @code{height} and
20150repetitively subtract one from its value. After each subtraction, we
20151test to see whether the value is an integral multiple of the
20152@code{Y-axis-label-spacing}. If it is, we construct a numbered label
20153using the @code{Y-axis-element} function; if not, we construct a
20154blank label using the @code{make-string} function. The base line
20155consists of the number one followed by a tic mark.
20156
20157@need 2000
d6adf7e7 20158@node print-Y-axis Penultimate
8cda6f8f
GM
20159@appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
20160
20161The list constructed by the @code{Y-axis-column} function is passed to
20162the @code{print-Y-axis} function, which inserts the list as a column.
20163
20164@findex print-Y-axis
20165@smallexample
20166@group
20167(defun print-Y-axis (height full-Y-label-width)
20168 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
20169Height must be the maximum height of the graph.
20170Full width is the width of the highest label element."
20171;; Value of height and full-Y-label-width
20172;; are passed by `print-graph'.
20173@end group
20174@group
20175 (let ((start (point)))
20176 (insert-rectangle
20177 (Y-axis-column height full-Y-label-width))
20178 ;; @r{Place point ready for inserting graph.}
20179 (goto-char start)
20180 ;; @r{Move point forward by value of} full-Y-label-width
20181 (forward-char full-Y-label-width)))
20182@end group
20183@end smallexample
20184
20185The @code{print-Y-axis} uses the @code{insert-rectangle} function to
20186insert the Y axis labels created by the @code{Y-axis-column} function.
20187In addition, it places point at the correct position for printing the body of
20188the graph.
20189
20190You can test @code{print-Y-axis}:
20191
20192@enumerate
20193@item
20194Install
20195
20196@smallexample
20197@group
20198Y-axis-label-spacing
20199Y-axis-tic
20200Y-axis-element
20201Y-axis-column
20202print-Y-axis
20203@end group
20204@end smallexample
20205
20206@item
20207Copy the following expression:
20208
20209@smallexample
20210(print-Y-axis 12 5)
20211@end smallexample
20212
20213@item
20214Switch to the @file{*scratch*} buffer and place the cursor where you
20215want the axis labels to start.
20216
20217@item
20218Type @kbd{M-:} (@code{eval-expression}).
20219
20220@item
20221Yank the @code{graph-body-print} expression into the minibuffer
20222with @kbd{C-y} (@code{yank)}.
20223
20224@item
20225Press @key{RET} to evaluate the expression.
20226@end enumerate
20227
20228Emacs will print labels vertically, the top one being @w{@samp{10 -@w{
20229}}}. (The @code{print-graph} function will pass the value of
20230@code{height-of-top-line}, which in this case will end up as 15,
20231thereby getting rid of what might appear as a bug.)
20232
20233@need 2000
d6adf7e7 20234@node print-X-axis
8cda6f8f
GM
20235@appendixsec The @code{print-X-axis} Function
20236@cindex Axis, print horizontal
20237@cindex X axis printing
20238@cindex Print horizontal axis
20239@cindex Horizontal axis printing
20240
20241X axis labels are much like Y axis labels, except that the ticks are on a
20242line above the numbers. Labels should look like this:
20243
20244@smallexample
20245@group
20246 | | | |
20247 1 5 10 15
20248@end group
20249@end smallexample
20250
20251The first tic is under the first column of the graph and is preceded by
20252several blank spaces. These spaces provide room in rows above for the Y
20253axis labels. The second, third, fourth, and subsequent ticks are all
20254spaced equally, according to the value of @code{X-axis-label-spacing}.
20255
20256The second row of the X axis consists of numbers, preceded by several
20257blank spaces and also separated according to the value of the variable
20258@code{X-axis-label-spacing}.
20259
20260The value of the variable @code{X-axis-label-spacing} should itself be
20261measured in units of @code{symbol-width}, since you may want to change
20262the width of the symbols that you are using to print the body of the
09e80d9f 20263graph without changing the ways the graph is labeled.
8cda6f8f
GM
20264
20265@menu
20266* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
20267* X Axis Tic Marks:: Create tic marks for the horizontal axis.
20268@end menu
20269
8cda6f8f 20270@ifnottex
d6adf7e7 20271@node Similarities differences
8cda6f8f
GM
20272@unnumberedsubsec Similarities and differences
20273@end ifnottex
20274
20275The @code{print-X-axis} function is constructed in more or less the
20276same fashion as the @code{print-Y-axis} function except that it has
20277two lines: the line of tic marks and the numbers. We will write a
20278separate function to print each line and then combine them within the
20279@code{print-X-axis} function.
20280
20281This is a three step process:
20282
20283@enumerate
20284@item
20285Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
20286
20287@item
20288Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
20289
20290@item
20291Write a function to print both lines, the @code{print-X-axis} function,
20292using @code{print-X-axis-tic-line} and
20293@code{print-X-axis-numbered-line}.
20294@end enumerate
20295
d6adf7e7 20296@node X Axis Tic Marks
8cda6f8f
GM
20297@appendixsubsec X Axis Tic Marks
20298
20299The first function should print the X axis tic marks. We must specify
20300the tic marks themselves and their spacing:
20301
20302@smallexample
20303@group
20304(defvar X-axis-label-spacing
20305 (if (boundp 'graph-blank)
20306 (* 5 (length graph-blank)) 5)
20307 "Number of units from one X axis label to next.")
20308@end group
20309@end smallexample
20310
20311@noindent
20312(Note that the value of @code{graph-blank} is set by another
20313@code{defvar}. The @code{boundp} predicate checks whether it has
20314already been set; @code{boundp} returns @code{nil} if it has not. If
20315@code{graph-blank} were unbound and we did not use this conditional
20316construction, in a recent GNU Emacs, we would enter the debugger and
20317see an error message saying @samp{@w{Debugger entered--Lisp error:}
20318@w{(void-variable graph-blank)}}.)
20319
20320@need 1200
20321Here is the @code{defvar} for @code{X-axis-tic-symbol}:
20322
20323@smallexample
20324@group
20325(defvar X-axis-tic-symbol "|"
20326 "String to insert to point to a column in X axis.")
20327@end group
20328@end smallexample
20329
20330@need 1250
20331The goal is to make a line that looks like this:
20332
20333@smallexample
20334 | | | |
20335@end smallexample
20336
20337The first tic is indented so that it is under the first column, which is
20338indented to provide space for the Y axis labels.
20339
20340A tic element consists of the blank spaces that stretch from one tic to
20341the next plus a tic symbol. The number of blanks is determined by the
20342width of the tic symbol and the @code{X-axis-label-spacing}.
20343
20344@need 1250
20345The code looks like this:
20346
20347@smallexample
20348@group
20349;;; X-axis-tic-element
20350@dots{}
20351(concat
20352 (make-string
20353 ;; @r{Make a string of blanks.}
20354 (- (* symbol-width X-axis-label-spacing)
20355 (length X-axis-tic-symbol))
20356 ? )
20357 ;; @r{Concatenate blanks with tic symbol.}
20358 X-axis-tic-symbol)
20359@dots{}
20360@end group
20361@end smallexample
20362
20363Next, we determine how many blanks are needed to indent the first tic
20364mark to the first column of the graph. This uses the value of
20365@code{full-Y-label-width} passed it by the @code{print-graph} function.
20366
20367@need 1250
20368The code to make @code{X-axis-leading-spaces}
20369looks like this:
20370
20371@smallexample
20372@group
20373;; X-axis-leading-spaces
20374@dots{}
20375(make-string full-Y-label-width ? )
20376@dots{}
20377@end group
20378@end smallexample
20379
20380We also need to determine the length of the horizontal axis, which is
20381the length of the numbers list, and the number of ticks in the horizontal
20382axis:
20383
20384@smallexample
20385@group
20386;; X-length
20387@dots{}
20388(length numbers-list)
20389@end group
20390
20391@group
20392;; tic-width
20393@dots{}
20394(* symbol-width X-axis-label-spacing)
20395@end group
20396
20397@group
20398;; number-of-X-ticks
20399(if (zerop (% (X-length tic-width)))
20400 (/ (X-length tic-width))
20401 (1+ (/ (X-length tic-width))))
20402@end group
20403@end smallexample
20404
20405@need 1250
20406All this leads us directly to the function for printing the X axis tic line:
20407
20408@findex print-X-axis-tic-line
20409@smallexample
20410@group
20411(defun print-X-axis-tic-line
20412 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20413 "Print ticks for X axis."
20414 (insert X-axis-leading-spaces)
20415 (insert X-axis-tic-symbol) ; @r{Under first column.}
20416@end group
20417@group
20418 ;; @r{Insert second tic in the right spot.}
20419 (insert (concat
20420 (make-string
20421 (- (* symbol-width X-axis-label-spacing)
20422 ;; @r{Insert white space up to second tic symbol.}
20423 (* 2 (length X-axis-tic-symbol)))
20424 ? )
20425 X-axis-tic-symbol))
20426@end group
20427@group
20428 ;; @r{Insert remaining ticks.}
20429 (while (> number-of-X-tics 1)
20430 (insert X-axis-tic-element)
20431 (setq number-of-X-tics (1- number-of-X-tics))))
20432@end group
20433@end smallexample
20434
20435The line of numbers is equally straightforward:
20436
20437@need 1250
20438First, we create a numbered element with blank spaces before each number:
20439
20440@findex X-axis-element
20441@smallexample
20442@group
20443(defun X-axis-element (number)
20444 "Construct a numbered X axis element."
20445 (let ((leading-spaces
20446 (- (* symbol-width X-axis-label-spacing)
20447 (length (number-to-string number)))))
20448 (concat (make-string leading-spaces ? )
20449 (number-to-string number))))
20450@end group
20451@end smallexample
20452
20453Next, we create the function to print the numbered line, starting with
20454the number ``1'' under the first column:
20455
20456@findex print-X-axis-numbered-line
20457@smallexample
20458@group
20459(defun print-X-axis-numbered-line
20460 (number-of-X-tics X-axis-leading-spaces)
20461 "Print line of X-axis numbers"
20462 (let ((number X-axis-label-spacing))
20463 (insert X-axis-leading-spaces)
20464 (insert "1")
20465@end group
20466@group
20467 (insert (concat
20468 (make-string
20469 ;; @r{Insert white space up to next number.}
20470 (- (* symbol-width X-axis-label-spacing) 2)
20471 ? )
20472 (number-to-string number)))
20473@end group
20474@group
20475 ;; @r{Insert remaining numbers.}
20476 (setq number (+ number X-axis-label-spacing))
20477 (while (> number-of-X-tics 1)
20478 (insert (X-axis-element number))
20479 (setq number (+ number X-axis-label-spacing))
20480 (setq number-of-X-tics (1- number-of-X-tics)))))
20481@end group
20482@end smallexample
20483
20484Finally, we need to write the @code{print-X-axis} that uses
20485@code{print-X-axis-tic-line} and
20486@code{print-X-axis-numbered-line}.
20487
20488The function must determine the local values of the variables used by both
20489@code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
20490then it must call them. Also, it must print the carriage return that
20491separates the two lines.
20492
20493The function consists of a varlist that specifies five local variables,
20494and calls to each of the two line printing functions:
20495
20496@findex print-X-axis
20497@smallexample
20498@group
20499(defun print-X-axis (numbers-list)
20500 "Print X axis labels to length of NUMBERS-LIST."
20501 (let* ((leading-spaces
20502 (make-string full-Y-label-width ? ))
20503@end group
20504@group
20505 ;; symbol-width @r{is provided by} graph-body-print
20506 (tic-width (* symbol-width X-axis-label-spacing))
20507 (X-length (length numbers-list))
20508@end group
20509@group
20510 (X-tic
20511 (concat
20512 (make-string
20513@end group
20514@group
20515 ;; @r{Make a string of blanks.}
20516 (- (* symbol-width X-axis-label-spacing)
20517 (length X-axis-tic-symbol))
20518 ? )
20519@end group
20520@group
20521 ;; @r{Concatenate blanks with tic symbol.}
20522 X-axis-tic-symbol))
20523@end group
20524@group
20525 (tic-number
20526 (if (zerop (% X-length tic-width))
20527 (/ X-length tic-width)
20528 (1+ (/ X-length tic-width)))))
20529@end group
20530@group
20531 (print-X-axis-tic-line tic-number leading-spaces X-tic)
20532 (insert "\n")
20533 (print-X-axis-numbered-line tic-number leading-spaces)))
20534@end group
20535@end smallexample
20536
20537@need 1250
20538You can test @code{print-X-axis}:
20539
20540@enumerate
20541@item
20542Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
20543@code{print-X-axis-tic-line}, as well as @code{X-axis-element},
20544@code{print-X-axis-numbered-line}, and @code{print-X-axis}.
20545
20546@item
20547Copy the following expression:
20548
20549@smallexample
20550@group
20551(progn
20552 (let ((full-Y-label-width 5)
20553 (symbol-width 1))
20554 (print-X-axis
20555 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
20556@end group
20557@end smallexample
20558
20559@item
20560Switch to the @file{*scratch*} buffer and place the cursor where you
20561want the axis labels to start.
20562
20563@item
20564Type @kbd{M-:} (@code{eval-expression}).
20565
20566@item
20567Yank the test expression into the minibuffer
20568with @kbd{C-y} (@code{yank)}.
20569
20570@item
20571Press @key{RET} to evaluate the expression.
20572@end enumerate
20573
20574@need 1250
20575Emacs will print the horizontal axis like this:
20576@sp 1
20577
20578@smallexample
20579@group
20580 | | | | |
20581 1 5 10 15 20
20582@end group
20583@end smallexample
20584
d6adf7e7 20585@node Print Whole Graph
8cda6f8f
GM
20586@appendixsec Printing the Whole Graph
20587@cindex Printing the whole graph
20588@cindex Whole graph printing
20589@cindex Graph, printing all
20590
20591Now we are nearly ready to print the whole graph.
20592
20593The function to print the graph with the proper labels follows the
09e80d9f 20594outline we created earlier (@pxref{Full Graph, , A Graph with Labeled
8cda6f8f
GM
20595Axes}), but with additions.
20596
20597@need 1250
20598Here is the outline:
20599
20600@smallexample
20601@group
20602(defun print-graph (numbers-list)
20603 "@var{documentation}@dots{}"
20604 (let ((height @dots{}
20605 @dots{}))
20606@end group
20607@group
20608 (print-Y-axis height @dots{} )
20609 (graph-body-print numbers-list)
20610 (print-X-axis @dots{} )))
20611@end group
20612@end smallexample
20613
20614@menu
20615* The final version:: A few changes.
20616* Test print-graph:: Run a short test.
20617* Graphing words in defuns:: Executing the final code.
20618* lambda:: How to write an anonymous function.
20619* mapcar:: Apply a function to elements of a list.
20620* Another Bug:: Yet another bug @dots{} most insidious.
20621* Final printed graph:: The graph itself!
20622@end menu
20623
8cda6f8f 20624@ifnottex
d6adf7e7 20625@node The final version
8cda6f8f
GM
20626@unnumberedsubsec Changes for the Final Version
20627@end ifnottex
20628
20629The final version is different from what we planned in two ways:
20630first, it contains additional values calculated once in the varlist;
20631second, it carries an option to specify the labels' increment per row.
20632This latter feature turns out to be essential; otherwise, a graph may
20633have more rows than fit on a display or on a sheet of paper.
20634
20635@need 1500
20636This new feature requires a change to the @code{Y-axis-column}
20637function, to add @code{vertical-step} to it. The function looks like
20638this:
20639
20640@findex Y-axis-column @r{Final version.}
20641@smallexample
20642@group
20643;;; @r{Final version.}
20644(defun Y-axis-column
20645 (height width-of-label &optional vertical-step)
20646 "Construct list of labels for Y axis.
20647HEIGHT is maximum height of graph.
20648WIDTH-OF-LABEL is maximum width of label.
20649VERTICAL-STEP, an option, is a positive integer
20650that specifies how much a Y axis label increments
20651for each line. For example, a step of 5 means
20652that each line is five units of the graph."
20653@end group
20654@group
20655 (let (Y-axis
20656 (number-per-line (or vertical-step 1)))
20657 (while (> height 1)
20658 (if (zerop (% height Y-axis-label-spacing))
20659@end group
20660@group
20661 ;; @r{Insert label.}
20662 (setq Y-axis
20663 (cons
20664 (Y-axis-element
20665 (* height number-per-line)
20666 width-of-label)
20667 Y-axis))
20668@end group
20669@group
20670 ;; @r{Else, insert blanks.}
20671 (setq Y-axis
20672 (cons
20673 (make-string width-of-label ? )
20674 Y-axis)))
20675 (setq height (1- height)))
20676@end group
20677@group
20678 ;; @r{Insert base line.}
20679 (setq Y-axis (cons (Y-axis-element
20680 (or vertical-step 1)
20681 width-of-label)
20682 Y-axis))
20683 (nreverse Y-axis)))
20684@end group
20685@end smallexample
20686
20687The values for the maximum height of graph and the width of a symbol
20688are computed by @code{print-graph} in its @code{let} expression; so
20689@code{graph-body-print} must be changed to accept them.
20690
20691@findex graph-body-print @r{Final version.}
20692@smallexample
20693@group
20694;;; @r{Final version.}
20695(defun graph-body-print (numbers-list height symbol-width)
20696 "Print a bar graph of the NUMBERS-LIST.
20697The numbers-list consists of the Y-axis values.
20698HEIGHT is maximum height of graph.
20699SYMBOL-WIDTH is number of each column."
20700@end group
20701@group
20702 (let (from-position)
20703 (while numbers-list
20704 (setq from-position (point))
20705 (insert-rectangle
20706 (column-of-graph height (car numbers-list)))
20707 (goto-char from-position)
20708 (forward-char symbol-width)
20709@end group
20710@group
20711 ;; @r{Draw graph column by column.}
20712 (sit-for 0)
20713 (setq numbers-list (cdr numbers-list)))
20714 ;; @r{Place point for X axis labels.}
20715 (forward-line height)
20716 (insert "\n")))
20717@end group
20718@end smallexample
20719
20720@need 1250
20721Finally, the code for the @code{print-graph} function:
20722
20723@findex print-graph @r{Final version.}
20724@smallexample
20725@group
20726;;; @r{Final version.}
20727(defun print-graph
20728 (numbers-list &optional vertical-step)
09e80d9f 20729 "Print labeled bar graph of the NUMBERS-LIST.
8cda6f8f
GM
20730The numbers-list consists of the Y-axis values.
20731@end group
20732
20733@group
20734Optionally, VERTICAL-STEP, a positive integer,
20735specifies how much a Y axis label increments for
20736each line. For example, a step of 5 means that
20737each row is five units."
20738@end group
20739@group
20740 (let* ((symbol-width (length graph-blank))
20741 ;; @code{height} @r{is both the largest number}
20742 ;; @r{and the number with the most digits.}
20743 (height (apply 'max numbers-list))
20744@end group
20745@group
20746 (height-of-top-line
20747 (if (zerop (% height Y-axis-label-spacing))
20748 height
20749 ;; @r{else}
20750 (* (1+ (/ height Y-axis-label-spacing))
20751 Y-axis-label-spacing)))
20752@end group
20753@group
20754 (vertical-step (or vertical-step 1))
20755 (full-Y-label-width
20756 (length
20757@end group
20758@group
20759 (concat
20760 (number-to-string
20761 (* height-of-top-line vertical-step))
20762 Y-axis-tic))))
20763@end group
20764
20765@group
20766 (print-Y-axis
20767 height-of-top-line full-Y-label-width vertical-step)
20768@end group
20769@group
20770 (graph-body-print
20771 numbers-list height-of-top-line symbol-width)
20772 (print-X-axis numbers-list)))
20773@end group
20774@end smallexample
20775
d6adf7e7 20776@node Test print-graph
8cda6f8f
GM
20777@appendixsubsec Testing @code{print-graph}
20778
20779@need 1250
20780We can test the @code{print-graph} function with a short list of numbers:
20781
20782@enumerate
20783@item
20784Install the final versions of @code{Y-axis-column},
20785@code{graph-body-print}, and @code{print-graph} (in addition to the
20786rest of the code.)
20787
20788@item
20789Copy the following expression:
20790
20791@smallexample
20792(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20793@end smallexample
20794
20795@item
20796Switch to the @file{*scratch*} buffer and place the cursor where you
20797want the axis labels to start.
20798
20799@item
20800Type @kbd{M-:} (@code{eval-expression}).
20801
20802@item
20803Yank the test expression into the minibuffer
20804with @kbd{C-y} (@code{yank)}.
20805
20806@item
20807Press @key{RET} to evaluate the expression.
20808@end enumerate
20809
20810@need 1250
20811Emacs will print a graph that looks like this:
20812
20813@smallexample
20814@group
2081510 -
20816
20817
20818 *
20819 ** *
20820 5 - **** *
20821 **** ***
20822 * *********
20823 ************
20824 1 - *************
20825
20826 | | | |
20827 1 5 10 15
20828@end group
20829@end smallexample
20830
20831@need 1200
20832On the other hand, if you pass @code{print-graph} a
20833@code{vertical-step} value of 2, by evaluating this expression:
20834
20835@smallexample
20836(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20837@end smallexample
20838
20839@need 1250
20840@noindent
20841The graph looks like this:
20842
20843@smallexample
20844@group
2084520 -
20846
20847
20848 *
20849 ** *
2085010 - **** *
20851 **** ***
20852 * *********
20853 ************
20854 2 - *************
20855
20856 | | | |
20857 1 5 10 15
20858@end group
20859@end smallexample
20860
20861@noindent
20862(A question: is the `2' on the bottom of the vertical axis a bug or a
20863feature? If you think it is a bug, and should be a `1' instead, (or
20864even a `0'), you can modify the sources.)
20865
d6adf7e7 20866@node Graphing words in defuns
8cda6f8f
GM
20867@appendixsubsec Graphing Numbers of Words and Symbols
20868
20869Now for the graph for which all this code was written: a graph that
20870shows how many function definitions contain fewer than 10 words and
20871symbols, how many contain between 10 and 19 words and symbols, how
20872many contain between 20 and 29 words and symbols, and so on.
20873
20874This is a multi-step process. First make sure you have loaded all the
20875requisite code.
20876
20877@need 1500
20878It is a good idea to reset the value of @code{top-of-ranges} in case
20879you have set it to some different value. You can evaluate the
20880following:
20881
20882@smallexample
20883@group
20884(setq top-of-ranges
20885 '(10 20 30 40 50
20886 60 70 80 90 100
20887 110 120 130 140 150
20888 160 170 180 190 200
20889 210 220 230 240 250
20890 260 270 280 290 300)
20891@end group
20892@end smallexample
20893
20894@noindent
20895Next create a list of the number of words and symbols in each range.
20896
20897@need 1500
20898@noindent
20899Evaluate the following:
20900
20901@smallexample
20902@group
20903(setq list-for-graph
20904 (defuns-per-range
20905 (sort
20906 (recursive-lengths-list-many-files
20907 (directory-files "/usr/local/emacs/lisp"
20908 t ".+el$"))
20909 '<)
20910 top-of-ranges))
20911@end group
20912@end smallexample
20913
20914@noindent
20915On my old machine, this took about an hour. It looked though 303 Lisp
20916files in my copy of Emacs version 19.23. After all that computing,
20917the @code{list-for-graph} had this value:
20918
20919@smallexample
20920@group
20921(537 1027 955 785 594 483 349 292 224 199 166 120 116 99
2092290 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20923@end group
20924@end smallexample
20925
20926@noindent
20927This means that my copy of Emacs had 537 function definitions with
20928fewer than 10 words or symbols in them, 1,027 function definitions
20929with 10 to 19 words or symbols in them, 955 function definitions with
2093020 to 29 words or symbols in them, and so on.
20931
20932Clearly, just by looking at this list we can see that most function
20933definitions contain ten to thirty words and symbols.
20934
20935Now for printing. We do @emph{not} want to print a graph that is
209361,030 lines high @dots{} Instead, we should print a graph that is
20937fewer than twenty-five lines high. A graph that height can be
20938displayed on almost any monitor, and easily printed on a sheet of paper.
20939
20940This means that each value in @code{list-for-graph} must be reduced to
20941one-fiftieth its present value.
20942
20943Here is a short function to do just that, using two functions we have
20944not yet seen, @code{mapcar} and @code{lambda}.
20945
20946@smallexample
20947@group
20948(defun one-fiftieth (full-range)
20949 "Return list, each number one-fiftieth of previous."
d1069532 20950 (mapcar (lambda (arg) (/ arg 50)) full-range))
8cda6f8f
GM
20951@end group
20952@end smallexample
20953
d6adf7e7 20954@node lambda
8cda6f8f
GM
20955@appendixsubsec A @code{lambda} Expression: Useful Anonymity
20956@cindex Anonymous function
20957@findex lambda
20958
20959@code{lambda} is the symbol for an anonymous function, a function
20960without a name. Every time you use an anonymous function, you need to
20961include its whole body.
20962
20963@need 1250
20964@noindent
20965Thus,
20966
20967@smallexample
20968(lambda (arg) (/ arg 50))
20969@end smallexample
20970
20971@noindent
20972is a function definition that says `return the value resulting from
20973dividing whatever is passed to me as @code{arg} by 50'.
20974
20975@need 1200
20976Earlier, for example, we had a function @code{multiply-by-seven}; it
20977multiplied its argument by 7. This function is similar, except it
20978divides its argument by 50; and, it has no name. The anonymous
20979equivalent of @code{multiply-by-seven} is:
20980
20981@smallexample
20982(lambda (number) (* 7 number))
20983@end smallexample
20984
20985@noindent
20986(@xref{defun, , The @code{defun} Special Form}.)
20987
20988@need 1250
20989@noindent
20990If we want to multiply 3 by 7, we can write:
20991
20992@c !!! Clear print-postscript-figures if the computer formatting this
20993@c document is too small and cannot handle all the diagrams and figures.
20994@c clear print-postscript-figures
20995@c set print-postscript-figures
20996@c lambda example diagram #1
20997@ifnottex
20998@smallexample
20999@group
21000(multiply-by-seven 3)
21001 \_______________/ ^
21002 | |
21003 function argument
21004@end group
21005@end smallexample
21006@end ifnottex
21007@ifset print-postscript-figures
21008@sp 1
21009@tex
21010@center @image{lambda-1}
21011%%%% old method of including an image
21012% \input /usr/local/lib/tex/inputs/psfig.tex
21013% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
21014% \catcode`\@=0 %
21015@end tex
21016@sp 1
21017@end ifset
21018@ifclear print-postscript-figures
21019@iftex
21020@smallexample
21021@group
21022(multiply-by-seven 3)
21023 \_______________/ ^
21024 | |
21025 function argument
21026@end group
21027@end smallexample
21028@end iftex
21029@end ifclear
21030
21031@noindent
21032This expression returns 21.
21033
21034@need 1250
21035@noindent
21036Similarly, we can write:
21037
21038@c lambda example diagram #2
21039@ifnottex
21040@smallexample
21041@group
21042((lambda (number) (* 7 number)) 3)
21043 \____________________________/ ^
21044 | |
21045 anonymous function argument
21046@end group
21047@end smallexample
21048@end ifnottex
21049@ifset print-postscript-figures
21050@sp 1
21051@tex
21052@center @image{lambda-2}
21053%%%% old method of including an image
21054% \input /usr/local/lib/tex/inputs/psfig.tex
21055% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
21056% \catcode`\@=0 %
21057@end tex
21058@sp 1
21059@end ifset
21060@ifclear print-postscript-figures
21061@iftex
21062@smallexample
21063@group
21064((lambda (number) (* 7 number)) 3)
21065 \____________________________/ ^
21066 | |
21067 anonymous function argument
21068@end group
21069@end smallexample
21070@end iftex
21071@end ifclear
21072
21073@need 1250
21074@noindent
21075If we want to divide 100 by 50, we can write:
21076
21077@c lambda example diagram #3
21078@ifnottex
21079@smallexample
21080@group
21081((lambda (arg) (/ arg 50)) 100)
21082 \______________________/ \_/
21083 | |
21084 anonymous function argument
21085@end group
21086@end smallexample
21087@end ifnottex
21088@ifset print-postscript-figures
21089@sp 1
21090@tex
21091@center @image{lambda-3}
21092%%%% old method of including an image
21093% \input /usr/local/lib/tex/inputs/psfig.tex
21094% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
21095% \catcode`\@=0 %
21096@end tex
21097@sp 1
21098@end ifset
21099@ifclear print-postscript-figures
21100@iftex
21101@smallexample
21102@group
21103((lambda (arg) (/ arg 50)) 100)
21104 \______________________/ \_/
21105 | |
21106 anonymous function argument
21107@end group
21108@end smallexample
21109@end iftex
21110@end ifclear
21111
21112@noindent
21113This expression returns 2. The 100 is passed to the function, which
21114divides that number by 50.
21115
21116@xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
21117Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
21118expressions derive from the Lambda Calculus.
21119
d6adf7e7 21120@node mapcar
8cda6f8f
GM
21121@appendixsubsec The @code{mapcar} Function
21122@findex mapcar
21123
21124@code{mapcar} is a function that calls its first argument with each
21125element of its second argument, in turn. The second argument must be
21126a sequence.
21127
21128The @samp{map} part of the name comes from the mathematical phrase,
21129`mapping over a domain', meaning to apply a function to each of the
21130elements in a domain. The mathematical phrase is based on the
21131metaphor of a surveyor walking, one step at a time, over an area he is
21132mapping. And @samp{car}, of course, comes from the Lisp notion of the
21133first of a list.
21134
21135@need 1250
21136@noindent
21137For example,
21138
21139@smallexample
21140@group
21141(mapcar '1+ '(2 4 6))
21142 @result{} (3 5 7)
21143@end group
21144@end smallexample
21145
21146@noindent
21147The function @code{1+} which adds one to its argument, is executed on
21148@emph{each} element of the list, and a new list is returned.
21149
21150Contrast this with @code{apply}, which applies its first argument to
21151all the remaining.
21152(@xref{Readying a Graph, , Readying a Graph}, for a explanation of
21153@code{apply}.)
21154
21155@need 1250
21156In the definition of @code{one-fiftieth}, the first argument is the
21157anonymous function:
21158
21159@smallexample
21160(lambda (arg) (/ arg 50))
21161@end smallexample
21162
21163@noindent
21164and the second argument is @code{full-range}, which will be bound to
21165@code{list-for-graph}.
21166
21167@need 1250
21168The whole expression looks like this:
21169
21170@smallexample
d1069532 21171(mapcar (lambda (arg) (/ arg 50)) full-range))
8cda6f8f
GM
21172@end smallexample
21173
21174@xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
21175Lisp Reference Manual}, for more about @code{mapcar}.
21176
21177Using the @code{one-fiftieth} function, we can generate a list in
21178which each element is one-fiftieth the size of the corresponding
21179element in @code{list-for-graph}.
21180
21181@smallexample
21182@group
21183(setq fiftieth-list-for-graph
21184 (one-fiftieth list-for-graph))
21185@end group
21186@end smallexample
21187
21188@need 1250
21189The resulting list looks like this:
21190
21191@smallexample
21192@group
21193(10 20 19 15 11 9 6 5 4 3 3 2 2
211941 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
21195@end group
21196@end smallexample
21197
21198@noindent
21199This, we are almost ready to print! (We also notice the loss of
21200information: many of the higher ranges are 0, meaning that fewer than
2120150 defuns had that many words or symbols---but not necessarily meaning
21202that none had that many words or symbols.)
21203
d6adf7e7 21204@node Another Bug
8cda6f8f
GM
21205@appendixsubsec Another Bug @dots{} Most Insidious
21206@cindex Bug, most insidious type
21207@cindex Insidious type of bug
21208
21209I said `almost ready to print'! Of course, there is a bug in the
21210@code{print-graph} function @dots{} It has a @code{vertical-step}
21211option, but not a @code{horizontal-step} option. The
21212@code{top-of-range} scale goes from 10 to 300 by tens. But the
21213@code{print-graph} function will print only by ones.
21214
21215This is a classic example of what some consider the most insidious
21216type of bug, the bug of omission. This is not the kind of bug you can
21217find by studying the code, for it is not in the code; it is an omitted
21218feature. Your best actions are to try your program early and often;
21219and try to arrange, as much as you can, to write code that is easy to
21220understand and easy to change. Try to be aware, whenever you can,
21221that whatever you have written, @emph{will} be rewritten, if not soon,
21222eventually. A hard maxim to follow.
21223
21224It is the @code{print-X-axis-numbered-line} function that needs the
21225work; and then the @code{print-X-axis} and the @code{print-graph}
21226functions need to be adapted. Not much needs to be done; there is one
21227nicety: the numbers ought to line up under the tic marks. This takes
21228a little thought.
21229
21230@need 1250
21231Here is the corrected @code{print-X-axis-numbered-line}:
21232
21233@smallexample
21234@group
21235(defun print-X-axis-numbered-line
21236 (number-of-X-tics X-axis-leading-spaces
21237 &optional horizontal-step)
21238 "Print line of X-axis numbers"
21239 (let ((number X-axis-label-spacing)
21240 (horizontal-step (or horizontal-step 1)))
21241@end group
21242@group
21243 (insert X-axis-leading-spaces)
21244 ;; @r{Delete extra leading spaces.}
21245 (delete-char
21246 (- (1-
21247 (length (number-to-string horizontal-step)))))
21248 (insert (concat
21249 (make-string
21250@end group
21251@group
21252 ;; @r{Insert white space.}
21253 (- (* symbol-width
21254 X-axis-label-spacing)
21255 (1-
21256 (length
21257 (number-to-string horizontal-step)))
21258 2)
21259 ? )
21260 (number-to-string
21261 (* number horizontal-step))))
21262@end group
21263@group
21264 ;; @r{Insert remaining numbers.}
21265 (setq number (+ number X-axis-label-spacing))
21266 (while (> number-of-X-tics 1)
21267 (insert (X-axis-element
21268 (* number horizontal-step)))
21269 (setq number (+ number X-axis-label-spacing))
21270 (setq number-of-X-tics (1- number-of-X-tics)))))
21271@end group
21272@end smallexample
21273
21274@need 1500
21275If you are reading this in Info, you can see the new versions of
21276@code{print-X-axis} @code{print-graph} and evaluate them. If you are
21277reading this in a printed book, you can see the changed lines here
21278(the full text is too much to print).
21279
21280@iftex
21281@smallexample
21282@group
21283(defun print-X-axis (numbers-list horizontal-step)
21284 @dots{}
21285 (print-X-axis-numbered-line
21286 tic-number leading-spaces horizontal-step))
21287@end group
21288@end smallexample
21289
21290@smallexample
21291@group
21292(defun print-graph
21293 (numbers-list
21294 &optional vertical-step horizontal-step)
21295 @dots{}
21296 (print-X-axis numbers-list horizontal-step))
21297@end group
21298@end smallexample
21299@end iftex
21300
21301@ifnottex
21302@smallexample
21303@group
21304(defun print-X-axis (numbers-list horizontal-step)
21305 "Print X axis labels to length of NUMBERS-LIST.
21306Optionally, HORIZONTAL-STEP, a positive integer,
21307specifies how much an X axis label increments for
21308each column."
21309@end group
21310@group
21311;; Value of symbol-width and full-Y-label-width
21312;; are passed by `print-graph'.
21313 (let* ((leading-spaces
21314 (make-string full-Y-label-width ? ))
21315 ;; symbol-width @r{is provided by} graph-body-print
21316 (tic-width (* symbol-width X-axis-label-spacing))
21317 (X-length (length numbers-list))
21318@end group
21319@group
21320 (X-tic
21321 (concat
21322 (make-string
21323 ;; @r{Make a string of blanks.}
21324 (- (* symbol-width X-axis-label-spacing)
21325 (length X-axis-tic-symbol))
21326 ? )
21327@end group
21328@group
21329 ;; @r{Concatenate blanks with tic symbol.}
21330 X-axis-tic-symbol))
21331 (tic-number
21332 (if (zerop (% X-length tic-width))
21333 (/ X-length tic-width)
21334 (1+ (/ X-length tic-width)))))
21335@end group
21336
21337@group
21338 (print-X-axis-tic-line
21339 tic-number leading-spaces X-tic)
21340 (insert "\n")
21341 (print-X-axis-numbered-line
21342 tic-number leading-spaces horizontal-step)))
21343@end group
21344@end smallexample
21345
21346@smallexample
21347@group
21348(defun print-graph
21349 (numbers-list &optional vertical-step horizontal-step)
09e80d9f 21350 "Print labeled bar graph of the NUMBERS-LIST.
8cda6f8f
GM
21351The numbers-list consists of the Y-axis values.
21352@end group
21353
21354@group
21355Optionally, VERTICAL-STEP, a positive integer,
21356specifies how much a Y axis label increments for
21357each line. For example, a step of 5 means that
21358each row is five units.
21359@end group
21360
21361@group
21362Optionally, HORIZONTAL-STEP, a positive integer,
21363specifies how much an X axis label increments for
21364each column."
21365 (let* ((symbol-width (length graph-blank))
21366 ;; @code{height} @r{is both the largest number}
21367 ;; @r{and the number with the most digits.}
21368 (height (apply 'max numbers-list))
21369@end group
21370@group
21371 (height-of-top-line
21372 (if (zerop (% height Y-axis-label-spacing))
21373 height
21374 ;; @r{else}
21375 (* (1+ (/ height Y-axis-label-spacing))
21376 Y-axis-label-spacing)))
21377@end group
21378@group
21379 (vertical-step (or vertical-step 1))
21380 (full-Y-label-width
21381 (length
21382 (concat
21383 (number-to-string
21384 (* height-of-top-line vertical-step))
21385 Y-axis-tic))))
21386@end group
21387@group
21388 (print-Y-axis
21389 height-of-top-line full-Y-label-width vertical-step)
21390 (graph-body-print
21391 numbers-list height-of-top-line symbol-width)
21392 (print-X-axis numbers-list horizontal-step)))
21393@end group
21394@end smallexample
21395@end ifnottex
21396
21397@c qqq
21398@ignore
21399Graphing Definitions Re-listed
21400
21401@need 1250
21402Here are all the graphing definitions in their final form:
21403
21404@smallexample
21405@group
21406(defvar top-of-ranges
21407 '(10 20 30 40 50
21408 60 70 80 90 100
21409 110 120 130 140 150
21410 160 170 180 190 200
21411 210 220 230 240 250)
21412 "List specifying ranges for `defuns-per-range'.")
21413@end group
21414
21415@group
21416(defvar graph-symbol "*"
21417 "String used as symbol in graph, usually an asterisk.")
21418@end group
21419
21420@group
21421(defvar graph-blank " "
21422 "String used as blank in graph, usually a blank space.
21423graph-blank must be the same number of columns wide
21424as graph-symbol.")
21425@end group
21426
21427@group
21428(defvar Y-axis-tic " - "
21429 "String that follows number in a Y axis label.")
21430@end group
21431
21432@group
21433(defvar Y-axis-label-spacing 5
21434 "Number of lines from one Y axis label to next.")
21435@end group
21436
21437@group
21438(defvar X-axis-tic-symbol "|"
21439 "String to insert to point to a column in X axis.")
21440@end group
21441
21442@group
21443(defvar X-axis-label-spacing
21444 (if (boundp 'graph-blank)
21445 (* 5 (length graph-blank)) 5)
21446 "Number of units from one X axis label to next.")
21447@end group
21448@end smallexample
21449
21450@smallexample
21451@group
21452(defun count-words-in-defun ()
21453 "Return the number of words and symbols in a defun."
21454 (beginning-of-defun)
21455 (let ((count 0)
21456 (end (save-excursion (end-of-defun) (point))))
21457@end group
21458
21459@group
21460 (while
21461 (and (< (point) end)
21462 (re-search-forward
21463 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
21464 end t))
21465 (setq count (1+ count)))
21466 count))
21467@end group
21468@end smallexample
21469
21470@smallexample
21471@group
21472(defun lengths-list-file (filename)
21473 "Return list of definitions' lengths within FILE.
21474The returned list is a list of numbers.
21475Each number is the number of words or
21476symbols in one function definition."
21477@end group
21478
21479@group
21480 (message "Working on `%s' ... " filename)
21481 (save-excursion
21482 (let ((buffer (find-file-noselect filename))
21483 (lengths-list))
21484 (set-buffer buffer)
21485 (setq buffer-read-only t)
21486 (widen)
21487 (goto-char (point-min))
21488@end group
21489
21490@group
21491 (while (re-search-forward "^(defun" nil t)
21492 (setq lengths-list
21493 (cons (count-words-in-defun) lengths-list)))
21494 (kill-buffer buffer)
21495 lengths-list)))
21496@end group
21497@end smallexample
21498
21499@smallexample
21500@group
21501(defun lengths-list-many-files (list-of-files)
21502 "Return list of lengths of defuns in LIST-OF-FILES."
21503 (let (lengths-list)
21504;;; @r{true-or-false-test}
21505 (while list-of-files
21506 (setq lengths-list
21507 (append
21508 lengths-list
21509@end group
21510@group
21511;;; @r{Generate a lengths' list.}
21512 (lengths-list-file
21513 (expand-file-name (car list-of-files)))))
21514;;; @r{Make files' list shorter.}
21515 (setq list-of-files (cdr list-of-files)))
21516;;; @r{Return final value of lengths' list.}
21517 lengths-list))
21518@end group
21519@end smallexample
21520
21521@smallexample
21522@group
21523(defun defuns-per-range (sorted-lengths top-of-ranges)
21524 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
21525 (let ((top-of-range (car top-of-ranges))
21526 (number-within-range 0)
21527 defuns-per-range-list)
21528@end group
21529
21530@group
21531 ;; @r{Outer loop.}
21532 (while top-of-ranges
21533
21534 ;; @r{Inner loop.}
21535 (while (and
21536 ;; @r{Need number for numeric test.}
21537 (car sorted-lengths)
21538 (< (car sorted-lengths) top-of-range))
21539
21540 ;; @r{Count number of definitions within current range.}
21541 (setq number-within-range (1+ number-within-range))
21542 (setq sorted-lengths (cdr sorted-lengths)))
21543@end group
21544
21545@group
21546 ;; @r{Exit inner loop but remain within outer loop.}
21547
21548 (setq defuns-per-range-list
21549 (cons number-within-range defuns-per-range-list))
21550 (setq number-within-range 0) ; @r{Reset count to zero.}
21551
21552 ;; @r{Move to next range.}
21553 (setq top-of-ranges (cdr top-of-ranges))
21554 ;; @r{Specify next top of range value.}
21555 (setq top-of-range (car top-of-ranges)))
21556@end group
21557
21558@group
21559 ;; @r{Exit outer loop and count the number of defuns larger than}
21560 ;; @r{ the largest top-of-range value.}
21561 (setq defuns-per-range-list
21562 (cons
21563 (length sorted-lengths)
21564 defuns-per-range-list))
21565
21566 ;; @r{Return a list of the number of definitions within each range,}
21567 ;; @r{ smallest to largest.}
21568 (nreverse defuns-per-range-list)))
21569@end group
21570@end smallexample
21571
21572@smallexample
21573@group
21574(defun column-of-graph (max-graph-height actual-height)
21575 "Return list of MAX-GRAPH-HEIGHT strings;
21576ACTUAL-HEIGHT are graph-symbols.
21577The graph-symbols are contiguous entries at the end
21578of the list.
21579The list will be inserted as one column of a graph.
21580The strings are either graph-blank or graph-symbol."
21581@end group
21582
21583@group
21584 (let ((insert-list nil)
21585 (number-of-top-blanks
21586 (- max-graph-height actual-height)))
21587
21588 ;; @r{Fill in @code{graph-symbols}.}
21589 (while (> actual-height 0)
21590 (setq insert-list (cons graph-symbol insert-list))
21591 (setq actual-height (1- actual-height)))
21592@end group
21593
21594@group
21595 ;; @r{Fill in @code{graph-blanks}.}
21596 (while (> number-of-top-blanks 0)
21597 (setq insert-list (cons graph-blank insert-list))
21598 (setq number-of-top-blanks
21599 (1- number-of-top-blanks)))
21600
21601 ;; @r{Return whole list.}
21602 insert-list))
21603@end group
21604@end smallexample
21605
21606@smallexample
21607@group
21608(defun Y-axis-element (number full-Y-label-width)
21609 "Construct a NUMBERed label element.
21610A numbered element looks like this ` 5 - ',
21611and is padded as needed so all line up with
21612the element for the largest number."
21613@end group
21614@group
21615 (let* ((leading-spaces
21616 (- full-Y-label-width
21617 (length
21618 (concat (number-to-string number)
21619 Y-axis-tic)))))
21620@end group
21621@group
21622 (concat
21623 (make-string leading-spaces ? )
21624 (number-to-string number)
21625 Y-axis-tic)))
21626@end group
21627@end smallexample
21628
21629@smallexample
21630@group
21631(defun print-Y-axis
21632 (height full-Y-label-width &optional vertical-step)
21633 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
21634Height must be the maximum height of the graph.
21635Full width is the width of the highest label element.
21636Optionally, print according to VERTICAL-STEP."
21637@end group
21638@group
21639;; Value of height and full-Y-label-width
21640;; are passed by `print-graph'.
21641 (let ((start (point)))
21642 (insert-rectangle
21643 (Y-axis-column height full-Y-label-width vertical-step))
21644@end group
21645@group
21646 ;; @r{Place point ready for inserting graph.}
21647 (goto-char start)
21648 ;; @r{Move point forward by value of} full-Y-label-width
21649 (forward-char full-Y-label-width)))
21650@end group
21651@end smallexample
21652
21653@smallexample
21654@group
21655(defun print-X-axis-tic-line
21656 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
21657 "Print ticks for X axis."
21658 (insert X-axis-leading-spaces)
21659 (insert X-axis-tic-symbol) ; @r{Under first column.}
21660@end group
21661@group
21662 ;; @r{Insert second tic in the right spot.}
21663 (insert (concat
21664 (make-string
21665 (- (* symbol-width X-axis-label-spacing)
21666 ;; @r{Insert white space up to second tic symbol.}
21667 (* 2 (length X-axis-tic-symbol)))
21668 ? )
21669 X-axis-tic-symbol))
21670@end group
21671@group
21672 ;; @r{Insert remaining ticks.}
21673 (while (> number-of-X-tics 1)
21674 (insert X-axis-tic-element)
21675 (setq number-of-X-tics (1- number-of-X-tics))))
21676@end group
21677@end smallexample
21678
21679@smallexample
21680@group
21681(defun X-axis-element (number)
21682 "Construct a numbered X axis element."
21683 (let ((leading-spaces
21684 (- (* symbol-width X-axis-label-spacing)
21685 (length (number-to-string number)))))
21686 (concat (make-string leading-spaces ? )
21687 (number-to-string number))))
21688@end group
21689@end smallexample
21690
21691@smallexample
21692@group
21693(defun graph-body-print (numbers-list height symbol-width)
21694 "Print a bar graph of the NUMBERS-LIST.
21695The numbers-list consists of the Y-axis values.
21696HEIGHT is maximum height of graph.
21697SYMBOL-WIDTH is number of each column."
21698@end group
21699@group
21700 (let (from-position)
21701 (while numbers-list
21702 (setq from-position (point))
21703 (insert-rectangle
21704 (column-of-graph height (car numbers-list)))
21705 (goto-char from-position)
21706 (forward-char symbol-width)
21707@end group
21708@group
21709 ;; @r{Draw graph column by column.}
21710 (sit-for 0)
21711 (setq numbers-list (cdr numbers-list)))
21712 ;; @r{Place point for X axis labels.}
21713 (forward-line height)
21714 (insert "\n")))
21715@end group
21716@end smallexample
21717
21718@smallexample
21719@group
21720(defun Y-axis-column
21721 (height width-of-label &optional vertical-step)
21722 "Construct list of labels for Y axis.
21723HEIGHT is maximum height of graph.
21724WIDTH-OF-LABEL is maximum width of label.
21725@end group
21726@group
21727VERTICAL-STEP, an option, is a positive integer
21728that specifies how much a Y axis label increments
21729for each line. For example, a step of 5 means
21730that each line is five units of the graph."
21731 (let (Y-axis
21732 (number-per-line (or vertical-step 1)))
21733@end group
21734@group
21735 (while (> height 1)
21736 (if (zerop (% height Y-axis-label-spacing))
21737 ;; @r{Insert label.}
21738 (setq Y-axis
21739 (cons
21740 (Y-axis-element
21741 (* height number-per-line)
21742 width-of-label)
21743 Y-axis))
21744@end group
21745@group
21746 ;; @r{Else, insert blanks.}
21747 (setq Y-axis
21748 (cons
21749 (make-string width-of-label ? )
21750 Y-axis)))
21751 (setq height (1- height)))
21752@end group
21753@group
21754 ;; @r{Insert base line.}
21755 (setq Y-axis (cons (Y-axis-element
21756 (or vertical-step 1)
21757 width-of-label)
21758 Y-axis))
21759 (nreverse Y-axis)))
21760@end group
21761@end smallexample
21762
21763@smallexample
21764@group
21765(defun print-X-axis-numbered-line
21766 (number-of-X-tics X-axis-leading-spaces
21767 &optional horizontal-step)
21768 "Print line of X-axis numbers"
21769 (let ((number X-axis-label-spacing)
21770 (horizontal-step (or horizontal-step 1)))
21771@end group
21772@group
21773 (insert X-axis-leading-spaces)
21774 ;; line up number
21775 (delete-char (- (1- (length (number-to-string horizontal-step)))))
21776 (insert (concat
21777 (make-string
21778 ;; @r{Insert white space up to next number.}
21779 (- (* symbol-width X-axis-label-spacing)
21780 (1- (length (number-to-string horizontal-step)))
21781 2)
21782 ? )
21783 (number-to-string (* number horizontal-step))))
21784@end group
21785@group
21786 ;; @r{Insert remaining numbers.}
21787 (setq number (+ number X-axis-label-spacing))
21788 (while (> number-of-X-tics 1)
21789 (insert (X-axis-element (* number horizontal-step)))
21790 (setq number (+ number X-axis-label-spacing))
21791 (setq number-of-X-tics (1- number-of-X-tics)))))
21792@end group
21793@end smallexample
21794
21795@smallexample
21796@group
21797(defun print-X-axis (numbers-list horizontal-step)
21798 "Print X axis labels to length of NUMBERS-LIST.
21799Optionally, HORIZONTAL-STEP, a positive integer,
21800specifies how much an X axis label increments for
21801each column."
21802@end group
21803@group
21804;; Value of symbol-width and full-Y-label-width
21805;; are passed by `print-graph'.
21806 (let* ((leading-spaces
21807 (make-string full-Y-label-width ? ))
21808 ;; symbol-width @r{is provided by} graph-body-print
21809 (tic-width (* symbol-width X-axis-label-spacing))
21810 (X-length (length numbers-list))
21811@end group
21812@group
21813 (X-tic
21814 (concat
21815 (make-string
21816 ;; @r{Make a string of blanks.}
21817 (- (* symbol-width X-axis-label-spacing)
21818 (length X-axis-tic-symbol))
21819 ? )
21820@end group
21821@group
21822 ;; @r{Concatenate blanks with tic symbol.}
21823 X-axis-tic-symbol))
21824 (tic-number
21825 (if (zerop (% X-length tic-width))
21826 (/ X-length tic-width)
21827 (1+ (/ X-length tic-width)))))
21828@end group
21829
21830@group
21831 (print-X-axis-tic-line
21832 tic-number leading-spaces X-tic)
21833 (insert "\n")
21834 (print-X-axis-numbered-line
21835 tic-number leading-spaces horizontal-step)))
21836@end group
21837@end smallexample
21838
21839@smallexample
21840@group
21841(defun one-fiftieth (full-range)
21842 "Return list, each number of which is 1/50th previous."
d1069532 21843 (mapcar (lambda (arg) (/ arg 50)) full-range))
8cda6f8f
GM
21844@end group
21845@end smallexample
21846
21847@smallexample
21848@group
21849(defun print-graph
21850 (numbers-list &optional vertical-step horizontal-step)
09e80d9f 21851 "Print labeled bar graph of the NUMBERS-LIST.
8cda6f8f
GM
21852The numbers-list consists of the Y-axis values.
21853@end group
21854
21855@group
21856Optionally, VERTICAL-STEP, a positive integer,
21857specifies how much a Y axis label increments for
21858each line. For example, a step of 5 means that
21859each row is five units.
21860@end group
21861
21862@group
21863Optionally, HORIZONTAL-STEP, a positive integer,
21864specifies how much an X axis label increments for
21865each column."
21866 (let* ((symbol-width (length graph-blank))
21867 ;; @code{height} @r{is both the largest number}
21868 ;; @r{and the number with the most digits.}
21869 (height (apply 'max numbers-list))
21870@end group
21871@group
21872 (height-of-top-line
21873 (if (zerop (% height Y-axis-label-spacing))
21874 height
21875 ;; @r{else}
21876 (* (1+ (/ height Y-axis-label-spacing))
21877 Y-axis-label-spacing)))
21878@end group
21879@group
21880 (vertical-step (or vertical-step 1))
21881 (full-Y-label-width
21882 (length
21883 (concat
21884 (number-to-string
21885 (* height-of-top-line vertical-step))
21886 Y-axis-tic))))
21887@end group
21888@group
21889
21890 (print-Y-axis
21891 height-of-top-line full-Y-label-width vertical-step)
21892 (graph-body-print
21893 numbers-list height-of-top-line symbol-width)
21894 (print-X-axis numbers-list horizontal-step)))
21895@end group
21896@end smallexample
21897@c qqq
21898@end ignore
21899
21900@page
d6adf7e7 21901@node Final printed graph
8cda6f8f
GM
21902@appendixsubsec The Printed Graph
21903
21904When made and installed, you can call the @code{print-graph} command
21905like this:
21906@sp 1
21907
21908@smallexample
21909@group
21910(print-graph fiftieth-list-for-graph 50 10)
21911@end group
21912@end smallexample
21913@sp 1
21914
21915@noindent
21916Here is the graph:
21917@sp 2
21918
21919@smallexample
21920@group
219211000 - *
21922 **
21923 **
21924 **
21925 **
21926 750 - ***
21927 ***
21928 ***
21929 ***
21930 ****
21931 500 - *****
21932 ******
21933 ******
21934 ******
21935 *******
21936 250 - ********
21937 ********* *
21938 *********** *
21939 ************* *
21940 50 - ***************** * *
21941 | | | | | | | |
21942 10 50 100 150 200 250 300 350
21943@end group
21944@end smallexample
21945
21946@sp 2
21947
21948@noindent
21949The largest group of functions contain 10 -- 19 words and symbols each.
21950
d6adf7e7 21951@node Free Software and Free Manuals
8cda6f8f
GM
21952@appendix Free Software and Free Manuals
21953
21954@strong{by Richard M. Stallman}
21955@sp 1
21956
21957The biggest deficiency in free operating systems is not in the
21958software---it is the lack of good free manuals that we can include in
21959these systems. Many of our most important programs do not come with
21960full manuals. Documentation is an essential part of any software
21961package; when an important free software package does not come with a
21962free manual, that is a major gap. We have many such gaps today.
21963
21964Once upon a time, many years ago, I thought I would learn Perl. I got
21965a copy of a free manual, but I found it hard to read. When I asked
21966Perl users about alternatives, they told me that there were better
21967introductory manuals---but those were not free.
21968
21969Why was this? The authors of the good manuals had written them for
21970O'Reilly Associates, which published them with restrictive terms---no
21971copying, no modification, source files not available---which exclude
21972them from the free software community.
21973
21974That wasn't the first time this sort of thing has happened, and (to
21975our community's great loss) it was far from the last. Proprietary
21976manual publishers have enticed a great many authors to restrict their
21977manuals since then. Many times I have heard a GNU user eagerly tell me
21978about a manual that he is writing, with which he expects to help the
21979GNU project---and then had my hopes dashed, as he proceeded to explain
21980that he had signed a contract with a publisher that would restrict it
21981so that we cannot use it.
21982
21983Given that writing good English is a rare skill among programmers, we
21984can ill afford to lose manuals this way.
21985
8cda6f8f
GM
21986Free documentation, like free software, is a matter of freedom, not
21987price. The problem with these manuals was not that O'Reilly Associates
31b62755
GM
21988charged a price for printed copies---that in itself is fine. The Free
21989Software Foundation @uref{http://shop.fsf.org, sells printed copies} of
21990free @uref{http://www.gnu.org/doc/doc.html, GNU manuals}, too.
8cda6f8f
GM
21991But GNU manuals are available in source code form, while these manuals
21992are available only on paper. GNU manuals come with permission to copy
21993and modify; the Perl manuals do not. These restrictions are the
21994problems.
21995
21996The criterion for a free manual is pretty much the same as for free
21997software: it is a matter of giving all users certain
21998freedoms. Redistribution (including commercial redistribution) must be
21999permitted, so that the manual can accompany every copy of the program,
22000on-line or on paper. Permission for modification is crucial too.
22001
22002As a general rule, I don't believe that it is essential for people to
22003have permission to modify all sorts of articles and books. The issues
22004for writings are not necessarily the same as those for software. For
22005example, I don't think you or I are obliged to give permission to
22006modify articles like this one, which describe our actions and our
22007views.
22008
22009But there is a particular reason why the freedom to modify is crucial
22010for documentation for free software. When people exercise their right
22011to modify the software, and add or change its features, if they are
22012conscientious they will change the manual too---so they can provide
22013accurate and usable documentation with the modified program. A manual
22014which forbids programmers to be conscientious and finish the job, or
22015more precisely requires them to write a new manual from scratch if
22016they change the program, does not fill our community's needs.
22017
22018While a blanket prohibition on modification is unacceptable, some
22019kinds of limits on the method of modification pose no problem. For
22020example, requirements to preserve the original author's copyright
22021notice, the distribution terms, or the list of authors, are ok. It is
22022also no problem to require modified versions to include notice that
22023they were modified, even to have entire sections that may not be
22024deleted or changed, as long as these sections deal with nontechnical
22025topics. (Some GNU manuals have them.)
22026
22027These kinds of restrictions are not a problem because, as a practical
22028matter, they don't stop the conscientious programmer from adapting the
22029manual to fit the modified program. In other words, they don't block
22030the free software community from making full use of the manual.
22031
22032However, it must be possible to modify all the technical content of
22033the manual, and then distribute the result in all the usual media,
22034through all the usual channels; otherwise, the restrictions do block
22035the community, the manual is not free, and so we need another manual.
22036
22037Unfortunately, it is often hard to find someone to write another
22038manual when a proprietary manual exists. The obstacle is that many
22039users think that a proprietary manual is good enough---so they don't
22040see the need to write a free manual. They do not see that the free
22041operating system has a gap that needs filling.
22042
22043Why do users think that proprietary manuals are good enough? Some have
22044not considered the issue. I hope this article will do something to
22045change that.
22046
22047Other users consider proprietary manuals acceptable for the same
22048reason so many people consider proprietary software acceptable: they
22049judge in purely practical terms, not using freedom as a
22050criterion. These people are entitled to their opinions, but since
22051those opinions spring from values which do not include freedom, they
22052are no guide for those of us who do value freedom.
22053
22054Please spread the word about this issue. We continue to lose manuals
22055to proprietary publishing. If we spread the word that proprietary
22056manuals are not sufficient, perhaps the next person who wants to help
22057GNU by writing documentation will realize, before it is too late, that
22058he must above all make it free.
22059
22060We can also encourage commercial publishers to sell free, copylefted
22061manuals instead of proprietary ones. One way you can help this is to
22062check the distribution terms of a manual before you buy it, and prefer
22063copylefted manuals to non-copylefted ones.
22064
22065@sp 2
22066@noindent
22067Note: The Free Software Foundation maintains a page on its Web site
22068that lists free books available from other publishers:@*
22069@uref{http://www.gnu.org/doc/other-free-books.html}
22070
d6adf7e7 22071@node GNU Free Documentation License
8cda6f8f
GM
22072@appendix GNU Free Documentation License
22073
22074@cindex FDL, GNU Free Documentation License
e41dfb1e 22075@include doclicense.texi
8cda6f8f 22076
d6adf7e7 22077@node Index
8cda6f8f
GM
22078@unnumbered Index
22079
22080@ignore
22081MENU ENTRY: NODE NAME.
22082@end ignore
22083
22084@printindex cp
22085
22086@iftex
22087@c Place biographical information on right-hand (verso) page
22088
22089@tex
a9097c6d 22090\par\vfill\supereject
8cda6f8f 22091\ifodd\pageno
8cda6f8f
GM
22092 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22093 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
a9097c6d 22094 %\page\hbox{}\page
8cda6f8f 22095\else
a9097c6d 22096% \par\vfill\supereject
8cda6f8f
GM
22097 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
22098 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
a9097c6d
KB
22099 %\page\hbox{}%\page
22100 %\page\hbox{}%\page
8cda6f8f
GM
22101\fi
22102@end tex
22103
a9097c6d 22104@c page
8cda6f8f
GM
22105@w{ }
22106
22107@c ================ Biographical information ================
22108
22109@w{ }
22110@sp 8
22111@center About the Author
22112@sp 1
22113@end iftex
22114
22115@ifnottex
d6adf7e7 22116@node About the Author
8cda6f8f
GM
22117@unnumbered About the Author
22118@end ifnottex
22119
22120@quotation
22121Robert J. Chassell has worked with GNU Emacs since 1985. He writes
22122and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
22123world on software freedom. Chassell was a founding Director and
22124Treasurer of the Free Software Foundation, Inc. He is co-author of
22125the @cite{Texinfo} manual, and has edited more than a dozen other
22126books. He graduated from Cambridge University, in England. He has an
22127abiding interest in social and economic history and flies his own
22128airplane.
22129@end quotation
22130
a9097c6d
KB
22131@c @page
22132@c @w{ }
22133@c
22134@c @c Prevent page number on blank verso, so eject it first.
22135@c @tex
22136@c \par\vfill\supereject
22137@c @end tex
22138
22139@c @iftex
22140@c @headings off
22141@c @evenheading @thispage @| @| @thistitle
22142@c @oddheading @| @| @thispage
22143@c @end iftex
8cda6f8f
GM
22144
22145@bye