Add arch taglines
[bpt/emacs.git] / lispintro / emacs-lisp-intro.texi
CommitLineData
c6f54b06 1\input texinfo @c -*-texinfo-*-
8b096dce
EZ
2@comment %**start of header
3@setfilename ../info/eintr
4@c sethtmlfilename emacs-lisp-intro.html
5@settitle Programming in Emacs Lisp
6@syncodeindex vr cp
7@syncodeindex fn cp
8@setchapternewpage odd
9@finalout
10
11@c ---------
475dc40a 12@c <<<< For hard copy printing, this file is now
28be162e 13@c set for smallbook, which works for all sizes
475dc40a
EZ
14@c of paper, and with Postscript figures >>>>
15@smallbook
c6f54b06 16@clear largebook
8b096dce 17@set print-postscript-figures
475dc40a
EZ
18@c set largebook
19@c clear print-postscript-figures
8b096dce
EZ
20@c ---------
21
22@comment %**end of header
23
c6f54b06
RC
24@set edition-number 2.10
25@set update-date 2003 July 15
8b096dce
EZ
26
27@ignore
28 ## Summary of shell commands to create various output formats:
29
30 ## Info output
31 makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
32
33 ## DVI output
34 texi2dvi emacs-lisp-intro.texi
35
36 ## HTML output
8b096dce
EZ
37 makeinfo --html --no-split --verbose emacs-lisp-intro.texi
38
39 ## Plain text output
40 makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
41 --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
42
b1bd267c
RC
43 ## DocBook output
44 makeinfo --docbook --no-split --paragraph-indent=0 \
45 --verbose emacs-lisp-intro.texi
46
47 ## XML output
48 makeinfo --xml --no-split --paragraph-indent=0 \
49 --verbose emacs-lisp-intro.texi
50
c6f54b06
RC
51 #### (You must be in the same directory as the viewed file.)
52
53 ## View DVI output
54 xdvi emacs-lisp-intro.dvi &
55
56 ## View HTML output
57 galeon emacs-lisp-intro.html
58
59 ## View Info output with standalone reader
60 info emacs-lisp-intro.info
61
8b096dce
EZ
62@end ignore
63
64@c ================ Included Figures ================
65
66@c Set print-postscript-figures if you print PostScript figures.
67@c If you clear this, the ten figures will be printed as ASCII diagrams.
68@c (This is not relevant to Info, since Info only handles ASCII.)
69@c Your site may require editing changes to print PostScript; in this
70@c case, search for `print-postscript-figures' and make appropriate changes.
71
72
73@c ================ How to Create an Info file ================
74
75@c If you have `makeinfo' installed, run the following command
76
77@c makeinfo emacs-lisp-intro.texi
78
79@c or, if you want a single, large Info file, and no paragraph indents:
80@c makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
81
82@c After creating the Info file, edit your Info `dir' file, if the
0860ed42 83@c `dircategory' section below does not enable your system to
8b096dce
EZ
84@c install the manual automatically.
85@c (The `dir' file is often in the `/usr/local/info/' directory.)
86
87@c ================ How to Create an HTML file ================
88
89@c To convert to HTML format
90@c makeinfo --html --no-split --verbose emacs-lisp-intro.texi
91
92@c ================ How to Print a Book in Various Sizes ================
93
94@c This book can be printed in any of three different sizes.
95@c In the above header, set @-commands appropriately.
96
97@c 7 by 9.25 inches:
98@c @smallbook
99@c @clear largebook
100
101@c 8.5 by 11 inches:
102@c @c smallbook
103@c @set largebook
104
105@c European A4 size paper:
106@c @c smallbook
107@c @afourpaper
108@c @set largebook
109
110@c ================ How to Typeset and Print ================
111
112@c If you do not include PostScript figures, run either of the
113@c following command sequences, or similar commands suited to your
114@c system:
115
116@c texi2dvi emacs-lisp-intro.texi
117@c lpr -d emacs-lisp-intro.dvi
118
119@c or else:
120
121@c tex emacs-lisp-intro.texi
122@c texindex emacs-lisp-intro.??
123@c tex emacs-lisp-intro.texi
124@c lpr -d emacs-lisp-intro.dvi
125
475dc40a
EZ
126@c If you include the PostScript figures, and you have old software,
127@c you may need to convert the .dvi file to a .ps file before
128@c printing. Run either of the following command sequences, or one
129@c similar:
8b096dce
EZ
130@c
131@c dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
132@c
133@c or else:
134@c
135@c postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
136@c
137
138@c (Note: if you edit the book so as to change the length of the
139@c table of contents, you may have to change the value of `pageno' below.)
140
8b096dce
EZ
141@c ================ End of Formatting Sections ================
142
143@c For next or subsequent edition:
144@c create function using with-output-to-temp-buffer
145@c create a major mode, with keymaps
146@c run an asynchronous process, like grep or diff
147
8b096dce 148@c For 8.5 by 11 inch format: do not use such a small amount of
2ec6f00d 149@c whitespace between paragraphs as smallbook format
8b096dce
EZ
150@ifset largebook
151@tex
152\global\parskip 6pt plus 1pt
153@end tex
154@end ifset
155
156@c For all sized formats: print within-book cross
157@c reference with ``...'' rather than [...]
c6f54b06
RC
158
159@c This works with the texinfo.tex file, version 2003-05-04.08,
160@c in the Texinfo version 4.6 of the 2003 Jun 13 distribution.
161
8b096dce 162@tex
c6f54b06 163\global\def\xrefprintnodename#1{``#1''}
8b096dce
EZ
164@end tex
165
166@c ----------------------------------------------------
167
d586ab6c
EZ
168@dircategory Emacs
169@direntry
170* Emacs Lisp Intro: (eintr).
8b096dce 171 A simple introduction to Emacs Lisp programming.
d586ab6c 172@end direntry
8b096dce 173
b1bd267c 174@copying
c6f54b06 175This is an @cite{Introduction to Programming in Emacs Lisp}, for
8b096dce 176people who are not programmers.
c6f54b06 177@sp 1
8b096dce 178Edition @value{edition-number}, @value{update-date}
c6f54b06 179@sp 1
16ad5f3a
RC
180Copyright @copyright{} 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001,
1812002, 2003 Free Software Foundation, Inc.
c6f54b06 182@sp 1
b1bd267c 183
c6f54b06
RC
184@iftex
185Published by the:@*
186
187GNU Press, @hfill @uref{http://www.gnupress.org}@*
188a division of the @hfill General: @email{press@@gnu.org}@*
189Free Software Foundation, Inc. @hfill Orders:@w{ } @email{sales@@gnu.org}@*
19059 Temple Place, Suite 330 @hfill Tel: +1 (617) 542-5942@*
191Boston, MA 02111-1307 USA @hfill Fax: +1 (617) 542-2652@*
192@end iftex
193
194@ifnottex
195Published by the:
196
197@example
198GNU Press, Website: http://www.gnupress.org
199a division of the General: press@@gnu.org
200Free Software Foundation, Inc. Orders: sales@@gnu.org
20159 Temple Place, Suite 330 Tel: +1 (617) 542-5942
202Boston, MA 02111-1307 USA Fax: +1 (617) 542-2652
203@end example
204@end ifnottex
b1bd267c 205
c6f54b06 206@sp 1
b1bd267c
RC
207@c Printed copies are available for $30 each.@*
208ISBN 1-882114-43-4
8b096dce
EZ
209
210Permission is granted to copy, distribute and/or modify this document
211under the terms of the GNU Free Documentation License, Version 1.1 or
9a2ed8db
RC
212any later version published by the Free Software Foundation; there
213being no Invariant Section, with the Front-Cover Texts being ``A GNU
214Manual'', and with the Back-Cover Texts as in (a) below. A copy of
215the license is included in the section entitled ``GNU Free
28be162e
RC
216Documentation License''.
217
218(a) The FSF's Back-Cover Text is: ``You have freedom to copy and
219modify this GNU Manual, like GNU software. Copies published by the
220Free Software Foundation raise funds for GNU development.''
b1bd267c 221@end copying
8b096dce
EZ
222
223@c half title; two lines here, so do not use `shorttitlepage'
224@tex
225{\begingroup%
226 \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
227 \endgroup}%
228{\begingroup\hbox{}\vskip 0.25in \chaprm%
229 \centerline{Programming in Emacs Lisp}%
230 \endgroup\page\hbox{}\page}
231@end tex
232
233@titlepage
234@sp 6
235@center @titlefont{An Introduction to}
236@sp 2
237@center @titlefont{Programming in Emacs Lisp}
238@sp 2
c6f54b06 239@center Revised Second Edition
8b096dce
EZ
240@sp 4
241@center by Robert J. Chassell
242
243@page
244@vskip 0pt plus 1filll
b1bd267c 245@insertcopying
8b096dce
EZ
246@end titlepage
247
248@iftex
249@headings off
250@evenheading @thispage @| @| @thischapter
251@oddheading @thissection @| @| @thispage
252@end iftex
253
475dc40a 254@ifnothtml
c6f54b06 255@c Keep T.O.C. short by tightening up for largebook
475dc40a
EZ
256@ifset largebook
257@tex
258\global\parskip 2pt plus 1pt
259\global\advance\baselineskip by -1pt
260@end tex
261@end ifset
c6f54b06 262@end ifnothtml
8b096dce 263
475dc40a
EZ
264@shortcontents
265@contents
266
475dc40a
EZ
267@ifnottex
268@node Top, Preface, (dir), (dir)
269@top An Introduction to Programming in Emacs Lisp
270
b1bd267c 271@insertcopying
475dc40a
EZ
272
273This master menu first lists each chapter and index; then it lists
274every node in every chapter.
275@end ifnottex
276
8b096dce
EZ
277@menu
278* Preface:: What to look for.
279* List Processing:: What is Lisp?
280* Practicing Evaluation:: Running several programs.
281* Writing Defuns:: How to write function definitions.
282* Buffer Walk Through:: Exploring a few buffer-related functions.
283* More Complex:: A few, even more complex functions.
284* Narrowing & Widening:: Restricting your and Emacs attention to
285 a region.
286* car cdr & cons:: Fundamental functions in Lisp.
287* Cutting & Storing Text:: Removing text and saving it.
288* List Implementation:: How lists are implemented in the computer.
289* Yanking:: Pasting stored text.
290* Loops & Recursion:: How to repeat a process.
291* Regexp Search:: Regular expression searches.
292* Counting Words:: A review of repetition and regexps.
293* Words in a defun:: Counting words in a @code{defun}.
294* Readying a Graph:: A prototype graph printing function.
295* Emacs Initialization:: How to write a @file{.emacs} file.
296* Debugging:: How to run the Emacs Lisp debuggers.
297* Conclusion:: Now you have the basics.
298* the-the:: An appendix: how to find reduplicated words.
299* Kill Ring:: An appendix: how the kill ring works.
300* Full Graph:: How to create a graph with labelled axes.
c6f54b06 301* Free Software and Free Manuals::
8b096dce
EZ
302* GNU Free Documentation License::
303* Index::
304* About the Author::
305
306@detailmenu
307 --- The Detailed Node Listing ---
308
309Preface
310
311* Why:: Why learn Emacs Lisp?
312* On Reading this Text:: Read, gain familiarity, pick up habits....
313* Who You Are:: For whom this is written.
314* Lisp History::
315* Note for Novices:: You can read this as a novice.
316* Thank You::
317
318List Processing
319
320* Lisp Lists:: What are lists?
321* Run a Program:: Any list in Lisp is a program ready to run.
322* Making Errors:: Generating an error message.
323* Names & Definitions:: Names of symbols and function definitions.
324* Lisp Interpreter:: What the Lisp interpreter does.
325* Evaluation:: Running a program.
326* Variables:: Returning a value from a variable.
327* Arguments:: Passing information to a function.
328* set & setq:: Setting the value of a variable.
329* Summary:: The major points.
330* Error Message Exercises::
331
332Lisp Lists
333
334* Numbers Lists:: List have numbers, other lists, in them.
335* Lisp Atoms:: Elemental entities.
336* Whitespace in Lists:: Formating lists to be readable.
337* Typing Lists:: How GNU Emacs helps you type lists.
338
339The Lisp Interpreter
340
341* Complications:: Variables, Special forms, Lists within.
342* Byte Compiling:: Specially processing code for speed.
343
344Evaluation
345
346* Evaluating Inner Lists:: Lists within lists...
347
348Variables
349
350* fill-column Example::
351* Void Function:: The error message for a symbol
352 without a function.
353* Void Variable:: The error message for a symbol without a value.
354
355Arguments
356
357* Data types:: Types of data passed to a function.
358* Args as Variable or List:: An argument can be the value
359 of a variable or list.
360* Variable Number of Arguments:: Some functions may take a
361 variable number of arguments.
362* Wrong Type of Argument:: Passing an argument of the wrong type
363 to a function.
364* message:: A useful function for sending messages.
365
366Setting the Value of a Variable
367
368* Using set:: Setting values.
369* Using setq:: Setting a quoted value.
370* Counting:: Using @code{setq} to count.
371
372Practicing Evaluation
373
374* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
375 causes evaluation.
376* Buffer Names:: Buffers and files are different.
377* Getting Buffers:: Getting a buffer itself, not merely its name.
378* Switching Buffers:: How to change to another buffer.
379* Buffer Size & Locations:: Where point is located and the size of
380 the buffer.
381* Evaluation Exercise::
382
383How To Write Function Definitions
384
385* Primitive Functions::
386* defun:: The @code{defun} special form.
387* Install:: Install a function definition.
388* Interactive:: Making a function interactive.
389* Interactive Options:: Different options for @code{interactive}.
390* Permanent Installation:: Installing code permanently.
391* let:: Creating and initializing local variables.
392* if:: What if?
393* else:: If--then--else expressions.
394* Truth & Falsehood:: What Lisp considers false and true.
395* save-excursion:: Keeping track of point, mark, and buffer.
396* Review::
397* defun Exercises::
398
399Install a Function Definition
400
401* Effect of installation::
402* Change a defun:: How to change a function definition.
403
404Make a Function Interactive
405
406* Interactive multiply-by-seven:: An overview.
407* multiply-by-seven in detail:: The interactive version.
408
409@code{let}
410
411* Prevent confusion::
412* Parts of let Expression::
413* Sample let Expression::
414* Uninitialized let Variables::
415
416The @code{if} Special Form
417
418* if in more detail::
419* type-of-animal in detail:: An example of an @code{if} expression.
420
421Truth and Falsehood in Emacs Lisp
422
423* nil explained:: @code{nil} has two meanings.
424
425@code{save-excursion}
426
427* Point and mark:: A review of various locations.
428* Template for save-excursion::
429
430A Few Buffer--Related Functions
431
432* Finding More:: How to find more information.
433* simplified-beginning-of-buffer:: Shows @code{goto-char},
434 @code{point-min}, and @code{push-mark}.
435* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
436* append-to-buffer:: Uses @code{save-excursion} and
437 @code{insert-buffer-substring}.
438* Buffer Related Review:: Review.
439* Buffer Exercises::
440
441The Definition of @code{mark-whole-buffer}
442
443* mark-whole-buffer overview::
444* Body of mark-whole-buffer:: Only three lines of code.
445
446The Definition of @code{append-to-buffer}
447
448* append-to-buffer overview::
449* append interactive:: A two part interactive expression.
450* append-to-buffer body:: Incorporates a @code{let} expression.
451* append save-excursion:: How the @code{save-excursion} works.
452
453A Few More Complex Functions
454
455* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
456* insert-buffer:: Read-only, and with @code{or}.
457* beginning-of-buffer:: Shows @code{goto-char},
458 @code{point-min}, and @code{push-mark}.
459* Second Buffer Related Review::
460* optional Exercise::
461
462The Definition of @code{insert-buffer}
463
464* insert-buffer code::
465* insert-buffer interactive:: When you can read, but not write.
466* insert-buffer body:: The body has an @code{or} and a @code{let}.
467* if & or:: Using an @code{if} instead of an @code{or}.
468* Insert or:: How the @code{or} expression works.
469* Insert let:: Two @code{save-excursion} expressions.
470
471The Interactive Expression in @code{insert-buffer}
472
473* Read-only buffer:: When a buffer cannot be modified.
474* b for interactive:: An existing buffer or else its name.
475
476Complete Definition of @code{beginning-of-buffer}
477
478* Optional Arguments::
479* beginning-of-buffer opt arg:: Example with optional argument.
480* beginning-of-buffer complete::
481
482@code{beginning-of-buffer} with an Argument
483
484* Disentangle beginning-of-buffer::
485* Large buffer case::
486* Small buffer case::
487
488Narrowing and Widening
489
490* Narrowing advantages:: The advantages of narrowing
491* save-restriction:: The @code{save-restriction} special form.
492* what-line:: The number of the line that point is on.
493* narrow Exercise::
494
495@code{car}, @code{cdr}, @code{cons}: Fundamental Functions
496
497* Strange Names:: An historical aside: why the strange names?
498* car & cdr:: Functions for extracting part of a list.
499* cons:: Constructing a list.
500* nthcdr:: Calling @code{cdr} repeatedly.
501* nth::
502* setcar:: Changing the first element of a list.
503* setcdr:: Changing the rest of a list.
504* cons Exercise::
505
506@code{cons}
507
508* Build a list::
509* length:: How to find the length of a list.
510
511Cutting and Storing Text
512
513* Storing Text:: Text is stored in a list.
514* zap-to-char:: Cutting out text up to a character.
515* kill-region:: Cutting text out of a region.
516* Digression into C:: Minor note on C programming language macros.
517* defvar:: How to give a variable an initial value.
518* copy-region-as-kill:: A definition for copying text.
519* cons & search-fwd Review::
520* search Exercises::
521
522@code{zap-to-char}
523
524* Complete zap-to-char:: The complete implementation.
525* zap-to-char interactive:: A three part interactive expression.
526* zap-to-char body:: A short overview.
527* search-forward:: How to search for a string.
528* progn:: The @code{progn} special form.
529* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
530
531@code{kill-region}
532
533* Complete kill-region:: The function definition.
534* condition-case:: Dealing with a problem.
535* delete-and-extract-region:: Doing the work.
536
537Initializing a Variable with @code{defvar}
538
539* See variable current value::
540* defvar and asterisk:: An old-time convention.
541
542@code{copy-region-as-kill}
543
544* Complete copy-region-as-kill:: The complete function definition.
545* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
546
547The Body of @code{copy-region-as-kill}
548
549* last-command & this-command::
550* kill-append function::
551* kill-new function::
552
553How Lists are Implemented
554
555* Lists diagrammed::
556* Symbols as Chest:: Exploring a powerful metaphor.
557* List Exercise::
558
559Yanking Text Back
560
561* Kill Ring Overview:: The kill ring is a list.
562* kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
563* yank nthcdr Exercises::
564
565Loops and Recursion
566
567* while:: Causing a stretch of code to repeat.
568* dolist dotimes::
569* Recursion:: Causing a function to call itself.
570* Looping exercise::
571
572@code{while}
573
574* Looping with while:: Repeat so long as test returns true.
575* Loop Example:: A @code{while} loop that uses a list.
576* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
577* Incrementing Loop:: A loop with an incrementing counter.
578* Decrementing Loop:: A loop with a decrementing counter.
579
580A Loop with an Incrementing Counter
581
582* Incrementing Example:: Counting pebbles in a triangle.
583* Inc Example parts:: The parts of the function definition.
584* Inc Example altogether:: Putting the function definition together.
585
586Loop with a Decrementing Counter
587
588* Decrementing Example:: More pebbles on the beach.
589* Dec Example parts:: The parts of the function definition.
590* Dec Example altogether:: Putting the function definition together.
591
592Save your time: @code{dolist} and @code{dotimes}
593
594* dolist::
595* dotimes::
596
597Recursion
598
599* Building Robots:: Same model, different serial number ...
600* Recursive Definition Parts:: Walk until you stop ...
601* Recursion with list:: Using a list as the test whether to recurse.
602* Recursive triangle function::
603* Recursion with cond::
604* Recursive Patterns:: Often used templates.
605* No Deferment:: Don't store up work ...
606* No deferment solution::
607
608Recursion in Place of a Counter
609
610* Recursive Example arg of 1 or 2::
611* Recursive Example arg of 3 or 4::
612
613Recursive Patterns
614
615* Every::
616* Accumulate::
617* Keep::
618
619Regular Expression Searches
620
621* sentence-end:: The regular expression for @code{sentence-end}.
622* re-search-forward:: Very similar to @code{search-forward}.
623* forward-sentence:: A straightforward example of regexp search.
624* forward-paragraph:: A somewhat complex example.
625* etags:: How to create your own @file{TAGS} table.
626* Regexp Review::
627* re-search Exercises::
628
629@code{forward-sentence}
630
631* Complete forward-sentence::
632* fwd-sentence while loops:: Two @code{while} loops.
633* fwd-sentence re-search:: A regular expression search.
634
635@code{forward-paragraph}: a Goldmine of Functions
636
637* forward-paragraph in brief:: Key parts of the function definition.
638* fwd-para let:: The @code{let*} expression.
639* fwd-para while:: The forward motion @code{while} loop.
640* fwd-para between paragraphs:: Movement between paragraphs.
641* fwd-para within paragraph:: Movement within paragraphs.
642* fwd-para no fill prefix:: When there is no fill prefix.
643* fwd-para with fill prefix:: When there is a fill prefix.
644* fwd-para summary:: Summary of @code{forward-paragraph} code.
645
646Counting: Repetition and Regexps
647
648* Why Count Words::
649* count-words-region:: Use a regexp, but find a problem.
650* recursive-count-words:: Start with case of no words in region.
651* Counting Exercise::
652
653The @code{count-words-region} Function
654
655* Design count-words-region:: The definition using a @code{while} loop.
656* Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
657
658Counting Words in a @code{defun}
659
660* Divide and Conquer::
661* Words and Symbols:: What to count?
662* Syntax:: What constitutes a word or symbol?
663* count-words-in-defun:: Very like @code{count-words}.
664* Several defuns:: Counting several defuns in a file.
665* Find a File:: Do you want to look at a file?
666* lengths-list-file:: A list of the lengths of many definitions.
667* Several files:: Counting in definitions in different files.
668* Several files recursively:: Recursively counting in different files.
669* Prepare the data:: Prepare the data for display in a graph.
670
671Count Words in @code{defuns} in Different Files
672
673* lengths-list-many-files:: Return a list of the lengths of defuns.
674* append:: Attach one list to another.
675
676Prepare the Data for Display in a Graph
677
678* Sorting:: Sorting lists.
679* Files List:: Making a list of files.
680* Counting function definitions::
681
682Readying a Graph
683
684* Columns of a graph::
685* graph-body-print:: How to print the body of a graph.
686* recursive-graph-body-print::
687* Printed Axes::
688* Line Graph Exercise::
689
690Your @file{.emacs} File
691
692* Default Configuration::
693* Site-wide Init:: You can write site-wide init files.
694* defcustom:: Emacs will write code for you.
695* Beginning a .emacs File:: How to write a @code{.emacs file}.
696* Text and Auto-fill:: Automatically wrap lines.
697* Mail Aliases:: Use abbreviations for email addresses.
698* Indent Tabs Mode:: Don't use tabs with @TeX{}
699* Keybindings:: Create some personal keybindings.
700* Keymaps:: More about key binding.
701* Loading Files:: Load (i.e., evaluate) files automatically.
702* Autoload:: Make functions available.
703* Simple Extension:: Define a function; bind it to a key.
704* X11 Colors:: Colors in version 19 in X.
705* Miscellaneous::
706* Mode Line:: How to customize your mode line.
707
708Debugging
709
710* debug:: How to use the built-in debugger.
711* debug-on-entry:: Start debugging when you call a function.
712* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
713* edebug:: How to use Edebug, a source level debugger.
714* Debugging Exercises::
715
716Handling the Kill Ring
717
718* rotate-yank-pointer:: Move a pointer along a list and around.
719* yank:: Paste a copy of a clipped element.
720* yank-pop:: Insert first element pointed to.
c6f54b06 721* ring file::
8b096dce
EZ
722
723The @code{rotate-yank-pointer} Function
724
725* Understanding rotate-yk-ptr::
726* rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
727
728The Body of @code{rotate-yank-pointer}
729
730* Digression concerning error:: How to mislead humans, but not computers.
731* rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
732* Remainder Function:: The remainder, @code{%}, function.
733* rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
734* kill-rng-yk-ptr last elt:: Pointing to the last element.
735
736@code{yank}
737
738* rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
739* rotate-yk-ptr negative arg:: Pass a negative argument.
740
741A Graph with Labelled Axes
742
743* Labelled Example::
744* print-graph Varlist:: @code{let} expression in @code{print-graph}.
745* print-Y-axis:: Print a label for the vertical axis.
746* print-X-axis:: Print a horizontal label.
747* Print Whole Graph:: The function to print a complete graph.
748
749The @code{print-Y-axis} Function
750
751* Height of label:: What height for the Y axis?
752* Compute a Remainder:: How to compute the remainder of a division.
753* Y Axis Element:: Construct a line for the Y axis.
754* Y-axis-column:: Generate a list of Y axis labels.
755* print-Y-axis Penultimate:: A not quite final version.
756
757The @code{print-X-axis} Function
758
759* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
760* X Axis Tic Marks:: Create tic marks for the horizontal axis.
761
762Printing the Whole Graph
763
764* The final version:: A few changes.
765* Test print-graph:: Run a short test.
766* Graphing words in defuns:: Executing the final code.
767* lambda:: How to write an anonymous function.
768* mapcar:: Apply a function to elements of a list.
769* Another Bug:: Yet another bug @dots{} most insidious.
770* Final printed graph:: The graph itself!
771
772@end detailmenu
773@end menu
774
c6f54b06
RC
775@c >>>> Set pageno appropriately <<<<
776
777@c The first page of the Preface is a roman numeral; it is the first
778@c right handed page after the Table of Contents; hence the following
779@c setting must be for an odd negative number.
780
781@iftex
782@global@pageno = -11
783@end iftex
784
8b096dce
EZ
785@node Preface, List Processing, Top, Top
786@comment node-name, next, previous, up
787@unnumbered Preface
788
789Most of the GNU Emacs integrated environment is written in the programming
790language called Emacs Lisp. The code written in this programming
791language is the software---the sets of instructions---that tell the
792computer what to do when you give it commands. Emacs is designed so
793that you can write new code in Emacs Lisp and easily install it as an
794extension to the editor.
795
796(GNU Emacs is sometimes called an ``extensible editor'', but it does
797much more than provide editing capabilities. It is better to refer to
798Emacs as an ``extensible computing environment''. However, that
799phrase is quite a mouthful. It is easier to refer to Emacs simply as
800an editor. Moreover, everything you do in Emacs---find the Mayan date
801and phases of the moon, simplify polynomials, debug code, manage
802files, read letters, write books---all these activities are kinds of
803editing in the most general sense of the word.)
804
805@menu
806* Why:: Why learn Emacs Lisp?
807* On Reading this Text:: Read, gain familiarity, pick up habits....
808* Who You Are:: For whom this is written.
809* Lisp History::
810* Note for Novices:: You can read this as a novice.
811* Thank You::
812@end menu
813
814@node Why, On Reading this Text, Preface, Preface
815@ifnottex
816@unnumberedsec Why Study Emacs Lisp?
817@end ifnottex
818
819Although Emacs Lisp is usually thought of in association only with Emacs,
820it is a full computer programming language. You can use Emacs Lisp as
821you would any other programming language.
822
823Perhaps you want to understand programming; perhaps you want to extend
824Emacs; or perhaps you want to become a programmer. This introduction to
825Emacs Lisp is designed to get you started: to guide you in learning the
826fundamentals of programming, and more importantly, to show you how you
827can teach yourself to go further.
828
829@node On Reading this Text, Who You Are, Why, Preface
830@comment node-name, next, previous, up
831@unnumberedsec On Reading this Text
832
833All through this document, you will see little sample programs you can
834run inside of Emacs. If you read this document in Info inside of GNU
835Emacs, you can run the programs as they appear. (This is easy to do and
836is explained when the examples are presented.) Alternatively, you can
837read this introduction as a printed book while sitting beside a computer
838running Emacs. (This is what I like to do; I like printed books.) If
839you don't have a running Emacs beside you, you can still read this book,
840but in this case, it is best to treat it as a novel or as a travel guide
841to a country not yet visited: interesting, but not the same as being
842there.
843
844Much of this introduction is dedicated to walk-throughs or guided tours
845of code used in GNU Emacs. These tours are designed for two purposes:
846first, to give you familiarity with real, working code (code you use
847every day); and, second, to give you familiarity with the way Emacs
848works. It is interesting to see how a working environment is
849implemented.
850Also, I
851hope that you will pick up the habit of browsing through source code.
852You can learn from it and mine it for ideas. Having GNU Emacs is like
853having a dragon's cave of treasures.
854
855In addition to learning about Emacs as an editor and Emacs Lisp as a
856programming language, the examples and guided tours will give you an
857opportunity to get acquainted with Emacs as a Lisp programming
858environment. GNU Emacs supports programming and provides tools that
859you will want to become comfortable using, such as @kbd{M-.} (the key
860which invokes the @code{find-tag} command). You will also learn about
861buffers and other objects that are part of the environment.
862Learning about these features of Emacs is like learning new routes
863around your home town.
864
865@ignore
866In addition, I have written several programs as extended examples.
867Although these are examples, the programs are real. I use them.
868Other people use them. You may use them. Beyond the fragments of
869programs used for illustrations, there is very little in here that is
870`just for teaching purposes'; what you see is used. This is a great
871advantage of Emacs Lisp: it is easy to learn to use it for work.
872@end ignore
873
874Finally, I hope to convey some of the skills for using Emacs to
875learn aspects of programming that you don't know. You can often use
876Emacs to help you understand what puzzles you or to find out how to do
877something new. This self-reliance is not only a pleasure, but an
878advantage.
879
880@node Who You Are, Lisp History, On Reading this Text, Preface
881@comment node-name, next, previous, up
882@unnumberedsec For Whom This is Written
883
884This text is written as an elementary introduction for people who are
885not programmers. If you are a programmer, you may not be satisfied with
886this primer. The reason is that you may have become expert at reading
887reference manuals and be put off by the way this text is organized.
888
889An expert programmer who reviewed this text said to me:
890
891@quotation
892@i{I prefer to learn from reference manuals. I ``dive into'' each
893paragraph, and ``come up for air'' between paragraphs.}
894
895@i{When I get to the end of a paragraph, I assume that that subject is
896done, finished, that I know everything I need (with the
897possible exception of the case when the next paragraph starts talking
898about it in more detail). I expect that a well written reference manual
899will not have a lot of redundancy, and that it will have excellent
900pointers to the (one) place where the information I want is.}
901@end quotation
902
903This introduction is not written for this person!
904
905Firstly, I try to say everything at least three times: first, to
906introduce it; second, to show it in context; and third, to show it in a
907different context, or to review it.
908
909Secondly, I hardly ever put all the information about a subject in one
910place, much less in one paragraph. To my way of thinking, that imposes
911too heavy a burden on the reader. Instead I try to explain only what
912you need to know at the time. (Sometimes I include a little extra
913information so you won't be surprised later when the additional
914information is formally introduced.)
915
916When you read this text, you are not expected to learn everything the
917first time. Frequently, you need only make, as it were, a `nodding
918acquaintance' with some of the items mentioned. My hope is that I have
919structured the text and given you enough hints that you will be alert to
920what is important, and concentrate on it.
921
922You will need to ``dive into'' some paragraphs; there is no other way
923to read them. But I have tried to keep down the number of such
924paragraphs. This book is intended as an approachable hill, rather than
925as a daunting mountain.
926
927This introduction to @cite{Programming in Emacs Lisp} has a companion
928document,
929@iftex
930@cite{The GNU Emacs Lisp Reference Manual}.
931@end iftex
932@ifnottex
933@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
934Emacs Lisp Reference Manual}.
935@end ifnottex
936The reference manual has more detail than this introduction. In the
937reference manual, all the information about one topic is concentrated
938in one place. You should turn to it if you are like the programmer
939quoted above. And, of course, after you have read this
940@cite{Introduction}, you will find the @cite{Reference Manual} useful
941when you are writing your own programs.
942
943@node Lisp History, Note for Novices, Who You Are, Preface
944@unnumberedsec Lisp History
945@cindex Lisp history
946
947Lisp was first developed in the late 1950s at the Massachusetts
948Institute of Technology for research in artificial intelligence. The
949great power of the Lisp language makes it superior for other purposes as
950well, such as writing editor commands and integrated environments.
951
952@cindex Maclisp
953@cindex Common Lisp
954GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
955in the 1960s. It is somewhat inspired by Common Lisp, which became a
956standard in the 1980s. However, Emacs Lisp is much simpler than Common
957Lisp. (The standard Emacs distribution contains an optional extensions
958file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
959
960@node Note for Novices, Thank You, Lisp History, Preface
961@comment node-name, next, previous, up
962@unnumberedsec A Note for Novices
963
964If you don't know GNU Emacs, you can still read this document
965profitably. However, I recommend you learn Emacs, if only to learn to
966move around your computer screen. You can teach yourself how to use
967Emacs with the on-line tutorial. To use it, type @kbd{C-h t}. (This
968means you press and release the @key{CTRL} key and the @kbd{h} at the
969same time, and then press and release @kbd{t}.)
970
971Also, I often refer to one of Emacs' standard commands by listing the
972keys which you press to invoke the command and then giving the name of
973the command in parentheses, like this: @kbd{M-C-\}
974(@code{indent-region}). What this means is that the
975@code{indent-region} command is customarily invoked by typing
976@kbd{M-C-\}. (You can, if you wish, change the keys that are typed to
977invoke the command; this is called @dfn{rebinding}. @xref{Keymaps, ,
978Keymaps}.) The abbreviation @kbd{M-C-\} means that you type your
979@key{META} key, @key{CTRL} key and @key{\} key all at the same time.
980(On many modern keyboards the @key{META} key is labelled
981@key{ALT}.)
982Sometimes a combination like this is called a keychord, since it is
983similar to the way you play a chord on a piano. If your keyboard does
984not have a @key{META} key, the @key{ESC} key prefix is used in place
985of it. In this case, @kbd{M-C-\} means that you press and release your
986@key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
987the same time. But usually @kbd{M-C-\} means press the @key{CTRL} key
988along with the key that is labelled @key{ALT} and, at the same time,
989press the @key{\} key.
990
991In addition to typing a lone keychord, you can prefix what you type
992with @kbd{C-u}, which is called the `universal argument'. The
993@kbd{C-u} keychord passes an argument to the subsequent command.
994Thus, to indent a region of plain text by 6 spaces, mark the region,
995and then type @w{@kbd{C-u 6 M-C-\}}. (If you do not specify a number,
996Emacs either passes the number 4 to the command or otherwise runs the
997command differently than it would otherwise.) @xref{Arguments, ,
998Numeric Arguments, emacs, The GNU Emacs Manual}.
999
1000If you are reading this in Info using GNU Emacs, you can read through
1001this whole document just by pressing the space bar, @key{SPC}.
1002(To learn about Info, type @kbd{C-h i} and then select Info.)
1003
1004A note on terminology: when I use the word Lisp alone, I often am
1005referring to the various dialects of Lisp in general, but when I speak
1006of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1007
1008@node Thank You, , Note for Novices, Preface
1009@comment node-name, next, previous, up
1010@unnumberedsec Thank You
1011
1012My thanks to all who helped me with this book. My especial thanks to
1013@r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1014McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1015Stallman}, and @w{Melissa Weisshaus}. My thanks also go to both
1016@w{Philip Johnson} and @w{David Stampe} for their patient
1017encouragement. My mistakes are my own.
1018
1019@flushright
1020Robert J. Chassell
1021@end flushright
1022
1023@c ================ Beginning of main text ================
1024
1025@c Start main text on right-hand (verso) page
1026
1027@tex
1028\par\vfill\supereject
1029\headings off
1030\ifodd\pageno
1031 \par\vfill\supereject
1032\else
1033 \par\vfill\supereject
1034 \page\hbox{}\page
1035 \par\vfill\supereject
1036\fi
1037@end tex
1038
1039@iftex
1040@headings off
1041@evenheading @thispage @| @| @thischapter
1042@oddheading @thissection @| @| @thispage
c6f54b06 1043@global@pageno = 1
8b096dce
EZ
1044@end iftex
1045
1046@node List Processing, Practicing Evaluation, Preface, Top
1047@comment node-name, next, previous, up
1048@chapter List Processing
1049
1050To the untutored eye, Lisp is a strange programming language. In Lisp
1051code there are parentheses everywhere. Some people even claim that the
1052name stands for `Lots of Isolated Silly Parentheses'. But the claim is
1053unwarranted. Lisp stands for LISt Processing, and the programming
1054language handles @emph{lists} (and lists of lists) by putting them
1055between parentheses. The parentheses mark the boundaries of the list.
1056Sometimes a list is preceded by a single apostrophe or quotation mark,
1057@samp{'}. Lists are the basis of Lisp.
1058
1059@menu
1060* Lisp Lists:: What are lists?
1061* Run a Program:: Any list in Lisp is a program ready to run.
1062* Making Errors:: Generating an error message.
1063* Names & Definitions:: Names of symbols and function definitions.
1064* Lisp Interpreter:: What the Lisp interpreter does.
1065* Evaluation:: Running a program.
1066* Variables:: Returning a value from a variable.
1067* Arguments:: Passing information to a function.
1068* set & setq:: Setting the value of a variable.
1069* Summary:: The major points.
1070* Error Message Exercises::
1071@end menu
1072
1073@node Lisp Lists, Run a Program, List Processing, List Processing
1074@comment node-name, next, previous, up
1075@section Lisp Lists
1076@cindex Lisp Lists
1077
1078In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1079This list is preceded by a single apostrophe. It could just as well be
1080written as follows, which looks more like the kind of list you are likely
1081to be familiar with:
1082
1083@smallexample
1084@group
1085'(rose
1086 violet
1087 daisy
1088 buttercup)
1089@end group
1090@end smallexample
1091
1092@noindent
1093The elements of this list are the names of the four different flowers,
1094separated from each other by whitespace and surrounded by parentheses,
1095like flowers in a field with a stone wall around them.
1096@cindex Flowers in a field
1097
1098@menu
1099* Numbers Lists:: List have numbers, other lists, in them.
1100* Lisp Atoms:: Elemental entities.
1101* Whitespace in Lists:: Formating lists to be readable.
1102* Typing Lists:: How GNU Emacs helps you type lists.
1103@end menu
1104
1105@node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1106@ifnottex
1107@unnumberedsubsec Numbers, Lists inside of Lists
1108@end ifnottex
1109
1110Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1111This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1112separated by whitespace.
1113
1114In Lisp, both data and programs are represented the same way; that is,
1115they are both lists of words, numbers, or other lists, separated by
1116whitespace and surrounded by parentheses. (Since a program looks like
1117data, one program may easily serve as data for another; this is a very
1118powerful feature of Lisp.) (Incidentally, these two parenthetical
1119remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1120@samp{.} as punctuation marks.)
1121
1122@need 1200
1123Here is another list, this time with a list inside of it:
1124
1125@smallexample
1126'(this list has (a list inside of it))
1127@end smallexample
1128
1129The components of this list are the words @samp{this}, @samp{list},
1130@samp{has}, and the list @samp{(a list inside of it)}. The interior
1131list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1132@samp{of}, @samp{it}.
1133
1134@node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1135@comment node-name, next, previous, up
1136@subsection Lisp Atoms
1137@cindex Lisp Atoms
1138
1139In Lisp, what we have been calling words are called @dfn{atoms}. This
1140term comes from the historical meaning of the word atom, which means
1141`indivisible'. As far as Lisp is concerned, the words we have been
1142using in the lists cannot be divided into any smaller parts and still
1143mean the same thing as part of a program; likewise with numbers and
1144single character symbols like @samp{+}. On the other hand, unlike an
1145atom, a list can be split into parts. (@xref{car cdr & cons, ,
1146@code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1147
1148In a list, atoms are separated from each other by whitespace. They can be
1149right next to a parenthesis.
1150
1151@cindex @samp{empty list} defined
1152Technically speaking, a list in Lisp consists of parentheses surrounding
1153atoms separated by whitespace or surrounding other lists or surrounding
1154both atoms and other lists. A list can have just one atom in it or
1155have nothing in it at all. A list with nothing in it looks like this:
1156@code{()}, and is called the @dfn{empty list}. Unlike anything else, an
1157empty list is considered both an atom and a list at the same time.
1158
1159@cindex Symbolic expressions, introduced
1160@cindex @samp{expression} defined
1161@cindex @samp{form} defined
1162The printed representation of both atoms and lists are called
1163@dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1164The word @dfn{expression} by itself can refer to either the printed
1165representation, or to the atom or list as it is held internally in the
1166computer. Often, people use the term @dfn{expression}
1167indiscriminately. (Also, in many texts, the word @dfn{form} is used
1168as a synonym for expression.)
1169
1170Incidentally, the atoms that make up our universe were named such when
1171they were thought to be indivisible; but it has been found that physical
1172atoms are not indivisible. Parts can split off an atom or it can
1173fission into two parts of roughly equal size. Physical atoms were named
1174prematurely, before their truer nature was found. In Lisp, certain
1175kinds of atom, such as an array, can be separated into parts; but the
1176mechanism for doing this is different from the mechanism for splitting a
1177list. As far as list operations are concerned, the atoms of a list are
1178unsplittable.
1179
1180As in English, the meanings of the component letters of a Lisp atom
1181are different from the meaning the letters make as a word. For
1182example, the word for the South American sloth, the @samp{ai}, is
1183completely different from the two words, @samp{a}, and @samp{i}.
1184
1185There are many kinds of atom in nature but only a few in Lisp: for
1186example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1187as @samp{+}, @samp{foo}, or @samp{forward-line}. The words we have
1188listed in the examples above are all symbols. In everyday Lisp
1189conversation, the word ``atom'' is not often used, because programmers
1190usually try to be more specific about what kind of atom they are dealing
1191with. Lisp programming is mostly about symbols (and sometimes numbers)
1192within lists. (Incidentally, the preceding three word parenthetical
1193remark is a proper list in Lisp, since it consists of atoms, which in
1194this case are symbols, separated by whitespace and enclosed by
1195parentheses, without any non-Lisp punctuation.)
1196
1197@need 1250
1198In addition, text between double quotation marks---even sentences or
1199paragraphs---is an atom. Here is an example:
1200@cindex Text between double quotation marks
1201
1202@smallexample
1203'(this list includes "text between quotation marks.")
1204@end smallexample
1205
1206@cindex @samp{string} defined
1207@noindent
1208In Lisp, all of the quoted text including the punctuation mark and the
1209blank spaces is a single atom. This kind of atom is called a
1210@dfn{string} (for `string of characters') and is the sort of thing that
1211is used for messages that a computer can print for a human to read.
1212Strings are a different kind of atom than numbers or symbols and are
1213used differently.
1214
1215@node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1216@comment node-name, next, previous, up
1217@subsection Whitespace in Lists
1218@cindex Whitespace in lists
1219
1220@need 1200
1221The amount of whitespace in a list does not matter. From the point of view
1222of the Lisp language,
1223
1224@smallexample
1225@group
1226'(this list
1227 looks like this)
1228@end group
1229@end smallexample
1230
1231@need 800
1232@noindent
1233is exactly the same as this:
1234
1235@smallexample
1236'(this list looks like this)
1237@end smallexample
1238
1239Both examples show what to Lisp is the same list, the list made up of
1240the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1241@samp{this} in that order.
1242
1243Extra whitespace and newlines are designed to make a list more readable
1244by humans. When Lisp reads the expression, it gets rid of all the extra
1245whitespace (but it needs to have at least one space between atoms in
1246order to tell them apart.)
1247
1248Odd as it seems, the examples we have seen cover almost all of what Lisp
1249lists look like! Every other list in Lisp looks more or less like one
1250of these examples, except that the list may be longer and more complex.
1251In brief, a list is between parentheses, a string is between quotation
1252marks, a symbol looks like a word, and a number looks like a number.
1253(For certain situations, square brackets, dots and a few other special
1254characters may be used; however, we will go quite far without them.)
1255
1256@node Typing Lists, , Whitespace in Lists, Lisp Lists
1257@comment node-name, next, previous, up
1258@subsection GNU Emacs Helps You Type Lists
1259@cindex Help typing lists
1260@cindex Formatting help
1261
1262When you type a Lisp expression in GNU Emacs using either Lisp
1263Interaction mode or Emacs Lisp mode, you have available to you several
1264commands to format the Lisp expression so it is easy to read. For
1265example, pressing the @key{TAB} key automatically indents the line the
1266cursor is on by the right amount. A command to properly indent the
1267code in a region is customarily bound to @kbd{M-C-\}. Indentation is
e601d8fd 1268designed so that you can see which elements of a list belong to which
8b096dce
EZ
1269list---elements of a sub-list are indented more than the elements of
1270the enclosing list.
1271
1272In addition, when you type a closing parenthesis, Emacs momentarily
1273jumps the cursor back to the matching opening parenthesis, so you can
1274see which one it is. This is very useful, since every list you type
1275in Lisp must have its closing parenthesis match its opening
1276parenthesis. (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1277Manual}, for more information about Emacs' modes.)
1278
1279@node Run a Program, Making Errors, Lisp Lists, List Processing
1280@comment node-name, next, previous, up
1281@section Run a Program
1282@cindex Run a program
1283@cindex Program, running one
1284
1285@cindex @samp{evaluate} defined
1286A list in Lisp---any list---is a program ready to run. If you run it
1287(for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1288of three things: do nothing except return to you the list itself; send
1289you an error message; or, treat the first symbol in the list as a
1290command to do something. (Usually, of course, it is the last of these
1291three things that you really want!)
1292
1293@c use code for the single apostrophe, not samp.
1294The single apostrophe, @code{'}, that I put in front of some of the
1295example lists in preceding sections is called a @dfn{quote}; when it
1296precedes a list, it tells Lisp to do nothing with the list, other than
1297take it as it is written. But if there is no quote preceding a list,
1298the first item of the list is special: it is a command for the computer
1299to obey. (In Lisp, these commands are called @emph{functions}.) The list
1300@code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1301understands that the @code{+} is an instruction to do something with the
1302rest of the list: add the numbers that follow.
1303
1304@need 1250
1305If you are reading this inside of GNU Emacs in Info, here is how you can
1306evaluate such a list: place your cursor immediately after the right
1307hand parenthesis of the following list and then type @kbd{C-x C-e}:
1308
1309@smallexample
1310(+ 2 2)
1311@end smallexample
1312
1313@c use code for the number four, not samp.
1314@noindent
1315You will see the number @code{4} appear in the echo area. (In the
1316jargon, what you have just done is ``evaluate the list.'' The echo area
1317is the line at the bottom of the screen that displays or ``echoes''
1318text.) Now try the same thing with a quoted list: place the cursor
1319right after the following list and type @kbd{C-x C-e}:
1320
1321@smallexample
1322'(this is a quoted list)
1323@end smallexample
1324
1325@noindent
1326You will see @code{(this is a quoted list)} appear in the echo area.
1327
1328@cindex Lisp interpreter, explained
1329@cindex Interpreter, Lisp, explained
1330In both cases, what you are doing is giving a command to the program
1331inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1332interpreter a command to evaluate the expression. The name of the Lisp
1333interpreter comes from the word for the task done by a human who comes
1334up with the meaning of an expression---who ``interprets'' it.
1335
1336You can also evaluate an atom that is not part of a list---one that is
1337not surrounded by parentheses; again, the Lisp interpreter translates
1338from the humanly readable expression to the language of the computer.
1339But before discussing this (@pxref{Variables}), we will discuss what the
1340Lisp interpreter does when you make an error.
1341
1342@node Making Errors, Names & Definitions, Run a Program, List Processing
1343@comment node-name, next, previous, up
1344@section Generate an Error Message
1345@cindex Generate an error message
1346@cindex Error message generation
1347
1348Partly so you won't worry if you do it accidentally, we will now give
1349a command to the Lisp interpreter that generates an error message.
1350This is a harmless activity; and indeed, we will often try to generate
1351error messages intentionally. Once you understand the jargon, error
1352messages can be informative. Instead of being called ``error''
1353messages, they should be called ``help'' messages. They are like
1354signposts to a traveller in a strange country; deciphering them can be
1355hard, but once understood, they can point the way.
1356
1357The error message is generated by a built-in GNU Emacs debugger. We
1358will `enter the debugger'. You get out of the debugger by typing @code{q}.
1359
1360What we will do is evaluate a list that is not quoted and does not
1361have a meaningful command as its first element. Here is a list almost
1362exactly the same as the one we just used, but without the single-quote
1363in front of it. Position the cursor right after it and type @kbd{C-x
1364C-e}:
1365
1366@smallexample
1367(this is an unquoted list)
1368@end smallexample
1369
1370@noindent
1371What you see depends on which version of Emacs you are running. GNU
1372Emacs version 21 provides more information than version 20 and before.
1373First, the more recent result of generating an error; then the
1374earlier, version 20 result.
1375
1376@need 1250
1377@noindent
1378In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1379you will see the following in it:
1380
1381@smallexample
1382@group
1383---------- Buffer: *Backtrace* ----------
1384Debugger entered--Lisp error: (void-function this)
1385 (this is an unquoted list)
1386 eval((this is an unquoted list))
1387 eval-last-sexp-1(nil)
1388 eval-last-sexp(nil)
1389 call-interactively(eval-last-sexp)
1390---------- Buffer: *Backtrace* ----------
1391@end group
1392@end smallexample
1393
1394@need 1200
1395@noindent
1396Your cursor will be in this window (you may have to wait a few seconds
1397before it becomes visible). To quit the debugger and make the
1398debugger window go away, type:
1399
1400@smallexample
1401q
1402@end smallexample
1403
1404@noindent
1405Please type @kbd{q} right now, so you become confident that you can
1406get out of the debugger. Then, type @kbd{C-x C-e} again to re-enter
1407it.
1408
1409@cindex @samp{function} defined
1410Based on what we already know, we can almost read this error message.
1411
1412You read the @file{*Backtrace*} buffer from the bottom up; it tells
1413you what Emacs did. When you typed @kbd{C-x C-e}, you made an
1414interactive call to the command @code{eval-last-sexp}. @code{eval} is
1415an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1416`symbolic expression'. The command means `evaluate last symbolic
1417expression', which is the expression just before your cursor.
1418
1419Each line above tells you what the Lisp interpreter evaluated next.
1420The most recent action is at the top. The buffer is called the
1421@file{*Backtrace*} buffer because it enables you to track Emacs
1422backwards.
1423
1424@need 800
1425At the top of the @file{*Backtrace*} buffer, you see the line:
1426
1427@smallexample
1428Debugger entered--Lisp error: (void-function this)
1429@end smallexample
1430
1431@noindent
1432The Lisp interpreter tried to evaluate the first atom of the list, the
1433word @samp{this}. It is this action that generated the error message
1434@samp{void-function this}.
1435
1436The message contains the words @samp{void-function} and @samp{this}.
1437
1438@cindex @samp{function} defined
1439The word @samp{function} was mentioned once before. It is a very
1440important word. For our purposes, we can define it by saying that a
1441@dfn{function} is a set of instructions to the computer that tell the
1442computer to do something.
1443
1444Now we can begin to understand the error message: @samp{void-function
1445this}. The function (that is, the word @samp{this}) does not have a
1446definition of any set of instructions for the computer to carry out.
1447
1448The slightly odd word, @samp{void-function}, is designed to cover the
1449way Emacs Lisp is implemented, which is that when a symbol does not
1450have a function definition attached to it, the place that should
1451contain the instructions is `void'.
1452
1453On the other hand, since we were able to add 2 plus 2 successfully, by
1454evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1455have a set of instructions for the computer to obey and those
1456instructions must be to add the numbers that follow the @code{+}.
1457
1458@need 1250
1459In GNU Emacs version 20, and in earlier versions, you will see only
1460one line of error message; it will appear in the echo area and look
1461like this:
1462
1463@smallexample
1464Symbol's function definition is void:@: this
1465@end smallexample
1466
1467@noindent
1468(Also, your terminal may beep at you---some do, some don't; and others
1469blink. This is just a device to get your attention.) The message goes
1470away as soon as you type another key, even just to move the cursor.
1471
1472We know the meaning of the word @samp{Symbol}. It refers to the first
1473atom of the list, the word @samp{this}. The word @samp{function}
1474refers to the instructions that tell the computer what to do.
1475(Technically, the symbol tells the computer where to find the
1476instructions, but this is a complication we can ignore for the
1477moment.)
1478
1479The error message can be understood: @samp{Symbol's function
1480definition is void:@: this}. The symbol (that is, the word
1481@samp{this}) lacks instructions for the computer to carry out.
1482
1483@node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1484@comment node-name, next, previous, up
1485@section Symbol Names and Function Definitions
1486@cindex Symbol names
1487
1488We can articulate another characteristic of Lisp based on what we have
1489discussed so far---an important characteristic: a symbol, like
1490@code{+}, is not itself the set of instructions for the computer to
1491carry out. Instead, the symbol is used, perhaps temporarily, as a way
1492of locating the definition or set of instructions. What we see is the
1493name through which the instructions can be found. Names of people
1494work the same way. I can be referred to as @samp{Bob}; however, I am
c6f54b06
RC
1495not the letters @samp{B}, @samp{o}, @samp{b} but am, or were, the
1496consciousness consistently associated with a particular life-form.
1497The name is not me, but it can be used to refer to me.
8b096dce
EZ
1498
1499In Lisp, one set of instructions can be attached to several names.
1500For example, the computer instructions for adding numbers can be
1501linked to the symbol @code{plus} as well as to the symbol @code{+}
1502(and are in some dialects of Lisp). Among humans, I can be referred
1503to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1504
1505On the other hand, a symbol can have only one function definition
1506attached to it at a time. Otherwise, the computer would be confused as
1507to which definition to use. If this were the case among people, only
1508one person in the world could be named @samp{Bob}. However, the function
1509definition to which the name refers can be changed readily.
1510(@xref{Install, , Install a Function Definition}.)
1511
1512Since Emacs Lisp is large, it is customary to name symbols in a way
1513that identifies the part of Emacs to which the function belongs.
1514Thus, all the names for functions that deal with Texinfo start with
1515@samp{texinfo-} and those for functions that deal with reading mail
1516start with @samp{rmail-}.
1517
1518@node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1519@comment node-name, next, previous, up
1520@section The Lisp Interpreter
1521@cindex Lisp interpreter, what it does
1522@cindex Interpreter, what it does
1523
1524Based on what we have seen, we can now start to figure out what the
1525Lisp interpreter does when we command it to evaluate a list.
1526First, it looks to see whether there is a quote before the list; if
1527there is, the interpreter just gives us the list. On the other
1528hand, if there is no quote, the interpreter looks at the first element
1529in the list and sees whether it has a function definition. If it does,
1530the interpreter carries out the instructions in the function definition.
1531Otherwise, the interpreter prints an error message.
1532
1533This is how Lisp works. Simple. There are added complications which we
1534will get to in a minute, but these are the fundamentals. Of course, to
1535write Lisp programs, you need to know how to write function definitions
1536and attach them to names, and how to do this without confusing either
1537yourself or the computer.
1538
1539@menu
1540* Complications:: Variables, Special forms, Lists within.
1541* Byte Compiling:: Specially processing code for speed.
1542@end menu
1543
1544@node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1545@ifnottex
1546@unnumberedsubsec Complications
1547@end ifnottex
1548
1549Now, for the first complication. In addition to lists, the Lisp
1550interpreter can evaluate a symbol that is not quoted and does not have
1551parentheses around it. The Lisp interpreter will attempt to determine
1552the symbol's value as a @dfn{variable}. This situation is described
1553in the section on variables. (@xref{Variables}.)
1554
1555@cindex Special form
1556The second complication occurs because some functions are unusual and do
1557not work in the usual manner. Those that don't are called @dfn{special
1558forms}. They are used for special jobs, like defining a function, and
1559there are not many of them. In the next few chapters, you will be
1560introduced to several of the more important special forms.
1561
1562The third and final complication is this: if the function that the
1563Lisp interpreter is looking at is not a special form, and if it is part
1564of a list, the Lisp interpreter looks to see whether the list has a list
1565inside of it. If there is an inner list, the Lisp interpreter first
1566figures out what it should do with the inside list, and then it works on
1567the outside list. If there is yet another list embedded inside the
1568inner list, it works on that one first, and so on. It always works on
1569the innermost list first. The interpreter works on the innermost list
1570first, to evaluate the result of that list. The result may be
1571used by the enclosing expression.
1572
1573Otherwise, the interpreter works left to right, from one expression to
1574the next.
1575
1576@node Byte Compiling, , Complications, Lisp Interpreter
1577@subsection Byte Compiling
1578@cindex Byte compiling
1579
1580One other aspect of interpreting: the Lisp interpreter is able to
1581interpret two kinds of entity: humanly readable code, on which we will
1582focus exclusively, and specially processed code, called @dfn{byte
1583compiled} code, which is not humanly readable. Byte compiled code
1584runs faster than humanly readable code.
1585
1586You can transform humanly readable code into byte compiled code by
1587running one of the compile commands such as @code{byte-compile-file}.
1588Byte compiled code is usually stored in a file that ends with a
1589@file{.elc} extension rather than a @file{.el} extension. You will
1590see both kinds of file in the @file{emacs/lisp} directory; the files
1591to read are those with @file{.el} extensions.
1592
1593As a practical matter, for most things you might do to customize or
1594extend Emacs, you do not need to byte compile; and I will not discuss
1595the topic here. @xref{Byte Compilation, , Byte Compilation, elisp,
1596The GNU Emacs Lisp Reference Manual}, for a full description of byte
1597compilation.
1598
1599@node Evaluation, Variables, Lisp Interpreter, List Processing
1600@comment node-name, next, previous, up
1601@section Evaluation
1602@cindex Evaluation
1603
1604When the Lisp interpreter works on an expression, the term for the
1605activity is called @dfn{evaluation}. We say that the interpreter
1606`evaluates the expression'. I've used this term several times before.
1607The word comes from its use in everyday language, `to ascertain the
1608value or amount of; to appraise', according to @cite{Webster's New
1609Collegiate Dictionary}.
1610
1611After evaluating an expression, the Lisp interpreter will most likely
1612@dfn{return} the value that the computer produces by carrying out the
1613instructions it found in the function definition, or perhaps it will
1614give up on that function and produce an error message. (The interpreter
1615may also find itself tossed, so to speak, to a different function or it
1616may attempt to repeat continually what it is doing for ever and ever in
1617what is called an `infinite loop'. These actions are less common; and
1618we can ignore them.) Most frequently, the interpreter returns a value.
1619
1620@cindex @samp{side effect} defined
1621At the same time the interpreter returns a value, it may do something
1622else as well, such as move a cursor or copy a file; this other kind of
1623action is called a @dfn{side effect}. Actions that we humans think are
1624important, such as printing results, are often ``side effects'' to the
1625Lisp interpreter. The jargon can sound peculiar, but it turns out that
1626it is fairly easy to learn to use side effects.
1627
1628In summary, evaluating a symbolic expression most commonly causes the
1629Lisp interpreter to return a value and perhaps carry out a side effect;
1630or else produce an error.
1631
1632@menu
1633* Evaluating Inner Lists:: Lists within lists...
1634@end menu
1635
1636@node Evaluating Inner Lists, , Evaluation, Evaluation
1637@comment node-name, next, previous, up
1638@subsection Evaluating Inner Lists
1639@cindex Inner list evaluation
1640@cindex Evaluating inner lists
1641
1642If evaluation applies to a list that is inside another list, the outer
1643list may use the value returned by the first evaluation as information
1644when the outer list is evaluated. This explains why inner expressions
1645are evaluated first: the values they return are used by the outer
1646expressions.
1647
1648@need 1250
1649We can investigate this process by evaluating another addition example.
1650Place your cursor after the following expression and type @kbd{C-x C-e}:
1651
1652@smallexample
1653(+ 2 (+ 3 3))
1654@end smallexample
1655
1656@noindent
1657The number 8 will appear in the echo area.
1658
1659What happens is that the Lisp interpreter first evaluates the inner
1660expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1661evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1662returns the value 8. Since there are no more enclosing expressions to
1663evaluate, the interpreter prints that value in the echo area.
1664
1665Now it is easy to understand the name of the command invoked by the
1666keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}. The
1667letters @code{sexp} are an abbreviation for `symbolic expression', and
1668@code{eval} is an abbreviation for `evaluate'. The command means
1669`evaluate last symbolic expression'.
1670
1671As an experiment, you can try evaluating the expression by putting the
1672cursor at the beginning of the next line immediately following the
1673expression, or inside the expression.
1674
1675@need 800
1676Here is another copy of the expression:
1677
1678@smallexample
1679(+ 2 (+ 3 3))
1680@end smallexample
1681
1682@noindent
1683If you place the cursor at the beginning of the blank line that
1684immediately follows the expression and type @kbd{C-x C-e}, you will
1685still get the value 8 printed in the echo area. Now try putting the
1686cursor inside the expression. If you put it right after the next to
1687last parenthesis (so it appears to sit on top of the last parenthesis),
1688you will get a 6 printed in the echo area! This is because the command
1689evaluates the expression @code{(+ 3 3)}.
1690
1691Now put the cursor immediately after a number. Type @kbd{C-x C-e} and
1692you will get the number itself. In Lisp, if you evaluate a number, you
1693get the number itself---this is how numbers differ from symbols. If you
1694evaluate a list starting with a symbol like @code{+}, you will get a
1695value returned that is the result of the computer carrying out the
1696instructions in the function definition attached to that name. If a
1697symbol by itself is evaluated, something different happens, as we will
1698see in the next section.
1699
1700@node Variables, Arguments, Evaluation, List Processing
1701@comment node-name, next, previous, up
1702@section Variables
1703@cindex Variables
1704
1705In Emacs Lisp, a symbol can have a value attached to it just as it can
1706have a function definition attached to it. The two are different.
1707The function definition is a set of instructions that a computer will
1708obey. A value, on the other hand, is something, such as number or a
1709name, that can vary (which is why such a symbol is called a variable).
1710The value of a symbol can be any expression in Lisp, such as a symbol,
1711number, list, or string. A symbol that has a value is often called a
1712@dfn{variable}.
1713
1714A symbol can have both a function definition and a value attached to
1715it at the same time. Or it can have just one or the other.
1716The two are separate. This is somewhat similar
1717to the way the name Cambridge can refer to the city in Massachusetts
1718and have some information attached to the name as well, such as
1719``great programming center''.
1720
1721@ignore
1722(Incidentally, in Emacs Lisp, a symbol can have two
1723other things attached to it, too: a property list and a documentation
1724string; these are discussed later.)
1725@end ignore
1726
1727Another way to think about this is to imagine a symbol as being a chest
1728of drawers. The function definition is put in one drawer, the value in
1729another, and so on. What is put in the drawer holding the value can be
1730changed without affecting the contents of the drawer holding the
1731function definition, and vice-versa.
1732
1733@menu
1734* fill-column Example::
1735* Void Function:: The error message for a symbol
1736 without a function.
1737* Void Variable:: The error message for a symbol without a value.
1738@end menu
1739
1740@node fill-column Example, Void Function, Variables, Variables
1741@ifnottex
1742@unnumberedsubsec @code{fill-column}, an Example Variable
1743@end ifnottex
1744
1745@findex fill-column, @r{an example variable}
1746@cindex Example variable, @code{fill-column}
1747@cindex Variable, example of, @code{fill-column}
1748The variable @code{fill-column} illustrates a symbol with a value
1749attached to it: in every GNU Emacs buffer, this symbol is set to some
1750value, usually 72 or 70, but sometimes to some other value. To find the
1751value of this symbol, evaluate it by itself. If you are reading this in
1752Info inside of GNU Emacs, you can do this by putting the cursor after
1753the symbol and typing @kbd{C-x C-e}:
1754
1755@smallexample
1756fill-column
1757@end smallexample
1758
1759@noindent
1760After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1761area. This is the value for which @code{fill-column} is set for me as I
1762write this. It may be different for you in your Info buffer. Notice
1763that the value returned as a variable is printed in exactly the same way
1764as the value returned by a function carrying out its instructions. From
1765the point of view of the Lisp interpreter, a value returned is a value
1766returned. What kind of expression it came from ceases to matter once
1767the value is known.
1768
1769A symbol can have any value attached to it or, to use the jargon, we can
1770@dfn{bind} the variable to a value: to a number, such as 72; to a
1771string, @code{"such as this"}; to a list, such as @code{(spruce pine
1772oak)}; we can even bind a variable to a function definition.
1773
1774A symbol can be bound to a value in several ways. @xref{set & setq, ,
1775Setting the Value of a Variable}, for information about one way to do
1776this.
1777
1778@node Void Function, Void Variable, fill-column Example, Variables
1779@comment node-name, next, previous, up
1780@subsection Error Message for a Symbol Without a Function
1781@cindex Symbol without function error
1782@cindex Error for symbol without function
1783
1784When we evaluated @code{fill-column} to find its value as a variable,
1785we did not place parentheses around the word. This is because we did
1786not intend to use it as a function name.
1787
1788If @code{fill-column} were the first or only element of a list, the
1789Lisp interpreter would attempt to find the function definition
1790attached to it. But @code{fill-column} has no function definition.
1791Try evaluating this:
1792
1793@smallexample
1794(fill-column)
1795@end smallexample
1796
1797@need 1250
1798@noindent
1799In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1800that says:
1801
1802@smallexample
1803@group
1804---------- Buffer: *Backtrace* ----------
1805Debugger entered--Lisp error: (void-function fill-column)
1806 (fill-column)
1807 eval((fill-column))
1808 eval-last-sexp-1(nil)
1809 eval-last-sexp(nil)
1810 call-interactively(eval-last-sexp)
1811---------- Buffer: *Backtrace* ----------
1812@end group
1813@end smallexample
1814
1815@noindent
1816(Remember, to quit the debugger and make the debugger window go away,
1817type @kbd{q} in the @file{*Backtrace*} buffer.)
1818
1819@need 800
1820In GNU Emacs 20 and before, you will produce an error message that says:
1821
1822@smallexample
1823Symbol's function definition is void:@: fill-column
1824@end smallexample
1825
1826@noindent
1827(The message will go away away as soon as you move the cursor or type
1828another key.)
1829
1830@node Void Variable, , Void Function, Variables
1831@comment node-name, next, previous, up
1832@subsection Error Message for a Symbol Without a Value
1833@cindex Symbol without value error
1834@cindex Error for symbol without value
1835
1836If you attempt to evaluate a symbol that does not have a value bound to
1837it, you will receive an error message. You can see this by
1838experimenting with our 2 plus 2 addition. In the following expression,
1839put your cursor right after the @code{+}, before the first number 2,
1840type @kbd{C-x C-e}:
1841
1842@smallexample
1843(+ 2 2)
1844@end smallexample
1845
1846@need 1500
1847@noindent
1848In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1849says:
1850
1851@smallexample
1852@group
1853---------- Buffer: *Backtrace* ----------
1854Debugger entered--Lisp error: (void-variable +)
1855 eval(+)
1856 eval-last-sexp-1(nil)
1857 eval-last-sexp(nil)
1858 call-interactively(eval-last-sexp)
1859---------- Buffer: *Backtrace* ----------
1860@end group
1861@end smallexample
1862
1863@noindent
1864(As with the other times we entered the debugger, you can quit by
1865typing @kbd{q} in the @file{*Backtrace*} buffer.)
1866
1867This backtrace is different from the very first error message we saw,
1868which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1869In this case, the function does not have a value as a variable; while
1870in the other error message, the function (the word `this') did not
1871have a definition.
1872
1873In this experiment with the @code{+}, what we did was cause the Lisp
1874interpreter to evaluate the @code{+} and look for the value of the
1875variable instead of the function definition. We did this by placing the
1876cursor right after the symbol rather than after the parenthesis of the
1877enclosing list as we did before. As a consequence, the Lisp interpreter
1878evaluated the preceding s-expression, which in this case was the
1879@code{+} by itself.
1880
1881Since @code{+} does not have a value bound to it, just the function
1882definition, the error message reported that the symbol's value as a
1883variable was void.
1884
1885@need 800
1886In GNU Emacs version 20 and before, your error message will say:
1887
1888@example
1889Symbol's value as variable is void:@: +
1890@end example
1891
1892@noindent
1893The meaning is the same as in GNU Emacs 21.
1894
1895@node Arguments, set & setq, Variables, List Processing
1896@comment node-name, next, previous, up
1897@section Arguments
1898@cindex Arguments
1899@cindex Passing information to functions
1900
1901To see how information is passed to functions, let's look again at
1902our old standby, the addition of two plus two. In Lisp, this is written
1903as follows:
1904
1905@smallexample
1906(+ 2 2)
1907@end smallexample
1908
1909If you evaluate this expression, the number 4 will appear in your echo
1910area. What the Lisp interpreter does is add the numbers that follow
1911the @code{+}.
1912
1913@cindex @samp{argument} defined
1914The numbers added by @code{+} are called the @dfn{arguments} of the
1915function @code{+}. These numbers are the information that is given to
1916or @dfn{passed} to the function.
1917
1918The word `argument' comes from the way it is used in mathematics and
1919does not refer to a disputation between two people; instead it refers to
1920the information presented to the function, in this case, to the
1921@code{+}. In Lisp, the arguments to a function are the atoms or lists
1922that follow the function. The values returned by the evaluation of
1923these atoms or lists are passed to the function. Different functions
1924require different numbers of arguments; some functions require none at
1925all.@footnote{It is curious to track the path by which the word `argument'
1926came to have two different meanings, one in mathematics and the other in
1927everyday English. According to the @cite{Oxford English Dictionary},
1928the word derives from the Latin for @samp{to make clear, prove}; thus it
1929came to mean, by one thread of derivation, `the evidence offered as
1930proof', which is to say, `the information offered', which led to its
1931meaning in Lisp. But in the other thread of derivation, it came to mean
1932`to assert in a manner against which others may make counter
1933assertions', which led to the meaning of the word as a disputation.
1934(Note here that the English word has two different definitions attached
1935to it at the same time. By contrast, in Emacs Lisp, a symbol cannot
1936have two different function definitions at the same time.)}
1937
1938@menu
1939* Data types:: Types of data passed to a function.
1940* Args as Variable or List:: An argument can be the value
1941 of a variable or list.
1942* Variable Number of Arguments:: Some functions may take a
1943 variable number of arguments.
1944* Wrong Type of Argument:: Passing an argument of the wrong type
1945 to a function.
1946* message:: A useful function for sending messages.
1947@end menu
1948
1949@node Data types, Args as Variable or List, Arguments, Arguments
1950@comment node-name, next, previous, up
1951@subsection Arguments' Data Types
1952@cindex Data types
1953@cindex Types of data
1954@cindex Arguments' data types
1955
1956The type of data that should be passed to a function depends on what
1957kind of information it uses. The arguments to a function such as
1958@code{+} must have values that are numbers, since @code{+} adds numbers.
1959Other functions use different kinds of data for their arguments.
1960
c6f54b06 1961@need 1250
8b096dce
EZ
1962@findex concat
1963For example, the @code{concat} function links together or unites two or
1964more strings of text to produce a string. The arguments are strings.
1965Concatenating the two character strings @code{abc}, @code{def} produces
1966the single string @code{abcdef}. This can be seen by evaluating the
1967following:
1968
1969@smallexample
1970(concat "abc" "def")
1971@end smallexample
1972
1973@noindent
1974The value produced by evaluating this expression is @code{"abcdef"}.
1975
1976A function such as @code{substring} uses both a string and numbers as
1977arguments. The function returns a part of the string, a substring of
1978the first argument. This function takes three arguments. Its first
1979argument is the string of characters, the second and third arguments are
1980numbers that indicate the beginning and end of the substring. The
1981numbers are a count of the number of characters (including spaces and
1982punctuations) from the beginning of the string.
1983
1984@need 800
1985For example, if you evaluate the following:
1986
1987@smallexample
1988(substring "The quick brown fox jumped." 16 19)
1989@end smallexample
1990
1991@noindent
1992you will see @code{"fox"} appear in the echo area. The arguments are the
1993string and the two numbers.
1994
1995Note that the string passed to @code{substring} is a single atom even
1996though it is made up of several words separated by spaces. Lisp counts
1997everything between the two quotation marks as part of the string,
1998including the spaces. You can think of the @code{substring} function as
1999a kind of `atom smasher' since it takes an otherwise indivisible atom
2000and extracts a part. However, @code{substring} is only able to extract
2001a substring from an argument that is a string, not from another type of
2002atom such as a number or symbol.
2003
2004@node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2005@comment node-name, next, previous, up
2006@subsection An Argument as the Value of a Variable or List
2007
2008An argument can be a symbol that returns a value when it is evaluated.
2009For example, when the symbol @code{fill-column} by itself is evaluated,
2010it returns a number. This number can be used in an addition.
2011
2012@need 1250
2013Position the cursor after the following expression and type @kbd{C-x
2014C-e}:
2015
2016@smallexample
2017(+ 2 fill-column)
2018@end smallexample
2019
2020@noindent
2021The value will be a number two more than what you get by evaluating
2022@code{fill-column} alone. For me, this is 74, because the value of
2023@code{fill-column} is 72.
2024
2025As we have just seen, an argument can be a symbol that returns a value
2026when evaluated. In addition, an argument can be a list that returns a
2027value when it is evaluated. For example, in the following expression,
2028the arguments to the function @code{concat} are the strings
2029@w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2030@code{(number-to-string (+ 2 fill-column))}.
2031
2032@c For Emacs 21, need number-to-string
2033@smallexample
2034(concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2035@end smallexample
2036
2037@noindent
2038If you evaluate this expression---and if, as with my Emacs,
2039@code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2040appear in the echo area. (Note that you must put spaces after the
2041word @samp{The} and before the word @samp{red} so they will appear in
2042the final string. The function @code{number-to-string} converts the
2043integer that the addition function returns to a string.
2044@code{number-to-string} is also known as @code{int-to-string}.)
2045
2046@node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2047@comment node-name, next, previous, up
2048@subsection Variable Number of Arguments
2049@cindex Variable number of arguments
2050@cindex Arguments, variable number of
2051
2052Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2053number of arguments. (The @code{*} is the symbol for multiplication.)
2054This can be seen by evaluating each of the following expressions in
2055the usual way. What you will see in the echo area is printed in this
2056text after @samp{@result{}}, which you may read as `evaluates to'.
2057
2058@need 1250
2059In the first set, the functions have no arguments:
2060
2061@smallexample
2062@group
2063(+) @result{} 0
2064
2065(*) @result{} 1
2066@end group
2067@end smallexample
2068
2069@need 1250
2070In this set, the functions have one argument each:
2071
2072@smallexample
2073@group
2074(+ 3) @result{} 3
2075
2076(* 3) @result{} 3
2077@end group
2078@end smallexample
2079
2080@need 1250
2081In this set, the functions have three arguments each:
2082
2083@smallexample
2084@group
2085(+ 3 4 5) @result{} 12
2086
2087(* 3 4 5) @result{} 60
2088@end group
2089@end smallexample
2090
2091@node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2092@comment node-name, next, previous, up
2093@subsection Using the Wrong Type Object as an Argument
2094@cindex Wrong type of argument
2095@cindex Argument, wrong type of
2096
2097When a function is passed an argument of the wrong type, the Lisp
2098interpreter produces an error message. For example, the @code{+}
2099function expects the values of its arguments to be numbers. As an
2100experiment we can pass it the quoted symbol @code{hello} instead of a
2101number. Position the cursor after the following expression and type
2102@kbd{C-x C-e}:
2103
2104@smallexample
2105(+ 2 'hello)
2106@end smallexample
2107
2108@noindent
2109When you do this you will generate an error message. What has happened
2110is that @code{+} has tried to add the 2 to the value returned by
2111@code{'hello}, but the value returned by @code{'hello} is the symbol
2112@code{hello}, not a number. Only numbers can be added. So @code{+}
2113could not carry out its addition.
2114
2115@need 1250
2116In GNU Emacs version 21, you will create and enter a
2117@file{*Backtrace*} buffer that says:
2118
2119@noindent
2120@smallexample
2121@group
2122---------- Buffer: *Backtrace* ----------
2123Debugger entered--Lisp error:
2124 (wrong-type-argument number-or-marker-p hello)
2125 +(2 hello)
2126 eval((+ 2 (quote hello)))
2127 eval-last-sexp-1(nil)
2128 eval-last-sexp(nil)
2129 call-interactively(eval-last-sexp)
2130---------- Buffer: *Backtrace* ----------
2131@end group
2132@end smallexample
2133
2134@need 1250
2135As usual, the error message tries to be helpful and makes sense after you
2136learn how to read it.
2137
2138The first part of the error message is straightforward; it says
2139@samp{wrong type argument}. Next comes the mysterious jargon word
2140@w{@samp{number-or-marker-p}}. This word is trying to tell you what
2141kind of argument the @code{+} expected.
2142
2143The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2144trying to determine whether the information presented it (the value of
2145the argument) is a number or a marker (a special object representing a
2146buffer position). What it does is test to see whether the @code{+} is
2147being given numbers to add. It also tests to see whether the
2148argument is something called a marker, which is a specific feature of
2149Emacs Lisp. (In Emacs, locations in a buffer are recorded as markers.
2150When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2151its position is kept as a marker. The mark can be considered a
2152number---the number of characters the location is from the beginning
2153of the buffer.) In Emacs Lisp, @code{+} can be used to add the
2154numeric value of marker positions as numbers.
2155
2156The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2157practice started in the early days of Lisp programming. The @samp{p}
2158stands for `predicate'. In the jargon used by the early Lisp
2159researchers, a predicate refers to a function to determine whether some
2160property is true or false. So the @samp{p} tells us that
2161@code{number-or-marker-p} is the name of a function that determines
2162whether it is true or false that the argument supplied is a number or
2163a marker. Other Lisp symbols that end in @samp{p} include @code{zerop},
2164a function that tests whether its argument has the value of zero, and
2165@code{listp}, a function that tests whether its argument is a list.
2166
2167Finally, the last part of the error message is the symbol @code{hello}.
2168This is the value of the argument that was passed to @code{+}. If the
2169addition had been passed the correct type of object, the value passed
2170would have been a number, such as 37, rather than a symbol like
2171@code{hello}. But then you would not have got the error message.
2172
2173@need 1250
2174In GNU Emacs version 20 and before, the echo area displays an error
2175message that says:
2176
2177@smallexample
2178Wrong type argument:@: number-or-marker-p, hello
2179@end smallexample
2180
2181This says, in different words, the same as the top line of the
2182@file{*Backtrace*} buffer.
2183
2184@node message, , Wrong Type of Argument, Arguments
2185@comment node-name, next, previous, up
2186@subsection The @code{message} Function
2187@findex message
2188
2189Like @code{+}, the @code{message} function takes a variable number of
2190arguments. It is used to send messages to the user and is so useful
2191that we will describe it here.
2192
2193@need 1250
2194A message is printed in the echo area. For example, you can print a
2195message in your echo area by evaluating the following list:
2196
2197@smallexample
2198(message "This message appears in the echo area!")
2199@end smallexample
2200
2201The whole string between double quotation marks is a single argument
2202and is printed @i{in toto}. (Note that in this example, the message
2203itself will appear in the echo area within double quotes; that is
2204because you see the value returned by the @code{message} function. In
2205most uses of @code{message} in programs that you write, the text will
2206be printed in the echo area as a side-effect, without the quotes.
2207@xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2208detail}, for an example of this.)
2209
2210However, if there is a @samp{%s} in the quoted string of characters, the
2211@code{message} function does not print the @samp{%s} as such, but looks
2212to the argument that follows the string. It evaluates the second
2213argument and prints the value at the location in the string where the
2214@samp{%s} is.
2215
2216@need 1250
2217You can see this by positioning the cursor after the following
2218expression and typing @kbd{C-x C-e}:
2219
2220@smallexample
2221(message "The name of this buffer is: %s." (buffer-name))
2222@end smallexample
2223
2224@noindent
2225In Info, @code{"The name of this buffer is: *info*."} will appear in the
2226echo area. The function @code{buffer-name} returns the name of the
2227buffer as a string, which the @code{message} function inserts in place
2228of @code{%s}.
2229
2230To print a value as an integer, use @samp{%d} in the same way as
2231@samp{%s}. For example, to print a message in the echo area that
2232states the value of the @code{fill-column}, evaluate the following:
2233
2234@smallexample
2235(message "The value of fill-column is %d." fill-column)
2236@end smallexample
2237
2238@noindent
2239On my system, when I evaluate this list, @code{"The value of
2240fill-column is 72."} appears in my echo area@footnote{Actually, you
2241can use @code{%s} to print a number. It is non-specific. @code{%d}
2242prints only the part of a number left of a decimal point, and not
2243anything that is not a number.}.
2244
2245If there is more than one @samp{%s} in the quoted string, the value of
2246the first argument following the quoted string is printed at the
2247location of the first @samp{%s} and the value of the second argument is
2248printed at the location of the second @samp{%s}, and so on.
2249
2250@need 1250
2251For example, if you evaluate the following,
2252
2253@smallexample
2254@group
2255(message "There are %d %s in the office!"
2256 (- fill-column 14) "pink elephants")
2257@end group
2258@end smallexample
2259
2260@noindent
2261a rather whimsical message will appear in your echo area. On my system
2262it says, @code{"There are 58 pink elephants in the office!"}.
2263
2264The expression @code{(- fill-column 14)} is evaluated and the resulting
2265number is inserted in place of the @samp{%d}; and the string in double
2266quotes, @code{"pink elephants"}, is treated as a single argument and
2267inserted in place of the @samp{%s}. (That is to say, a string between
2268double quotes evaluates to itself, like a number.)
2269
2270Finally, here is a somewhat complex example that not only illustrates
2271the computation of a number, but also shows how you can use an
2272expression within an expression to generate the text that is substituted
2273for @samp{%s}:
2274
2275@smallexample
2276@group
2277(message "He saw %d %s"
c6f54b06 2278 (- fill-column 32)
8b096dce
EZ
2279 (concat "red "
2280 (substring
2281 "The quick brown foxes jumped." 16 21)
2282 " leaping."))
2283@end group
2284@end smallexample
2285
2286In this example, @code{message} has three arguments: the string,
2287@code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2288the expression beginning with the function @code{concat}. The value
2289resulting from the evaluation of @code{(- fill-column 32)} is inserted
2290in place of the @samp{%d}; and the value returned by the expression
2291beginning with @code{concat} is inserted in place of the @samp{%s}.
2292
2293When I evaluate the expression, the message @code{"He saw 38 red
2294foxes leaping."} appears in my echo area.
2295
2296@node set & setq, Summary, Arguments, List Processing
2297@comment node-name, next, previous, up
2298@section Setting the Value of a Variable
2299@cindex Variable, setting value
2300@cindex Setting value of variable
2301
2302@cindex @samp{bind} defined
2303There are several ways by which a variable can be given a value. One of
2304the ways is to use either the function @code{set} or the function
2305@code{setq}. Another way is to use @code{let} (@pxref{let}). (The
2306jargon for this process is to @dfn{bind} a variable to a value.)
2307
2308The following sections not only describe how @code{set} and @code{setq}
2309work but also illustrate how arguments are passed.
2310
2311@menu
2312* Using set:: Setting values.
2313* Using setq:: Setting a quoted value.
2314* Counting:: Using @code{setq} to count.
2315@end menu
2316
2317@node Using set, Using setq, set & setq, set & setq
2318@comment node-name, next, previous, up
2319@subsection Using @code{set}
2320@findex set
2321
2322To set the value of the symbol @code{flowers} to the list @code{'(rose
2323violet daisy buttercup)}, evaluate the following expression by
2324positioning the cursor after the expression and typing @kbd{C-x C-e}.
2325
2326@smallexample
2327(set 'flowers '(rose violet daisy buttercup))
2328@end smallexample
2329
2330@noindent
2331The list @code{(rose violet daisy buttercup)} will appear in the echo
2332area. This is what is @emph{returned} by the @code{set} function. As a
2333side effect, the symbol @code{flowers} is bound to the list ; that is,
2334the symbol @code{flowers}, which can be viewed as a variable, is given
2335the list as its value. (This process, by the way, illustrates how a
2336side effect to the Lisp interpreter, setting the value, can be the
2337primary effect that we humans are interested in. This is because every
2338Lisp function must return a value if it does not get an error, but it
2339will only have a side effect if it is designed to have one.)
2340
2341After evaluating the @code{set} expression, you can evaluate the symbol
2342@code{flowers} and it will return the value you just set. Here is the
2343symbol. Place your cursor after it and type @kbd{C-x C-e}.
2344
2345@smallexample
2346flowers
2347@end smallexample
2348
2349@noindent
2350When you evaluate @code{flowers}, the list
2351@code{(rose violet daisy buttercup)} appears in the echo area.
2352
2353Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2354in front of it, what you will see in the echo area is the symbol itself,
2355@code{flowers}. Here is the quoted symbol, so you can try this:
2356
2357@smallexample
2358'flowers
2359@end smallexample
2360
2361Note also, that when you use @code{set}, you need to quote both
2362arguments to @code{set}, unless you want them evaluated. Since we do
2363not want either argument evaluated, neither the variable
2364@code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2365are quoted. (When you use @code{set} without quoting its first
2366argument, the first argument is evaluated before anything else is
2367done. If you did this and @code{flowers} did not have a value
2368already, you would get an error message that the @samp{Symbol's value
2369as variable is void}; on the other hand, if @code{flowers} did return
2370a value after it was evaluated, the @code{set} would attempt to set
2371the value that was returned. There are situations where this is the
2372right thing for the function to do; but such situations are rare.)
2373
2374@node Using setq, Counting, Using set, set & setq
2375@comment node-name, next, previous, up
2376@subsection Using @code{setq}
2377@findex setq
2378
2379As a practical matter, you almost always quote the first argument to
2380@code{set}. The combination of @code{set} and a quoted first argument
2381is so common that it has its own name: the special form @code{setq}.
2382This special form is just like @code{set} except that the first argument
2383is quoted automatically, so you don't need to type the quote mark
2384yourself. Also, as an added convenience, @code{setq} permits you to set
2385several different variables to different values, all in one expression.
2386
2387To set the value of the variable @code{carnivores} to the list
2388@code{'(lion tiger leopard)} using @code{setq}, the following expression
2389is used:
2390
2391@smallexample
2392(setq carnivores '(lion tiger leopard))
2393@end smallexample
2394
2395@noindent
2396This is exactly the same as using @code{set} except the first argument
2397is automatically quoted by @code{setq}. (The @samp{q} in @code{setq}
2398means @code{quote}.)
2399
2400@need 1250
2401With @code{set}, the expression would look like this:
2402
2403@smallexample
2404(set 'carnivores '(lion tiger leopard))
2405@end smallexample
2406
2407Also, @code{setq} can be used to assign different values to
2408different variables. The first argument is bound to the value
2409of the second argument, the third argument is bound to the value of the
2410fourth argument, and so on. For example, you could use the following to
2411assign a list of trees to the symbol @code{trees} and a list of herbivores
2412to the symbol @code{herbivores}:
2413
2414@smallexample
2415@group
2416(setq trees '(pine fir oak maple)
2417 herbivores '(gazelle antelope zebra))
2418@end group
2419@end smallexample
2420
2421@noindent
2422(The expression could just as well have been on one line, but it might
2423not have fit on a page; and humans find it easier to read nicely
2424formatted lists.)
2425
2426Although I have been using the term `assign', there is another way of
2427thinking about the workings of @code{set} and @code{setq}; and that is to
2428say that @code{set} and @code{setq} make the symbol @emph{point} to the
2429list. This latter way of thinking is very common and in forthcoming
2430chapters we shall come upon at least one symbol that has `pointer' as
2431part of its name. The name is chosen because the symbol has a value,
2432specifically a list, attached to it; or, expressed another way,
2433the symbol is set to ``point'' to the list.
2434
2435@node Counting, , Using setq, set & setq
2436@comment node-name, next, previous, up
2437@subsection Counting
2438@cindex Counting
2439
2440Here is an example that shows how to use @code{setq} in a counter. You
2441might use this to count how many times a part of your program repeats
2442itself. First set a variable to zero; then add one to the number each
2443time the program repeats itself. To do this, you need a variable that
2444serves as a counter, and two expressions: an initial @code{setq}
2445expression that sets the counter variable to zero; and a second
2446@code{setq} expression that increments the counter each time it is
2447evaluated.
2448
2449@smallexample
2450@group
2451(setq counter 0) ; @r{Let's call this the initializer.}
2452
2453(setq counter (+ counter 1)) ; @r{This is the incrementer.}
2454
2455counter ; @r{This is the counter.}
2456@end group
2457@end smallexample
2458
2459@noindent
2460(The text following the @samp{;} are comments. @xref{Change a
2461defun, , Change a Function Definition}.)
2462
2463If you evaluate the first of these expressions, the initializer,
2464@code{(setq counter 0)}, and then evaluate the third expression,
2465@code{counter}, the number @code{0} will appear in the echo area. If
2466you then evaluate the second expression, the incrementer, @code{(setq
2467counter (+ counter 1))}, the counter will get the value 1. So if you
2468again evaluate @code{counter}, the number @code{1} will appear in the
2469echo area. Each time you evaluate the second expression, the value of
2470the counter will be incremented.
2471
2472When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2473the Lisp interpreter first evaluates the innermost list; this is the
2474addition. In order to evaluate this list, it must evaluate the variable
2475@code{counter} and the number @code{1}. When it evaluates the variable
2476@code{counter}, it receives its current value. It passes this value and
2477the number @code{1} to the @code{+} which adds them together. The sum
2478is then returned as the value of the inner list and passed to the
2479@code{setq} which sets the variable @code{counter} to this new value.
2480Thus, the value of the variable, @code{counter}, is changed.
2481
2482@node Summary, Error Message Exercises, set & setq, List Processing
2483@comment node-name, next, previous, up
2484@section Summary
2485
2486Learning Lisp is like climbing a hill in which the first part is the
2487steepest. You have now climbed the most difficult part; what remains
2488becomes easier as you progress onwards.
2489
c6f54b06 2490@need 1000
8b096dce
EZ
2491In summary,
2492
2493@itemize @bullet
2494
2495@item
2496Lisp programs are made up of expressions, which are lists or single atoms.
2497
2498@item
2499Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2500surrounded by parentheses. A list can be empty.
2501
2502@item
2503Atoms are multi-character symbols, like @code{forward-paragraph}, single
2504character symbols like @code{+}, strings of characters between double
2505quotation marks, or numbers.
2506
2507@item
2508A number evaluates to itself.
2509
2510@item
2511A string between double quotes also evaluates to itself.
2512
2513@item
2514When you evaluate a symbol by itself, its value is returned.
2515
2516@item
2517When you evaluate a list, the Lisp interpreter looks at the first symbol
2518in the list and then at the function definition bound to that symbol.
2519Then the instructions in the function definition are carried out.
2520
2521@item
2522A single-quote, @code{'}, tells the Lisp interpreter that it should
2523return the following expression as written, and not evaluate it as it
2524would if the quote were not there.
2525
2526@item
2527Arguments are the information passed to a function. The arguments to a
2528function are computed by evaluating the rest of the elements of the list
2529of which the function is the first element.
2530
2531@item
2532A function always returns a value when it is evaluated (unless it gets
2533an error); in addition, it may also carry out some action called a
2534``side effect''. In many cases, a function's primary purpose is to
2535create a side effect.
2536@end itemize
2537
2538@node Error Message Exercises, , Summary, List Processing
2539@comment node-name, next, previous, up
2540@section Exercises
2541
2542A few simple exercises:
2543
2544@itemize @bullet
2545@item
2546Generate an error message by evaluating an appropriate symbol that is
2547not within parentheses.
2548
2549@item
2550Generate an error message by evaluating an appropriate symbol that is
2551between parentheses.
2552
2553@item
2554Create a counter that increments by two rather than one.
2555
2556@item
2557Write an expression that prints a message in the echo area when
2558evaluated.
2559@end itemize
2560
2561@node Practicing Evaluation, Writing Defuns, List Processing, Top
2562@comment node-name, next, previous, up
2563@chapter Practicing Evaluation
2564@cindex Practicing evaluation
2565@cindex Evaluation practice
2566
2567Before learning how to write a function definition in Emacs Lisp, it is
2568useful to spend a little time evaluating various expressions that have
2569already been written. These expressions will be lists with the
2570functions as their first (and often only) element. Since some of the
2571functions associated with buffers are both simple and interesting, we
2572will start with those. In this section, we will evaluate a few of
2573these. In another section, we will study the code of several other
2574buffer-related functions, to see how they were written.
2575
2576@menu
2577* How to Evaluate:: Typing editing commands or @kbd{C-x C-e}
2578 causes evaluation.
2579* Buffer Names:: Buffers and files are different.
2580* Getting Buffers:: Getting a buffer itself, not merely its name.
2581* Switching Buffers:: How to change to another buffer.
2582* Buffer Size & Locations:: Where point is located and the size of
2583 the buffer.
2584* Evaluation Exercise::
2585@end menu
2586
2587@node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2588@ifnottex
2589@unnumberedsec How to Evaluate
2590@end ifnottex
2591
2592@i{Whenever you give an editing command} to Emacs Lisp, such as the
2593command to move the cursor or to scroll the screen, @i{you are evaluating
2594an expression,} the first element of which is a function. @i{This is
2595how Emacs works.}
2596
2597@cindex @samp{interactive function} defined
2598@cindex @samp{command} defined
2599When you type keys, you cause the Lisp interpreter to evaluate an
2600expression and that is how you get your results. Even typing plain text
2601involves evaluating an Emacs Lisp function, in this case, one that uses
2602@code{self-insert-command}, which simply inserts the character you
2603typed. The functions you evaluate by typing keystrokes are called
2604@dfn{interactive} functions, or @dfn{commands}; how you make a function
2605interactive will be illustrated in the chapter on how to write function
2606definitions. @xref{Interactive, , Making a Function Interactive}.
2607
2608In addition to typing keyboard commands, we have seen a second way to
2609evaluate an expression: by positioning the cursor after a list and
2610typing @kbd{C-x C-e}. This is what we will do in the rest of this
2611section. There are other ways to evaluate an expression as well; these
2612will be described as we come to them.
2613
2614Besides being used for practicing evaluation, the functions shown in the
2615next few sections are important in their own right. A study of these
2616functions makes clear the distinction between buffers and files, how to
2617switch to a buffer, and how to determine a location within it.
2618
2619@node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2620@comment node-name, next, previous, up
2621@section Buffer Names
2622@findex buffer-name
2623@findex buffer-file-name
2624
2625The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2626the difference between a file and a buffer. When you evaluate the
2627following expression, @code{(buffer-name)}, the name of the buffer
2628appears in the echo area. When you evaluate @code{(buffer-file-name)},
2629the name of the file to which the buffer refers appears in the echo
2630area. Usually, the name returned by @code{(buffer-name)} is the same as
2631the name of the file to which it refers, and the name returned by
2632@code{(buffer-file-name)} is the full path-name of the file.
2633
2634A file and a buffer are two different entities. A file is information
2635recorded permanently in the computer (unless you delete it). A buffer,
2636on the other hand, is information inside of Emacs that will vanish at
2637the end of the editing session (or when you kill the buffer). Usually,
2638a buffer contains information that you have copied from a file; we say
2639the buffer is @dfn{visiting} that file. This copy is what you work on
2640and modify. Changes to the buffer do not change the file, until you
2641save the buffer. When you save the buffer, the buffer is copied to the file
2642and is thus saved permanently.
2643
2644@need 1250
2645If you are reading this in Info inside of GNU Emacs, you can evaluate
2646each of the following expressions by positioning the cursor after it and
2647typing @kbd{C-x C-e}.
2648
2649@smallexample
2650@group
2651(buffer-name)
2652
2653(buffer-file-name)
2654@end group
2655@end smallexample
2656
2657@noindent
2658When I do this, @file{"introduction.texinfo"} is the value returned by
2659evaluating @code{(buffer-name)}, and
2660@file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2661evaluating @code{(buffer-file-name)}. The former is the name of the
2662buffer and the latter is the name of the file. (In the expressions, the
2663parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2664@code{buffer-file-name} as functions; without the parentheses, the
2665interpreter would attempt to evaluate the symbols as variables.
2666@xref{Variables}.)
2667
2668In spite of the distinction between files and buffers, you will often
2669find that people refer to a file when they mean a buffer and vice-versa.
2670Indeed, most people say, ``I am editing a file,'' rather than saying,
2671``I am editing a buffer which I will soon save to a file.'' It is
2672almost always clear from context what people mean. When dealing with
2673computer programs, however, it is important to keep the distinction in mind,
2674since the computer is not as smart as a person.
2675
2676@cindex Buffer, history of word
2677The word `buffer', by the way, comes from the meaning of the word as a
2678cushion that deadens the force of a collision. In early computers, a
2679buffer cushioned the interaction between files and the computer's
2680central processing unit. The drums or tapes that held a file and the
2681central processing unit were pieces of equipment that were very
2682different from each other, working at their own speeds, in spurts. The
2683buffer made it possible for them to work together effectively.
2684Eventually, the buffer grew from being an intermediary, a temporary
2685holding place, to being the place where work is done. This
2686transformation is rather like that of a small seaport that grew into a
2687great city: once it was merely the place where cargo was warehoused
2688temporarily before being loaded onto ships; then it became a business
2689and cultural center in its own right.
2690
2691Not all buffers are associated with files. For example, when you start
2692an Emacs session by typing the command @code{emacs} alone, without
2693naming any files, Emacs will start with the @file{*scratch*} buffer on
2694the screen. This buffer is not visiting any file. Similarly, a
2695@file{*Help*} buffer is not associated with any file.
2696
2697@cindex @code{nil}, history of word
2698If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2699position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2700expression, the name @code{"*scratch*"} is returned and will appear in
2701the echo area. @code{"*scratch*"} is the name of the buffer. However,
2702if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2703evaluate that, @code{nil} will appear in the echo area. @code{nil} is
2704from the Latin word for `nothing'; in this case, it means that the
2705@file{*scratch*} buffer is not associated with any file. (In Lisp,
2706@code{nil} is also used to mean `false' and is a synonym for the empty
2707list, @code{()}.)
2708
2709Incidentally, if you are in the @file{*scratch*} buffer and want the
2710value returned by an expression to appear in the @file{*scratch*}
2711buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2712instead of @kbd{C-x C-e}. This causes the value returned to appear
2713after the expression. The buffer will look like this:
2714
2715@smallexample
2716(buffer-name)"*scratch*"
2717@end smallexample
2718
2719@noindent
2720You cannot do this in Info since Info is read-only and it will not allow
2721you to change the contents of the buffer. But you can do this in any
2722buffer you can edit; and when you write code or documentation (such as
2723this book), this feature is very useful.
2724
2725@node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2726@comment node-name, next, previous, up
2727@section Getting Buffers
2728@findex current-buffer
2729@findex other-buffer
2730@cindex Getting a buffer
2731
2732The @code{buffer-name} function returns the @emph{name} of the buffer;
2733to get the buffer @emph{itself}, a different function is needed: the
2734@code{current-buffer} function. If you use this function in code, what
2735you get is the buffer itself.
2736
2737A name and the object or entity to which the name refers are different
2738from each other. You are not your name. You are a person to whom
2739others refer by name. If you ask to speak to George and someone hands you
2740a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2741@samp{g}, and @samp{e} written on it, you might be amused, but you would
2742not be satisfied. You do not want to speak to the name, but to the
2743person to whom the name refers. A buffer is similar: the name of the
2744scratch buffer is @file{*scratch*}, but the name is not the buffer. To
2745get a buffer itself, you need to use a function such as
2746@code{current-buffer}.
2747
2748However, there is a slight complication: if you evaluate
2749@code{current-buffer} in an expression on its own, as we will do here,
2750what you see is a printed representation of the name of the buffer
2751without the contents of the buffer. Emacs works this way for two
2752reasons: the buffer may be thousands of lines long---too long to be
2753conveniently displayed; and, another buffer may have the same contents
2754but a different name, and it is important to distinguish between them.
2755
2756@need 800
2757Here is an expression containing the function:
2758
2759@smallexample
2760(current-buffer)
2761@end smallexample
2762
2763@noindent
2764If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2765appears in the echo area. The special format indicates that the
2766buffer itself is being returned, rather than just its name.
2767
2768Incidentally, while you can type a number or symbol into a program, you
2769cannot do that with the printed representation of a buffer: the only way
2770to get a buffer itself is with a function such as @code{current-buffer}.
2771
2772A related function is @code{other-buffer}. This returns the most
2773recently selected buffer other than the one you are in currently. If
2774you have recently switched back and forth from the @file{*scratch*}
2775buffer, @code{other-buffer} will return that buffer.
2776
2777@need 800
2778You can see this by evaluating the expression:
2779
2780@smallexample
2781(other-buffer)
2782@end smallexample
2783
2784@noindent
2785You should see @file{#<buffer *scratch*>} appear in the echo area, or
2786the name of whatever other buffer you switched back from most
2787recently@footnote{Actually, by default, if the buffer from which you
2788just switched is visible to you in another window, @code{other-buffer}
2789will choose the most recent buffer that you cannot see; this is a
2790subtlety that I often forget.}.
2791
2792@node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2793@comment node-name, next, previous, up
2794@section Switching Buffers
2795@findex switch-to-buffer
2796@findex set-buffer
2797@cindex Switching to a buffer
2798
2799The @code{other-buffer} function actually provides a buffer when it is
2800used as an argument to a function that requires one. We can see this
2801by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2802different buffer.
2803
2804But first, a brief introduction to the @code{switch-to-buffer}
2805function. When you switched back and forth from Info to the
2806@file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2807likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2808rather, to save typing, you probably typed just part of the name, such
2809as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2810expand to the full name; and then typed your @kbd{RET} key.} when
2811prompted in the minibuffer for the name of the buffer to which you
2812wanted to switch. The keystrokes, @kbd{C-x b}, cause the Lisp
2813interpreter to evaluate the interactive function
2814@code{switch-to-buffer}. As we said before, this is how Emacs works:
2815different keystrokes call or run different functions. For example,
2816@kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2817@code{forward-sentence}, and so on.
2818
2819By writing @code{switch-to-buffer} in an expression, and giving it a
2820buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2821does.
2822
2823@need 1000
2824Here is the Lisp expression:
2825
2826@smallexample
2827(switch-to-buffer (other-buffer))
2828@end smallexample
2829
2830@noindent
2831The symbol @code{switch-to-buffer} is the first element of the list,
2832so the Lisp interpreter will treat it as a function and carry out the
2833instructions that are attached to it. But before doing that, the
2834interpreter will note that @code{other-buffer} is inside parentheses
2835and work on that symbol first. @code{other-buffer} is the first (and
2836in this case, the only) element of this list, so the Lisp interpreter
2837calls or runs the function. It returns another buffer. Next, the
2838interpreter runs @code{switch-to-buffer}, passing to it, as an
2839argument, the other buffer, which is what Emacs will switch to. If
2840you are reading this in Info, try this now. Evaluate the expression.
2841(To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2842expression will move you to your most recent other buffer that you
2843cannot see. If you really want to go to your most recently selected
2844buffer, even if you can still see it, you need to evaluate the
2845following more complex expression:
2846
2847@smallexample
2848(switch-to-buffer (other-buffer (current-buffer) t))
2849@end smallexample
2850
28be162e 2851@c noindent
8b096dce
EZ
2852In this case, the first argument to @code{other-buffer} tells it which
2853buffer to skip---the current one---and the second argument tells
2854@code{other-buffer} it is OK to switch to a visible buffer.
2855In regular use, @code{switch-to-buffer} takes you to an invisible
2856window since you would most likely use @kbd{C-x o} (@code{other-window})
2857to go to another visible buffer.}
2858
2859In the programming examples in later sections of this document, you will
2860see the function @code{set-buffer} more often than
2861@code{switch-to-buffer}. This is because of a difference between
2862computer programs and humans: humans have eyes and expect to see the
2863buffer on which they are working on their computer terminals. This is
2864so obvious, it almost goes without saying. However, programs do not
2865have eyes. When a computer program works on a buffer, that buffer does
2866not need to be visible on the screen.
2867
2868@code{switch-to-buffer} is designed for humans and does two different
2869things: it switches the buffer to which Emacs' attention is directed; and
2870it switches the buffer displayed in the window to the new buffer.
2871@code{set-buffer}, on the other hand, does only one thing: it switches
2872the attention of the computer program to a different buffer. The buffer
2873on the screen remains unchanged (of course, normally nothing happens
2874there until the command finishes running).
2875
2876@cindex @samp{call} defined
2877Also, we have just introduced another jargon term, the word @dfn{call}.
2878When you evaluate a list in which the first symbol is a function, you
2879are calling that function. The use of the term comes from the notion of
2880the function as an entity that can do something for you if you `call'
2881it---just as a plumber is an entity who can fix a leak if you call him
2882or her.
2883
2884@node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2885@comment node-name, next, previous, up
2886@section Buffer Size and the Location of Point
2887@cindex Size of buffer
2888@cindex Buffer size
2889@cindex Point location
2890@cindex Location of point
2891
2892Finally, let's look at several rather simple functions,
2893@code{buffer-size}, @code{point}, @code{point-min}, and
2894@code{point-max}. These give information about the size of a buffer and
2895the location of point within it.
2896
2897The function @code{buffer-size} tells you the size of the current
2898buffer; that is, the function returns a count of the number of
2899characters in the buffer.
2900
2901@smallexample
2902(buffer-size)
2903@end smallexample
2904
2905@noindent
2906You can evaluate this in the usual way, by positioning the
2907cursor after the expression and typing @kbd{C-x C-e}.
2908
2909@cindex @samp{point} defined
2910In Emacs, the current position of the cursor is called @dfn{point}.
2911The expression @code{(point)} returns a number that tells you where the
2912cursor is located as a count of the number of characters from the
2913beginning of the buffer up to point.
2914
2915@need 1250
2916You can see the character count for point in this buffer by evaluating
2917the following expression in the usual way:
2918
2919@smallexample
2920(point)
2921@end smallexample
2922
2923@noindent
2924As I write this, the value of @code{point} is 65724. The @code{point}
2925function is frequently used in some of the examples later in this
2926book.
2927
2928@need 1250
2929The value of point depends, of course, on its location within the
2930buffer. If you evaluate point in this spot, the number will be larger:
2931
2932@smallexample
2933(point)
2934@end smallexample
2935
2936@noindent
2937For me, the value of point in this location is 66043, which means that
2938there are 319 characters (including spaces) between the two expressions.
2939
2940@cindex @samp{narrowing} defined
2941The function @code{point-min} is somewhat similar to @code{point}, but
2942it returns the value of the minimum permissible value of point in the
2943current buffer. This is the number 1 unless @dfn{narrowing} is in
2944effect. (Narrowing is a mechanism whereby you can restrict yourself,
2945or a program, to operations on just a part of a buffer.
2946@xref{Narrowing & Widening, , Narrowing and Widening}.) Likewise, the
2947function @code{point-max} returns the value of the maximum permissible
2948value of point in the current buffer.
2949
2950@node Evaluation Exercise, , Buffer Size & Locations, Practicing Evaluation
2951@section Exercise
2952
2953Find a file with which you are working and move towards its middle.
2954Find its buffer name, file name, length, and your position in the file.
2955
2956@node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
2957@comment node-name, next, previous, up
2958@chapter How To Write Function Definitions
2959@cindex Definition writing
2960@cindex Function definition writing
2961@cindex Writing a function definition
2962
2963When the Lisp interpreter evaluates a list, it looks to see whether the
2964first symbol on the list has a function definition attached to it; or,
2965put another way, whether the symbol points to a function definition. If
2966it does, the computer carries out the instructions in the definition. A
2967symbol that has a function definition is called, simply, a function
2968(although, properly speaking, the definition is the function and the
2969symbol refers to it.)
2970
2971@menu
2972* Primitive Functions::
2973* defun:: The @code{defun} special form.
2974* Install:: Install a function definition.
2975* Interactive:: Making a function interactive.
2976* Interactive Options:: Different options for @code{interactive}.
2977* Permanent Installation:: Installing code permanently.
2978* let:: Creating and initializing local variables.
2979* if:: What if?
2980* else:: If--then--else expressions.
2981* Truth & Falsehood:: What Lisp considers false and true.
2982* save-excursion:: Keeping track of point, mark, and buffer.
2983* Review::
2984* defun Exercises::
2985@end menu
2986
2987@node Primitive Functions, defun, Writing Defuns, Writing Defuns
2988@ifnottex
2989@unnumberedsec An Aside about Primitive Functions
2990@end ifnottex
2991@cindex Primitive functions
2992@cindex Functions, primitive
2993
2994@cindex C language primitives
2995@cindex Primitives written in C
2996All functions are defined in terms of other functions, except for a few
2997@dfn{primitive} functions that are written in the C programming
2998language. When you write functions' definitions, you will write them in
2999Emacs Lisp and use other functions as your building blocks. Some of the
3000functions you will use will themselves be written in Emacs Lisp (perhaps
3001by you) and some will be primitives written in C. The primitive
3002functions are used exactly like those written in Emacs Lisp and behave
3003like them. They are written in C so we can easily run GNU Emacs on any
3004computer that has sufficient power and can run C.
3005
3006Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3007distinguish between the use of functions written in C and the use of
3008functions written in Emacs Lisp. The difference is irrelevant. I
3009mention the distinction only because it is interesting to know. Indeed,
3010unless you investigate, you won't know whether an already-written
3011function is written in Emacs Lisp or C.
3012
3013@node defun, Install, Primitive Functions, Writing Defuns
3014@comment node-name, next, previous, up
3015@section The @code{defun} Special Form
3016@findex defun
3017@cindex Special form of @code{defun}
3018
3019@cindex @samp{function definition} defined
3020In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3021it that tells the computer what to do when the function is called.
3022This code is called the @dfn{function definition} and is created by
3023evaluating a Lisp expression that starts with the symbol @code{defun}
3024(which is an abbreviation for @emph{define function}). Because
3025@code{defun} does not evaluate its arguments in the usual way, it is
3026called a @dfn{special form}.
3027
3028In subsequent sections, we will look at function definitions from the
3029Emacs source code, such as @code{mark-whole-buffer}. In this section,
3030we will describe a simple function definition so you can see how it
3031looks. This function definition uses arithmetic because it makes for a
3032simple example. Some people dislike examples using arithmetic; however,
3033if you are such a person, do not despair. Hardly any of the code we
3034will study in the remainder of this introduction involves arithmetic or
3035mathematics. The examples mostly involve text in one way or another.
3036
3037A function definition has up to five parts following the word
3038@code{defun}:
3039
3040@enumerate
3041@item
3042The name of the symbol to which the function definition should be
3043attached.
3044
3045@item
3046A list of the arguments that will be passed to the function. If no
3047arguments will be passed to the function, this is an empty list,
3048@code{()}.
3049
3050@item
3051Documentation describing the function. (Technically optional, but
3052strongly recommended.)
3053
3054@item
3055Optionally, an expression to make the function interactive so you can
3056use it by typing @kbd{M-x} and then the name of the function; or by
3057typing an appropriate key or keychord.
3058
3059@cindex @samp{body} defined
3060@item
3061The code that instructs the computer what to do: the @dfn{body} of the
3062function definition.
3063@end enumerate
3064
3065It is helpful to think of the five parts of a function definition as
3066being organized in a template, with slots for each part:
3067
3068@smallexample
3069@group
3070(defun @var{function-name} (@var{arguments}@dots{})
3071 "@var{optional-documentation}@dots{}"
3072 (interactive @var{argument-passing-info}) ; @r{optional}
3073 @var{body}@dots{})
3074@end group
3075@end smallexample
3076
3077As an example, here is the code for a function that multiplies its
3078argument by 7. (This example is not interactive. @xref{Interactive,
3079, Making a Function Interactive}, for that information.)
3080
3081@smallexample
3082@group
3083(defun multiply-by-seven (number)
3084 "Multiply NUMBER by seven."
3085 (* 7 number))
3086@end group
3087@end smallexample
3088
3089This definition begins with a parenthesis and the symbol @code{defun},
3090followed by the name of the function.
3091
3092@cindex @samp{argument list} defined
3093The name of the function is followed by a list that contains the
3094arguments that will be passed to the function. This list is called
3095the @dfn{argument list}. In this example, the list has only one
3096element, the symbol, @code{number}. When the function is used, the
3097symbol will be bound to the value that is used as the argument to the
3098function.
3099
3100Instead of choosing the word @code{number} for the name of the argument,
3101I could have picked any other name. For example, I could have chosen
3102the word @code{multiplicand}. I picked the word `number' because it
3103tells what kind of value is intended for this slot; but I could just as
3104well have chosen the word `multiplicand' to indicate the role that the
3105value placed in this slot will play in the workings of the function. I
3106could have called it @code{foogle}, but that would have been a bad
3107choice because it would not tell humans what it means. The choice of
3108name is up to the programmer and should be chosen to make the meaning of
3109the function clear.
3110
3111Indeed, you can choose any name you wish for a symbol in an argument
3112list, even the name of a symbol used in some other function: the name
3113you use in an argument list is private to that particular definition.
3114In that definition, the name refers to a different entity than any use
3115of the same name outside the function definition. Suppose you have a
3116nick-name `Shorty' in your family; when your family members refer to
3117`Shorty', they mean you. But outside your family, in a movie, for
3118example, the name `Shorty' refers to someone else. Because a name in an
3119argument list is private to the function definition, you can change the
3120value of such a symbol inside the body of a function without changing
3121its value outside the function. The effect is similar to that produced
3122by a @code{let} expression. (@xref{let, , @code{let}}.)
3123
3124@ignore
3125Note also that we discuss the word `number' in two different ways: as a
3126symbol that appears in the code, and as the name of something that will
3127be replaced by a something else during the evaluation of the function.
3128In the first case, @code{number} is a symbol, not a number; it happens
3129that within the function, it is a variable who value is the number in
3130question, but our primary interest in it is as a symbol. On the other
3131hand, when we are talking about the function, our interest is that we
3132will substitute a number for the word @var{number}. To keep this
3133distinction clear, we use different typography for the two
3134circumstances. When we talk about this function, or about how it works,
3135we refer to this number by writing @var{number}. In the function
3136itself, we refer to it by writing @code{number}.
3137@end ignore
3138
3139The argument list is followed by the documentation string that
3140describes the function. This is what you see when you type
3141@w{@kbd{C-h f}} and the name of a function. Incidentally, when you
3142write a documentation string like this, you should make the first line
3143a complete sentence since some commands, such as @code{apropos}, print
3144only the first line of a multi-line documentation string. Also, you
3145should not indent the second line of a documentation string, if you
3146have one, because that looks odd when you use @kbd{C-h f}
3147(@code{describe-function}). The documentation string is optional, but
3148it is so useful, it should be included in almost every function you
3149write.
3150
3151@findex * @r{(multiplication)}
3152The third line of the example consists of the body of the function
3153definition. (Most functions' definitions, of course, are longer than
3154this.) In this function, the body is the list, @code{(* 7 number)}, which
3155says to multiply the value of @var{number} by 7. (In Emacs Lisp,
3156@code{*} is the function for multiplication, just as @code{+} is the
3157function for addition.)
3158
3159When you use the @code{multiply-by-seven} function, the argument
3160@code{number} evaluates to the actual number you want used. Here is an
3161example that shows how @code{multiply-by-seven} is used; but don't try
3162to evaluate this yet!
3163
3164@smallexample
3165(multiply-by-seven 3)
3166@end smallexample
3167
3168@noindent
3169The symbol @code{number}, specified in the function definition in the
3170next section, is given or ``bound to'' the value 3 in the actual use of
3171the function. Note that although @code{number} was inside parentheses
3172in the function definition, the argument passed to the
3173@code{multiply-by-seven} function is not in parentheses. The
3174parentheses are written in the function definition so the computer can
3175figure out where the argument list ends and the rest of the function
3176definition begins.
3177
3178If you evaluate this example, you are likely to get an error message.
3179(Go ahead, try it!) This is because we have written the function
3180definition, but not yet told the computer about the definition---we have
3181not yet installed (or `loaded') the function definition in Emacs.
3182Installing a function is the process that tells the Lisp interpreter the
3183definition of the function. Installation is described in the next
3184section.
3185
3186@node Install, Interactive, defun, Writing Defuns
3187@comment node-name, next, previous, up
3188@section Install a Function Definition
3189@cindex Install a Function Definition
3190@cindex Definition installation
3191@cindex Function definition installation
3192
3193If you are reading this inside of Info in Emacs, you can try out the
3194@code{multiply-by-seven} function by first evaluating the function
3195definition and then evaluating @code{(multiply-by-seven 3)}. A copy of
3196the function definition follows. Place the cursor after the last
3197parenthesis of the function definition and type @kbd{C-x C-e}. When you
3198do this, @code{multiply-by-seven} will appear in the echo area. (What
3199this means is that when a function definition is evaluated, the value it
3200returns is the name of the defined function.) At the same time, this
3201action installs the function definition.
3202
3203@smallexample
3204@group
3205(defun multiply-by-seven (number)
3206 "Multiply NUMBER by seven."
3207 (* 7 number))
3208@end group
3209@end smallexample
3210
3211@noindent
3212By evaluating this @code{defun}, you have just installed
3213@code{multiply-by-seven} in Emacs. The function is now just as much a
3214part of Emacs as @code{forward-word} or any other editing function you
3215use. (@code{multiply-by-seven} will stay installed until you quit
3216Emacs. To reload code automatically whenever you start Emacs, see
3217@ref{Permanent Installation, , Installing Code Permanently}.)
3218
3219
3220@menu
3221* Effect of installation::
3222* Change a defun:: How to change a function definition.
3223@end menu
3224
3225@node Effect of installation, Change a defun, Install, Install
3226@ifnottex
3227@unnumberedsubsec The effect of installation
3228@end ifnottex
3229
3230
3231You can see the effect of installing @code{multiply-by-seven} by
3232evaluating the following sample. Place the cursor after the following
3233expression and type @kbd{C-x C-e}. The number 21 will appear in the
3234echo area.
3235
3236@smallexample
3237(multiply-by-seven 3)
3238@end smallexample
3239
3240If you wish, you can read the documentation for the function by typing
3241@kbd{C-h f} (@code{describe-function}) and then the name of the
3242function, @code{multiply-by-seven}. When you do this, a
3243@file{*Help*} window will appear on your screen that says:
3244
3245@smallexample
3246@group
3247multiply-by-seven:
3248Multiply NUMBER by seven.
3249@end group
3250@end smallexample
3251
3252@noindent
3253(To return to a single window on your screen, type @kbd{C-x 1}.)
3254
3255@node Change a defun, , Effect of installation, Install
3256@comment node-name, next, previous, up
3257@subsection Change a Function Definition
3258@cindex Changing a function definition
3259@cindex Function definition, how to change
3260@cindex Definition, how to change
3261
3262If you want to change the code in @code{multiply-by-seven}, just rewrite
3263it. To install the new version in place of the old one, evaluate the
3264function definition again. This is how you modify code in Emacs. It is
3265very simple.
3266
3267As an example, you can change the @code{multiply-by-seven} function to
3268add the number to itself seven times instead of multiplying the number
3269by seven. It produces the same answer, but by a different path. At
3270the same time, we will add a comment to the code; a comment is text
3271that the Lisp interpreter ignores, but that a human reader may find
3272useful or enlightening. The comment is that this is the ``second
3273version''.
3274
3275@smallexample
3276@group
3277(defun multiply-by-seven (number) ; @r{Second version.}
3278 "Multiply NUMBER by seven."
3279 (+ number number number number number number number))
3280@end group
3281@end smallexample
3282
3283@cindex Comments in Lisp code
3284The comment follows a semicolon, @samp{;}. In Lisp, everything on a
3285line that follows a semicolon is a comment. The end of the line is the
3286end of the comment. To stretch a comment over two or more lines, begin
3287each line with a semicolon.
3288
3289@xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3290File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3291Reference Manual}, for more about comments.
3292
3293You can install this version of the @code{multiply-by-seven} function by
3294evaluating it in the same way you evaluated the first function: place
3295the cursor after the last parenthesis and type @kbd{C-x C-e}.
3296
3297In summary, this is how you write code in Emacs Lisp: you write a
3298function; install it; test it; and then make fixes or enhancements and
3299install it again.
3300
3301@node Interactive, Interactive Options, Install, Writing Defuns
3302@comment node-name, next, previous, up
3303@section Make a Function Interactive
3304@cindex Interactive functions
3305@findex interactive
3306
3307You make a function interactive by placing a list that begins with
3308the special form @code{interactive} immediately after the
3309documentation. A user can invoke an interactive function by typing
3310@kbd{M-x} and then the name of the function; or by typing the keys to
3311which it is bound, for example, by typing @kbd{C-n} for
3312@code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3313
3314Interestingly, when you call an interactive function interactively,
3315the value returned is not automatically displayed in the echo area.
3316This is because you often call an interactive function for its side
3317effects, such as moving forward by a word or line, and not for the
3318value returned. If the returned value were displayed in the echo area
3319each time you typed a key, it would be very distracting.
3320
3321@menu
3322* Interactive multiply-by-seven:: An overview.
3323* multiply-by-seven in detail:: The interactive version.
3324@end menu
3325
3326@node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3327@ifnottex
3328@unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3329@end ifnottex
3330
3331Both the use of the special form @code{interactive} and one way to
3332display a value in the echo area can be illustrated by creating an
3333interactive version of @code{multiply-by-seven}.
3334
3335@need 1250
3336Here is the code:
3337
3338@smallexample
3339@group
3340(defun multiply-by-seven (number) ; @r{Interactive version.}
3341 "Multiply NUMBER by seven."
3342 (interactive "p")
3343 (message "The result is %d" (* 7 number)))
3344@end group
3345@end smallexample
3346
3347@noindent
3348You can install this code by placing your cursor after it and typing
3349@kbd{C-x C-e}. The name of the function will appear in your echo area.
3350Then, you can use this code by typing @kbd{C-u} and a number and then
3351typing @kbd{M-x multiply-by-seven} and pressing @key{RET}. The phrase
3352@samp{The result is @dots{}} followed by the product will appear in the
3353echo area.
3354
3355Speaking more generally, you invoke a function like this in either of two
3356ways:
3357
3358@enumerate
3359@item
3360By typing a prefix argument that contains the number to be passed, and
3361then typing @kbd{M-x} and the name of the function, as with
3362@kbd{C-u 3 M-x forward-sentence}; or,
3363
3364@item
3365By typing whatever key or keychord the function is bound to, as with
3366@kbd{C-u 3 M-e}.
3367@end enumerate
3368
3369@noindent
3370Both the examples just mentioned work identically to move point forward
3371three sentences. (Since @code{multiply-by-seven} is not bound to a key,
3372it could not be used as an example of key binding.)
3373
3374(@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3375to a key.)
3376
3377A prefix argument is passed to an interactive function by typing the
3378@key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3379typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3380type @kbd{C-u} without a number, it defaults to 4).
3381
3382@node multiply-by-seven in detail, , Interactive multiply-by-seven, Interactive
3383@comment node-name, next, previous, up
3384@subsection An Interactive @code{multiply-by-seven}
3385
3386Let's look at the use of the special form @code{interactive} and then at
3387the function @code{message} in the interactive version of
3388@code{multiply-by-seven}. You will recall that the function definition
3389looks like this:
3390
3391@smallexample
3392@group
3393(defun multiply-by-seven (number) ; @r{Interactive version.}
3394 "Multiply NUMBER by seven."
3395 (interactive "p")
3396 (message "The result is %d" (* 7 number)))
3397@end group
3398@end smallexample
3399
3400In this function, the expression, @code{(interactive "p")}, is a list of
3401two elements. The @code{"p"} tells Emacs to pass the prefix argument to
3402the function and use its value for the argument of the function.
3403
3404@need 1000
3405The argument will be a number. This means that the symbol
3406@code{number} will be bound to a number in the line:
3407
3408@smallexample
3409(message "The result is %d" (* 7 number))
3410@end smallexample
3411
3412@need 1250
3413@noindent
3414For example, if your prefix argument is 5, the Lisp interpreter will
3415evaluate the line as if it were:
3416
3417@smallexample
3418(message "The result is %d" (* 7 5))
3419@end smallexample
3420
3421@noindent
3422(If you are reading this in GNU Emacs, you can evaluate this expression
3423yourself.) First, the interpreter will evaluate the inner list, which
3424is @code{(* 7 5)}. This returns a value of 35. Next, it
3425will evaluate the outer list, passing the values of the second and
3426subsequent elements of the list to the function @code{message}.
3427
3428As we have seen, @code{message} is an Emacs Lisp function especially
3429designed for sending a one line message to a user. (@xref{message, , The
3430@code{message} function}.)
3431In summary, the @code{message} function prints its first argument in the
3432echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3433@samp{%c}. When it sees one of these control sequences, the function
3434looks to the second and subsequent arguments and prints the value of the
3435argument in the location in the string where the control sequence is
3436located.
3437
3438In the interactive @code{multiply-by-seven} function, the control string
3439is @samp{%d}, which requires a number, and the value returned by
3440evaluating @code{(* 7 5)} is the number 35. Consequently, the number 35
3441is printed in place of the @samp{%d} and the message is @samp{The result
3442is 35}.
3443
3444(Note that when you call the function @code{multiply-by-seven}, the
3445message is printed without quotes, but when you call @code{message}, the
3446text is printed in double quotes. This is because the value returned by
3447@code{message} is what appears in the echo area when you evaluate an
3448expression whose first element is @code{message}; but when embedded in a
3449function, @code{message} prints the text as a side effect without
3450quotes.)
3451
3452@node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3453@comment node-name, next, previous, up
3454@section Different Options for @code{interactive}
3455@cindex Options for @code{interactive}
3456@cindex Interactive options
3457
3458In the example, @code{multiply-by-seven} used @code{"p"} as the
3459argument to @code{interactive}. This argument told Emacs to interpret
3460your typing either @kbd{C-u} followed by a number or @key{META}
3461followed by a number as a command to pass that number to the function
3462as its argument. Emacs has more than twenty characters predefined for
3463use with @code{interactive}. In almost every case, one of these
3464options will enable you to pass the right information interactively to
3465a function. (@xref{Interactive Codes, , Code Characters for
3466@code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3467
3468@need 1250
3469For example, the character @samp{r} causes Emacs to pass the beginning
3470and end of the region (the current values of point and mark) to the
3471function as two separate arguments. It is used as follows:
3472
3473@smallexample
3474(interactive "r")
3475@end smallexample
3476
3477On the other hand, a @samp{B} tells Emacs to ask for the name of a
3478buffer that will be passed to the function. When it sees a @samp{B},
3479Emacs will ask for the name by prompting the user in the minibuffer,
3480using a string that follows the @samp{B}, as in @code{"BAppend to
3481buffer:@: "}. Not only will Emacs prompt for the name, but Emacs will
3482complete the name if you type enough of it and press @key{TAB}.
3483
3484A function with two or more arguments can have information passed to
3485each argument by adding parts to the string that follows
3486@code{interactive}. When you do this, the information is passed to
3487each argument in the same order it is specified in the
3488@code{interactive} list. In the string, each part is separated from
3489the next part by a @samp{\n}, which is a newline. For example, you
c6f54b06 3490could follow @code{"BAppend to buffer:@: "} with a @samp{\n} and an
8b096dce
EZ
3491@samp{r}. This would cause Emacs to pass the values of point and mark
3492to the function as well as prompt you for the buffer---three arguments
3493in all.
3494
3495In this case, the function definition would look like the following,
3496where @code{buffer}, @code{start}, and @code{end} are the symbols to
3497which @code{interactive} binds the buffer and the current values of the
3498beginning and ending of the region:
3499
3500@smallexample
3501@group
3502(defun @var{name-of-function} (buffer start end)
3503 "@var{documentation}@dots{}"
3504 (interactive "BAppend to buffer:@: \nr")
3505 @var{body-of-function}@dots{})
3506@end group
3507@end smallexample
3508
3509@noindent
3510(The space after the colon in the prompt makes it look better when you
3511are prompted. The @code{append-to-buffer} function looks exactly like
3512this. @xref{append-to-buffer, , The Definition of
3513@code{append-to-buffer}}.)
3514
3515If a function does not have arguments, then @code{interactive} does not
3516require any. Such a function contains the simple expression
3517@code{(interactive)}. The @code{mark-whole-buffer} function is like
3518this.
3519
3520Alternatively, if the special letter-codes are not right for your
3521application, you can pass your own arguments to @code{interactive} as
3522a list. @xref{interactive, , Using @code{Interactive}, elisp, The
3523GNU Emacs Lisp Reference Manual}, for more information about this advanced
3524technique.
3525
3526@node Permanent Installation, let, Interactive Options, Writing Defuns
3527@comment node-name, next, previous, up
3528@section Install Code Permanently
3529@cindex Install code permanently
3530@cindex Permanent code installation
3531@cindex Code installation
3532
3533When you install a function definition by evaluating it, it will stay
3534installed until you quit Emacs. The next time you start a new session
3535of Emacs, the function will not be installed unless you evaluate the
3536function definition again.
3537
3538At some point, you may want to have code installed automatically
3539whenever you start a new session of Emacs. There are several ways of
3540doing this:
3541
3542@itemize @bullet
3543@item
3544If you have code that is just for yourself, you can put the code for the
3545function definition in your @file{.emacs} initialization file. When you
3546start Emacs, your @file{.emacs} file is automatically evaluated and all
3547the function definitions within it are installed.
3548@xref{Emacs Initialization, , Your @file{.emacs} File}.
3549
3550@item
3551Alternatively, you can put the function definitions that you want
3552installed in one or more files of their own and use the @code{load}
3553function to cause Emacs to evaluate and thereby install each of the
3554functions in the files.
3555@xref{Loading Files, , Loading Files}.
3556
3557@item
3558On the other hand, if you have code that your whole site will use, it
3559is usual to put it in a file called @file{site-init.el} that is loaded
3560when Emacs is built. This makes the code available to everyone who
3561uses your machine. (See the @file{INSTALL} file that is part of the
3562Emacs distribution.)
3563@end itemize
3564
3565Finally, if you have code that everyone who uses Emacs may want, you
3566can post it on a computer network or send a copy to the Free Software
3567Foundation. (When you do this, please license the code and its
3568documentation under a license that permits other people to run, copy,
3569study, modify, and redistribute the code and which protects you from
3570having your work taken from you.) If you send a copy of your code to
3571the Free Software Foundation, and properly protect yourself and
3572others, it may be included in the next release of Emacs. In large
3573part, this is how Emacs has grown over the past years, by donations.
3574
3575@node let, if, Permanent Installation, Writing Defuns
3576@comment node-name, next, previous, up
3577@section @code{let}
3578@findex let
3579
3580The @code{let} expression is a special form in Lisp that you will need
3581to use in most function definitions.
3582
3583@code{let} is used to attach or bind a symbol to a value in such a way
3584that the Lisp interpreter will not confuse the variable with a
3585variable of the same name that is not part of the function.
3586
3587To understand why the @code{let} special form is necessary, consider
3588the situation in which you own a home that you generally refer to as
3589`the house', as in the sentence, ``The house needs painting.'' If you
3590are visiting a friend and your host refers to `the house', he is
3591likely to be referring to @emph{his} house, not yours, that is, to a
3592different house.
3593
3594If your friend is referring to his house and you think he is referring
3595to your house, you may be in for some confusion. The same thing could
3596happen in Lisp if a variable that is used inside of one function has
3597the same name as a variable that is used inside of another function,
3598and the two are not intended to refer to the same value. The
3599@code{let} special form prevents this kind of confusion.
3600
3601@menu
3602* Prevent confusion::
3603* Parts of let Expression::
3604* Sample let Expression::
3605* Uninitialized let Variables::
3606@end menu
3607
3608@node Prevent confusion, Parts of let Expression, let, let
3609@ifnottex
3610@unnumberedsubsec @code{let} Prevents Confusion
3611@end ifnottex
3612
3613@cindex @samp{local variable} defined
3614The @code{let} special form prevents confusion. @code{let} creates a
3615name for a @dfn{local variable} that overshadows any use of the same
3616name outside the @code{let} expression. This is like understanding
3617that whenever your host refers to `the house', he means his house, not
3618yours. (Symbols used in argument lists work the same way.
3619@xref{defun, , The @code{defun} Special Form}.)
3620
3621Local variables created by a @code{let} expression retain their value
3622@emph{only} within the @code{let} expression itself (and within
3623expressions called within the @code{let} expression); the local
3624variables have no effect outside the @code{let} expression.
3625
3626Another way to think about @code{let} is that it is like a @code{setq}
3627that is temporary and local. The values set by @code{let} are
3628automatically undone when the @code{let} is finished. The setting
e601d8fd 3629only affects expressions that are inside the bounds of the @code{let}
8b096dce
EZ
3630expression. In computer science jargon, we would say ``the binding of
3631a symbol is visible only in functions called in the @code{let} form;
3632in Emacs Lisp, scoping is dynamic, not lexical.''
3633
3634@code{let} can create more than one variable at once. Also,
3635@code{let} gives each variable it creates an initial value, either a
3636value specified by you, or @code{nil}. (In the jargon, this is called
3637`binding the variable to the value'.) After @code{let} has created
3638and bound the variables, it executes the code in the body of the
3639@code{let}, and returns the value of the last expression in the body,
3640as the value of the whole @code{let} expression. (`Execute' is a jargon
3641term that means to evaluate a list; it comes from the use of the word
3642meaning `to give practical effect to' (@cite{Oxford English
3643Dictionary}). Since you evaluate an expression to perform an action,
3644`execute' has evolved as a synonym to `evaluate'.)
3645
3646@node Parts of let Expression, Sample let Expression, Prevent confusion, let
3647@comment node-name, next, previous, up
3648@subsection The Parts of a @code{let} Expression
3649@cindex @code{let} expression, parts of
3650@cindex Parts of @code{let} expression
3651
3652@cindex @samp{varlist} defined
3653A @code{let} expression is a list of three parts. The first part is
3654the symbol @code{let}. The second part is a list, called a
3655@dfn{varlist}, each element of which is either a symbol by itself or a
3656two-element list, the first element of which is a symbol. The third
3657part of the @code{let} expression is the body of the @code{let}. The
3658body usually consists of one or more lists.
3659
3660@need 800
3661A template for a @code{let} expression looks like this:
3662
3663@smallexample
3664(let @var{varlist} @var{body}@dots{})
3665@end smallexample
3666
3667@noindent
3668The symbols in the varlist are the variables that are given initial
3669values by the @code{let} special form. Symbols by themselves are given
3670the initial value of @code{nil}; and each symbol that is the first
3671element of a two-element list is bound to the value that is returned
3672when the Lisp interpreter evaluates the second element.
3673
3674Thus, a varlist might look like this: @code{(thread (needles 3))}. In
3675this case, in a @code{let} expression, Emacs binds the symbol
3676@code{thread} to an initial value of @code{nil}, and binds the symbol
3677@code{needles} to an initial value of 3.
3678
3679When you write a @code{let} expression, what you do is put the
3680appropriate expressions in the slots of the @code{let} expression
3681template.
3682
3683If the varlist is composed of two-element lists, as is often the case,
3684the template for the @code{let} expression looks like this:
3685
3686@smallexample
3687@group
3688(let ((@var{variable} @var{value})
3689 (@var{variable} @var{value})
3690 @dots{})
3691 @var{body}@dots{})
3692@end group
3693@end smallexample
3694
3695@node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3696@comment node-name, next, previous, up
3697@subsection Sample @code{let} Expression
3698@cindex Sample @code{let} expression
3699@cindex @code{let} expression sample
3700
3701The following expression creates and gives initial values
3702to the two variables @code{zebra} and @code{tiger}. The body of the
3703@code{let} expression is a list which calls the @code{message} function.
3704
3705@smallexample
3706@group
3707(let ((zebra 'stripes)
3708 (tiger 'fierce))
3709 (message "One kind of animal has %s and another is %s."
3710 zebra tiger))
3711@end group
3712@end smallexample
3713
3714Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3715
3716The two variables are @code{zebra} and @code{tiger}. Each variable is
3717the first element of a two-element list and each value is the second
3718element of its two-element list. In the varlist, Emacs binds the
3719variable @code{zebra} to the value @code{stripes}, and binds the
3720variable @code{tiger} to the value @code{fierce}. In this example,
3721both values are symbols preceded by a quote. The values could just as
3722well have been another list or a string. The body of the @code{let}
3723follows after the list holding the variables. In this example, the body
3724is a list that uses the @code{message} function to print a string in
3725the echo area.
3726
3727@need 1500
3728You may evaluate the example in the usual fashion, by placing the
3729cursor after the last parenthesis and typing @kbd{C-x C-e}. When you do
3730this, the following will appear in the echo area:
3731
3732@smallexample
3733"One kind of animal has stripes and another is fierce."
3734@end smallexample
3735
3736As we have seen before, the @code{message} function prints its first
3737argument, except for @samp{%s}. In this example, the value of the variable
3738@code{zebra} is printed at the location of the first @samp{%s} and the
3739value of the variable @code{tiger} is printed at the location of the
3740second @samp{%s}.
3741
3742@node Uninitialized let Variables, , Sample let Expression, let
3743@comment node-name, next, previous, up
3744@subsection Uninitialized Variables in a @code{let} Statement
3745@cindex Uninitialized @code{let} variables
3746@cindex @code{let} variables uninitialized
3747
3748If you do not bind the variables in a @code{let} statement to specific
3749initial values, they will automatically be bound to an initial value of
3750@code{nil}, as in the following expression:
3751
3752@smallexample
3753@group
3754(let ((birch 3)
3755 pine
3756 fir
3757 (oak 'some))
3758 (message
3759 "Here are %d variables with %s, %s, and %s value."
3760 birch pine fir oak))
3761@end group
3762@end smallexample
3763
3764@noindent
3765Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3766
3767@need 1250
3768If you evaluate this expression in the usual way, the following will
3769appear in your echo area:
3770
3771@smallexample
3772"Here are 3 variables with nil, nil, and some value."
3773@end smallexample
3774
3775@noindent
3776In this example, Emacs binds the symbol @code{birch} to the number 3,
3777binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3778the symbol @code{oak} to the value @code{some}.
3779
3780Note that in the first part of the @code{let}, the variables @code{pine}
3781and @code{fir} stand alone as atoms that are not surrounded by
3782parentheses; this is because they are being bound to @code{nil}, the
3783empty list. But @code{oak} is bound to @code{some} and so is a part of
3784the list @code{(oak 'some)}. Similarly, @code{birch} is bound to the
3785number 3 and so is in a list with that number. (Since a number
3786evaluates to itself, the number does not need to be quoted. Also, the
3787number is printed in the message using a @samp{%d} rather than a
3788@samp{%s}.) The four variables as a group are put into a list to
3789delimit them from the body of the @code{let}.
3790
3791@node if, else, let, Writing Defuns
3792@comment node-name, next, previous, up
3793@section The @code{if} Special Form
3794@findex if
3795@cindex Conditional with @code{if}
3796
3797A third special form, in addition to @code{defun} and @code{let}, is the
3798conditional @code{if}. This form is used to instruct the computer to
3799make decisions. You can write function definitions without using
3800@code{if}, but it is used often enough, and is important enough, to be
3801included here. It is used, for example, in the code for the
3802function @code{beginning-of-buffer}.
3803
3804The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3805@emph{then} an expression is evaluated.'' If the test is not true, the
3806expression is not evaluated. For example, you might make a decision
3807such as, ``if it is warm and sunny, then go to the beach!''
3808
3809@menu
3810* if in more detail::
3811* type-of-animal in detail:: An example of an @code{if} expression.
3812@end menu
3813
3814@node if in more detail, type-of-animal in detail, if, if
3815@ifnottex
3816@unnumberedsubsec @code{if} in more detail
3817@end ifnottex
3818
3819@cindex @samp{if-part} defined
3820@cindex @samp{then-part} defined
3821An @code{if} expression written in Lisp does not use the word `then';
3822the test and the action are the second and third elements of the list
3823whose first element is @code{if}. Nonetheless, the test part of an
3824@code{if} expression is often called the @dfn{if-part} and the second
3825argument is often called the @dfn{then-part}.
3826
3827Also, when an @code{if} expression is written, the true-or-false-test
3828is usually written on the same line as the symbol @code{if}, but the
3829action to carry out if the test is true, the ``then-part'', is written
3830on the second and subsequent lines. This makes the @code{if}
3831expression easier to read.
3832
3833@smallexample
3834@group
3835(if @var{true-or-false-test}
3836 @var{action-to-carry-out-if-test-is-true})
3837@end group
3838@end smallexample
3839
3840@noindent
3841The true-or-false-test will be an expression that
3842is evaluated by the Lisp interpreter.
3843
3844Here is an example that you can evaluate in the usual manner. The test
3845is whether the number 5 is greater than the number 4. Since it is, the
3846message @samp{5 is greater than 4!} will be printed.
3847
3848@smallexample
3849@group
3850(if (> 5 4) ; @r{if-part}
3851 (message "5 is greater than 4!")) ; @r{then-part}
3852@end group
3853@end smallexample
3854
3855@noindent
3856(The function @code{>} tests whether its first argument is greater than
3857its second argument and returns true if it is.)
3858@findex > (greater than)
3859
3860Of course, in actual use, the test in an @code{if} expression will not
3861be fixed for all time as it is by the expression @code{(> 5 4)}.
3862Instead, at least one of the variables used in the test will be bound to
3863a value that is not known ahead of time. (If the value were known ahead
3864of time, we would not need to run the test!)
3865
3866For example, the value may be bound to an argument of a function
3867definition. In the following function definition, the character of the
3868animal is a value that is passed to the function. If the value bound to
3869@code{characteristic} is @code{fierce}, then the message, @samp{It's a
3870tiger!} will be printed; otherwise, @code{nil} will be returned.
3871
3872@smallexample
3873@group
3874(defun type-of-animal (characteristic)
3875 "Print message in echo area depending on CHARACTERISTIC.
3876If the CHARACTERISTIC is the symbol `fierce',
3877then warn of a tiger."
3878 (if (equal characteristic 'fierce)
3879 (message "It's a tiger!")))
3880@end group
3881@end smallexample
3882
3883@need 1500
3884@noindent
3885If you are reading this inside of GNU Emacs, you can evaluate the
3886function definition in the usual way to install it in Emacs, and then you
3887can evaluate the following two expressions to see the results:
3888
3889@smallexample
3890@group
3891(type-of-animal 'fierce)
3892
3893(type-of-animal 'zebra)
3894
3895@end group
3896@end smallexample
3897
3898@c Following sentences rewritten to prevent overfull hbox.
3899@noindent
3900When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3901following message printed in the echo area: @code{"It's a tiger!"}; and
3902when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3903printed in the echo area.
3904
3905@node type-of-animal in detail, , if in more detail, if
3906@comment node-name, next, previous, up
3907@subsection The @code{type-of-animal} Function in Detail
3908
3909Let's look at the @code{type-of-animal} function in detail.
3910
3911The function definition for @code{type-of-animal} was written by filling
3912the slots of two templates, one for a function definition as a whole, and
3913a second for an @code{if} expression.
3914
3915@need 1250
3916The template for every function that is not interactive is:
3917
3918@smallexample
3919@group
3920(defun @var{name-of-function} (@var{argument-list})
3921 "@var{documentation}@dots{}"
3922 @var{body}@dots{})
3923@end group
3924@end smallexample
3925
3926@need 800
3927The parts of the function that match this template look like this:
3928
3929@smallexample
3930@group
3931(defun type-of-animal (characteristic)
3932 "Print message in echo area depending on CHARACTERISTIC.
3933If the CHARACTERISTIC is the symbol `fierce',
3934then warn of a tiger."
3935 @var{body: the} @code{if} @var{expression})
3936@end group
3937@end smallexample
3938
3939The name of function is @code{type-of-animal}; it is passed the value
3940of one argument. The argument list is followed by a multi-line
3941documentation string. The documentation string is included in the
3942example because it is a good habit to write documentation string for
3943every function definition. The body of the function definition
3944consists of the @code{if} expression.
3945
3946@need 800
3947The template for an @code{if} expression looks like this:
3948
3949@smallexample
3950@group
3951(if @var{true-or-false-test}
3952 @var{action-to-carry-out-if-the-test-returns-true})
3953@end group
3954@end smallexample
3955
3956@need 1250
3957In the @code{type-of-animal} function, the code for the @code{if}
3958looks like this:
3959
3960@smallexample
3961@group
3962(if (equal characteristic 'fierce)
3963 (message "It's a tiger!")))
3964@end group
3965@end smallexample
3966
3967@need 800
3968Here, the true-or-false-test is the expression:
3969
3970@smallexample
3971(equal characteristic 'fierce)
3972@end smallexample
3973
3974@noindent
3975In Lisp, @code{equal} is a function that determines whether its first
3976argument is equal to its second argument. The second argument is the
3977quoted symbol @code{'fierce} and the first argument is the value of the
3978symbol @code{characteristic}---in other words, the argument passed to
3979this function.
3980
3981In the first exercise of @code{type-of-animal}, the argument
3982@code{fierce} is passed to @code{type-of-animal}. Since @code{fierce}
3983is equal to @code{fierce}, the expression, @code{(equal characteristic
3984'fierce)}, returns a value of true. When this happens, the @code{if}
3985evaluates the second argument or then-part of the @code{if}:
3986@code{(message "It's tiger!")}.
3987
3988On the other hand, in the second exercise of @code{type-of-animal}, the
3989argument @code{zebra} is passed to @code{type-of-animal}. @code{zebra}
3990is not equal to @code{fierce}, so the then-part is not evaluated and
3991@code{nil} is returned by the @code{if} expression.
3992
3993@node else, Truth & Falsehood, if, Writing Defuns
3994@comment node-name, next, previous, up
3995@section If--then--else Expressions
3996@cindex Else
3997
3998An @code{if} expression may have an optional third argument, called
3999the @dfn{else-part}, for the case when the true-or-false-test returns
4000false. When this happens, the second argument or then-part of the
4001overall @code{if} expression is @emph{not} evaluated, but the third or
4002else-part @emph{is} evaluated. You might think of this as the cloudy
4003day alternative for the decision `if it is warm and sunny, then go to
4004the beach, else read a book!''.
4005
4006The word ``else'' is not written in the Lisp code; the else-part of an
4007@code{if} expression comes after the then-part. In the written Lisp, the
4008else-part is usually written to start on a line of its own and is
4009indented less than the then-part:
4010
4011@smallexample
4012@group
4013(if @var{true-or-false-test}
4014 @var{action-to-carry-out-if-the-test-returns-true}
4015 @var{action-to-carry-out-if-the-test-returns-false})
4016@end group
4017@end smallexample
4018
4019For example, the following @code{if} expression prints the message @samp{4
4020is not greater than 5!} when you evaluate it in the usual way:
4021
4022@smallexample
4023@group
4024(if (> 4 5) ; @r{if-part}
4025 (message "5 is greater than 4!") ; @r{then-part}
4026 (message "4 is not greater than 5!")) ; @r{else-part}
4027@end group
4028@end smallexample
4029
4030@noindent
4031Note that the different levels of indentation make it easy to
4032distinguish the then-part from the else-part. (GNU Emacs has several
4033commands that automatically indent @code{if} expressions correctly.
4034@xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4035
4036We can extend the @code{type-of-animal} function to include an
4037else-part by simply incorporating an additional part to the @code{if}
4038expression.
4039
4040@need 1500
4041You can see the consequences of doing this if you evaluate the following
4042version of the @code{type-of-animal} function definition to install it
4043and then evaluate the two subsequent expressions to pass different
4044arguments to the function.
4045
4046@smallexample
4047@group
4048(defun type-of-animal (characteristic) ; @r{Second version.}
4049 "Print message in echo area depending on CHARACTERISTIC.
4050If the CHARACTERISTIC is the symbol `fierce',
4051then warn of a tiger;
4052else say it's not fierce."
4053 (if (equal characteristic 'fierce)
4054 (message "It's a tiger!")
4055 (message "It's not fierce!")))
4056@end group
4057@end smallexample
4058@sp 1
4059
4060@smallexample
4061@group
4062(type-of-animal 'fierce)
4063
4064(type-of-animal 'zebra)
4065
4066@end group
4067@end smallexample
4068
4069@c Following sentence rewritten to prevent overfull hbox.
4070@noindent
4071When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4072following message printed in the echo area: @code{"It's a tiger!"}; but
4073when you evaluate @code{(type-of-animal 'zebra)}, you will see
4074@code{"It's not fierce!"}.
4075
4076(Of course, if the @var{characteristic} were @code{ferocious}, the
4077message @code{"It's not fierce!"} would be printed; and it would be
4078misleading! When you write code, you need to take into account the
4079possibility that some such argument will be tested by the @code{if} and
4080write your program accordingly.)
4081
4082@node Truth & Falsehood, save-excursion, else, Writing Defuns
4083@comment node-name, next, previous, up
4084@section Truth and Falsehood in Emacs Lisp
4085@cindex Truth and falsehood in Emacs Lisp
4086@cindex Falsehood and truth in Emacs Lisp
4087@findex nil
4088
4089There is an important aspect to the truth test in an @code{if}
4090expression. So far, we have spoken of `true' and `false' as values of
4091predicates as if they were new kinds of Emacs Lisp objects. In fact,
4092`false' is just our old friend @code{nil}. Anything else---anything
4093at all---is `true'.
4094
4095The expression that tests for truth is interpreted as @dfn{true}
4096if the result of evaluating it is a value that is not @code{nil}. In
4097other words, the result of the test is considered true if the value
4098returned is a number such as 47, a string such as @code{"hello"}, or a
4099symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4100even a buffer!
4101
4102@menu
4103* nil explained:: @code{nil} has two meanings.
4104@end menu
4105
4106@node nil explained, , Truth & Falsehood, Truth & Falsehood
4107@ifnottex
4108@unnumberedsubsec An explanation of @code{nil}
4109@end ifnottex
4110
4111Before illustrating a test for truth, we need an explanation of @code{nil}.
4112
4113In Emacs Lisp, the symbol @code{nil} has two meanings. First, it means the
4114empty list. Second, it means false and is the value returned when a
4115true-or-false-test tests false. @code{nil} can be written as an empty
4116list, @code{()}, or as @code{nil}. As far as the Lisp interpreter is
4117concerned, @code{()} and @code{nil} are the same. Humans, however, tend
4118to use @code{nil} for false and @code{()} for the empty list.
4119
4120In Emacs Lisp, any value that is not @code{nil}---is not the empty
4121list---is considered true. This means that if an evaluation returns
4122something that is not an empty list, an @code{if} expression will test
4123true. For example, if a number is put in the slot for the test, it
4124will be evaluated and will return itself, since that is what numbers
4125do when evaluated. In this conditional, the @code{if} expression will
4126test true. The expression tests false only when @code{nil}, an empty
4127list, is returned by evaluating the expression.
4128
4129You can see this by evaluating the two expressions in the following examples.
4130
4131In the first example, the number 4 is evaluated as the test in the
4132@code{if} expression and returns itself; consequently, the then-part
4133of the expression is evaluated and returned: @samp{true} appears in
4134the echo area. In the second example, the @code{nil} indicates false;
4135consequently, the else-part of the expression is evaluated and
4136returned: @samp{false} appears in the echo area.
4137
4138@smallexample
4139@group
4140(if 4
4141 'true
4142 'false)
4143@end group
4144
4145@group
4146(if nil
4147 'true
4148 'false)
4149@end group
4150@end smallexample
4151
4152@need 1250
4153Incidentally, if some other useful value is not available for a test that
4154returns true, then the Lisp interpreter will return the symbol @code{t}
4155for true. For example, the expression @code{(> 5 4)} returns @code{t}
4156when evaluated, as you can see by evaluating it in the usual way:
4157
4158@smallexample
4159(> 5 4)
4160@end smallexample
4161
4162@need 1250
4163@noindent
4164On the other hand, this function returns @code{nil} if the test is false.
4165
4166@smallexample
4167(> 4 5)
4168@end smallexample
4169
4170@node save-excursion, Review, Truth & Falsehood, Writing Defuns
4171@comment node-name, next, previous, up
4172@section @code{save-excursion}
4173@findex save-excursion
4174@cindex Region, what it is
4175@cindex Preserving point, mark, and buffer
4176@cindex Point, mark, buffer preservation
4177@findex point
4178@findex mark
4179
4180The @code{save-excursion} function is the fourth and final special form
4181that we will discuss in this chapter.
4182
4183In Emacs Lisp programs used for editing, the @code{save-excursion}
4184function is very common. It saves the location of point and mark,
4185executes the body of the function, and then restores point and mark to
4186their previous positions if their locations were changed. Its primary
4187purpose is to keep the user from being surprised and disturbed by
4188unexpected movement of point or mark.
4189
4190@menu
4191* Point and mark:: A review of various locations.
4192* Template for save-excursion::
4193@end menu
4194
4195@node Point and mark, Template for save-excursion, save-excursion, save-excursion
4196@ifnottex
4197@unnumberedsubsec Point and Mark
4198@end ifnottex
4199
4200Before discussing @code{save-excursion}, however, it may be useful
4201first to review what point and mark are in GNU Emacs. @dfn{Point} is
4202the current location of the cursor. Wherever the cursor
4203is, that is point. More precisely, on terminals where the cursor
4204appears to be on top of a character, point is immediately before the
4205character. In Emacs Lisp, point is an integer. The first character in
4206a buffer is number one, the second is number two, and so on. The
4207function @code{point} returns the current position of the cursor as a
4208number. Each buffer has its own value for point.
4209
4210The @dfn{mark} is another position in the buffer; its value can be set
4211with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}). If
4212a mark has been set, you can use the command @kbd{C-x C-x}
4213(@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4214and set the mark to be the previous position of point. In addition, if
4215you set another mark, the position of the previous mark is saved in the
4216mark ring. Many mark positions can be saved this way. You can jump the
4217cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4218times.
4219
4220The part of the buffer between point and mark is called @dfn{the
4221region}. Numerous commands work on the region, including
4222@code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4223@code{print-region}.
4224
4225The @code{save-excursion} special form saves the locations of point and
4226mark and restores those positions after the code within the body of the
4227special form is evaluated by the Lisp interpreter. Thus, if point were
4228in the beginning of a piece of text and some code moved point to the end
4229of the buffer, the @code{save-excursion} would put point back to where
4230it was before, after the expressions in the body of the function were
4231evaluated.
4232
4233In Emacs, a function frequently moves point as part of its internal
4234workings even though a user would not expect this. For example,
4235@code{count-lines-region} moves point. To prevent the user from being
4236bothered by jumps that are both unexpected and (from the user's point of
4237view) unnecessary, @code{save-excursion} is often used to keep point and
4238mark in the location expected by the user. The use of
4239@code{save-excursion} is good housekeeping.
4240
4241To make sure the house stays clean, @code{save-excursion} restores the
4242values of point and mark even if something goes wrong in the code inside
4243of it (or, to be more precise and to use the proper jargon, ``in case of
4244abnormal exit''). This feature is very helpful.
4245
4246In addition to recording the values of point and mark,
4247@code{save-excursion} keeps track of the current buffer, and restores
4248it, too. This means you can write code that will change the buffer and
4249have @code{save-excursion} switch you back to the original buffer. This
4250is how @code{save-excursion} is used in @code{append-to-buffer}.
4251(@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4252
4253@node Template for save-excursion, , Point and mark, save-excursion
4254@comment node-name, next, previous, up
4255@subsection Template for a @code{save-excursion} Expression
4256
4257@need 800
4258The template for code using @code{save-excursion} is simple:
4259
4260@smallexample
4261@group
4262(save-excursion
4263 @var{body}@dots{})
4264@end group
4265@end smallexample
4266
4267@noindent
4268The body of the function is one or more expressions that will be
4269evaluated in sequence by the Lisp interpreter. If there is more than
4270one expression in the body, the value of the last one will be returned
4271as the value of the @code{save-excursion} function. The other
4272expressions in the body are evaluated only for their side effects; and
4273@code{save-excursion} itself is used only for its side effect (which
4274is restoring the positions of point and mark).
4275
4276@need 1250
4277In more detail, the template for a @code{save-excursion} expression
4278looks like this:
4279
4280@smallexample
4281@group
4282(save-excursion
4283 @var{first-expression-in-body}
4284 @var{second-expression-in-body}
4285 @var{third-expression-in-body}
4286 @dots{}
4287 @var{last-expression-in-body})
4288@end group
4289@end smallexample
4290
4291@noindent
4292An expression, of course, may be a symbol on its own or a list.
4293
4294In Emacs Lisp code, a @code{save-excursion} expression often occurs
4295within the body of a @code{let} expression. It looks like this:
4296
4297@smallexample
4298@group
4299(let @var{varlist}
4300 (save-excursion
4301 @var{body}@dots{}))
4302@end group
4303@end smallexample
4304
4305@node Review, defun Exercises, save-excursion, Writing Defuns
4306@comment node-name, next, previous, up
4307@section Review
4308
4309In the last few chapters we have introduced a fair number of functions
4310and special forms. Here they are described in brief, along with a few
4311similar functions that have not been mentioned yet.
4312
4313@table @code
4314@item eval-last-sexp
4315Evaluate the last symbolic expression before the current location of
4316point. The value is printed in the echo area unless the function is
4317invoked with an argument; in that case, the output is printed in the
4318current buffer. This command is normally bound to @kbd{C-x C-e}.
4319
4320@item defun
4321Define function. This special form has up to five parts: the name,
4322a template for the arguments that will be passed to the function,
4323documentation, an optional interactive declaration, and the body of the
4324definition.
4325
4326@need 1250
4327For example:
4328
4329@smallexample
4330@group
4331(defun back-to-indentation ()
4332 "Move point to first visible character on line."
4333 (interactive)
4334 (beginning-of-line 1)
4335 (skip-chars-forward " \t"))
4336@end group
4337@end smallexample
4338
4339@item interactive
4340Declare to the interpreter that the function can be used
4341interactively. This special form may be followed by a string with one
4342or more parts that pass the information to the arguments of the
4343function, in sequence. These parts may also tell the interpreter to
4344prompt for information. Parts of the string are separated by
4345newlines, @samp{\n}.
4346
c6f54b06 4347@need 1000
8b096dce
EZ
4348Common code characters are:
4349
4350@table @code
4351@item b
4352The name of an existing buffer.
4353
4354@item f
4355The name of an existing file.
4356
4357@item p
4358The numeric prefix argument. (Note that this `p' is lower case.)
4359
4360@item r
4361Point and the mark, as two numeric arguments, smallest first. This
4362is the only code letter that specifies two successive arguments
4363rather than one.
4364@end table
4365
4366@xref{Interactive Codes, , Code Characters for @samp{interactive},
4367elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4368code characters.
4369
4370@item let
4371Declare that a list of variables is for use within the body of the
4372@code{let} and give them an initial value, either @code{nil} or a
4373specified value; then evaluate the rest of the expressions in the body
4374of the @code{let} and return the value of the last one. Inside the
4375body of the @code{let}, the Lisp interpreter does not see the values of
4376the variables of the same names that are bound outside of the
4377@code{let}.
4378
4379@need 1250
4380For example,
4381
4382@smallexample
4383@group
4384(let ((foo (buffer-name))
4385 (bar (buffer-size)))
4386 (message
4387 "This buffer is %s and has %d characters."
4388 foo bar))
4389@end group
4390@end smallexample
4391
4392@item save-excursion
4393Record the values of point and mark and the current buffer before
4394evaluating the body of this special form. Restore the values of point
4395and mark and buffer afterward.
4396
4397@need 1250
4398For example,
4399
4400@smallexample
4401@group
4402(message "We are %d characters into this buffer."
4403 (- (point)
4404 (save-excursion
4405 (goto-char (point-min)) (point))))
4406@end group
4407@end smallexample
4408
4409@item if
4410Evaluate the first argument to the function; if it is true, evaluate
4411the second argument; else evaluate the third argument, if there is one.
4412
4413The @code{if} special form is called a @dfn{conditional}. There are
4414other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4415commonly used.
4416
4417@need 1250
4418For example,
4419
4420@smallexample
4421@group
4422(if (string-equal
4423 (number-to-string 21)
4424 (substring (emacs-version) 10 12))
4425 (message "This is version 21 Emacs")
4426 (message "This is not version 21 Emacs"))
4427@end group
4428@end smallexample
4429
4430@item equal
4431@itemx eq
4432Test whether two objects are the same. @code{equal} uses one meaning
4433of the word `same' and @code{eq} uses another: @code{equal} returns
4434true if the two objects have a similar structure and contents, such as
4435two copies of the same book. On the other hand, @code{eq}, returns
4436true if both arguments are actually the same object.
4437@findex equal
4438@findex eq
4439
4440@need 1250
4441@item <
4442@itemx >
4443@itemx <=
4444@itemx >=
4445The @code{<} function tests whether its first argument is smaller than
4446its second argument. A corresponding function, @code{>}, tests whether
4447the first argument is greater than the second. Likewise, @code{<=}
4448tests whether the first argument is less than or equal to the second and
4449@code{>=} tests whether the first argument is greater than or equal to
4450the second. In all cases, both arguments must be numbers or markers
4451(markers indicate positions in buffers).
4452
4453@item string<
4454@itemx string-lessp
4455@itemx string=
4456@itemx string-equal
4457The @code{string-lessp} function tests whether its first argument is
4458smaller than the second argument. A shorter, alternative name for the
4459same function (a @code{defalias}) is @code{string<}.
4460
4461The arguments to @code{string-lessp} must be strings or symbols; the
4462ordering is lexicographic, so case is significant. The print names of
4463symbols are used instead of the symbols themselves.
4464
4540f8f8 4465@cindex @samp{empty string} defined
1dcb89ad
RC
4466An empty string, @samp{""}, a string with no characters in it, is
4467smaller than any string of characters.
4468
8b096dce
EZ
4469@code{string-equal} provides the corresponding test for equality. Its
4470shorter, alternative name is @code{string=}. There are no string test
4471functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4472
4473@item message
4474Print a message in the echo area. The first argument is a string that
4475can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4476arguments that follow the string. The argument used by @samp{%s} must
4477be a string or a symbol; the argument used by @samp{%d} must be a
c6f54b06
RC
4478number. The argument used by @samp{%c} must be an @sc{ascii} code
4479number; it will be printed as the character with that @sc{ascii} code.
8b096dce
EZ
4480
4481@item setq
4482@itemx set
4483The @code{setq} function sets the value of its first argument to the
4484value of the second argument. The first argument is automatically
4485quoted by @code{setq}. It does the same for succeeding pairs of
4486arguments. Another function, @code{set}, takes only two arguments and
4487evaluates both of them before setting the value returned by its first
4488argument to the value returned by its second argument.
4489
4490@item buffer-name
4491Without an argument, return the name of the buffer, as a string.
4492
4493@itemx buffer-file-name
4494Without an argument, return the name of the file the buffer is
4495visiting.
4496
4497@item current-buffer
4498Return the buffer in which Emacs is active; it may not be
4499the buffer that is visible on the screen.
4500
4501@item other-buffer
4502Return the most recently selected buffer (other than the buffer passed
4503to @code{other-buffer} as an argument and other than the current
4504buffer).
4505
4506@item switch-to-buffer
4507Select a buffer for Emacs to be active in and display it in the current
4508window so users can look at it. Usually bound to @kbd{C-x b}.
4509
4510@item set-buffer
4511Switch Emacs' attention to a buffer on which programs will run. Don't
4512alter what the window is showing.
4513
4514@item buffer-size
4515Return the number of characters in the current buffer.
4516
4517@item point
4518Return the value of the current position of the cursor, as an
4519integer counting the number of characters from the beginning of the
4520buffer.
4521
4522@item point-min
4523Return the minimum permissible value of point in
4524the current buffer. This is 1, unless narrowing is in effect.
4525
4526@item point-max
4527Return the value of the maximum permissible value of point in the
4528current buffer. This is the end of the buffer, unless narrowing is in
4529effect.
4530@end table
4531
4532@need 1500
4533@node defun Exercises, , Review, Writing Defuns
4534@section Exercises
4535
4536@itemize @bullet
4537@item
4538Write a non-interactive function that doubles the value of its
4539argument, a number. Make that function interactive.
4540
4541@item
4542Write a function that tests whether the current value of
4543@code{fill-column} is greater than the argument passed to the function,
4544and if so, prints an appropriate message.
4545@end itemize
4546
4547@node Buffer Walk Through, More Complex, Writing Defuns, Top
4548@comment node-name, next, previous, up
4549@chapter A Few Buffer--Related Functions
4550
4551In this chapter we study in detail several of the functions used in GNU
4552Emacs. This is called a ``walk-through''. These functions are used as
4553examples of Lisp code, but are not imaginary examples; with the
4554exception of the first, simplified function definition, these functions
4555show the actual code used in GNU Emacs. You can learn a great deal from
4556these definitions. The functions described here are all related to
4557buffers. Later, we will study other functions.
4558
4559@menu
4560* Finding More:: How to find more information.
4561* simplified-beginning-of-buffer:: Shows @code{goto-char},
4562 @code{point-min}, and @code{push-mark}.
4563* mark-whole-buffer:: Almost the same as @code{beginning-of-buffer}.
4564* append-to-buffer:: Uses @code{save-excursion} and
4565 @code{insert-buffer-substring}.
4566* Buffer Related Review:: Review.
4567* Buffer Exercises::
4568@end menu
4569
4570@node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4571@section Finding More Information
4572
4573@findex describe-function, @r{introduced}
4574@cindex Find function documentation
4575In this walk-through, I will describe each new function as we come to
4576it, sometimes in detail and sometimes briefly. If you are interested,
4577you can get the full documentation of any Emacs Lisp function at any
4578time by typing @kbd{C-h f} and then the name of the function (and then
4579@key{RET}). Similarly, you can get the full documentation for a
4580variable by typing @kbd{C-h v} and then the name of the variable (and
4581then @key{RET}).
4582
4583@cindex Find source of function
4584In versions 20 and higher, when a function is written in Emacs Lisp,
4585@code{describe-function} will also tell you the location of the
4586function definition. If you move point over the file name and press
c6f54b06 4587the @key{RET} key, which in this case means @code{help-follow} rather
8b096dce
EZ
4588than `return' or `enter', Emacs will take you directly to the function
4589definition.
4590
4591More generally, if you want to see a function in its original source
4592file, you can use the @code{find-tags} function to jump to it.
4593@code{find-tags} works with a wide variety of languages, not just
4594Lisp, and C, and it works with non-programming text as well. For
4595example, @code{find-tags} will jump to the various nodes in the
4596Texinfo source file of this document.
4597
4598The @code{find-tags} function depends on `tags tables' that record
4599the locations of the functions, variables, and other items to which
4600@code{find-tags} jumps.
4601
c6f54b06
RC
4602To use the @code{find-tags} command, type @kbd{M-.} (i.e., press the
4603period key while holding down the @key{META} key, or else type the
8b096dce
EZ
4604@key{ESC} key and then type the period key), and then, at the prompt,
4605type in the name of the function whose source code you want to see,
4606such as @code{mark-whole-buffer}, and then type @key{RET}. Emacs will
4607switch buffers and display the source code for the function on your
4608screen. To switch back to your current buffer, type @kbd{C-x b
4609@key{RET}}. (On some keyboards, the @key{META} key is labelled
4610@key{ALT}.)
4611
4612@c !!! 21.0.100 tags table location in this paragraph
4613@cindex TAGS table, specifying
4614@findex find-tags
4615Depending on how the initial default values of your copy of Emacs are
4616set, you may also need to specify the location of your `tags table',
4617which is a file called @file{TAGS}. For example, if you are
4618interested in Emacs sources, the tags table you will most likely want,
4619if it has already been created for you, will be in a subdirectory of
4620the @file{/usr/local/share/emacs/} directory; thus you would use the
4621@code{M-x visit-tags-table} command and specify a pathname such as
4622@file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
c6f54b06 4623@file{/usr/local/src/emacs/src/TAGS}. If the tags table has
8b096dce
EZ
4624not already been created, you will have to create it yourself.
4625
4626@need 1250
4627To create a @file{TAGS} file in a specific directory, switch to that
4628directory in Emacs using @kbd{M-x cd} command, or list the directory
4629with @kbd{C-x d} (@code{dired}). Then run the compile command, with
4630@w{@code{etags *.el}} as the command to execute
4631
4632@smallexample
4633M-x compile RET etags *.el RET
4634@end smallexample
4635
4636For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4637
4638After you become more familiar with Emacs Lisp, you will find that you will
4639frequently use @code{find-tags} to navigate your way around source code;
4640and you will create your own @file{TAGS} tables.
4641
4642@cindex Library, as term for `file'
4643Incidentally, the files that contain Lisp code are conventionally
4644called @dfn{libraries}. The metaphor is derived from that of a
4645specialized library, such as a law library or an engineering library,
4646rather than a general library. Each library, or file, contains
4647functions that relate to a particular topic or activity, such as
4648@file{abbrev.el} for handling abbreviations and other typing
4649shortcuts, and @file{help.el} for on-line help. (Sometimes several
4650libraries provide code for a single activity, as the various
4651@file{rmail@dots{}} files provide code for reading electronic mail.)
4652In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4653@kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4654by topic keywords.''
4655
4656@node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4657@comment node-name, next, previous, up
4658@section A Simplified @code{beginning-of-buffer} Definition
4659@findex simplified-beginning-of-buffer
4660
4661The @code{beginning-of-buffer} command is a good function to start with
4662since you are likely to be familiar with it and it is easy to
4663understand. Used as an interactive command, @code{beginning-of-buffer}
4664moves the cursor to the beginning of the buffer, leaving the mark at the
4665previous position. It is generally bound to @kbd{M-<}.
4666
4667In this section, we will discuss a shortened version of the function
4668that shows how it is most frequently used. This shortened function
4669works as written, but it does not contain the code for a complex option.
4670In another section, we will describe the entire function.
4671(@xref{beginning-of-buffer, , Complete Definition of
4672@code{beginning-of-buffer}}.)
4673
4674Before looking at the code, let's consider what the function
4675definition has to contain: it must include an expression that makes
4676the function interactive so it can be called by typing @kbd{M-x
e601d8fd 4677beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
8b096dce
EZ
4678must include code to leave a mark at the original position in the
4679buffer; and it must include code to move the cursor to the beginning
4680of the buffer.
4681
4682@need 1250
4683Here is the complete text of the shortened version of the function:
4684
4685@smallexample
4686@group
4687(defun simplified-beginning-of-buffer ()
4688 "Move point to the beginning of the buffer;
4689leave mark at previous position."
4690 (interactive)
4691 (push-mark)
4692 (goto-char (point-min)))
4693@end group
4694@end smallexample
4695
4696Like all function definitions, this definition has five parts following
4697the special form @code{defun}:
4698
4699@enumerate
4700@item
4701The name: in this example, @code{simplified-beginning-of-buffer}.
4702
4703@item
4704A list of the arguments: in this example, an empty list, @code{()},
4705
4706@item
4707The documentation string.
4708
4709@item
4710The interactive expression.
4711
4712@item
4713The body.
4714@end enumerate
4715
4716@noindent
4717In this function definition, the argument list is empty; this means that
4718this function does not require any arguments. (When we look at the
4719definition for the complete function, we will see that it may be passed
4720an optional argument.)
4721
4722The interactive expression tells Emacs that the function is intended to
4723be used interactively. In this example, @code{interactive} does not have
4724an argument because @code{simplified-beginning-of-buffer} does not
4725require one.
4726
4727@need 800
4728The body of the function consists of the two lines:
4729
4730@smallexample
4731@group
4732(push-mark)
4733(goto-char (point-min))
4734@end group
4735@end smallexample
4736
4737The first of these lines is the expression, @code{(push-mark)}. When
4738this expression is evaluated by the Lisp interpreter, it sets a mark at
4739the current position of the cursor, wherever that may be. The position
4740of this mark is saved in the mark ring.
4741
4742The next line is @code{(goto-char (point-min))}. This expression
4743jumps the cursor to the minimum point in the buffer, that is, to the
4744beginning of the buffer (or to the beginning of the accessible portion
4745of the buffer if it is narrowed. @xref{Narrowing & Widening, ,
4746Narrowing and Widening}.)
4747
4748The @code{push-mark} command sets a mark at the place where the cursor
4749was located before it was moved to the beginning of the buffer by the
4750@code{(goto-char (point-min))} expression. Consequently, you can, if
4751you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4752
4753That is all there is to the function definition!
4754
4755@findex describe-function
4756When you are reading code such as this and come upon an unfamiliar
4757function, such as @code{goto-char}, you can find out what it does by
4758using the @code{describe-function} command. To use this command, type
4759@kbd{C-h f} and then type in the name of the function and press
4760@key{RET}. The @code{describe-function} command will print the
4761function's documentation string in a @file{*Help*} window. For
4762example, the documentation for @code{goto-char} is:
4763
4764@smallexample
4765@group
4766One arg, a number. Set point to that number.
4767Beginning of buffer is position (point-min),
4768end is (point-max).
4769@end group
4770@end smallexample
4771
4772@noindent
4773(The prompt for @code{describe-function} will offer you the symbol
4774under or preceding the cursor, so you can save typing by positioning
4775the cursor right over or after the function and then typing @kbd{C-h f
4776@key{RET}}.)
4777
4778The @code{end-of-buffer} function definition is written in the same way as
4779the @code{beginning-of-buffer} definition except that the body of the
4780function contains the expression @code{(goto-char (point-max))} in place
4781of @code{(goto-char (point-min))}.
4782
4783@node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4784@comment node-name, next, previous, up
4785@section The Definition of @code{mark-whole-buffer}
4786@findex mark-whole-buffer
4787
4788The @code{mark-whole-buffer} function is no harder to understand than the
4789@code{simplified-beginning-of-buffer} function. In this case, however,
4790we will look at the complete function, not a shortened version.
4791
4792The @code{mark-whole-buffer} function is not as commonly used as the
4793@code{beginning-of-buffer} function, but is useful nonetheless: it
4794marks a whole buffer as a region by putting point at the beginning and
4795a mark at the end of the buffer. It is generally bound to @kbd{C-x
4796h}.
4797
4798
4799@menu
4800* mark-whole-buffer overview::
4801* Body of mark-whole-buffer:: Only three lines of code.
4802@end menu
4803
4804
4805@node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4806@ifnottex
4807@unnumberedsubsec An overview of @code{mark-whole-buffer}
4808@end ifnottex
4809
4810@need 1250
4811In GNU Emacs 20, the code for the complete function looks like this:
4812
4813@smallexample
4814@group
4815(defun mark-whole-buffer ()
4816 "Put point at beginning and mark at end of buffer."
4817 (interactive)
4818 (push-mark (point))
4819 (push-mark (point-max))
4820 (goto-char (point-min)))
4821@end group
4822@end smallexample
4823
4824@need 1250
4825Like all other functions, the @code{mark-whole-buffer} function fits
4826into the template for a function definition. The template looks like
4827this:
4828
4829@smallexample
4830@group
4831(defun @var{name-of-function} (@var{argument-list})
4832 "@var{documentation}@dots{}"
4833 (@var{interactive-expression}@dots{})
4834 @var{body}@dots{})
4835@end group
4836@end smallexample
4837
4838Here is how the function works: the name of the function is
4839@code{mark-whole-buffer}; it is followed by an empty argument list,
4840@samp{()}, which means that the function does not require arguments.
4841The documentation comes next.
4842
4843The next line is an @code{(interactive)} expression that tells Emacs
4844that the function will be used interactively. These details are similar
4845to the @code{simplified-beginning-of-buffer} function described in the
4846previous section.
4847
c6f54b06 4848@need 1250
8b096dce
EZ
4849@node Body of mark-whole-buffer, , mark-whole-buffer overview, mark-whole-buffer
4850@comment node-name, next, previous, up
4851@subsection Body of @code{mark-whole-buffer}
4852
4853The body of the @code{mark-whole-buffer} function consists of three
4854lines of code:
4855
4856@smallexample
4857@group
4858(push-mark (point))
4859(push-mark (point-max))
4860(goto-char (point-min))
4861@end group
4862@end smallexample
4863
4864The first of these lines is the expression, @code{(push-mark (point))}.
4865
4866This line does exactly the same job as the first line of the body of
4867the @code{simplified-beginning-of-buffer} function, which is written
4868@code{(push-mark)}. In both cases, the Lisp interpreter sets a mark
4869at the current position of the cursor.
4870
4871I don't know why the expression in @code{mark-whole-buffer} is written
4872@code{(push-mark (point))} and the expression in
4873@code{beginning-of-buffer} is written @code{(push-mark)}. Perhaps
4874whoever wrote the code did not know that the arguments for
4875@code{push-mark} are optional and that if @code{push-mark} is not
4876passed an argument, the function automatically sets mark at the
4877location of point by default. Or perhaps the expression was written
4878so as to parallel the structure of the next line. In any case, the
4879line causes Emacs to determine the position of point and set a mark
4880there.
4881
4882The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4883This expression sets a mark at the point in the buffer
4884that has the highest number. This will be the end of the buffer (or,
4885if the buffer is narrowed, the end of the accessible portion of the
4886buffer. @xref{Narrowing & Widening, , Narrowing and Widening}, for
4887more about narrowing.) After this mark has been set, the previous
4888mark, the one set at point, is no longer set, but Emacs remembers its
4889position, just as all other recent marks are always remembered. This
4890means that you can, if you wish, go back to that position by typing
4891@kbd{C-u C-@key{SPC}} twice.
4892
4893(In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4894complicated than shown here. The line reads
4895
4896@smallexample
4897(push-mark (point-max) nil t)
4898@end smallexample
4899
4900@noindent
4901(The expression works nearly the same as before. It sets a mark at
4902the highest numbered place in the buffer that it can. However, in
6964db14
RC
4903this version, @code{push-mark} has two additional arguments. The
4904second argument to @code{push-mark} is @code{nil}. This tells the
4905function it @emph{should} display a message that says `Mark set' when
4906it pushes the mark. The third argument is @code{t}. This tells
8b096dce
EZ
4907@code{push-mark} to activate the mark when Transient Mark mode is
4908turned on. Transient Mark mode highlights the currently active
4909region. It is usually turned off.)
4910
4911Finally, the last line of the function is @code{(goto-char
4912(point-min)))}. This is written exactly the same way as it is written
4913in @code{beginning-of-buffer}. The expression moves the cursor to
4914the minimum point in the buffer, that is, to the beginning of the buffer
4915(or to the beginning of the accessible portion of the buffer). As a
4916result of this, point is placed at the beginning of the buffer and mark
4917is set at the end of the buffer. The whole buffer is, therefore, the
4918region.
4919
4920@node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4921@comment node-name, next, previous, up
4922@section The Definition of @code{append-to-buffer}
4923@findex append-to-buffer
4924
4925The @code{append-to-buffer} command is very nearly as simple as the
4926@code{mark-whole-buffer} command. What it does is copy the region (that
4927is, the part of the buffer between point and mark) from the current
4928buffer to a specified buffer.
4929
4930@menu
4931* append-to-buffer overview::
4932* append interactive:: A two part interactive expression.
4933* append-to-buffer body:: Incorporates a @code{let} expression.
4934* append save-excursion:: How the @code{save-excursion} works.
4935@end menu
4936
4937@node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4938@ifnottex
4939@unnumberedsubsec An Overview of @code{append-to-buffer}
4940@end ifnottex
4941
4942@findex insert-buffer-substring
4943The @code{append-to-buffer} command uses the
4944@code{insert-buffer-substring} function to copy the region.
4945@code{insert-buffer-substring} is described by its name: it takes a
4946string of characters from part of a buffer, a ``substring'', and
4947inserts them into another buffer. Most of @code{append-to-buffer} is
4948concerned with setting up the conditions for
4949@code{insert-buffer-substring} to work: the code must specify both the
4950buffer to which the text will go and the region that will be copied.
4951Here is the complete text of the function:
4952
4953@smallexample
4954@group
4955(defun append-to-buffer (buffer start end)
4956 "Append to specified buffer the text of the region.
4957It is inserted into that buffer before its point.
4958@end group
4959
4960@group
4961When calling from a program, give three arguments:
4962a buffer or the name of one, and two character numbers
4963specifying the portion of the current buffer to be copied."
4964 (interactive "BAppend to buffer:@: \nr")
4965 (let ((oldbuf (current-buffer)))
4966 (save-excursion
4967 (set-buffer (get-buffer-create buffer))
4968 (insert-buffer-substring oldbuf start end))))
4969@end group
4970@end smallexample
4971
4972The function can be understood by looking at it as a series of
4973filled-in templates.
4974
4975The outermost template is for the function definition. In this
4976function, it looks like this (with several slots filled in):
4977
4978@smallexample
4979@group
4980(defun append-to-buffer (buffer start end)
4981 "@var{documentation}@dots{}"
4982 (interactive "BAppend to buffer:@: \nr")
4983 @var{body}@dots{})
4984@end group
4985@end smallexample
4986
4987The first line of the function includes its name and three arguments.
4988The arguments are the @code{buffer} to which the text will be copied, and
4989the @code{start} and @code{end} of the region in the current buffer that
4990will be copied.
4991
4992The next part of the function is the documentation, which is clear and
4993complete.
4994
4995@node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
4996@comment node-name, next, previous, up
4997@subsection The @code{append-to-buffer} Interactive Expression
4998
4999Since the @code{append-to-buffer} function will be used interactively,
5000the function must have an @code{interactive} expression. (For a
5001review of @code{interactive}, see @ref{Interactive, , Making a
5002Function Interactive}.) The expression reads as follows:
5003
5004@smallexample
5005(interactive "BAppend to buffer:@: \nr")
5006@end smallexample
5007
5008@noindent
5009This expression has an argument inside of quotation marks and that
5010argument has two parts, separated by @samp{\n}.
5011
5012The first part is @samp{BAppend to buffer:@: }. Here, the @samp{B}
5013tells Emacs to ask for the name of the buffer that will be passed to the
5014function. Emacs will ask for the name by prompting the user in the
5015minibuffer, using the string following the @samp{B}, which is the string
5016@samp{Append to buffer:@: }. Emacs then binds the variable @code{buffer}
5017in the function's argument list to the specified buffer.
5018
5019The newline, @samp{\n}, separates the first part of the argument from
5020the second part. It is followed by an @samp{r} that tells Emacs to bind
5021the two arguments that follow the symbol @code{buffer} in the function's
5022argument list (that is, @code{start} and @code{end}) to the values of
5023point and mark.
5024
5025@node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5026@comment node-name, next, previous, up
5027@subsection The Body of @code{append-to-buffer}
5028
5029The body of the @code{append-to-buffer} function begins with @code{let}.
5030
5031As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5032@code{let} expression is to create and give initial values to one or
5033more variables that will only be used within the body of the
5034@code{let}. This means that such a variable will not be confused with
5035any variable of the same name outside the @code{let} expression.
5036
5037We can see how the @code{let} expression fits into the function as a
5038whole by showing a template for @code{append-to-buffer} with the
5039@code{let} expression in outline:
5040
5041@smallexample
5042@group
5043(defun append-to-buffer (buffer start end)
5044 "@var{documentation}@dots{}"
5045 (interactive "BAppend to buffer:@: \nr")
5046 (let ((@var{variable} @var{value}))
5047 @var{body}@dots{})
5048@end group
5049@end smallexample
5050
5051The @code{let} expression has three elements:
5052
5053@enumerate
5054@item
5055The symbol @code{let};
5056
5057@item
5058A varlist containing, in this case, a single two-element list,
5059@code{(@var{variable} @var{value})};
5060
5061@item
5062The body of the @code{let} expression.
5063@end enumerate
5064
5065@need 800
5066In the @code{append-to-buffer} function, the varlist looks like this:
5067
5068@smallexample
5069(oldbuf (current-buffer))
5070@end smallexample
5071
5072@noindent
5073In this part of the @code{let} expression, the one variable,
5074@code{oldbuf}, is bound to the value returned by the
5075@code{(current-buffer)} expression. The variable, @code{oldbuf}, is
5076used to keep track of the buffer in which you are working and from
5077which you will copy.
5078
5079The element or elements of a varlist are surrounded by a set of
5080parentheses so the Lisp interpreter can distinguish the varlist from
5081the body of the @code{let}. As a consequence, the two-element list
5082within the varlist is surrounded by a circumscribing set of parentheses.
5083The line looks like this:
5084
5085@smallexample
5086@group
5087(let ((oldbuf (current-buffer)))
5088 @dots{} )
5089@end group
5090@end smallexample
5091
5092@noindent
5093The two parentheses before @code{oldbuf} might surprise you if you did
5094not realize that the first parenthesis before @code{oldbuf} marks the
5095boundary of the varlist and the second parenthesis marks the beginning
5096of the two-element list, @code{(oldbuf (current-buffer))}.
5097
5098@node append save-excursion, , append-to-buffer body, append-to-buffer
5099@comment node-name, next, previous, up
5100@subsection @code{save-excursion} in @code{append-to-buffer}
5101
5102The body of the @code{let} expression in @code{append-to-buffer}
5103consists of a @code{save-excursion} expression.
5104
5105The @code{save-excursion} function saves the locations of point and
5106mark, and restores them to those positions after the expressions in the
5107body of the @code{save-excursion} complete execution. In addition,
5108@code{save-excursion} keeps track of the original buffer, and
5109restores it. This is how @code{save-excursion} is used in
5110@code{append-to-buffer}.
5111
5112@need 1500
5113@cindex Indentation for formatting
5114@cindex Formatting convention
5115Incidentally, it is worth noting here that a Lisp function is normally
5116formatted so that everything that is enclosed in a multi-line spread is
5117indented more to the right than the first symbol. In this function
5118definition, the @code{let} is indented more than the @code{defun}, and
5119the @code{save-excursion} is indented more than the @code{let}, like
5120this:
5121
5122@smallexample
5123@group
5124(defun @dots{}
5125 @dots{}
5126 @dots{}
5127 (let@dots{}
5128 (save-excursion
5129 @dots{}
5130@end group
5131@end smallexample
5132
5133@need 1500
5134@noindent
5135This formatting convention makes it easy to see that the two lines in
5136the body of the @code{save-excursion} are enclosed by the parentheses
5137associated with @code{save-excursion}, just as the
5138@code{save-excursion} itself is enclosed by the parentheses associated
5139with the @code{let}:
5140
5141@smallexample
5142@group
5143(let ((oldbuf (current-buffer)))
5144 (save-excursion
5145 (set-buffer (get-buffer-create buffer))
5146 (insert-buffer-substring oldbuf start end))))
5147@end group
5148@end smallexample
5149
5150@need 1200
5151The use of the @code{save-excursion} function can be viewed as a process
5152of filling in the slots of a template:
5153
5154@smallexample
5155@group
5156(save-excursion
5157 @var{first-expression-in-body}
5158 @var{second-expression-in-body}
5159 @dots{}
5160 @var{last-expression-in-body})
5161@end group
5162@end smallexample
5163
5164@need 1200
5165@noindent
5166In this function, the body of the @code{save-excursion} contains only
5167two expressions. The body looks like this:
5168
5169@smallexample
5170@group
5171(set-buffer (get-buffer-create buffer))
5172(insert-buffer-substring oldbuf start end)
5173@end group
5174@end smallexample
5175
5176When the @code{append-to-buffer} function is evaluated, the two
5177expressions in the body of the @code{save-excursion} are evaluated in
5178sequence. The value of the last expression is returned as the value of
5179the @code{save-excursion} function; the other expression is evaluated
5180only for its side effects.
5181
5182The first line in the body of the @code{save-excursion} uses the
5183@code{set-buffer} function to change the current buffer to the one
5184specified in the first argument to @code{append-to-buffer}. (Changing
5185the buffer is the side effect; as we have said before, in Lisp, a side
5186effect is often the primary thing we want.) The second line does the
5187primary work of the function.
5188
5189The @code{set-buffer} function changes Emacs' attention to the buffer to
5190which the text will be copied and from which @code{save-excursion} will
5191return.
5192
5193@need 800
5194The line looks like this:
5195
5196@smallexample
5197(set-buffer (get-buffer-create buffer))
5198@end smallexample
5199
5200The innermost expression of this list is @code{(get-buffer-create
5201buffer)}. This expression uses the @code{get-buffer-create} function,
5202which either gets the named buffer, or if it does not exist, creates one
5203with the given name. This means you can use @code{append-to-buffer} to
5204put text into a buffer that did not previously exist.
5205
5206@code{get-buffer-create} also keeps @code{set-buffer} from getting an
5207unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5208were to specify a buffer that does not exist, Emacs would baulk.
5209Since @code{get-buffer-create} will create a buffer if none exists,
5210@code{set-buffer} is always provided with a buffer.
5211
5212@need 1250
5213The last line of @code{append-to-buffer} does the work of appending
5214the text:
5215
5216@smallexample
5217(insert-buffer-substring oldbuf start end)
5218@end smallexample
5219
5220@noindent
5221The @code{insert-buffer-substring} function copies a string @emph{from}
5222the buffer specified as its first argument and inserts the string into
5223the present buffer. In this case, the argument to
5224@code{insert-buffer-substring} is the value of the variable created and
5225bound by the @code{let}, namely the value of @code{oldbuf}, which was
5226the current buffer when you gave the @code{append-to-buffer} command.
5227
5228After @code{insert-buffer-substring} has done its work,
5229@code{save-excursion} will restore the action to the original buffer and
5230@code{append-to-buffer} will have done its job.
5231
5232@need 800
5233Written in skeletal form, the workings of the body look like this:
5234
5235@smallexample
5236@group
5237(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5238 (save-excursion ; @r{Keep track of buffer.}
5239 @var{change-buffer}
5240 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5241
5242 @var{change-back-to-original-buffer-when-finished}
5243@var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5244
5245@end group
5246@end smallexample
5247
5248In summary, @code{append-to-buffer} works as follows: it saves the value
5249of the current buffer in the variable called @code{oldbuf}. It gets the
5250new buffer, creating one if need be, and switches Emacs to it. Using
5251the value of @code{oldbuf}, it inserts the region of text from the old
5252buffer into the new buffer; and then using @code{save-excursion}, it
5253brings you back to your original buffer.
5254
5255In looking at @code{append-to-buffer}, you have explored a fairly
5256complex function. It shows how to use @code{let} and
5257@code{save-excursion}, and how to change to and come back from another
5258buffer. Many function definitions use @code{let},
5259@code{save-excursion}, and @code{set-buffer} this way.
5260
5261@node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5262@comment node-name, next, previous, up
5263@section Review
5264
5265Here is a brief summary of the various functions discussed in this chapter.
5266
5267@table @code
5268@item describe-function
5269@itemx describe-variable
5270Print the documentation for a function or variable.
5271Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5272
5273@item find-tag
5274Find the file containing the source for a function or variable and
5275switch buffers to it, positioning point at the beginning of the item.
5276Conventionally bound to @kbd{M-.} (that's a period following the
5277@key{META} key).
5278
5279@item save-excursion
5280Save the location of point and mark and restore their values after the
5281arguments to @code{save-excursion} have been evaluated. Also, remember
5282the current buffer and return to it.
5283
5284@item push-mark
5285Set mark at a location and record the value of the previous mark on the
5286mark ring. The mark is a location in the buffer that will keep its
5287relative position even if text is added to or removed from the buffer.
5288
5289@item goto-char
5290Set point to the location specified by the value of the argument, which
5291can be a number, a marker, or an expression that returns the number of
5292a position, such as @code{(point-min)}.
5293
5294@item insert-buffer-substring
5295Copy a region of text from a buffer that is passed to the function as
5296an argument and insert the region into the current buffer.
5297
5298@item mark-whole-buffer
5299Mark the whole buffer as a region. Normally bound to @kbd{C-x h}.
5300
5301@item set-buffer
5302Switch the attention of Emacs to another buffer, but do not change the
5303window being displayed. Used when the program rather than a human is
5304to work on a different buffer.
5305
5306@item get-buffer-create
5307@itemx get-buffer
5308Find a named buffer or create one if a buffer of that name does not
5309exist. The @code{get-buffer} function returns @code{nil} if the named
5310buffer does not exist.
5311@end table
5312
5313@need 1500
5314@node Buffer Exercises, , Buffer Related Review, Buffer Walk Through
5315@section Exercises
5316
5317@itemize @bullet
5318@item
5319Write your own @code{simplified-end-of-buffer} function definition;
5320then test it to see whether it works.
5321
5322@item
5323Use @code{if} and @code{get-buffer} to write a function that prints a
5324message telling you whether a buffer exists.
5325
5326@item
5327Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5328function.
5329@end itemize
5330
5331@node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5332@comment node-name, next, previous, up
5333@chapter A Few More Complex Functions
5334
5335In this chapter, we build on what we have learned in previous chapters
5336by looking at more complex functions. The @code{copy-to-buffer}
5337function illustrates use of two @code{save-excursion} expressions in
5338one definition, while the @code{insert-buffer} function illustrates
5339use of an asterisk in an @code{interactive} expression, use of
5340@code{or}, and the important distinction between a name and the object
5341to which the name refers.
5342
5343@menu
5344* copy-to-buffer:: With @code{set-buffer}, @code{get-buffer-create}.
5345* insert-buffer:: Read-only, and with @code{or}.
5346* beginning-of-buffer:: Shows @code{goto-char},
5347 @code{point-min}, and @code{push-mark}.
5348* Second Buffer Related Review::
5349* optional Exercise::
5350@end menu
5351
5352@node copy-to-buffer, insert-buffer, More Complex, More Complex
5353@comment node-name, next, previous, up
5354@section The Definition of @code{copy-to-buffer}
5355@findex copy-to-buffer
5356
5357After understanding how @code{append-to-buffer} works, it is easy to
5358understand @code{copy-to-buffer}. This function copies text into a
5359buffer, but instead of adding to the second buffer, it replaces the
5360previous text in the second buffer. The code for the
5361@code{copy-to-buffer} function is almost the same as the code for
5362@code{append-to-buffer}, except that @code{erase-buffer} and a second
5363@code{save-excursion} are used. (@xref{append-to-buffer, , The
5364Definition of @code{append-to-buffer}}, for the description of
5365@code{append-to-buffer}.)
5366
5367@need 800
5368The body of @code{copy-to-buffer} looks like this
5369
5370@smallexample
5371@group
5372@dots{}
5373(interactive "BCopy to buffer:@: \nr")
5374 (let ((oldbuf (current-buffer)))
5375 (save-excursion
5376 (set-buffer (get-buffer-create buffer))
5377 (erase-buffer)
5378 (save-excursion
5379 (insert-buffer-substring oldbuf start end)))))
5380@end group
5381@end smallexample
5382
5383This code is similar to the code in @code{append-to-buffer}: it is
5384only after changing to the buffer to which the text will be copied
5385that the definition for this function diverges from the definition for
5386@code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5387buffer's former contents. (This is what is meant by `replacement'; to
5388replace text, Emacs erases the previous text and then inserts new
5389text.) After erasing the previous contents of the buffer,
5390@code{save-excursion} is used for a second time and the new text is
5391inserted.
5392
5393Why is @code{save-excursion} used twice? Consider again what the
5394function does.
5395
5396@need 1250
5397In outline, the body of @code{copy-to-buffer} looks like this:
5398
5399@smallexample
5400@group
5401(let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5402 (save-excursion ; @r{First use of @code{save-excursion}.}
5403 @var{change-buffer}
5404 (erase-buffer)
5405 (save-excursion ; @r{Second use of @code{save-excursion}.}
5406 @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5407@end group
5408@end smallexample
5409
5410The first use of @code{save-excursion} returns Emacs to the buffer from
5411which the text is being copied. That is clear, and is just like its use
5412in @code{append-to-buffer}. Why the second use? The reason is that
5413@code{insert-buffer-substring} always leaves point at the @emph{end} of
5414the region being inserted. The second @code{save-excursion} causes
5415Emacs to leave point at the beginning of the text being inserted. In
5416most circumstances, users prefer to find point at the beginning of
5417inserted text. (Of course, the @code{copy-to-buffer} function returns
5418the user to the original buffer when done---but if the user @emph{then}
5419switches to the copied-to buffer, point will go to the beginning of the
5420text. Thus, this use of a second @code{save-excursion} is a little
5421nicety.)
5422
5423@node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5424@comment node-name, next, previous, up
5425@section The Definition of @code{insert-buffer}
5426@findex insert-buffer
5427
5428@code{insert-buffer} is yet another buffer-related function. This
5429command copies another buffer @emph{into} the current buffer. It is the
5430reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5431copy a region of text @emph{from} the current buffer to another buffer.
5432
c6f54b06
RC
5433Here is a discussion based on the original code. The code was
5434simplified in 2003 and is harder to understand.
5435
8b096dce
EZ
5436In addition, this code illustrates the use of @code{interactive} with a
5437buffer that might be @dfn{read-only} and the important distinction
5438between the name of an object and the object actually referred to.
5439
5440@menu
5441* insert-buffer code::
5442* insert-buffer interactive:: When you can read, but not write.
5443* insert-buffer body:: The body has an @code{or} and a @code{let}.
5444* if & or:: Using an @code{if} instead of an @code{or}.
5445* Insert or:: How the @code{or} expression works.
5446* Insert let:: Two @code{save-excursion} expressions.
5447@end menu
5448
5449@node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5450@ifnottex
5451@unnumberedsubsec The Code for @code{insert-buffer}
5452@end ifnottex
5453
5454@need 800
5455Here is the code:
5456
5457@smallexample
5458@group
5459(defun insert-buffer (buffer)
5460 "Insert after point the contents of BUFFER.
5461Puts mark after the inserted text.
5462BUFFER may be a buffer or a buffer name."
5463 (interactive "*bInsert buffer:@: ")
5464@end group
5465@group
5466 (or (bufferp buffer)
5467 (setq buffer (get-buffer buffer)))
5468 (let (start end newmark)
5469 (save-excursion
5470 (save-excursion
5471 (set-buffer buffer)
5472 (setq start (point-min) end (point-max)))
5473@end group
5474@group
5475 (insert-buffer-substring buffer start end)
5476 (setq newmark (point)))
5477 (push-mark newmark)))
5478@end group
5479@end smallexample
5480
5481@need 1200
5482As with other function definitions, you can use a template to see an
5483outline of the function:
5484
5485@smallexample
5486@group
5487(defun insert-buffer (buffer)
5488 "@var{documentation}@dots{}"
5489 (interactive "*bInsert buffer:@: ")
5490 @var{body}@dots{})
5491@end group
5492@end smallexample
5493
5494@node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5495@comment node-name, next, previous, up
5496@subsection The Interactive Expression in @code{insert-buffer}
5497@findex interactive, @r{example use of}
5498
5499In @code{insert-buffer}, the argument to the @code{interactive}
5500declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5501buffer:@: }.
5502
5503@menu
5504* Read-only buffer:: When a buffer cannot be modified.
5505* b for interactive:: An existing buffer or else its name.
5506@end menu
5507
5508@node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5509@comment node-name, next, previous, up
5510@unnumberedsubsubsec A Read-only Buffer
5511@cindex Read-only buffer
5512@cindex Asterisk for read-only buffer
5513@findex * @r{for read-only buffer}
5514
e601d8fd
RC
5515The asterisk is for the situation when the current buffer is a
5516read-only buffer---a buffer that cannot be modified. If
5517@code{insert-buffer} is called when the current buffer is read-only, a
5518message to this effect is printed in the echo area and the terminal
5519may beep or blink at you; you will not be permitted to insert anything
5520into current buffer. The asterisk does not need to be followed by a
5521newline to separate it from the next argument.
8b096dce
EZ
5522
5523@node b for interactive, , Read-only buffer, insert-buffer interactive
5524@comment node-name, next, previous, up
5525@unnumberedsubsubsec @samp{b} in an Interactive Expression
5526
5527The next argument in the interactive expression starts with a lower
5528case @samp{b}. (This is different from the code for
5529@code{append-to-buffer}, which uses an upper-case @samp{B}.
5530@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5531The lower-case @samp{b} tells the Lisp interpreter that the argument
5532for @code{insert-buffer} should be an existing buffer or else its
5533name. (The upper-case @samp{B} option provides for the possibility
5534that the buffer does not exist.) Emacs will prompt you for the name
5535of the buffer, offering you a default buffer, with name completion
5536enabled. If the buffer does not exist, you receive a message that
5537says ``No match''; your terminal may beep at you as well.
5538
5539@node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5540@comment node-name, next, previous, up
5541@subsection The Body of the @code{insert-buffer} Function
5542
5543The body of the @code{insert-buffer} function has two major parts: an
5544@code{or} expression and a @code{let} expression. The purpose of the
5545@code{or} expression is to ensure that the argument @code{buffer} is
5546bound to a buffer and not just the name of a buffer. The body of the
5547@code{let} expression contains the code which copies the other buffer
5548into the current buffer.
5549
5550@need 1250
5551In outline, the two expressions fit into the @code{insert-buffer}
5552function like this:
5553
5554@smallexample
5555@group
5556(defun insert-buffer (buffer)
5557 "@var{documentation}@dots{}"
5558 (interactive "*bInsert buffer:@: ")
5559 (or @dots{}
5560 @dots{}
5561@end group
5562@group
5563 (let (@var{varlist})
5564 @var{body-of-}@code{let}@dots{} )
5565@end group
5566@end smallexample
5567
5568To understand how the @code{or} expression ensures that the argument
5569@code{buffer} is bound to a buffer and not to the name of a buffer, it
5570is first necessary to understand the @code{or} function.
5571
5572Before doing this, let me rewrite this part of the function using
5573@code{if} so that you can see what is done in a manner that will be familiar.
5574
5575@node if & or, Insert or, insert-buffer body, insert-buffer
5576@comment node-name, next, previous, up
5577@subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5578
5579The job to be done is to make sure the value of @code{buffer} is a
5580buffer itself and not the name of a buffer. If the value is the name,
5581then the buffer itself must be got.
5582
5583You can imagine yourself at a conference where an usher is wandering
5584around holding a list with your name on it and looking for you: the
5585usher is ``bound'' to your name, not to you; but when the usher finds
5586you and takes your arm, the usher becomes ``bound'' to you.
5587
5588@need 800
5589In Lisp, you might describe this situation like this:
5590
5591@smallexample
5592@group
5593(if (not (holding-on-to-guest))
5594 (find-and-take-arm-of-guest))
5595@end group
5596@end smallexample
5597
5598We want to do the same thing with a buffer---if we do not have the
5599buffer itself, we want to get it.
5600
5601@need 1200
5602Using a predicate called @code{bufferp} that tells us whether we have a
5603buffer (rather than its name), we can write the code like this:
5604
5605@smallexample
5606@group
5607(if (not (bufferp buffer)) ; @r{if-part}
5608 (setq buffer (get-buffer buffer))) ; @r{then-part}
5609@end group
5610@end smallexample
5611
5612@noindent
5613Here, the true-or-false-test of the @code{if} expression is
5614@w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5615@w{@code{(setq buffer (get-buffer buffer))}}.
5616
5617In the test, the function @code{bufferp} returns true if its argument is
5618a buffer---but false if its argument is the name of the buffer. (The
5619last character of the function name @code{bufferp} is the character
5620@samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5621indicates that the function is a predicate, which is a term that means
5622that the function will determine whether some property is true or false.
5623@xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5624Argument}.)
5625
5626@need 1200
5627The function @code{not} precedes the expression @code{(bufferp buffer)},
5628so the true-or-false-test looks like this:
5629
5630@smallexample
5631(not (bufferp buffer))
5632@end smallexample
5633
5634@noindent
5635@code{not} is a function that returns true if its argument is false
5636and false if its argument is true. So if @code{(bufferp buffer)}
5637returns true, the @code{not} expression returns false and vice-versa:
5638what is ``not true'' is false and what is ``not false'' is true.
5639
5640Using this test, the @code{if} expression works as follows: when the
f5cb0355 5641value of the variable @code{buffer} is actually a buffer rather than
8b096dce
EZ
5642its name, the true-or-false-test returns false and the @code{if}
5643expression does not evaluate the then-part. This is fine, since we do
5644not need to do anything to the variable @code{buffer} if it really is
5645a buffer.
5646
5647On the other hand, when the value of @code{buffer} is not a buffer
5648itself, but the name of a buffer, the true-or-false-test returns true
5649and the then-part of the expression is evaluated. In this case, the
5650then-part is @code{(setq buffer (get-buffer buffer))}. This
5651expression uses the @code{get-buffer} function to return an actual
5652buffer itself, given its name. The @code{setq} then sets the variable
5653@code{buffer} to the value of the buffer itself, replacing its previous
5654value (which was the name of the buffer).
5655
5656@node Insert or, Insert let, if & or, insert-buffer
5657@comment node-name, next, previous, up
5658@subsection The @code{or} in the Body
5659
5660The purpose of the @code{or} expression in the @code{insert-buffer}
5661function is to ensure that the argument @code{buffer} is bound to a
5662buffer and not just to the name of a buffer. The previous section shows
5663how the job could have been done using an @code{if} expression.
5664However, the @code{insert-buffer} function actually uses @code{or}.
5665To understand this, it is necessary to understand how @code{or} works.
5666
5667@findex or
5668An @code{or} function can have any number of arguments. It evaluates
5669each argument in turn and returns the value of the first of its
5670arguments that is not @code{nil}. Also, and this is a crucial feature
5671of @code{or}, it does not evaluate any subsequent arguments after
5672returning the first non-@code{nil} value.
5673
5674@need 800
5675The @code{or} expression looks like this:
5676
5677@smallexample
5678@group
5679(or (bufferp buffer)
5680 (setq buffer (get-buffer buffer)))
5681@end group
5682@end smallexample
5683
5684@noindent
5685The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5686This expression returns true (a non-@code{nil} value) if the buffer is
5687actually a buffer, and not just the name of a buffer. In the @code{or}
5688expression, if this is the case, the @code{or} expression returns this
5689true value and does not evaluate the next expression---and this is fine
5690with us, since we do not want to do anything to the value of
5691@code{buffer} if it really is a buffer.
5692
5693On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5694which it will be if the value of @code{buffer} is the name of a buffer,
5695the Lisp interpreter evaluates the next element of the @code{or}
5696expression. This is the expression @code{(setq buffer (get-buffer
5697buffer))}. This expression returns a non-@code{nil} value, which
5698is the value to which it sets the variable @code{buffer}---and this
5699value is a buffer itself, not the name of a buffer.
5700
5701The result of all this is that the symbol @code{buffer} is always
5702bound to a buffer itself rather than to the name of a buffer. All
5703this is necessary because the @code{set-buffer} function in a
5704following line only works with a buffer itself, not with the name to a
5705buffer.
5706
5707@need 1250
5708Incidentally, using @code{or}, the situation with the usher would be
5709written like this:
5710
5711@smallexample
5712(or (holding-on-to-guest) (find-and-take-arm-of-guest))
5713@end smallexample
5714
5715@node Insert let, , Insert or, insert-buffer
5716@comment node-name, next, previous, up
5717@subsection The @code{let} Expression in @code{insert-buffer}
5718
5719After ensuring that the variable @code{buffer} refers to a buffer itself
5720and not just to the name of a buffer, the @code{insert-buffer function}
5721continues with a @code{let} expression. This specifies three local
5722variables, @code{start}, @code{end}, and @code{newmark} and binds them
5723to the initial value @code{nil}. These variables are used inside the
5724remainder of the @code{let} and temporarily hide any other occurrence of
5725variables of the same name in Emacs until the end of the @code{let}.
5726
5727@need 1200
5728The body of the @code{let} contains two @code{save-excursion}
5729expressions. First, we will look at the inner @code{save-excursion}
5730expression in detail. The expression looks like this:
5731
5732@smallexample
5733@group
5734(save-excursion
5735 (set-buffer buffer)
5736 (setq start (point-min) end (point-max)))
5737@end group
5738@end smallexample
5739
5740@noindent
5741The expression @code{(set-buffer buffer)} changes Emacs' attention
5742from the current buffer to the one from which the text will copied.
5743In that buffer, the variables @code{start} and @code{end} are set to
5744the beginning and end of the buffer, using the commands
5745@code{point-min} and @code{point-max}. Note that we have here an
5746illustration of how @code{setq} is able to set two variables in the
5747same expression. The first argument of @code{setq} is set to the
5748value of its second, and its third argument is set to the value of its
5749fourth.
5750
5751After the body of the inner @code{save-excursion} is evaluated, the
5752@code{save-excursion} restores the original buffer, but @code{start} and
5753@code{end} remain set to the values of the beginning and end of the
5754buffer from which the text will be copied.
5755
5756@need 1250
5757The outer @code{save-excursion} expression looks like this:
5758
5759@smallexample
5760@group
5761(save-excursion
5762 (@var{inner-}@code{save-excursion}@var{-expression}
5763 (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5764 (insert-buffer-substring buffer start end)
5765 (setq newmark (point)))
5766@end group
5767@end smallexample
5768
5769@noindent
5770The @code{insert-buffer-substring} function copies the text
5771@emph{into} the current buffer @emph{from} the region indicated by
5772@code{start} and @code{end} in @code{buffer}. Since the whole of the
5773second buffer lies between @code{start} and @code{end}, the whole of
5774the second buffer is copied into the buffer you are editing. Next,
5775the value of point, which will be at the end of the inserted text, is
5776recorded in the variable @code{newmark}.
5777
5778After the body of the outer @code{save-excursion} is evaluated, point
5779and mark are relocated to their original places.
5780
5781However, it is convenient to locate a mark at the end of the newly
5782inserted text and locate point at its beginning. The @code{newmark}
5783variable records the end of the inserted text. In the last line of
5784the @code{let} expression, the @code{(push-mark newmark)} expression
5785function sets a mark to this location. (The previous location of the
5786mark is still accessible; it is recorded on the mark ring and you can
5787go back to it with @kbd{C-u C-@key{SPC}}.) Meanwhile, point is
5788located at the beginning of the inserted text, which is where it was
c6f54b06
RC
5789before you called the insert function, the position of which was saved
5790by the first @code{save-excursion}.
8b096dce
EZ
5791
5792@need 1250
5793The whole @code{let} expression looks like this:
5794
5795@smallexample
5796@group
5797(let (start end newmark)
5798 (save-excursion
5799 (save-excursion
5800 (set-buffer buffer)
5801 (setq start (point-min) end (point-max)))
5802 (insert-buffer-substring buffer start end)
5803 (setq newmark (point)))
5804 (push-mark newmark))
5805@end group
5806@end smallexample
5807
5808Like the @code{append-to-buffer} function, the @code{insert-buffer}
5809function uses @code{let}, @code{save-excursion}, and
5810@code{set-buffer}. In addition, the function illustrates one way to
5811use @code{or}. All these functions are building blocks that we will
5812find and use again and again.
5813
5814@node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5815@comment node-name, next, previous, up
5816@section Complete Definition of @code{beginning-of-buffer}
5817@findex beginning-of-buffer
5818
5819The basic structure of the @code{beginning-of-buffer} function has
5820already been discussed. (@xref{simplified-beginning-of-buffer, , A
5821Simplified @code{beginning-of-buffer} Definition}.)
5822This section describes the complex part of the definition.
5823
5824As previously described, when invoked without an argument,
5825@code{beginning-of-buffer} moves the cursor to the beginning of the
5826buffer, leaving the mark at the previous position. However, when the
5827command is invoked with a number between one and ten, the function
5828considers that number to be a fraction of the length of the buffer,
5829measured in tenths, and Emacs moves the cursor that fraction of the way
5830from the beginning of the buffer. Thus, you can either call this
5831function with the key command @kbd{M-<}, which will move the cursor to
5832the beginning of the buffer, or with a key command such as @kbd{C-u 7
5833M-<} which will move the cursor to a point 70% of the way through the
5834buffer. If a number bigger than ten is used for the argument, it moves
5835to the end of the buffer.
5836
5837The @code{beginning-of-buffer} function can be called with or without an
5838argument. The use of the argument is optional.
5839
5840@menu
5841* Optional Arguments::
5842* beginning-of-buffer opt arg:: Example with optional argument.
5843* beginning-of-buffer complete::
5844@end menu
5845
5846@node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5847@subsection Optional Arguments
5848
5849Unless told otherwise, Lisp expects that a function with an argument in
5850its function definition will be called with a value for that argument.
5851If that does not happen, you get an error and a message that says
5852@samp{Wrong number of arguments}.
5853
5854@cindex Optional arguments
5855@cindex Keyword
5856@findex optional
5857However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5858be used to tell the Lisp interpreter that an argument is optional.
5859The keyword is @code{&optional}. (The @samp{&} in front of
5860@samp{optional} is part of the keyword.) In a function definition, if
5861an argument follows the keyword @code{&optional}, a value does not
5862need to be passed to that argument when the function is called.
5863
5864@need 1200
5865The first line of the function definition of @code{beginning-of-buffer}
5866therefore looks like this:
5867
5868@smallexample
5869(defun beginning-of-buffer (&optional arg)
5870@end smallexample
5871
5872@need 1250
5873In outline, the whole function looks like this:
5874
5875@smallexample
5876@group
5877(defun beginning-of-buffer (&optional arg)
5878 "@var{documentation}@dots{}"
5879 (interactive "P")
5880 (push-mark)
5881 (goto-char
5882 (@var{if-there-is-an-argument}
5883 @var{figure-out-where-to-go}
5884 @var{else-go-to}
5885 (point-min))))
5886@end group
5887@end smallexample
5888
5889The function is similar to the @code{simplified-beginning-of-buffer}
5890function except that the @code{interactive} expression has @code{"P"}
5891as an argument and the @code{goto-char} function is followed by an
5892if-then-else expression that figures out where to put the cursor if
5893there is an argument.
5894
5895The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5896a prefix argument, if there is one, to the function. A prefix argument
5897is made by typing the @key{META} key followed by a number, or by typing
5898@kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5899defaults to 4).
5900
5901The true-or-false-test of the @code{if} expression is simple: it is
5902simply the argument @code{arg}. If @code{arg} has a value that is not
5903@code{nil}, which will be the case if @code{beginning-of-buffer} is
5904called with an argument, then this true-or-false-test will return true
5905and the then-part of the @code{if} expression will be evaluated. On the
5906other hand, if @code{beginning-of-buffer} is not called with an
5907argument, the value of @code{arg} will be @code{nil} and the else-part
5908of the @code{if} expression will be evaluated. The else-part is simply
5909@code{point-min}, and when this is the outcome, the whole
5910@code{goto-char} expression is @code{(goto-char (point-min))}, which is
5911how we saw the @code{beginning-of-buffer} function in its simplified
5912form.
5913
5914@node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5915@subsection @code{beginning-of-buffer} with an Argument
5916
5917When @code{beginning-of-buffer} is called with an argument, an
5918expression is evaluated which calculates what value to pass to
5919@code{goto-char}. This expression is rather complicated at first sight.
5920It includes an inner @code{if} expression and much arithmetic. It looks
5921like this:
5922
5923@smallexample
5924@group
5925(if (> (buffer-size) 10000)
5926 ;; @r{Avoid overflow for large buffer sizes!}
5927 (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5928 (/
5929 (+ 10
5930 (*
5931 (buffer-size) (prefix-numeric-value arg))) 10))
5932@end group
5933@end smallexample
5934
5935@menu
5936* Disentangle beginning-of-buffer::
5937* Large buffer case::
5938* Small buffer case::
5939@end menu
5940
5941@node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5942@ifnottex
5943@unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5944@end ifnottex
5945
5946Like other complex-looking expressions, the conditional expression
5947within @code{beginning-of-buffer} can be disentangled by looking at it
5948as parts of a template, in this case, the template for an if-then-else
5949expression. In skeletal form, the expression looks like this:
5950
5951@smallexample
5952@group
5953(if (@var{buffer-is-large}
5954 @var{divide-buffer-size-by-10-and-multiply-by-arg}
5955 @var{else-use-alternate-calculation}
5956@end group
5957@end smallexample
5958
5959The true-or-false-test of this inner @code{if} expression checks the
5960size of the buffer. The reason for this is that the old Version 18
5961Emacs used numbers that are no bigger than eight million or so
5962and in the computation that followed, the programmer feared that Emacs
5963might try to use over-large numbers if the buffer were large. The
5964term `overflow', mentioned in the comment, means numbers that are over
5965large. Version 21 Emacs uses larger numbers, but this code has not
5966been touched, if only because people now look at buffers that are far,
5967far larger than ever before.
5968
5969There are two cases: if the buffer is large and if it is not.
5970
5971@node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
5972@comment node-name, next, previous, up
5973@unnumberedsubsubsec What happens in a large buffer
5974
5975In @code{beginning-of-buffer}, the inner @code{if} expression tests
5976whether the size of the buffer is greater than 10,000 characters. To do
5977this, it uses the @code{>} function and the @code{buffer-size} function.
5978
5979@need 800
5980The line looks like this:
5981
5982@smallexample
5983(if (> (buffer-size) 10000)
5984@end smallexample
5985
5986@need 1200
5987@noindent
5988When the buffer is large, the then-part of the @code{if} expression is
5989evaluated. It reads like this (after formatting for easy reading):
5990
5991@smallexample
5992@group
5993(*
5994 (prefix-numeric-value arg)
5995 (/ (buffer-size) 10))
5996@end group
5997@end smallexample
5998
5999@noindent
6000This expression is a multiplication, with two arguments to the function
6001@code{*}.
6002
6003The first argument is @code{(prefix-numeric-value arg)}. When
6004@code{"P"} is used as the argument for @code{interactive}, the value
6005passed to the function as its argument is passed a ``raw prefix
6006argument'', and not a number. (It is a number in a list.) To perform
6007the arithmetic, a conversion is necessary, and
6008@code{prefix-numeric-value} does the job.
6009
6010@findex / @r{(division)}
6011@cindex Division
6012The second argument is @code{(/ (buffer-size) 10)}. This expression
6013divides the numeric value of the buffer by ten. This produces a number
6014that tells how many characters make up one tenth of the buffer size.
6015(In Lisp, @code{/} is used for division, just as @code{*} is
6016used for multiplication.)
6017
6018@need 1200
6019In the multiplication expression as a whole, this amount is multiplied
6020by the value of the prefix argument---the multiplication looks like this:
6021
6022@smallexample
6023@group
6024(* @var{numeric-value-of-prefix-arg}
6025 @var{number-of-characters-in-one-tenth-of-the-buffer})
6026@end group
6027@end smallexample
6028
6029@noindent
6030If, for example, the prefix argument is @samp{7}, the one-tenth value
6031will be multiplied by 7 to give a position 70% of the way through the
6032buffer.
6033
6034@need 1200
6035The result of all this is that if the buffer is large, the
6036@code{goto-char} expression reads like this:
6037
6038@smallexample
6039@group
6040(goto-char (* (prefix-numeric-value arg)
6041 (/ (buffer-size) 10)))
6042@end group
6043@end smallexample
6044
6045This puts the cursor where we want it.
6046
6047@node Small buffer case, , Large buffer case, beginning-of-buffer opt arg
6048@comment node-name, next, previous, up
6049@unnumberedsubsubsec What happens in a small buffer
6050
6051If the buffer contains fewer than 10,000 characters, a slightly
6052different computation is performed. You might think this is not
6053necessary, since the first computation could do the job. However, in
6054a small buffer, the first method may not put the cursor on exactly the
6055desired line; the second method does a better job.
6056
6057@need 800
6058The code looks like this:
6059
6060@c Keep this on one line.
6061@smallexample
6062(/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6063@end smallexample
6064
6065@need 1200
6066@noindent
6067This is code in which you figure out what happens by discovering how the
6068functions are embedded in parentheses. It is easier to read if you
6069reformat it with each expression indented more deeply than its
6070enclosing expression:
6071
6072@smallexample
6073@group
6074 (/
6075 (+ 10
6076 (*
6077 (buffer-size)
6078 (prefix-numeric-value arg)))
6079 10))
6080@end group
6081@end smallexample
6082
6083@need 1200
6084@noindent
6085Looking at parentheses, we see that the innermost operation is
6086@code{(prefix-numeric-value arg)}, which converts the raw argument to a
6087number. This number is multiplied by the buffer size in the following
6088expression:
6089
6090@smallexample
6091(* (buffer-size) (prefix-numeric-value arg)
6092@end smallexample
6093
6094@noindent
6095This multiplication creates a number that may be larger than the size of
6096the buffer---seven times larger if the argument is 7, for example. Ten
6097is then added to this number and finally the large number is divided by
6098ten to provide a value that is one character larger than the percentage
6099position in the buffer.
6100
6101The number that results from all this is passed to @code{goto-char} and
6102the cursor is moved to that point.
6103
c6f54b06 6104@need 1500
8b096dce
EZ
6105@node beginning-of-buffer complete, , beginning-of-buffer opt arg, beginning-of-buffer
6106@comment node-name, next, previous, up
6107@subsection The Complete @code{beginning-of-buffer}
6108
c6f54b06 6109@need 1000
8b096dce 6110Here is the complete text of the @code{beginning-of-buffer} function:
c6f54b06 6111@sp 1
8b096dce
EZ
6112
6113@smallexample
6114@group
6115(defun beginning-of-buffer (&optional arg)
6116 "Move point to the beginning of the buffer;
6117leave mark at previous position.
6118With arg N, put point N/10 of the way
6119from the true beginning.
c6f54b06
RC
6120@end group
6121@group
8b096dce
EZ
6122Don't use this in Lisp programs!
6123\(goto-char (point-min)) is faster
6124and does not set the mark."
6125 (interactive "P")
6126 (push-mark)
6127@end group
6128@group
6129 (goto-char
6130 (if arg
6131 (if (> (buffer-size) 10000)
6132 ;; @r{Avoid overflow for large buffer sizes!}
6133 (* (prefix-numeric-value arg)
6134 (/ (buffer-size) 10))
6135@end group
6136@group
6137 (/ (+ 10 (* (buffer-size)
6138 (prefix-numeric-value arg)))
6139 10))
6140 (point-min)))
6141 (if arg (forward-line 1)))
6142@end group
6143@end smallexample
6144
6145@noindent
6146Except for two small points, the previous discussion shows how this
6147function works. The first point deals with a detail in the
6148documentation string, and the second point concerns the last line of
6149the function.
6150
6151@need 800
6152In the documentation string, there is reference to an expression:
6153
6154@smallexample
6155\(goto-char (point-min))
6156@end smallexample
6157
6158@noindent
6159A @samp{\} is used before the first parenthesis of this expression.
6160This @samp{\} tells the Lisp interpreter that the expression should be
6161printed as shown in the documentation rather than evaluated as a
6162symbolic expression, which is what it looks like.
6163
6164@need 1200
6165Finally, the last line of the @code{beginning-of-buffer} command says to
6166move point to the beginning of the next line if the command is
6167invoked with an argument:
6168
6169@smallexample
6170(if arg (forward-line 1)))
6171@end smallexample
6172
6173@noindent
6174This puts the cursor at the beginning of the first line after the
6175appropriate tenths position in the buffer. This is a flourish that
6176means that the cursor is always located @emph{at least} the requested
6177tenths of the way through the buffer, which is a nicety that is,
6178perhaps, not necessary, but which, if it did not occur, would be sure to
6179draw complaints.
6180
6181@node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6182@comment node-name, next, previous, up
6183@section Review
6184
6185Here is a brief summary of some of the topics covered in this chapter.
6186
6187@table @code
6188@item or
6189Evaluate each argument in sequence, and return the value of the first
6190argument that is not @code{nil}; if none return a value that is not
6191@code{nil}, return @code{nil}. In brief, return the first true value
6192of the arguments; return a true value if one @emph{or} any of the
6193other are true.
6194
6195@item and
6196Evaluate each argument in sequence, and if any are @code{nil}, return
6197@code{nil}; if none are @code{nil}, return the value of the last
6198argument. In brief, return a true value only if all the arguments are
6199true; return a true value if one @emph{and} each of the others is
6200true.
6201
6202@item &optional
6203A keyword used to indicate that an argument to a function definition
6204is optional; this means that the function can be evaluated without the
6205argument, if desired.
6206
6207@item prefix-numeric-value
6208Convert the `raw prefix argument' produced by @code{(interactive
6209"P")} to a numeric value.
6210
6211@item forward-line
6212Move point forward to the beginning of the next line, or if the argument
6213is greater than one, forward that many lines. If it can't move as far
6214forward as it is supposed to, @code{forward-line} goes forward as far as
6215it can and then returns a count of the number of additional lines it was
6216supposed to move but couldn't.
6217
6218@item erase-buffer
6219Delete the entire contents of the current buffer.
6220
6221@item bufferp
6222Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6223@end table
6224
6225@node optional Exercise, , Second Buffer Related Review, More Complex
6226@section @code{optional} Argument Exercise
6227
6228Write an interactive function with an optional argument that tests
c6f54b06
RC
6229whether its argument, a number, is greater than or equal to, or else,
6230less than the value of @code{fill-column}, and tells you which, in a
6231message. However, if you do not pass an argument to the function, use
623256 as a default value.
8b096dce
EZ
6233
6234@node Narrowing & Widening, car cdr & cons, More Complex, Top
6235@comment node-name, next, previous, up
6236@chapter Narrowing and Widening
6237@cindex Focusing attention (narrowing)
6238@cindex Narrowing
6239@cindex Widening
6240
6241Narrowing is a feature of Emacs that makes it possible for you to focus
6242on a specific part of a buffer, and work without accidentally changing
6243other parts. Narrowing is normally disabled since it can confuse
6244novices.
6245
6246@menu
6247* Narrowing advantages:: The advantages of narrowing
6248* save-restriction:: The @code{save-restriction} special form.
6249* what-line:: The number of the line that point is on.
6250* narrow Exercise::
6251@end menu
6252
6253@node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6254@ifnottex
6255@unnumberedsec The Advantages of Narrowing
6256@end ifnottex
6257
6258With narrowing, the rest of a buffer is made invisible, as if it weren't
6259there. This is an advantage if, for example, you want to replace a word
6260in one part of a buffer but not in another: you narrow to the part you want
6261and the replacement is carried out only in that section, not in the rest
6262of the buffer. Searches will only work within a narrowed region, not
6263outside of one, so if you are fixing a part of a document, you can keep
6264yourself from accidentally finding parts you do not need to fix by
6265narrowing just to the region you want.
6266(The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6267
6268However, narrowing does make the rest of the buffer invisible, which
6269can scare people who inadvertently invoke narrowing and think they
6270have deleted a part of their file. Moreover, the @code{undo} command
6271(which is usually bound to @kbd{C-x u}) does not turn off narrowing
6272(nor should it), so people can become quite desperate if they do not
6273know that they can return the rest of a buffer to visibility with the
6274@code{widen} command.
6275(The key binding for @code{widen} is @kbd{C-x n w}.)
6276
6277Narrowing is just as useful to the Lisp interpreter as to a human.
6278Often, an Emacs Lisp function is designed to work on just part of a
6279buffer; or conversely, an Emacs Lisp function needs to work on all of a
6280buffer that has been narrowed. The @code{what-line} function, for
6281example, removes the narrowing from a buffer, if it has any narrowing
6282and when it has finished its job, restores the narrowing to what it was.
6283On the other hand, the @code{count-lines} function, which is called by
6284@code{what-line}, uses narrowing to restrict itself to just that portion
6285of the buffer in which it is interested and then restores the previous
6286situation.
6287
6288@node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6289@comment node-name, next, previous, up
6290@section The @code{save-restriction} Special Form
6291@findex save-restriction
6292
6293In Emacs Lisp, you can use the @code{save-restriction} special form to
6294keep track of whatever narrowing is in effect, if any. When the Lisp
6295interpreter meets with @code{save-restriction}, it executes the code
6296in the body of the @code{save-restriction} expression, and then undoes
6297any changes to narrowing that the code caused. If, for example, the
6298buffer is narrowed and the code that follows @code{save-restriction}
6299gets rid of the narrowing, @code{save-restriction} returns the buffer
6300to its narrowed region afterwards. In the @code{what-line} command,
6301any narrowing the buffer may have is undone by the @code{widen}
6302command that immediately follows the @code{save-restriction} command.
6303Any original narrowing is restored just before the completion of the
6304function.
6305
6306@need 1250
6307The template for a @code{save-restriction} expression is simple:
6308
6309@smallexample
6310@group
6311(save-restriction
6312 @var{body}@dots{} )
6313@end group
6314@end smallexample
6315
6316@noindent
6317The body of the @code{save-restriction} is one or more expressions that
6318will be evaluated in sequence by the Lisp interpreter.
6319
6320Finally, a point to note: when you use both @code{save-excursion} and
6321@code{save-restriction}, one right after the other, you should use
6322@code{save-excursion} outermost. If you write them in reverse order,
6323you may fail to record narrowing in the buffer to which Emacs switches
6324after calling @code{save-excursion}. Thus, when written together,
6325@code{save-excursion} and @code{save-restriction} should be written
6326like this:
6327
6328@smallexample
6329@group
6330(save-excursion
6331 (save-restriction
6332 @var{body}@dots{}))
6333@end group
6334@end smallexample
6335
6336In other circumstances, when not written together, the
6337@code{save-excursion} and @code{save-restriction} special forms must
6338be written in the order appropriate to the function.
6339
6340@need 1250
6341For example,
6342
6343@smallexample
6344@group
6345 (save-restriction
6346 (widen)
6347 (save-excursion
6348 @var{body}@dots{}))
6349@end group
6350@end smallexample
6351
6352@node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6353@comment node-name, next, previous, up
6354@section @code{what-line}
6355@findex what-line
6356@cindex Widening, example of
6357
6358The @code{what-line} command tells you the number of the line in which
6359the cursor is located. The function illustrates the use of the
6360@code{save-restriction} and @code{save-excursion} commands. Here is the
c6f54b06 6361original text of the function:
8b096dce
EZ
6362
6363@smallexample
6364@group
6365(defun what-line ()
6366 "Print the current line number (in the buffer) of point."
6367 (interactive)
6368 (save-restriction
6369 (widen)
6370 (save-excursion
6371 (beginning-of-line)
6372 (message "Line %d"
6373 (1+ (count-lines 1 (point)))))))
6374@end group
6375@end smallexample
6376
c6f54b06
RC
6377(In recent versions of GNU Emacs, the @code{what-line} function has
6378been expanded to tell you your line number in a narrowed buffer as
6379well as your line number in a widened buffer. The recent version is
6380more complex than the version shown here. If you feel adventurous,
6381you might want to look at it after figuring out how this version
6382works. The newer version uses a conditional to determine whether the
6383buffer has been narrowed, and rather than use @code{beginning-of-line}
6384to move point to the beginning of the current line, if need be, the
6385function uses @code{(forward-line 0)}.)
6386
6387The function as shown here has a documentation line and is
6388interactive, as you would expect. The next two lines use the
6389functions @code{save-restriction} and @code{widen}.
8b096dce
EZ
6390
6391The @code{save-restriction} special form notes whatever narrowing is in
6392effect, if any, in the current buffer and restores that narrowing after
6393the code in the body of the @code{save-restriction} has been evaluated.
6394
6395The @code{save-restriction} special form is followed by @code{widen}.
6396This function undoes any narrowing the current buffer may have had
6397when @code{what-line} was called. (The narrowing that was there is
6398the narrowing that @code{save-restriction} remembers.) This widening
6399makes it possible for the line counting commands to count from the
6400beginning of the buffer. Otherwise, they would have been limited to
6401counting within the accessible region. Any original narrowing is
6402restored just before the completion of the function by the
6403@code{save-restriction} special form.
6404
6405The call to @code{widen} is followed by @code{save-excursion}, which
6406saves the location of the cursor (i.e., of point) and of the mark, and
6407restores them after the code in the body of the @code{save-excursion}
6408uses the @code{beginning-of-line} function to move point.
6409
6410(Note that the @code{(widen)} expression comes between the
6411@code{save-restriction} and @code{save-excursion} special forms. When
6412you write the two @code{save- @dots{}} expressions in sequence, write
6413@code{save-excursion} outermost.)
6414
6415@need 1200
6416The last two lines of the @code{what-line} function are functions to
6417count the number of lines in the buffer and then print the number in the
6418echo area.
6419
6420@smallexample
6421@group
6422(message "Line %d"
6423 (1+ (count-lines 1 (point)))))))
6424@end group
6425@end smallexample
6426
6427The @code{message} function prints a one-line message at the bottom of the
6428Emacs screen. The first argument is inside of quotation marks and is
6429printed as a string of characters. However, it may contain @samp{%d},
6430@samp{%s}, or @samp{%c} to print arguments that follow the string.
6431@samp{%d} prints the argument as a decimal, so the message will say
6432something such as @samp{Line 243}.
6433
6434@need 1200
c6f54b06 6435
8b096dce
EZ
6436The number that is printed in place of the @samp{%d} is computed by the
6437last line of the function:
6438
6439@smallexample
6440(1+ (count-lines 1 (point)))
6441@end smallexample
6442
6443@noindent
6444What this does is count the lines from the first position of the
6445buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6446one to that number. (The @code{1+} function adds one to its
6447argument.) We add one to it because line 2 has only one line before
6448it, and @code{count-lines} counts only the lines @emph{before} the
6449current line.
6450
6451After @code{count-lines} has done its job, and the message has been
6452printed in the echo area, the @code{save-excursion} restores point and
6453mark to their original positions; and @code{save-restriction} restores
6454the original narrowing, if any.
6455
6456@node narrow Exercise, , what-line, Narrowing & Widening
6457@section Exercise with Narrowing
6458
6459Write a function that will display the first 60 characters of the
6460current buffer, even if you have narrowed the buffer to its latter
c6f54b06
RC
6461half so that the first line is inaccessible. Restore point, mark, and
6462narrowing. For this exercise, you need to use a whole potpourri of
6463functions, including @code{save-restriction}, @code{widen},
6464@code{goto-char}, @code{point-min}, @code{message}, and
6465@code{buffer-substring}.
6466
6467@cindex Properties, mention of @code{buffer-substring-no-properties}
6468(@code{buffer-substring} is a previously unmentioned function you will
6469have to investigate yourself; or perhaps you will have to use
6470@code{buffer-substring-no-properties} @dots{}, yet another function
6471and one that introduces text properties, a feature otherwise not
6472discussed here. @xref{Text Properties, , Text Properties, elisp, The
6473GNU Emacs Lisp Reference Manual}. Additionally, do you really need
6474@code{goto-char} or @code{point-min}? Or can you write the function
6475without them?)
8b096dce
EZ
6476
6477@node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6478@comment node-name, next, previous, up
6479@chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6480@findex car, @r{introduced}
6481@findex cdr, @r{introduced}
6482
6483In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6484functions. The @code{cons} function is used to construct lists, and
6485the @code{car} and @code{cdr} functions are used to take them apart.
6486
6487In the walk through of the @code{copy-region-as-kill} function, we
6488will see @code{cons} as well as two variants on @code{cdr},
6489namely, @code{setcdr} and @code{nthcdr}. (@xref{copy-region-as-kill}.)
6490
6491@menu
6492* Strange Names:: An historical aside: why the strange names?
6493* car & cdr:: Functions for extracting part of a list.
6494* cons:: Constructing a list.
6495* nthcdr:: Calling @code{cdr} repeatedly.
6496* nth::
6497* setcar:: Changing the first element of a list.
6498* setcdr:: Changing the rest of a list.
6499* cons Exercise::
6500@end menu
6501
6502@node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6503@ifnottex
6504@unnumberedsec Strange Names
6505@end ifnottex
6506
6507The name of the @code{cons} function is not unreasonable: it is an
6508abbreviation of the word `construct'. The origins of the names for
6509@code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6510is an acronym from the phrase `Contents of the Address part of the
6511Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6512the phrase `Contents of the Decrement part of the Register'. These
6513phrases refer to specific pieces of hardware on the very early
6514computer on which the original Lisp was developed. Besides being
6515obsolete, the phrases have been completely irrelevant for more than 25
6516years to anyone thinking about Lisp. Nonetheless, although a few
6517brave scholars have begun to use more reasonable names for these
6518functions, the old terms are still in use. In particular, since the
6519terms are used in the Emacs Lisp source code, we will use them in this
6520introduction.
6521
6522@node car & cdr, cons, Strange Names, car cdr & cons
6523@comment node-name, next, previous, up
6524@section @code{car} and @code{cdr}
6525
6526The @sc{car} of a list is, quite simply, the first item in the list.
6527Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6528@code{rose}.
6529
6530@need 1200
6531If you are reading this in Info in GNU Emacs, you can see this by
6532evaluating the following:
6533
6534@smallexample
6535(car '(rose violet daisy buttercup))
6536@end smallexample
6537
6538@noindent
6539After evaluating the expression, @code{rose} will appear in the echo
6540area.
6541
6542Clearly, a more reasonable name for the @code{car} function would be
6543@code{first} and this is often suggested.
6544
6545@code{car} does not remove the first item from the list; it only reports
6546what it is. After @code{car} has been applied to a list, the list is
6547still the same as it was. In the jargon, @code{car} is
6548`non-destructive'. This feature turns out to be important.
6549
6550The @sc{cdr} of a list is the rest of the list, that is, the
6551@code{cdr} function returns the part of the list that follows the
6552first item. Thus, while the @sc{car} of the list @code{'(rose violet
6553daisy buttercup)} is @code{rose}, the rest of the list, the value
6554returned by the @code{cdr} function, is @code{(violet daisy
6555buttercup)}.
6556
c6f54b06 6557@need 800
8b096dce
EZ
6558You can see this by evaluating the following in the usual way:
6559
6560@smallexample
6561(cdr '(rose violet daisy buttercup))
6562@end smallexample
6563
6564@noindent
6565When you evaluate this, @code{(violet daisy buttercup)} will appear in
6566the echo area.
6567
6568Like @code{car}, @code{cdr} does not remove any elements from the
6569list---it just returns a report of what the second and subsequent
6570elements are.
6571
6572Incidentally, in the example, the list of flowers is quoted. If it were
6573not, the Lisp interpreter would try to evaluate the list by calling
6574@code{rose} as a function. In this example, we do not want to do that.
6575
6576Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6577
6578(There is a lesson here: when you name new functions, consider very
6579carefully what you are doing, since you may be stuck with the names
6580for far longer than you expect. The reason this document perpetuates
6581these names is that the Emacs Lisp source code uses them, and if I did
6582not use them, you would have a hard time reading the code; but do,
6583please, try to avoid using these terms yourself. The people who come
6584after you will be grateful to you.)
6585
6586When @code{car} and @code{cdr} are applied to a list made up of symbols,
6587such as the list @code{(pine fir oak maple)}, the element of the list
6588returned by the function @code{car} is the symbol @code{pine} without
6589any parentheses around it. @code{pine} is the first element in the
6590list. However, the @sc{cdr} of the list is a list itself, @code{(fir
6591oak maple)}, as you can see by evaluating the following expressions in
6592the usual way:
6593
6594@smallexample
6595@group
6596(car '(pine fir oak maple))
6597
6598(cdr '(pine fir oak maple))
6599@end group
6600@end smallexample
6601
6602On the other hand, in a list of lists, the first element is itself a
6603list. @code{car} returns this first element as a list. For example,
6604the following list contains three sub-lists, a list of carnivores, a
6605list of herbivores and a list of sea mammals:
6606
6607@smallexample
6608@group
6609(car '((lion tiger cheetah)
6610 (gazelle antelope zebra)
6611 (whale dolphin seal)))
6612@end group
6613@end smallexample
6614
6615@noindent
6616In this example, the first element or @sc{car} of the list is the list of
6617carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6618@code{((gazelle antelope zebra) (whale dolphin seal))}.
6619
6620@smallexample
6621@group
6622(cdr '((lion tiger cheetah)
6623 (gazelle antelope zebra)
6624 (whale dolphin seal)))
6625@end group
6626@end smallexample
6627
6628It is worth saying again that @code{car} and @code{cdr} are
6629non-destructive---that is, they do not modify or change lists to which
6630they are applied. This is very important for how they are used.
6631
6632Also, in the first chapter, in the discussion about atoms, I said that
6633in Lisp, ``certain kinds of atom, such as an array, can be separated
6634into parts; but the mechanism for doing this is different from the
6635mechanism for splitting a list. As far as Lisp is concerned, the
6636atoms of a list are unsplittable.'' (@xref{Lisp Atoms}.) The
6637@code{car} and @code{cdr} functions are used for splitting lists and
6638are considered fundamental to Lisp. Since they cannot split or gain
6639access to the parts of an array, an array is considered an atom.
6640Conversely, the other fundamental function, @code{cons}, can put
6641together or construct a list, but not an array. (Arrays are handled
6642by array-specific functions. @xref{Arrays, , Arrays, elisp, The GNU
6643Emacs Lisp Reference Manual}.)
6644
6645@node cons, nthcdr, car & cdr, car cdr & cons
6646@comment node-name, next, previous, up
6647@section @code{cons}
6648@findex cons, @r{introduced}
6649
6650The @code{cons} function constructs lists; it is the inverse of
6651@code{car} and @code{cdr}. For example, @code{cons} can be used to make
6652a four element list from the three element list, @code{(fir oak maple)}:
6653
6654@smallexample
6655(cons 'pine '(fir oak maple))
6656@end smallexample
6657
6658@need 800
6659@noindent
6660After evaluating this list, you will see
6661
6662@smallexample
6663(pine fir oak maple)
6664@end smallexample
6665
6666@noindent
b15dd613
RC
6667appear in the echo area. @code{cons} causes the creation of a new
6668list in which the element is followed by the elements of the original
6669list.
6670
6671We often say that `@code{cons} puts a new element at the beginning of
6672a list; it attaches or pushes elements onto the list', but this
6673phrasing can be misleading, since @code{cons} does not change an
6674existing list, but creates a new one.
6675
6676Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
8b096dce
EZ
6677
6678@menu
6679* Build a list::
6680* length:: How to find the length of a list.
6681@end menu
6682
6683@node Build a list, length, cons, cons
6684@ifnottex
6685@unnumberedsubsec Build a list
6686@end ifnottex
6687
6688@code{cons} must have a list to attach to.@footnote{Actually, you can
6689@code{cons} an element to an atom to produce a dotted pair. Dotted
6690pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6691Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.} You
6692cannot start from absolutely nothing. If you are building a list, you
6693need to provide at least an empty list at the beginning. Here is a
6694series of @code{cons} expressions that build up a list of flowers. If
6695you are reading this in Info in GNU Emacs, you can evaluate each of
6696the expressions in the usual way; the value is printed in this text
6697after @samp{@result{}}, which you may read as `evaluates to'.
6698
6699@smallexample
6700@group
6701(cons 'buttercup ())
6702 @result{} (buttercup)
6703@end group
6704
6705@group
6706(cons 'daisy '(buttercup))
6707 @result{} (daisy buttercup)
6708@end group
6709
6710@group
6711(cons 'violet '(daisy buttercup))
6712 @result{} (violet daisy buttercup)
6713@end group
6714
6715@group
6716(cons 'rose '(violet daisy buttercup))
6717 @result{} (rose violet daisy buttercup)
6718@end group
6719@end smallexample
6720
6721@noindent
6722In the first example, the empty list is shown as @code{()} and a list
6723made up of @code{buttercup} followed by the empty list is constructed.
6724As you can see, the empty list is not shown in the list that was
6725constructed. All that you see is @code{(buttercup)}. The empty list is
6726not counted as an element of a list because there is nothing in an empty
6727list. Generally speaking, an empty list is invisible.
6728
6729The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6730two element list by putting @code{daisy} in front of @code{buttercup};
6731and the third example constructs a three element list by putting
6732@code{violet} in front of @code{daisy} and @code{buttercup}.
6733
6734@node length, , Build a list, cons
6735@comment node-name, next, previous, up
6736@subsection Find the Length of a List: @code{length}
6737@findex length
6738
6739You can find out how many elements there are in a list by using the Lisp
6740function @code{length}, as in the following examples:
6741
6742@smallexample
6743@group
6744(length '(buttercup))
6745 @result{} 1
6746@end group
6747
6748@group
6749(length '(daisy buttercup))
6750 @result{} 2
6751@end group
6752
6753@group
6754(length (cons 'violet '(daisy buttercup)))
6755 @result{} 3
6756@end group
6757@end smallexample
6758
6759@noindent
6760In the third example, the @code{cons} function is used to construct a
6761three element list which is then passed to the @code{length} function as
6762its argument.
6763
6764@need 1200
6765We can also use @code{length} to count the number of elements in an
6766empty list:
6767
6768@smallexample
6769@group
6770(length ())
6771 @result{} 0
6772@end group
6773@end smallexample
6774
6775@noindent
6776As you would expect, the number of elements in an empty list is zero.
6777
6778An interesting experiment is to find out what happens if you try to find
6779the length of no list at all; that is, if you try to call @code{length}
6780without giving it an argument, not even an empty list:
6781
6782@smallexample
6783(length )
6784@end smallexample
6785
6786@need 800
6787@noindent
6788What you see, if you evaluate this, is the error message
6789
6790@smallexample
6791Wrong number of arguments: #<subr length>, 0
6792@end smallexample
6793
6794@noindent
6795This means that the function receives the wrong number of
6796arguments, zero, when it expects some other number of arguments. In
6797this case, one argument is expected, the argument being a list whose
6798length the function is measuring. (Note that @emph{one} list is
6799@emph{one} argument, even if the list has many elements inside it.)
6800
6801The part of the error message that says @samp{#<subr length>} is the
6802name of the function. This is written with a special notation,
6803@samp{#<subr}, that indicates that the function @code{length} is one
6804of the primitive functions written in C rather than in Emacs Lisp.
6805(@samp{subr} is an abbreviation for `subroutine'.) @xref{What Is a
6806Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6807Manual}, for more about subroutines.
6808
6809@node nthcdr, nth, cons, car cdr & cons
6810@comment node-name, next, previous, up
6811@section @code{nthcdr}
6812@findex nthcdr
6813
6814The @code{nthcdr} function is associated with the @code{cdr} function.
6815What it does is take the @sc{cdr} of a list repeatedly.
6816
6817If you take the @sc{cdr} of the list @code{(pine fir
6818oak maple)}, you will be returned the list @code{(fir oak maple)}. If you
6819repeat this on what was returned, you will be returned the list
6820@code{(oak maple)}. (Of course, repeated @sc{cdr}ing on the original
6821list will just give you the original @sc{cdr} since the function does
6822not change the list. You need to evaluate the @sc{cdr} of the
6823@sc{cdr} and so on.) If you continue this, eventually you will be
6824returned an empty list, which in this case, instead of being shown as
6825@code{()} is shown as @code{nil}.
6826
6827@need 1200
6828For review, here is a series of repeated @sc{cdr}s, the text following
6829the @samp{@result{}} shows what is returned.
6830
6831@smallexample
6832@group
6833(cdr '(pine fir oak maple))
6834 @result{}(fir oak maple)
6835@end group
6836
6837@group
6838(cdr '(fir oak maple))
6839 @result{} (oak maple)
6840@end group
6841
6842@group
6843(cdr '(oak maple))
6844 @result{}(maple)
6845@end group
6846
6847@group
6848(cdr '(maple))
6849 @result{} nil
6850@end group
6851
6852@group
6853(cdr 'nil)
6854 @result{} nil
6855@end group
6856
6857@group
6858(cdr ())
6859 @result{} nil
6860@end group
6861@end smallexample
6862
6863@need 1200
6864You can also do several @sc{cdr}s without printing the values in
6865between, like this:
6866
6867@smallexample
6868@group
6869(cdr (cdr '(pine fir oak maple)))
6870 @result{} (oak maple)
6871@end group
6872@end smallexample
6873
6874@noindent
6875In this example, the Lisp interpreter evaluates the innermost list first.
6876The innermost list is quoted, so it just passes the list as it is to the
6877innermost @code{cdr}. This @code{cdr} passes a list made up of the
6878second and subsequent elements of the list to the outermost @code{cdr},
6879which produces a list composed of the third and subsequent elements of
6880the original list. In this example, the @code{cdr} function is repeated
6881and returns a list that consists of the original list without its
6882first two elements.
6883
6884The @code{nthcdr} function does the same as repeating the call to
6885@code{cdr}. In the following example, the argument 2 is passed to the
6886function @code{nthcdr}, along with the list, and the value returned is
6887the list without its first two items, which is exactly the same
6888as repeating @code{cdr} twice on the list:
6889
6890@smallexample
6891@group
6892(nthcdr 2 '(pine fir oak maple))
6893 @result{} (oak maple)
6894@end group
6895@end smallexample
6896
6897@need 1200
6898Using the original four element list, we can see what happens when
6899various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6900and 5:
6901
6902@smallexample
6903@group
6904;; @r{Leave the list as it was.}
6905(nthcdr 0 '(pine fir oak maple))
6906 @result{} (pine fir oak maple)
6907@end group
6908
6909@group
6910;; @r{Return a copy without the first element.}
6911(nthcdr 1 '(pine fir oak maple))
6912 @result{} (fir oak maple)
6913@end group
6914
6915@group
6916;; @r{Return a copy of the list without three elements.}
6917(nthcdr 3 '(pine fir oak maple))
6918 @result{} (maple)
6919@end group
6920
6921@group
6922;; @r{Return a copy lacking all four elements.}
6923(nthcdr 4 '(pine fir oak maple))
6924 @result{} nil
6925@end group
6926
6927@group
6928;; @r{Return a copy lacking all elements.}
6929(nthcdr 5 '(pine fir oak maple))
6930 @result{} nil
6931@end group
6932@end smallexample
6933
6934@node nth, setcar, nthcdr, car cdr & cons
6935@comment node-name, next, previous, up
6936@section @code{nth}
6937@findex nth
6938
6939The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6940The @code{nth} function takes the @sc{car} of the result returned by
6941@code{nthcdr}. It returns the Nth element of the list.
6942
6943@need 1500
6944Thus, if it were not defined in C for speed, the definition of
6945@code{nth} would be:
6946
6947@smallexample
6948@group
6949(defun nth (n list)
6950 "Returns the Nth element of LIST.
6951N counts from zero. If LIST is not that long, nil is returned."
6952 (car (nthcdr n list)))
6953@end group
6954@end smallexample
6955
6956@noindent
6957(Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6958but its definition was redone in C in the 1980s.)
6959
6960The @code{nth} function returns a single element of a list.
6961This can be very convenient.
6962
6963Note that the elements are numbered from zero, not one. That is to
6964say, the first element of a list, its @sc{car} is the zeroth element.
6965This is called `zero-based' counting and often bothers people who
6966are accustomed to the first element in a list being number one, which
6967is `one-based'.
6968
6969@need 1250
6970For example:
6971
6972@smallexample
6973@group
6974(nth 0 '("one" "two" "three"))
6975 @result{} "one"
6976
6977(nth 1 '("one" "two" "three"))
6978 @result{} "two"
6979@end group
6980@end smallexample
6981
6982It is worth mentioning that @code{nth}, like @code{nthcdr} and
6983@code{cdr}, does not change the original list---the function is
6984non-destructive. This is in sharp contrast to the @code{setcar} and
6985@code{setcdr} functions.
6986
6987@node setcar, setcdr, nth, car cdr & cons
6988@comment node-name, next, previous, up
6989@section @code{setcar}
6990@findex setcar
6991
6992As you might guess from their names, the @code{setcar} and @code{setcdr}
6993functions set the @sc{car} or the @sc{cdr} of a list to a new value.
6994They actually change the original list, unlike @code{car} and @code{cdr}
6995which leave the original list as it was. One way to find out how this
6996works is to experiment. We will start with the @code{setcar} function.
6997
6998@need 1200
6999First, we can make a list and then set the value of a variable to the
7000list, using the @code{setq} function. Here is a list of animals:
7001
7002@smallexample
7003(setq animals '(antelope giraffe lion tiger))
7004@end smallexample
7005
7006@noindent
7007If you are reading this in Info inside of GNU Emacs, you can evaluate
7008this expression in the usual fashion, by positioning the cursor after
7009the expression and typing @kbd{C-x C-e}. (I'm doing this right here as
7010I write this. This is one of the advantages of having the interpreter
7011built into the computing environment.)
7012
7013@need 1200
7014When we evaluate the variable @code{animals}, we see that it is bound to
7015the list @code{(antelope giraffe lion tiger)}:
7016
7017@smallexample
7018@group
7019animals
7020 @result{} (antelope giraffe lion tiger)
7021@end group
7022@end smallexample
7023
7024@noindent
7025Put another way, the variable @code{animals} points to the list
7026@code{(antelope giraffe lion tiger)}.
7027
7028Next, evaluate the function @code{setcar} while passing it two
7029arguments, the variable @code{animals} and the quoted symbol
7030@code{hippopotamus}; this is done by writing the three element list
7031@code{(setcar animals 'hippopotamus)} and then evaluating it in the
7032usual fashion:
7033
7034@smallexample
7035(setcar animals 'hippopotamus)
7036@end smallexample
7037
7038@need 1200
7039@noindent
7040After evaluating this expression, evaluate the variable @code{animals}
7041again. You will see that the list of animals has changed:
7042
7043@smallexample
7044@group
7045animals
7046 @result{} (hippopotamus giraffe lion tiger)
7047@end group
7048@end smallexample
7049
7050@noindent
7051The first element on the list, @code{antelope} is replaced by
7052@code{hippopotamus}.
7053
7054So we can see that @code{setcar} did not add a new element to the list
7055as @code{cons} would have; it replaced @code{giraffe} with
7056@code{hippopotamus}; it @emph{changed} the list.
7057
7058@node setcdr, cons Exercise, setcar, car cdr & cons
7059@comment node-name, next, previous, up
7060@section @code{setcdr}
7061@findex setcdr
7062
7063The @code{setcdr} function is similar to the @code{setcar} function,
7064except that the function replaces the second and subsequent elements of
7065a list rather than the first element.
7066
c6f54b06
RC
7067(To see how to change the last element of a list, look ahead to
7068@ref{kill-new function, , The @code{kill-new} function}, which uses
7069the @code{nthcdr} and @code{setcdr} functions.)
7070
8b096dce
EZ
7071@need 1200
7072To see how this works, set the value of the variable to a list of
7073domesticated animals by evaluating the following expression:
7074
7075@smallexample
7076(setq domesticated-animals '(horse cow sheep goat))
7077@end smallexample
7078
7079@need 1200
7080@noindent
7081If you now evaluate the list, you will be returned the list
7082@code{(horse cow sheep goat)}:
7083
7084@smallexample
7085@group
7086domesticated-animals
7087 @result{} (horse cow sheep goat)
7088@end group
7089@end smallexample
7090
7091@need 1200
7092Next, evaluate @code{setcdr} with two arguments, the name of the
7093variable which has a list as its value, and the list to which the
7094@sc{cdr} of the first list will be set;
7095
7096@smallexample
7097(setcdr domesticated-animals '(cat dog))
7098@end smallexample
7099
7100@noindent
7101If you evaluate this expression, the list @code{(cat dog)} will appear
7102in the echo area. This is the value returned by the function. The
7103result we are interested in is the ``side effect'', which we can see by
7104evaluating the variable @code{domesticated-animals}:
7105
7106@smallexample
7107@group
7108domesticated-animals
7109 @result{} (horse cat dog)
7110@end group
7111@end smallexample
7112
7113@noindent
7114Indeed, the list is changed from @code{(horse cow sheep goat)} to
7115@code{(horse cat dog)}. The @sc{cdr} of the list is changed from
7116@code{(cow sheep goat)} to @code{(cat dog)}.
7117
7118@node cons Exercise, , setcdr, car cdr & cons
7119@section Exercise
7120
7121Construct a list of four birds by evaluating several expressions with
7122@code{cons}. Find out what happens when you @code{cons} a list onto
7123itself. Replace the first element of the list of four birds with a
7124fish. Replace the rest of that list with a list of other fish.
e601d8fd 7125
8b096dce
EZ
7126@node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7127@comment node-name, next, previous, up
7128@chapter Cutting and Storing Text
7129@cindex Cutting and storing text
7130@cindex Storing and cutting text
7131@cindex Killing text
7132@cindex Clipping text
7133@cindex Erasing text
7134@cindex Deleting text
7135
7136Whenever you cut or clip text out of a buffer with a `kill' command in
7137GNU Emacs, it is stored in a list and you can bring it back with a
7138`yank' command.
7139
7140(The use of the word `kill' in Emacs for processes which specifically
7141@emph{do not} destroy the values of the entities is an unfortunate
7142historical accident. A much more appropriate word would be `clip' since
7143that is what the kill commands do; they clip text out of a buffer and
7144put it into storage from which it can be brought back. I have often
7145been tempted to replace globally all occurrences of `kill' in the Emacs
7146sources with `clip' and all occurrences of `killed' with `clipped'.)
7147
7148@menu
7149* Storing Text:: Text is stored in a list.
7150* zap-to-char:: Cutting out text up to a character.
7151* kill-region:: Cutting text out of a region.
7152* Digression into C:: Minor note on C programming language macros.
7153* defvar:: How to give a variable an initial value.
7154* copy-region-as-kill:: A definition for copying text.
7155* cons & search-fwd Review::
7156* search Exercises::
7157@end menu
7158
7159@node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7160@ifnottex
7161@unnumberedsec Storing Text in a List
7162@end ifnottex
7163
7164When text is cut out of a buffer, it is stored on a list. Successive
7165pieces of text are stored on the list successively, so the list might
7166look like this:
7167
7168@smallexample
7169("a piece of text" "previous piece")
7170@end smallexample
7171
7172@need 1200
7173@noindent
b15dd613
RC
7174The function @code{cons} can be used to to create a new list from a
7175piece of text (an `atom', to use the jargon) and an existing list,
8b096dce
EZ
7176like this:
7177
7178@smallexample
7179@group
7180(cons "another piece"
7181 '("a piece of text" "previous piece"))
7182@end group
7183@end smallexample
7184
7185@need 1200
7186@noindent
7187If you evaluate this expression, a list of three elements will appear in
7188the echo area:
7189
7190@smallexample
7191("another piece" "a piece of text" "previous piece")
7192@end smallexample
7193
7194With the @code{car} and @code{nthcdr} functions, you can retrieve
7195whichever piece of text you want. For example, in the following code,
7196@code{nthcdr 1 @dots{}} returns the list with the first item removed;
7197and the @code{car} returns the first element of that remainder---the
7198second element of the original list:
7199
7200@smallexample
7201@group
7202(car (nthcdr 1 '("another piece"
7203 "a piece of text"
7204 "previous piece")))
7205 @result{} "a piece of text"
7206@end group
7207@end smallexample
7208
7209The actual functions in Emacs are more complex than this, of course.
7210The code for cutting and retrieving text has to be written so that
7211Emacs can figure out which element in the list you want---the first,
7212second, third, or whatever. In addition, when you get to the end of
7213the list, Emacs should give you the first element of the list, rather
7214than nothing at all.
7215
7216The list that holds the pieces of text is called the @dfn{kill ring}.
7217This chapter leads up to a description of the kill ring and how it is
7218used by first tracing how the @code{zap-to-char} function works. This
7219function uses (or `calls') a function that invokes a function that
7220manipulates the kill ring. Thus, before reaching the mountains, we
7221climb the foothills.
7222
7223A subsequent chapter describes how text that is cut from the buffer is
7224retrieved. @xref{Yanking, , Yanking Text Back}.
7225
7226@node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7227@comment node-name, next, previous, up
7228@section @code{zap-to-char}
7229@findex zap-to-char
7230
7231The @code{zap-to-char} function barely changed between GNU Emacs
7232version 19 and GNU Emacs version 21. However, @code{zap-to-char}
7233calls another function, @code{kill-region}, which enjoyed a major rewrite
7234on the way to version 21.
7235
7236The @code{kill-region} function in Emacs 19 is complex, but does not
7237use code that is important at this time. We will skip it.
7238
7239The @code{kill-region} function in Emacs 21 is easier to read than the
7240same function in Emacs 19 and introduces a very important concept,
7241that of error handling. We will walk through the function.
7242
7243But first, let us look at the interactive @code{zap-to-char} function.
7244
7245@menu
7246* Complete zap-to-char:: The complete implementation.
7247* zap-to-char interactive:: A three part interactive expression.
7248* zap-to-char body:: A short overview.
7249* search-forward:: How to search for a string.
7250* progn:: The @code{progn} special form.
7251* Summing up zap-to-char:: Using @code{point} and @code{search-forward}.
7252@end menu
7253
7254@node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7255@ifnottex
7256@unnumberedsubsec The Complete @code{zap-to-char} Implementation
7257@end ifnottex
7258
7259The GNU Emacs version 19 and version 21 implementations of the
7260@code{zap-to-char} function are nearly identical in form, and they
7261work alike. The function removes the text in the region between the
7262location of the cursor (i.e., of point) up to and including the next
7263occurrence of a specified character. The text that @code{zap-to-char}
7264removes is put in the kill ring; and it can be retrieved from the kill
7265ring by typing @kbd{C-y} (@code{yank}). If the command is given an
7266argument, it removes text through that number of occurrences. Thus,
7267if the cursor were at the beginning of this sentence and the character
7268were @samp{s}, @samp{Thus} would be removed. If the argument were
7269two, @samp{Thus, if the curs} would be removed, up to and including
7270the @samp{s} in @samp{cursor}.
7271
7272If the specified character is not found, @code{zap-to-char} will say
7273``Search failed'', tell you the character you typed, and not remove
7274any text.
7275
7276In order to determine how much text to remove, @code{zap-to-char} uses
7277a search function. Searches are used extensively in code that
7278manipulates text, and we will focus attention on them as well as on the
7279deletion command.
7280
7281@need 800
7282Here is the complete text of the version 19 implementation of the function:
7283
7284@c v 19
7285@smallexample
7286@group
7287(defun zap-to-char (arg char) ; version 19 implementation
7288 "Kill up to and including ARG'th occurrence of CHAR.
7289Goes backward if ARG is negative; error if CHAR not found."
7290 (interactive "*p\ncZap to char: ")
7291 (kill-region (point)
7292 (progn
7293 (search-forward
7294 (char-to-string char) nil nil arg)
7295 (point))))
7296@end group
7297@end smallexample
7298
7299@node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7300@comment node-name, next, previous, up
7301@subsection The @code{interactive} Expression
7302
7303@need 800
7304The interactive expression in the @code{zap-to-char} command looks like
7305this:
7306
7307@smallexample
7308(interactive "*p\ncZap to char: ")
7309@end smallexample
7310
7311The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7312three different things. First, and most simply, the asterisk, @samp{*},
7313causes an error to be signalled if the buffer is read-only. This means that
7314if you try @code{zap-to-char} in a read-only buffer you will not be able to
7315remove text, and you will receive a message that says ``Buffer is
7316read-only''; your terminal may beep at you as well.
7317
7318The version 21 implementation does not have the asterisk, @samp{*}. The
7319function works the same as in version 19: in both cases, it cannot
7320remove text from a read-only buffer but the function does copy the
7321text that would have been removed to the kill ring. Also, in both
7322cases, you see an error message.
7323
7324However, the version 19 implementation copies text from a read-only
7325buffer only because of a mistake in the implementation of
7326@code{interactive}. According to the documentation for
7327@code{interactive}, the asterisk, @samp{*}, should prevent the
7328@code{zap-to-char} function from doing anything at all when the buffer
c6f54b06
RC
7329is read only. In version 19, the function should not copy the text to
7330the kill ring. It is a bug that it does.
8b096dce 7331
c6f54b06
RC
7332In version 21, the function is designed to copy the text to the kill
7333ring; moreover, @code{interactive} is implemented correctly. So the
8b096dce 7334asterisk, @samp{*}, had to be removed from the interactive
c6f54b06
RC
7335specification. However, if you insert an @samp{*} yourself and
7336evaluate the function definition, then the next time you run the
7337@code{zap-to-char} function on a read-only buffer, you will not copy
7338any text.
8b096dce
EZ
7339
7340That change aside, and a change to the documentation, the two versions
7341of the @code{zap-to-char} function are identical.
7342
7343Let us continue with the interactive specification.
7344
7345The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7346This part is separated from the next part by a newline, @samp{\n}.
7347The @samp{p} means that the first argument to the function will be
7348passed the value of a `processed prefix'. The prefix argument is
7349passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number. If
7350the function is called interactively without a prefix, 1 is passed to
7351this argument.
7352
7353The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7354}. In this part, the lower case @samp{c} indicates that
7355@code{interactive} expects a prompt and that the argument will be a
7356character. The prompt follows the @samp{c} and is the string @samp{Zap
7357to char:@: } (with a space after the colon to make it look good).
7358
7359What all this does is prepare the arguments to @code{zap-to-char} so they
7360are of the right type, and give the user a prompt.
7361
7362@node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7363@comment node-name, next, previous, up
7364@subsection The Body of @code{zap-to-char}
7365
7366The body of the @code{zap-to-char} function contains the code that
7367kills (that is, removes) the text in the region from the current
7368position of the cursor up to and including the specified character.
7369The first part of the code looks like this:
7370
7371@smallexample
7372(kill-region (point) @dots{}
7373@end smallexample
7374
7375@noindent
7376@code{(point)} is the current position of the cursor.
7377
7378The next part of the code is an expression using @code{progn}. The body
7379of the @code{progn} consists of calls to @code{search-forward} and
7380@code{point}.
7381
7382It is easier to understand how @code{progn} works after learning about
7383@code{search-forward}, so we will look at @code{search-forward} and
7384then at @code{progn}.
7385
7386@node search-forward, progn, zap-to-char body, zap-to-char
7387@comment node-name, next, previous, up
7388@subsection The @code{search-forward} Function
7389@findex search-forward
7390
7391The @code{search-forward} function is used to locate the
7392zapped-for-character in @code{zap-to-char}. If the search is
7393successful, @code{search-forward} leaves point immediately after the
7394last character in the target string. (In @code{zap-to-char}, the
7395target string is just one character long.) If the search is
7396backwards, @code{search-forward} leaves point just before the first
7397character in the target. Also, @code{search-forward} returns @code{t}
7398for true. (Moving point is therefore a `side effect'.)
7399
7400@need 1250
7401In @code{zap-to-char}, the @code{search-forward} function looks like this:
7402
7403@smallexample
7404(search-forward (char-to-string char) nil nil arg)
7405@end smallexample
7406
7407The @code{search-forward} function takes four arguments:
7408
7409@enumerate
7410@item
7411The first argument is the target, what is searched for. This must be a
7412string, such as @samp{"z"}.
7413
7414As it happens, the argument passed to @code{zap-to-char} is a single
7415character. Because of the way computers are built, the Lisp
7416interpreter may treat a single character as being different from a
7417string of characters. Inside the computer, a single character has a
7418different electronic format than a string of one character. (A single
7419character can often be recorded in the computer using exactly one
7420byte; but a string may be longer, and the computer needs to be ready
7421for this.) Since the @code{search-forward} function searches for a
7422string, the character that the @code{zap-to-char} function receives as
7423its argument must be converted inside the computer from one format to
7424the other; otherwise the @code{search-forward} function will fail.
7425The @code{char-to-string} function is used to make this conversion.
7426
7427@item
7428The second argument bounds the search; it is specified as a position in
7429the buffer. In this case, the search can go to the end of the buffer,
7430so no bound is set and the second argument is @code{nil}.
7431
7432@item
7433The third argument tells the function what it should do if the search
7434fails---it can signal an error (and print a message) or it can return
7435@code{nil}. A @code{nil} as the third argument causes the function to
7436signal an error when the search fails.
7437
7438@item
7439The fourth argument to @code{search-forward} is the repeat count---how
7440many occurrences of the string to look for. This argument is optional
7441and if the function is called without a repeat count, this argument is
7442passed the value 1. If this argument is negative, the search goes
7443backwards.
7444@end enumerate
7445
7446@need 800
7447In template form, a @code{search-forward} expression looks like this:
7448
7449@smallexample
7450@group
7451(search-forward "@var{target-string}"
7452 @var{limit-of-search}
7453 @var{what-to-do-if-search-fails}
7454 @var{repeat-count})
7455@end group
7456@end smallexample
7457
7458We will look at @code{progn} next.
7459
7460@node progn, Summing up zap-to-char, search-forward, zap-to-char
7461@comment node-name, next, previous, up
7462@subsection The @code{progn} Special Form
7463@findex progn
7464
7465@code{progn} is a special form that causes each of its arguments to be
7466evaluated in sequence and then returns the value of the last one. The
7467preceding expressions are evaluated only for the side effects they
7468perform. The values produced by them are discarded.
7469
7470@need 800
7471The template for a @code{progn} expression is very simple:
7472
7473@smallexample
7474@group
7475(progn
7476 @var{body}@dots{})
7477@end group
7478@end smallexample
7479
7480In @code{zap-to-char}, the @code{progn} expression has to do two things:
7481put point in exactly the right position; and return the location of
7482point so that @code{kill-region} will know how far to kill to.
7483
7484The first argument to the @code{progn} is @code{search-forward}. When
7485@code{search-forward} finds the string, the function leaves point
7486immediately after the last character in the target string. (In this
7487case the target string is just one character long.) If the search is
7488backwards, @code{search-forward} leaves point just before the first
7489character in the target. The movement of point is a side effect.
7490
7491The second and last argument to @code{progn} is the expression
7492@code{(point)}. This expression returns the value of point, which in
7493this case will be the location to which it has been moved by
7494@code{search-forward}. This value is returned by the @code{progn}
7495expression and is passed to @code{kill-region} as @code{kill-region}'s
7496second argument.
7497
7498@node Summing up zap-to-char, , progn, zap-to-char
7499@comment node-name, next, previous, up
7500@subsection Summing up @code{zap-to-char}
7501
7502Now that we have seen how @code{search-forward} and @code{progn} work,
7503we can see how the @code{zap-to-char} function works as a whole.
7504
7505The first argument to @code{kill-region} is the position of the cursor
7506when the @code{zap-to-char} command is given---the value of point at
7507that time. Within the @code{progn}, the search function then moves
7508point to just after the zapped-to-character and @code{point} returns the
7509value of this location. The @code{kill-region} function puts together
7510these two values of point, the first one as the beginning of the region
7511and the second one as the end of the region, and removes the region.
7512
7513The @code{progn} special form is necessary because the @code{kill-region}
7514command takes two arguments; and it would fail if @code{search-forward}
7515and @code{point} expressions were written in sequence as two
7516additional arguments. The @code{progn} expression is a single argument
7517to @code{kill-region} and returns the one value that @code{kill-region}
7518needs for its second argument.
7519
7520@node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7521@comment node-name, next, previous, up
7522@section @code{kill-region}
7523@findex kill-region
7524
7525The @code{zap-to-char} function uses the @code{kill-region} function.
7526This function clips text from a region and copies that text to
7527the kill ring, from which it may be retrieved.
7528
7529The Emacs 21 version of that function uses @code{condition-case} and
7530@code{copy-region-as-kill}, both of which we will explain.
7531@code{condition-case} is an important special form.
7532
7533In essence, the @code{kill-region} function calls
7534@code{condition-case}, which takes three arguments. In this function,
7535the first argument does nothing. The second argument contains the
7536code that does the work when all goes well. The third argument
7537contains the code that is called in the event of an error.
7538
7539@menu
7540* Complete kill-region:: The function definition.
7541* condition-case:: Dealing with a problem.
7542* delete-and-extract-region:: Doing the work.
7543@end menu
7544
7545@node Complete kill-region, condition-case, kill-region, kill-region
7546@ifnottex
7547@unnumberedsubsec The Complete @code{kill-region} Definition
7548@end ifnottex
7549
7550@need 1200
7551We will go through the @code{condition-case} code in a moment. First,
c6f54b06
RC
7552let us look at the original definition of @code{kill-region}, with
7553comments added (the newer definition has an optional third argument
7554and is more complex):
8b096dce
EZ
7555
7556@c v 21
7557@smallexample
7558@group
7559(defun kill-region (beg end)
7560 "Kill between point and mark.
7561The text is deleted but saved in the kill ring."
7562 (interactive "r")
7563@end group
7564
7565@group
7566 ;; 1. `condition-case' takes three arguments.
7567 ;; If the first argument is nil, as it is here,
7568 ;; information about the error signal is not
7569 ;; stored for use by another function.
7570 (condition-case nil
7571@end group
7572
7573@group
7574 ;; 2. The second argument to `condition-case'
7575 ;; tells the Lisp interpreter what to do when all goes well.
7576@end group
7577
7578@group
7579 ;; The `delete-and-extract-region' function usually does the
7580 ;; work. If the beginning and ending of the region are both
7581 ;; the same, then the variable `string' will be empty, or nil
7582 (let ((string (delete-and-extract-region beg end)))
7583@end group
7584
7585@group
7586 ;; `when' is an `if' clause that cannot take an `else-part'.
7587 ;; Emacs normally sets the value of `last-command' to the
7588 ;; previous command.
7589@end group
7590@group
7591 ;; `kill-append' concatenates the new string and the old.
7592 ;; `kill-new' inserts text into a new item in the kill ring.
7593 (when string
7594 (if (eq last-command 'kill-region)
7595 ;; if true, prepend string
7596 (kill-append string (< end beg))
7597 (kill-new string)))
7598 (setq this-command 'kill-region))
7599@end group
7600
7601@group
7602 ;; 3. The third argument to `condition-case' tells the interpreter
7603 ;; what to do with an error.
7604@end group
7605@group
7606 ;; The third argument has a conditions part and a body part.
7607 ;; If the conditions are met (in this case,
7608 ;; if text or buffer is read-only)
7609 ;; then the body is executed.
7610@end group
7611@group
7612 ((buffer-read-only text-read-only) ;; this is the if-part
7613 ;; then...
7614 (copy-region-as-kill beg end)
7615@end group
7616@group
7617 (if kill-read-only-ok ;; usually this variable is nil
7618 (message "Read only text copied to kill ring")
7619 ;; or else, signal an error if the buffer is read-only;
7620 (barf-if-buffer-read-only)
7621 ;; and, in any case, signal that the text is read-only.
7622 (signal 'text-read-only (list (current-buffer)))))))
7623@end group
7624@end smallexample
7625
7626@node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7627@comment node-name, next, previous, up
7628@subsection @code{condition-case}
7629@findex condition-case
7630
7631As we have seen earlier (@pxref{Making Errors, , Generate an Error
7632Message}), when the Emacs Lisp interpreter has trouble evaluating an
7633expression, it provides you with help; in the jargon, this is called
7634``signaling an error''. Usually, the computer stops the program and
7635shows you a message.
7636
7637However, some programs undertake complicated actions. They should not
7638simply stop on an error. In the @code{kill-region} function, the most
7639likely error is that you will try to kill text that is read-only and
7640cannot be removed. So the @code{kill-region} function contains code
7641to handle this circumstance. This code, which makes up the body of
7642the @code{kill-region} function, is inside of a @code{condition-case}
7643special form.
7644
7645@need 800
7646The template for @code{condition-case} looks like this:
7647
7648@smallexample
7649@group
7650(condition-case
7651 @var{var}
7652 @var{bodyform}
7653 @var{error-handler}@dots{})
7654@end group
7655@end smallexample
7656
7657The second argument, @var{bodyform}, is straightforward. The
7658@code{condition-case} special form causes the Lisp interpreter to
7659evaluate the code in @var{bodyform}. If no error occurs, the special
7660form returns the code's value and produces the side-effects, if any.
7661
7662In short, the @var{bodyform} part of a @code{condition-case}
7663expression determines what should happen when everything works
7664correctly.
7665
7666However, if an error occurs, among its other actions, the function
7667generating the error signal will define one or more error condition
7668names.
7669
7670An error handler is the third argument to @code{condition case}.
7671An error handler has two parts, a @var{condition-name} and a
7672@var{body}. If the @var{condition-name} part of an error handler
7673matches a condition name generated by an error, then the @var{body}
7674part of the error handler is run.
7675
7676As you will expect, the @var{condition-name} part of an error handler
7677may be either a single condition name or a list of condition names.
7678
7679Also, a complete @code{condition-case} expression may contain more
7680than one error handler. When an error occurs, the first applicable
7681handler is run.
7682
7683Lastly, the first argument to the @code{condition-case} expression,
7684the @var{var} argument, is sometimes bound to a variable that
7685contains information about the error. However, if that argument is
7686nil, as is the case in @code{kill-region}, that information is
7687discarded.
7688
7689@need 1200
7690In brief, in the @code{kill-region} function, the code
7691@code{condition-case} works like this:
7692
7693@smallexample
7694@group
7695@var{If no errors}, @var{run only this code}
7696 @var{but}, @var{if errors}, @var{run this other code}.
7697@end group
7698@end smallexample
7699
7700@node delete-and-extract-region, , condition-case, kill-region
7701@comment node-name, next, previous, up
7702@subsection @code{delete-and-extract-region}
7703@findex delete-and-extract-region
7704
7705A @code{condition-case} expression has two parts, a part that is
7706evaluated in the expectation that all will go well, but which may
7707generate an error; and a part that is evaluated when there is an
7708error.
7709
7710First, let us look at the code in @code{kill-region} that is run in
7711the expectation that all goes well. This is the core of the function.
7712The code looks like this:
7713
7714@smallexample
7715@group
7716(let ((string (delete-and-extract-region beg end)))
7717 (when string
7718 (if (eq last-command 'kill-region)
7719 (kill-append string (< end beg))
7720 (kill-new string)))
7721 (setq this-command 'kill-region))
7722@end group
7723@end smallexample
7724
7725It looks complicated because we have the new functions
7726@code{delete-and-extract-region}, @code{kill-append}, and
7727@code{kill-new} as well as the new variables,
7728@code{last-command} and @code{this-command}.
7729
7730The @code{delete-and-extract-region} function is straightforward. It
7731is a built-in function that deletes the text in a region (a side
7732effect) and also returns that text. This is the function that
7733actually removes the text. (And if it cannot do that, it signals the
7734error.)
7735
7736In this @code{let} expression, the text that
7737@code{delete-and-extract-region} returns is placed in the local
7738variable called @samp{string}. This is the text that is removed from
7739the buffer. (To be more precise, the variable is set to point to the
7740address of the extracted text; to say it is `placed in' the variable
7741is simply a shorthand.)
7742
7743If the variable @samp{string} does point to text, that text is added
7744to the kill ring. The variable will have a @code{nil} value if no
7745text was removed.
7746
7747The code uses @code{when} to determine whether the variable
7748@samp{string} points to text. A @code{when} statement is simply a
7749programmers' convenience. A @code{when} statement is an @code{if}
7750statement without the possibility of an else clause. In your mind, you
7751can replace @code{when} with @code{if} and understand what goes on.
7752That is what the Lisp interpreter does.
7753
7754@cindex Macro, lisp
7755@cindex Lisp macro
7756Technically speaking, @code{when} is a Lisp macro. A Lisp @dfn{macro}
7757enables you to define new control constructs and other language
7758features. It tells the interpreter how to compute another Lisp
7759expression which will in turn compute the value. In this case, the
7760`other expression' is an @code{if} expression. For more about Lisp
7761macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7762Manual}. The C programming language also provides macros. These are
7763different, but also useful. We will briefly look at C macros in
b15dd613 7764@ref{Digression into C}.
8b096dce
EZ
7765
7766@need 1200
7767If the string has content, then another conditional expression is
7768executed. This is an @code{if} with both a then-part and an else-part.
7769
7770@smallexample
7771@group
7772(if (eq last-command 'kill-region)
7773 (kill-append string (< end beg))
7774 (kill-new string)))
7775@end group
7776@end smallexample
7777
7778The then-part is evaluated if the previous command was another call to
7779@code{kill-region}; if not, the else-part is evaluated.
7780
7781@code{last-command} is a variable that comes with Emacs that we have
7782not seen before. Normally, whenever a function is executed, Emacs
7783sets the value of @code{last-command} to the previous command.
7784
7785@need 1200
7786In this segment of the definition, the @code{if} expression checks
7787whether the previous command was @code{kill-region}. If it was,
7788
7789@smallexample
7790(kill-append string (< end beg))
7791@end smallexample
7792
7793@noindent
7794concatenates a copy of the newly clipped text to the just previously
7795clipped text in the kill ring. (If the @w{@code{(< end beg))}}
7796expression is true, @code{kill-append} prepends the string to the just
7797previously clipped text. For a detailed discussion, see
7798@ref{kill-append function, , The @code{kill-append} function}.)
7799
7800If you then yank back the text, i.e., `paste' it, you get both
7801pieces of text at once. That way, if you delete two words in a row,
7802and then yank them back, you get both words, in their proper order,
7803with one yank. (The @w{@code{(< end beg))}} expression makes sure the
7804order is correct.)
7805
7806On the other hand, if the previous command is not @code{kill-region},
7807then the @code{kill-new} function is called, which adds the text to
7808the kill ring as the latest item, and sets the
7809@code{kill-ring-yank-pointer} variable to point to it.
7810
7811@node Digression into C, defvar, kill-region, Cutting & Storing Text
7812@comment node-name, next, previous, up
b15dd613 7813@section Digression into C
8b096dce
EZ
7814@findex delete-and-extract-region
7815@cindex C, a digression into
7816@cindex Digression into C
7817
7818The @code{zap-to-char} command uses the
7819@code{delete-and-extract-region} function, which in turn uses two
7820other functions, @code{copy-region-as-kill} and
7821@code{del_range_1}. The @code{copy-region-as-kill} function will be
7822described in a following section; it puts a copy of the region in the
7823kill ring so it can be yanked back. (@xref{copy-region-as-kill, ,
7824@code{copy-region-as-kill}}.)
7825
7826The @code{delete-and-extract-region} function removes the contents of
7827a region and you cannot get them back.
7828
7829Unlike the other code discussed here, @code{delete-and-extract-region}
7830is not written in Emacs Lisp; it is written in C and is one of the
7831primitives of the GNU Emacs system. Since it is very simple, I will
7832digress briefly from Lisp and describe it here.
7833
7834@need 1500
7835Like many of the other Emacs primitives,
7836@code{delete-and-extract-region} is written as an instance of a C
7837macro, a macro being a template for code. The complete macro looks
7838like this:
7839
7840@c /usr/local/src/emacs/src/editfns.c
7841@smallexample
7842@group
7843DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7844 Sdelete_and_extract_region, 2, 2, 0,
7845 "Delete the text between START and END and return it.")
7846 (start, end)
7847 Lisp_Object start, end;
7848@{
7849 validate_region (&start, &end);
7850 return del_range_1 (XINT (start), XINT (end), 1, 1);
7851@}
7852@end group
7853@end smallexample
7854
7855Without going into the details of the macro writing process, let me
7856point out that this macro starts with the word @code{DEFUN}. The word
7857@code{DEFUN} was chosen since the code serves the same purpose as
7858@code{defun} does in Lisp. The word @code{DEFUN} is followed by seven
7859parts inside of parentheses:
7860
7861@itemize @bullet
7862@item
7863The first part is the name given to the function in Lisp,
7864@code{delete-and-extract-region}.
7865
7866@item
7867The second part is the name of the function in C,
7868@code{Fdelete_and_extract_region}. By convention, it starts with
7869@samp{F}. Since C does not use hyphens in names, underscores are used
7870instead.
7871
7872@item
7873The third part is the name for the C constant structure that records
7874information on this function for internal use. It is the name of the
7875function in C but begins with an @samp{S} instead of an @samp{F}.
7876
7877@item
7878The fourth and fifth parts specify the minimum and maximum number of
7879arguments the function can have. This function demands exactly 2
7880arguments.
7881
7882@item
7883The sixth part is nearly like the argument that follows the
7884@code{interactive} declaration in a function written in Lisp: a letter
7885followed, perhaps, by a prompt. The only difference from the Lisp is
7886when the macro is called with no arguments. Then you write a @code{0}
7887(which is a `null string'), as in this macro.
7888
7889If you were to specify arguments, you would place them between
7890quotation marks. The C macro for @code{goto-char} includes
7891@code{"NGoto char: "} in this position to indicate that the function
7892expects a raw prefix, in this case, a numerical location in a buffer,
7893and provides a prompt.
7894
7895@item
7896The seventh part is a documentation string, just like the one for a
7897function written in Emacs Lisp, except that every newline must be
7898written explicitly as @samp{\n} followed by a backslash and carriage
7899return.
7900
7901@need 1000
7902Thus, the first two lines of documentation for @code{goto-char} are
7903written like this:
7904
7905@smallexample
7906@group
7907 "Set point to POSITION, a number or marker.\n\
7908Beginning of buffer is position (point-min), end is (point-max).
7909@end group
7910@end smallexample
7911@end itemize
7912
7913@need 1200
7914In a C macro, the formal parameters come next, with a statement of
7915what kind of object they are, followed by what might be called the `body'
7916of the macro. For @code{delete-and-extract-region} the `body'
7917consists of the following two lines:
7918
7919@smallexample
7920@group
7921validate_region (&start, &end);
7922return del_range_1 (XINT (start), XINT (end), 1, 1);
7923@end group
7924@end smallexample
7925
7926The first function, @code{validate_region} checks whether the values
7927passed as the beginning and end of the region are the proper type and
7928are within range. The second function, @code{del_range_1}, actually
7929deletes the text.
7930
7931@code{del_range_1} is a complex function we will not look into. It
7932updates the buffer and does other things.
7933
7934However, it is worth looking at the two arguments passed to
7935@code{del_range}. These are @w{@code{XINT (start)}} and @w{@code{XINT
7936(end)}}.
7937
7938As far as the C language is concerned, @code{start} and @code{end} are
7939two integers that mark the beginning and end of the region to be
7940deleted@footnote{More precisely, and requiring more expert knowledge
7941to understand, the two integers are of type `Lisp_Object', which can
7942also be a C union instead of an integer type.}.
7943
7944In early versions of Emacs, these two numbers were thirty-two bits
7945long, but the code is slowly being generalized to handle other
7946lengths. Three of the available bits are used to specify the type of
7947information and a fourth bit is used for handling the computer's
7948memory; the remaining bits are used as `content'.
7949
7950@samp{XINT} is a C macro that extracts the relevant number from the
7951longer collection of bits; the four other bits are discarded.
7952
7953@need 800
7954The command in @code{delete-and-extract-region} looks like this:
7955
7956@smallexample
7957del_range_1 (XINT (start), XINT (end), 1, 1);
7958@end smallexample
7959
7960@noindent
7961It deletes the region between the beginning position, @code{start},
7962and the ending position, @code{end}.
7963
7964From the point of view of the person writing Lisp, Emacs is all very
7965simple; but hidden underneath is a great deal of complexity to make it
7966all work.
7967
7968@node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7969@comment node-name, next, previous, up
7970@section Initializing a Variable with @code{defvar}
7971@findex defvar
7972@cindex Initializing a variable
7973@cindex Variable initialization
7974
7975Unlike the @code{delete-and-extract-region} function, the
7976@code{copy-region-as-kill} function is written in Emacs Lisp. Two
7977functions within it, @code{kill-append} and @code{kill-new}, copy a
7978region in a buffer and save it in a variable called the
7979@code{kill-ring}. This section describes how the @code{kill-ring}
7980variable is created and initialized using the @code{defvar} special
7981form.
7982
7983(Again we note that the term @code{kill-ring} is a misnomer. The text
7984that is clipped out of the buffer can be brought back; it is not a ring
7985of corpses, but a ring of resurrectable text.)
7986
7987In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7988given an initial value by using the @code{defvar} special form. The
7989name comes from ``define variable''.
7990
7991The @code{defvar} special form is similar to @code{setq} in that it sets
7992the value of a variable. It is unlike @code{setq} in two ways: first,
7993it only sets the value of the variable if the variable does not already
7994have a value. If the variable already has a value, @code{defvar} does
7995not override the existing value. Second, @code{defvar} has a
7996documentation string.
7997
7998(Another special form, @code{defcustom}, is designed for variables
7999that people customize. It has more features than @code{defvar}.
8000(@xref{defcustom, , Setting Variables with @code{defcustom}}.)
8001
8002@menu
8003* See variable current value::
8004* defvar and asterisk:: An old-time convention.
8005@end menu
8006
8007@node See variable current value, defvar and asterisk, defvar, defvar
8008@ifnottex
8009@unnumberedsubsec Seeing the Current Value of a Variable
8010@end ifnottex
8011
8012You can see the current value of a variable, any variable, by using
8013the @code{describe-variable} function, which is usually invoked by
8014typing @kbd{C-h v}. If you type @kbd{C-h v} and then @code{kill-ring}
8015(followed by @key{RET}) when prompted, you will see what is in your
8016current kill ring---this may be quite a lot! Conversely, if you have
8017been doing nothing this Emacs session except read this document, you
8018may have nothing in it. Also, you will see the documentation for
8019@code{kill-ring}:
8020
8021@smallexample
8022@group
8023Documentation:
8024List of killed text sequences.
8025Since the kill ring is supposed to interact nicely with cut-and-paste
8026facilities offered by window systems, use of this variable should
8027@end group
8028@group
8029interact nicely with `interprogram-cut-function' and
8030`interprogram-paste-function'. The functions `kill-new',
8031`kill-append', and `current-kill' are supposed to implement this
8032interaction; you may want to use them instead of manipulating the kill
8033ring directly.
8034@end group
8035@end smallexample
8036
8037@need 800
8038The kill ring is defined by a @code{defvar} in the following way:
8039
8040@smallexample
8041@group
8042(defvar kill-ring nil
8043 "List of killed text sequences.
8044@dots{}")
8045@end group
8046@end smallexample
8047
8048@noindent
8049In this variable definition, the variable is given an initial value of
8050@code{nil}, which makes sense, since if you have saved nothing, you want
8051nothing back if you give a @code{yank} command. The documentation
8052string is written just like the documentation string of a @code{defun}.
8053As with the documentation string of the @code{defun}, the first line of
8054the documentation should be a complete sentence, since some commands,
8055like @code{apropos}, print only the first line of documentation.
8056Succeeding lines should not be indented; otherwise they look odd when
8057you use @kbd{C-h v} (@code{describe-variable}).
8058
8059@node defvar and asterisk, , See variable current value, defvar
8060@subsection @code{defvar} and an asterisk
8061@findex defvar @r{for a user customizable variable}
8062@findex defvar @r{with an asterisk}
8063
8064In the past, Emacs used the @code{defvar} special form both for
8065internal variables that you would not expect a user to change and for
8066variables that you do expect a user to change. Although you can still
8067use @code{defvar} for user customizable variables, please use
8068@code{defcustom} instead, since that special form provides a path into
8069the Customization commands. (@xref{defcustom, , Setting Variables
8070with @code{defcustom}}.)
8071
8072When you specified a variable using the @code{defvar} special form,
8073you could distinguish a readily settable variable from others by
8074typing an asterisk, @samp{*}, in the first column of its documentation
8075string. For example:
8076
8077@smallexample
8078@group
8079(defvar shell-command-default-error-buffer nil
8080 "*Buffer name for `shell-command' @dots{} error output.
8081@dots{} ")
8082@end group
8083@end smallexample
8084
8085@noindent
8086This means that you could (and still can) use the @code{edit-options}
8087command to change the value of
8088@code{shell-command-default-error-buffer} temporarily.
8089
8090@findex edit-options
8091However, options set using @code{edit-options} are set only for the
8092duration of your editing session. The new values are not saved
8093between sessions. Each time Emacs starts, it reads the original
8094value, unless you change the value within your @file{.emacs} file,
8095either by setting it manually or by using @code{customize}.
8096@xref{Emacs Initialization, , Your @file{.emacs} File}.
8097
8098For me, the major use of the @code{edit-options} command is to suggest
8099variables that I might want to set in my @file{.emacs} file. I urge
8100you to look through the list. (@xref{Edit Options, , Editing Variable
8101Values, emacs, The GNU Emacs Manual}.)
8102
8103@node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8104@comment node-name, next, previous, up
8105@section @code{copy-region-as-kill}
8106@findex copy-region-as-kill
8107@findex nthcdr
8108
8109The @code{copy-region-as-kill} function copies a region of text from a
8110buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8111in the @code{kill-ring}.
8112
8113If you call @code{copy-region-as-kill} immediately after a
8114@code{kill-region} command, Emacs appends the newly copied text to the
8115previously copied text. This means that if you yank back the text, you
8116get it all, from both this and the previous operation. On the other
8117hand, if some other command precedes the @code{copy-region-as-kill},
8118the function copies the text into a separate entry in the kill ring.
8119
8120@menu
8121* Complete copy-region-as-kill:: The complete function definition.
8122* copy-region-as-kill body:: The body of @code{copy-region-as-kill}.
8123@end menu
8124
8125@node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8126@ifnottex
8127@unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8128@end ifnottex
8129
8130@need 1200
8131Here is the complete text of the version 21 @code{copy-region-as-kill}
8132function:
8133
c6f54b06
RC
8134@c !!! for no text properties, use buffer-substring-no-properties
8135
8b096dce
EZ
8136@smallexample
8137@group
8138(defun copy-region-as-kill (beg end)
8139 "Save the region as if killed, but don't kill it.
8140In Transient Mark mode, deactivate the mark.
8141If `interprogram-cut-function' is non-nil, also save
8142the text for a window system cut and paste."
8143 (interactive "r")
8144@end group
8145@group
8146 (if (eq last-command 'kill-region)
8147 (kill-append (buffer-substring beg end) (< end beg))
8148 (kill-new (buffer-substring beg end)))
8149@end group
8150@group
8151 (if transient-mark-mode
8152 (setq deactivate-mark t))
8153 nil)
8154@end group
8155@end smallexample
8156
8157@need 800
8158As usual, this function can be divided into its component parts:
8159
8160@smallexample
8161@group
8162(defun copy-region-as-kill (@var{argument-list})
8163 "@var{documentation}@dots{}"
8164 (interactive "r")
8165 @var{body}@dots{})
8166@end group
8167@end smallexample
8168
8169The arguments are @code{beg} and @code{end} and the function is
8170interactive with @code{"r"}, so the two arguments must refer to the
8171beginning and end of the region. If you have been reading though this
8172document from the beginning, understanding these parts of a function is
8173almost becoming routine.
8174
8175The documentation is somewhat confusing unless you remember that the
8176word `kill' has a meaning different from its usual meaning. The
8177`Transient Mark' and @code{interprogram-cut-function} comments explain
8178certain side-effects.
8179
8180After you once set a mark, a buffer always contains a region. If you
8181wish, you can use Transient Mark mode to highlight the region
8182temporarily. (No one wants to highlight the region all the time, so
8183Transient Mark mode highlights it only at appropriate times. Many
8184people turn off Transient Mark mode, so the region is never
8185highlighted.)
8186
8187Also, a windowing system allows you to copy, cut, and paste among
8188different programs. In the X windowing system, for example, the
8189@code{interprogram-cut-function} function is @code{x-select-text},
8190which works with the windowing system's equivalent of the Emacs kill
8191ring.
8192
8193The body of the @code{copy-region-as-kill} function starts with an
8194@code{if} clause. What this clause does is distinguish between two
8195different situations: whether or not this command is executed
8196immediately after a previous @code{kill-region} command. In the first
8197case, the new region is appended to the previously copied text.
8198Otherwise, it is inserted into the beginning of the kill ring as a
8199separate piece of text from the previous piece.
8200
8201The last two lines of the function prevent the region from lighting up
8202if Transient Mark mode is turned on.
8203
8204The body of @code{copy-region-as-kill} merits discussion in detail.
8205
8206@node copy-region-as-kill body, , Complete copy-region-as-kill, copy-region-as-kill
8207@comment node-name, next, previous, up
8208@subsection The Body of @code{copy-region-as-kill}
8209
8210The @code{copy-region-as-kill} function works in much the same way as
8211the @code{kill-region} function (@pxref{kill-region,
8212,@code{kill-region}}). Both are written so that two or more kills in
8213a row combine their text into a single entry. If you yank back the
8214text from the kill ring, you get it all in one piece. Moreover, kills
8215that kill forward from the current position of the cursor are added to
8216the end of the previously copied text and commands that copy text
8217backwards add it to the beginning of the previously copied text. This
8218way, the words in the text stay in the proper order.
8219
8220Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8221use of the @code{last-command} variable that keeps track of the
8222previous Emacs command.
8223
8224@menu
8225* last-command & this-command::
8226* kill-append function::
8227* kill-new function::
8228@end menu
8229
8230@node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8231@ifnottex
8232@unnumberedsubsubsec @code{last-command} and @code{this-command}
8233@end ifnottex
8234
8235Normally, whenever a function is executed, Emacs sets the value of
8236@code{this-command} to the function being executed (which in this case
8237would be @code{copy-region-as-kill}). At the same time, Emacs sets
8238the value of @code{last-command} to the previous value of
8239@code{this-command}.
8240
8241In the first part of the body of the @code{copy-region-as-kill}
8242function, an @code{if} expression determines whether the value of
8243@code{last-command} is @code{kill-region}. If so, the then-part of
8244the @code{if} expression is evaluated; it uses the @code{kill-append}
8245function to concatenate the text copied at this call to the function
8246with the text already in the first element (the @sc{car}) of the kill
8247ring. On the other hand, if the value of @code{last-command} is not
8248@code{kill-region}, then the @code{copy-region-as-kill} function
8249attaches a new element to the kill ring using the @code{kill-new}
8250function.
8251
8252@need 1250
8253The @code{if} expression reads as follows; it uses @code{eq}, which is
8254a function we have not yet seen:
8255
8256@smallexample
8257@group
8258 (if (eq last-command 'kill-region)
8259 ;; @r{then-part}
8260 (kill-append (buffer-substring beg end) (< end beg))
8261 ;; @r{else-part}
8262 (kill-new (buffer-substring beg end)))
8263@end group
8264@end smallexample
8265
8266@findex eq @r{(example of use)}
8267@noindent
8268The @code{eq} function tests whether its first argument is the same Lisp
8269object as its second argument. The @code{eq} function is similar to the
8270@code{equal} function in that it is used to test for equality, but
8271differs in that it determines whether two representations are actually
8272the same object inside the computer, but with different names.
8273@code{equal} determines whether the structure and contents of two
8274expressions are the same.
8275
8276If the previous command was @code{kill-region}, then the Emacs Lisp
8277interpreter calls the @code{kill-append} function
8278
8279@node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8280@unnumberedsubsubsec The @code{kill-append} function
8281@findex kill-append
8282
8283@need 800
8284The @code{kill-append} function looks like this:
8285
8286@smallexample
8287@group
8288(defun kill-append (string before-p)
8289 "Append STRING to the end of the latest kill in the kill ring.
8290If BEFORE-P is non-nil, prepend STRING to the kill.
8291If `interprogram-cut-function' is set, pass the resulting kill to
8292it."
8293 (kill-new (if before-p
8294 (concat string (car kill-ring))
8295 (concat (car kill-ring) string))
8296 t))
8297@end group
8298@end smallexample
8299
8300@noindent
8301The @code{kill-append} function is fairly straightforward. It uses
8302the @code{kill-new} function, which we will discuss in more detail in
8303a moment.
8304
8305First, let us look at the conditional that is one of the two arguments
8306to @code{kill-new}. It uses @code{concat} to concatenate the new text
8307to the @sc{car} of the kill ring. Whether it prepends or appends the
8308text depends on the results of an @code{if} expression:
8309
8310@smallexample
8311@group
8312(if before-p ; @r{if-part}
8313 (concat string (car kill-ring)) ; @r{then-part}
8314 (concat (car kill-ring) string)) ; @r{else-part}
8315@end group
8316@end smallexample
8317
8318@noindent
8319If the region being killed is before the region that was killed in the
8320last command, then it should be prepended before the material that was
8321saved in the previous kill; and conversely, if the killed text follows
8322what was just killed, it should be appended after the previous text.
8323The @code{if} expression depends on the predicate @code{before-p} to
8324decide whether the newly saved text should be put before or after the
8325previously saved text.
8326
8327The symbol @code{before-p} is the name of one of the arguments to
8328@code{kill-append}. When the @code{kill-append} function is
8329evaluated, it is bound to the value returned by evaluating the actual
8330argument. In this case, this is the expression @code{(< end beg)}.
8331This expression does not directly determine whether the killed text in
8332this command is located before or after the kill text of the last
f5cb0355 8333command; what it does is determine whether the value of the variable
8b096dce
EZ
8334@code{end} is less than the value of the variable @code{beg}. If it
8335is, it means that the user is most likely heading towards the
8336beginning of the buffer. Also, the result of evaluating the predicate
8337expression, @code{(< end beg)}, will be true and the text will be
8338prepended before the previous text. On the other hand, if the value of
8339the variable @code{end} is greater than the value of the variable
8340@code{beg}, the text will be appended after the previous text.
8341
8342@need 800
8343When the newly saved text will be prepended, then the string with the new
8344text will be concatenated before the old text:
8345
8346@smallexample
8347(concat string (car kill-ring))
8348@end smallexample
8349
8350@need 1200
8351@noindent
8352But if the text will be appended, it will be concatenated
8353after the old text:
8354
8355@smallexample
8356(concat (car kill-ring) string))
8357@end smallexample
8358
8359To understand how this works, we first need to review the
8360@code{concat} function. The @code{concat} function links together or
8361unites two strings of text. The result is a string. For example:
8362
8363@smallexample
8364@group
8365(concat "abc" "def")
8366 @result{} "abcdef"
8367@end group
8368
8369@group
8370(concat "new "
8371 (car '("first element" "second element")))
8372 @result{} "new first element"
8373
8374(concat (car
8375 '("first element" "second element")) " modified")
8376 @result{} "first element modified"
8377@end group
8378@end smallexample
8379
8380We can now make sense of @code{kill-append}: it modifies the contents
8381of the kill ring. The kill ring is a list, each element of which is
8382saved text. The @code{kill-append} function uses the @code{kill-new}
8383function which in turn uses the @code{setcar} function.
8384
8385@node kill-new function, , kill-append function, copy-region-as-kill body
8386@unnumberedsubsubsec The @code{kill-new} function
8387@findex kill-new
8388
8389@need 1200
8390The @code{kill-new} function looks like this:
8391
8392@smallexample
8393@group
8394(defun kill-new (string &optional replace)
8395 "Make STRING the latest kill in the kill ring.
8396Set the kill-ring-yank pointer to point to it.
8397If `interprogram-cut-function' is non-nil, apply it to STRING.
8398Optional second argument REPLACE non-nil means that STRING will replace
8399the front of the kill ring, rather than being added to the list."
8400@end group
8401@group
8402 (and (fboundp 'menu-bar-update-yank-menu)
8403 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8404@end group
8405@group
8406 (if (and replace kill-ring)
8407 (setcar kill-ring string)
8408 (setq kill-ring (cons string kill-ring))
8409 (if (> (length kill-ring) kill-ring-max)
8410 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8411@end group
8412@group
8413 (setq kill-ring-yank-pointer kill-ring)
8414 (if interprogram-cut-function
8415 (funcall interprogram-cut-function string (not replace))))
8416@end group
8417@end smallexample
8418
8419As usual, we can look at this function in parts.
8420
8421@need 1200
8422The first line of the documentation makes sense:
8423
8424@smallexample
8425Make STRING the latest kill in the kill ring.
8426@end smallexample
8427
8428@noindent
8429Let's skip over the rest of the documentation for the moment.
8430
8431Also, let's skip over the first two lines of code, those involving
8432@code{menu-bar-update-yank-menu}. We will explain them below.
8433
8434@need 1200
8435The critical lines are these:
8436
8437@smallexample
8438@group
8439 (if (and replace kill-ring)
8440 ;; @r{then}
8441 (setcar kill-ring string)
8442@end group
8443@group
8444 ;; @r{else}
8445 (setq kill-ring (cons string kill-ring))
8446 (if (> (length kill-ring) kill-ring-max)
8447 ;; @r{avoid overly long kill ring}
8448 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8449@end group
8450@group
8451 (setq kill-ring-yank-pointer kill-ring)
8452 (if interprogram-cut-function
8453 (funcall interprogram-cut-function string (not replace))))
8454@end group
8455@end smallexample
8456
8457The conditional test is @w{@code{(and replace kill-ring)}}.
8458This will be true when two conditions are met: the kill ring has
8459something in it, and the @code{replace} variable is true.
8460
8461@need 1250
8462The @code{kill-append} function sets @code{replace} to be true; then,
8463when the kill ring has at least one item in it, the @code{setcar}
8464expression is executed:
8465
8466@smallexample
8467(setcar kill-ring string)
8468@end smallexample
8469
8470The @code{setcar} function actually changes the first element of the
8471@code{kill-ring} list to the value of @code{string}. It replaces the
8472first element.
8473
8474On the other hand, if the kill ring is empty, or replace is false, the
8475else-part of the condition is executed:
8476
8477@smallexample
8478@group
8479(setq kill-ring (cons string kill-ring))
8480(if (> (length kill-ring) kill-ring-max)
8481 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8482@end group
8483@end smallexample
8484
8485@noindent
8486This expression first constructs a new version of the kill ring by
8487prepending @code{string} to the existing kill ring as a new element.
8488Then it executes a second @code{if} clause. This second @code{if}
8489clause keeps the kill ring from growing too long.
8490
8491Let's look at these two expressions in order.
8492
8493The @code{setq} line of the else-part sets the new value of the kill
8494ring to what results from adding the string being killed to the old kill
8495ring.
8496
8497@need 800
8498We can see how this works with an example:
8499
8500@smallexample
8501(setq example-list '("here is a clause" "another clause"))
8502@end smallexample
8503
8504@need 1200
8505@noindent
8506After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8507@code{example-list} and see what it returns:
8508
8509@smallexample
8510@group
8511example-list
8512 @result{} ("here is a clause" "another clause")
8513@end group
8514@end smallexample
8515
8516@need 1200
8517@noindent
8518Now, we can add a new element on to this list by evaluating the
8519following expression:
8520@findex cons, @r{example}
8521
8522@smallexample
8523(setq example-list (cons "a third clause" example-list))
8524@end smallexample
8525
8526@need 800
8527@noindent
8528When we evaluate @code{example-list}, we find its value is:
8529
8530@smallexample
8531@group
8532example-list
8533 @result{} ("a third clause" "here is a clause" "another clause")
8534@end group
8535@end smallexample
8536
8537@noindent
8538Thus, the third clause was added to the list by @code{cons}.
8539
8540@need 1200
8541This is exactly similar to what the @code{setq} and @code{cons} do in
8542the function. Here is the line again:
8543
8544@smallexample
8545(setq kill-ring (cons string kill-ring))
8546@end smallexample
8547
8548@need 1200
8549Now for the second part of the @code{if} clause. This expression
8550keeps the kill ring from growing too long. It looks like this:
8551
8552@smallexample
8553@group
8554(if (> (length kill-ring) kill-ring-max)
8555 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8556@end group
8557@end smallexample
8558
8559The code checks whether the length of the kill ring is greater than
8560the maximum permitted length. This is the value of
8561@code{kill-ring-max} (which is 60, by default). If the length of the
8562kill ring is too long, then this code sets the last element of the
8563kill ring to @code{nil}. It does this by using two functions,
8564@code{nthcdr} and @code{setcdr}.
8565
8566We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8567It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8568@sc{car} of a list. In this case, however, @code{setcdr} will not be
8569setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8570function is used to cause it to set the @sc{cdr} of the next to last
8571element of the kill ring---this means that since the @sc{cdr} of the
8572next to last element is the last element of the kill ring, it will set
8573the last element of the kill ring.
8574
8575@findex nthcdr, @r{example}
8576The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8577list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8578@dots{} It does this @var{N} times and returns the results.
8579
8580@findex setcdr, @r{example}
8581Thus, if we had a four element list that was supposed to be three
8582elements long, we could set the @sc{cdr} of the next to last element
c6f54b06
RC
8583to @code{nil}, and thereby shorten the list. (If you sent the last
8584element to some other value than @code{nil}, which you could do, then
8585you would not have shortened the list.)
8b096dce 8586
c6f54b06
RC
8587You can see shortening by evaluating the following three expressions
8588in turn. First set the value of @code{trees} to @code{(maple oak pine
8589birch)}, then set the @sc{cdr} of its second @sc{cdr} to @code{nil}
8590and then find the value of @code{trees}:
8b096dce
EZ
8591
8592@smallexample
8593@group
8594(setq trees '(maple oak pine birch))
8595 @result{} (maple oak pine birch)
8596@end group
8597
8598@group
8599(setcdr (nthcdr 2 trees) nil)
8600 @result{} nil
8601
8602trees
8603 @result{} (maple oak pine)
8604@end group
8605@end smallexample
8606
8607@noindent
8608(The value returned by the @code{setcdr} expression is @code{nil} since
8609that is what the @sc{cdr} is set to.)
8610
8611To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8612@sc{cdr} a number of times that is one less than the maximum permitted
8613size of the kill ring and sets the @sc{cdr} of that element (which
8614will be the rest of the elements in the kill ring) to @code{nil}.
8615This prevents the kill ring from growing too long.
8616
8617@need 800
8618The next to last expression in the @code{kill-new} function is
8619
8620@smallexample
8621(setq kill-ring-yank-pointer kill-ring)
8622@end smallexample
8623
8624The @code{kill-ring-yank-pointer} is a global variable that is set to be
8625the @code{kill-ring}.
8626
8627Even though the @code{kill-ring-yank-pointer} is called a
8628@samp{pointer}, it is a variable just like the kill ring. However, the
8629name has been chosen to help humans understand how the variable is used.
8630The variable is used in functions such as @code{yank} and
8631@code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8632
8633@need 1200
8634Now, to return to the first two lines in the body of the function:
8635
8636@smallexample
8637@group
8638 (and (fboundp 'menu-bar-update-yank-menu)
8639 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8640@end group
8641@end smallexample
8642
8643@noindent
8644This is an expression whose first element is the function @code{and}.
8645
8646@findex and, @r{introduced}
8647The @code{and} special form evaluates each of its arguments until one of
8648the arguments returns a value of @code{nil}, in which case the
8649@code{and} expression returns @code{nil}; however, if none of the
8650arguments returns a value of @code{nil}, the value resulting from
8651evaluating the last argument is returned. (Since such a value is not
8652@code{nil}, it is considered true in Emacs Lisp.) In other words, an
8653@code{and} expression returns a true value only if all its arguments
8654are true.
8655@findex and
8656
8657In this case, the expression tests first to see whether
8658@code{menu-bar-update-yank-menu} exists as a function, and if so,
8659calls it. The @code{fboundp} function returns true if the symbol it
8660is testing has a function definition that `is not void'. If the
8661symbol's function definition were void, we would receive an error
8662message, as we did when we created errors intentionally (@pxref{Making
8663Errors, , Generate an Error Message}).
8664
8665@need 1200
8666Essentially, the @code{and} is an @code{if} expression that reads like
8667this:
8668
8669@smallexample
8670@group
8671if @var{the-menu-bar-function-exists}
8672 then @var{execute-it}
8673@end group
8674@end smallexample
8675
8676@code{menu-bar-update-yank-menu} is one of the functions that make it
8677possible to use the `Select and Paste' menu in the Edit item of a menu
8678bar; using a mouse, you can look at the various pieces of text you
8679have saved and select one piece to paste.
8680
8681Finally, the last expression in the @code{kill-new} function adds the
8682newly copied string to whatever facility exists for copying and
8683pasting among different programs running in a windowing system. In
8684the X Windowing system, for example, the @code{x-select-text} function
8685takes the string and stores it in memory operated by X. You can paste
8686the string in another program, such as an Xterm.
8687
8688@need 1200
8689The expression looks like this:
8690
8691@smallexample
8692@group
8693 (if interprogram-cut-function
8694 (funcall interprogram-cut-function string (not replace))))
8695@end group
8696@end smallexample
8697
8698If an @code{interprogram-cut-function} exists, then Emacs executes
8699@code{funcall}, which in turn calls its first argument as a function
8700and passes the remaining arguments to it. (Incidentally, as far as I
8701can see, this @code{if} expression could be replaced by an @code{and}
8702expression similar to the one in the first part of the function.)
8703
8704We are not going to discuss windowing systems and other programs
8705further, but merely note that this is a mechanism that enables GNU
8706Emacs to work easily and well with other programs.
8707
8708This code for placing text in the kill ring, either concatenated with
8709an existing element or as a new element, leads us to the code for
8710bringing back text that has been cut out of the buffer---the yank
8711commands. However, before discussing the yank commands, it is better
8712to learn how lists are implemented in a computer. This will make
8713clear such mysteries as the use of the term `pointer'.
8714
c6f54b06 8715@need 1250
8b096dce
EZ
8716@node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8717@comment node-name, next, previous, up
8718@section Review
8719
8720Here is a brief summary of some recently introduced functions.
8721
8722@table @code
8723@item car
8724@itemx cdr
8725@code{car} returns the first element of a list; @code{cdr} returns the
8726second and subsequent elements of a list.
8727
8728@need 1250
8729For example:
8730
8731@smallexample
8732@group
8733(car '(1 2 3 4 5 6 7))
8734 @result{} 1
8735(cdr '(1 2 3 4 5 6 7))
8736 @result{} (2 3 4 5 6 7)
8737@end group
8738@end smallexample
8739
8740@item cons
8741@code{cons} constructs a list by prepending its first argument to its
8742second argument.
8743
8744@need 1250
8745For example:
8746
8747@smallexample
8748@group
8749(cons 1 '(2 3 4))
8750 @result{} (1 2 3 4)
8751@end group
8752@end smallexample
8753
8754@item nthcdr
8755Return the result of taking @sc{cdr} `n' times on a list.
8756@iftex
8757The
8758@tex
8759$n^{th}$
8760@end tex
8761@code{cdr}.
8762@end iftex
8763The `rest of the rest', as it were.
8764
8765@need 1250
8766For example:
8767
8768@smallexample
8769@group
8770(nthcdr 3 '(1 2 3 4 5 6 7))
8771 @result{} (4 5 6 7)
8772@end group
8773@end smallexample
8774
8775@item setcar
8776@itemx setcdr
8777@code{setcar} changes the first element of a list; @code{setcdr}
8778changes the second and subsequent elements of a list.
8779
8780@need 1250
8781For example:
8782
8783@smallexample
8784@group
8785(setq triple '(1 2 3))
8786
8787(setcar triple '37)
8788
8789triple
8790 @result{} (37 2 3)
8791
8792(setcdr triple '("foo" "bar"))
8793
8794triple
8795 @result{} (37 "foo" "bar")
8796@end group
8797@end smallexample
8798
8799@item progn
8800Evaluate each argument in sequence and then return the value of the
8801last.
8802
8803@need 1250
8804For example:
8805
8806@smallexample
8807@group
8808(progn 1 2 3 4)
8809 @result{} 4
8810@end group
8811@end smallexample
8812
8813@item save-restriction
8814Record whatever narrowing is in effect in the current buffer, if any,
8815and restore that narrowing after evaluating the arguments.
8816
8817@item search-forward
8818Search for a string, and if the string is found, move point.
8819
8820@need 1250
8821@noindent
8822Takes four arguments:
8823
8824@enumerate
8825@item
8826The string to search for.
8827
8828@item
8829Optionally, the limit of the search.
8830
8831@item
8832Optionally, what to do if the search fails, return @code{nil} or an
8833error message.
8834
8835@item
8836Optionally, how many times to repeat the search; if negative, the
8837search goes backwards.
8838@end enumerate
8839
8840@item kill-region
c6f54b06 8841@itemx delete-and-extract-region
8b096dce
EZ
8842@itemx copy-region-as-kill
8843
8844@code{kill-region} cuts the text between point and mark from the
8845buffer and stores that text in the kill ring, so you can get it back
8846by yanking.
8847
8848@code{delete-and-extract-region} removes the text between point and
8849mark from the buffer and throws it away. You cannot get it back.
8850
8851@code{copy-region-as-kill} copies the text between point and mark into
8852the kill ring, from which you can get it by yanking. The function
8853does not cut or remove the text from the buffer.
8854@end table
8855
8856@need 1500
8857@node search Exercises, , cons & search-fwd Review, Cutting & Storing Text
8858@section Searching Exercises
8859
8860@itemize @bullet
8861@item
8862Write an interactive function that searches for a string. If the
8863search finds the string, leave point after it and display a message
8864that says ``Found!''. (Do not use @code{search-forward} for the name
8865of this function; if you do, you will overwrite the existing version of
8866@code{search-forward} that comes with Emacs. Use a name such as
8867@code{test-search} instead.)
8868
8869@item
8870Write a function that prints the third element of the kill ring in the
8871echo area, if any; if the kill ring does not contain a third element,
8872print an appropriate message.
8873@end itemize
8874
8875@node List Implementation, Yanking, Cutting & Storing Text, Top
8876@comment node-name, next, previous, up
8877@chapter How Lists are Implemented
8878@cindex Lists in a computer
8879
8880In Lisp, atoms are recorded in a straightforward fashion; if the
8881implementation is not straightforward in practice, it is, nonetheless,
8882straightforward in theory. The atom @samp{rose}, for example, is
8883recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8884@samp{e}. A list, on the other hand, is kept differently. The mechanism
8885is equally simple, but it takes a moment to get used to the idea. A
8886list is kept using a series of pairs of pointers. In the series, the
8887first pointer in each pair points to an atom or to another list, and the
8888second pointer in each pair points to the next pair, or to the symbol
8889@code{nil}, which marks the end of the list.
8890
8891A pointer itself is quite simply the electronic address of what is
8892pointed to. Hence, a list is kept as a series of electronic addresses.
8893
8894@menu
8895* Lists diagrammed::
8896* Symbols as Chest:: Exploring a powerful metaphor.
8897* List Exercise::
8898@end menu
8899
8900@node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8901@ifnottex
8902@unnumberedsec Lists diagrammed
8903@end ifnottex
8904
8905For example, the list @code{(rose violet buttercup)} has three elements,
8906@samp{rose}, @samp{violet}, and @samp{buttercup}. In the computer, the
8907electronic address of @samp{rose} is recorded in a segment of computer
8908memory along with the address that gives the electronic address of where
8909the atom @samp{violet} is located; and that address (the one that tells
8910where @samp{violet} is located) is kept along with an address that tells
8911where the address for the atom @samp{buttercup} is located.
8912
8913@need 1200
8914This sounds more complicated than it is and is easier seen in a diagram:
8915
8916@c clear print-postscript-figures
8917@c !!! cons-cell-diagram #1
8918@ifnottex
8919@smallexample
8920@group
8921 ___ ___ ___ ___ ___ ___
8922 |___|___|--> |___|___|--> |___|___|--> nil
8923 | | |
8924 | | |
8925 --> rose --> violet --> buttercup
8926@end group
8927@end smallexample
8928@end ifnottex
8929@ifset print-postscript-figures
8930@sp 1
8931@tex
8932@image{cons-1}
8933%%%% old method of including an image
8934% \input /usr/local/lib/tex/inputs/psfig.tex
8935% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8936% \catcode`\@=0 %
8937@end tex
8938@sp 1
8939@end ifset
8940@ifclear print-postscript-figures
8941@iftex
8942@smallexample
8943@group
8944 ___ ___ ___ ___ ___ ___
8945 |___|___|--> |___|___|--> |___|___|--> nil
8946 | | |
8947 | | |
8948 --> rose --> violet --> buttercup
8949@end group
8950@end smallexample
8951@end iftex
8952@end ifclear
8953
8954@noindent
8955In the diagram, each box represents a word of computer memory that
8956holds a Lisp object, usually in the form of a memory address. The boxes,
8957i.e.@: the addresses, are in pairs. Each arrow points to what the address
8958is the address of, either an atom or another pair of addresses. The
8959first box is the electronic address of @samp{rose} and the arrow points
8960to @samp{rose}; the second box is the address of the next pair of boxes,
8961the first part of which is the address of @samp{violet} and the second
8962part of which is the address of the next pair. The very last box
8963points to the symbol @code{nil}, which marks the end of the list.
8964
8965@need 1200
8966When a variable is set to a list with a function such as @code{setq},
8967it stores the address of the first box in the variable. Thus,
8968evaluation of the expression
8969
8970@smallexample
8971(setq bouquet '(rose violet buttercup))
8972@end smallexample
8973
8974@need 1250
8975@noindent
8976creates a situation like this:
8977
8978@c cons-cell-diagram #2
8979@ifnottex
8980@smallexample
8981@group
8982bouquet
8983 |
8984 | ___ ___ ___ ___ ___ ___
8985 --> |___|___|--> |___|___|--> |___|___|--> nil
8986 | | |
8987 | | |
8988 --> rose --> violet --> buttercup
8989@end group
8990@end smallexample
8991@end ifnottex
8992@ifset print-postscript-figures
8993@sp 1
8994@tex
8995@image{cons-2}
8996%%%% old method of including an image
8997% \input /usr/local/lib/tex/inputs/psfig.tex
8998% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
8999% \catcode`\@=0 %
9000@end tex
9001@sp 1
9002@end ifset
9003@ifclear print-postscript-figures
9004@iftex
9005@smallexample
9006@group
9007bouquet
9008 |
9009 | ___ ___ ___ ___ ___ ___
9010 --> |___|___|--> |___|___|--> |___|___|--> nil
9011 | | |
9012 | | |
9013 --> rose --> violet --> buttercup
9014@end group
9015@end smallexample
9016@end iftex
9017@end ifclear
9018
9019@noindent
9020In this example, the symbol @code{bouquet} holds the address of the first
9021pair of boxes.
9022
9023@need 1200
9024This same list can be illustrated in a different sort of box notation
9025like this:
9026
9027@c cons-cell-diagram #2a
9028@ifnottex
9029@smallexample
9030@group
9031bouquet
9032 |
9033 | -------------- --------------- ----------------
9034 | | car | cdr | | car | cdr | | car | cdr |
9035 -->| rose | o------->| violet | o------->| butter- | nil |
9036 | | | | | | | cup | |
9037 -------------- --------------- ----------------
9038@end group
9039@end smallexample
9040@end ifnottex
9041@ifset print-postscript-figures
9042@sp 1
9043@tex
9044@image{cons-2a}
9045%%%% old method of including an image
9046% \input /usr/local/lib/tex/inputs/psfig.tex
9047% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9048% \catcode`\@=0 %
9049@end tex
9050@sp 1
9051@end ifset
9052@ifclear print-postscript-figures
9053@iftex
9054@smallexample
9055@group
9056bouquet
9057 |
9058 | -------------- --------------- ----------------
9059 | | car | cdr | | car | cdr | | car | cdr |
9060 -->| rose | o------->| violet | o------->| butter- | nil |
9061 | | | | | | | cup | |
9062 -------------- --------------- ----------------
9063@end group
9064@end smallexample
9065@end iftex
9066@end ifclear
9067
9068(Symbols consist of more than pairs of addresses, but the structure of
9069a symbol is made up of addresses. Indeed, the symbol @code{bouquet}
9070consists of a group of address-boxes, one of which is the address of
9071the printed word @samp{bouquet}, a second of which is the address of a
9072function definition attached to the symbol, if any, a third of which
9073is the address of the first pair of address-boxes for the list
9074@code{(rose violet buttercup)}, and so on. Here we are showing that
9075the symbol's third address-box points to the first pair of
9076address-boxes for the list.)
9077
9078If a symbol is set to the @sc{cdr} of a list, the list itself is not
9079changed; the symbol simply has an address further down the list. (In
9080the jargon, @sc{car} and @sc{cdr} are `non-destructive'.) Thus,
9081evaluation of the following expression
9082
9083@smallexample
9084(setq flowers (cdr bouquet))
9085@end smallexample
9086
9087@need 800
9088@noindent
9089produces this:
9090
9091@c cons-cell-diagram #3
9092@ifnottex
9093@sp 1
9094@smallexample
9095@group
9096bouquet flowers
9097 | |
9098 | ___ ___ | ___ ___ ___ ___
9099 --> | | | --> | | | | | |
9100 |___|___|----> |___|___|--> |___|___|--> nil
9101 | | |
9102 | | |
9103 --> rose --> violet --> buttercup
9104@end group
9105@end smallexample
9106@sp 1
9107@end ifnottex
9108@ifset print-postscript-figures
9109@sp 1
9110@tex
9111@image{cons-3}
9112%%%% old method of including an image
9113% \input /usr/local/lib/tex/inputs/psfig.tex
9114% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9115% \catcode`\@=0 %
9116@end tex
9117@sp 1
9118@end ifset
9119@ifclear print-postscript-figures
9120@iftex
9121@sp 1
9122@smallexample
9123@group
9124bouquet flowers
9125 | |
9126 | ___ ___ | ___ ___ ___ ___
9127 --> | | | --> | | | | | |
9128 |___|___|----> |___|___|--> |___|___|--> nil
9129 | | |
9130 | | |
9131 --> rose --> violet --> buttercup
9132@end group
9133@end smallexample
9134@sp 1
9135@end iftex
9136@end ifclear
9137
9138@noindent
9139The value of @code{flowers} is @code{(violet buttercup)}, which is
9140to say, the symbol @code{flowers} holds the address of the pair of
9141address-boxes, the first of which holds the address of @code{violet},
9142and the second of which holds the address of @code{buttercup}.
9143
9144A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9145pair}. @xref{List Type, , List Type , elisp, The GNU Emacs Lisp
9146Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9147Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9148information about cons cells and dotted pairs.
9149
9150@need 1200
9151The function @code{cons} adds a new pair of addresses to the front of
9152a series of addresses like that shown above. For example, evaluating
9153the expression
9154
9155@smallexample
9156(setq bouquet (cons 'lily bouquet))
9157@end smallexample
9158
9159@need 1500
9160@noindent
9161produces:
9162
9163@c cons-cell-diagram #4
9164@ifnottex
9165@sp 1
9166@smallexample
9167@group
9168bouquet flowers
9169 | |
9170 | ___ ___ ___ ___ | ___ ___ ___ ___
9171 --> | | | | | | --> | | | | | |
9172 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9173 | | | |
9174 | | | |
9175 --> lily --> rose --> violet --> buttercup
9176@end group
9177@end smallexample
9178@sp 1
9179@end ifnottex
9180@ifset print-postscript-figures
9181@sp 1
9182@tex
9183@image{cons-4}
9184%%%% old method of including an image
9185% \input /usr/local/lib/tex/inputs/psfig.tex
9186% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9187% \catcode`\@=0 %
9188@end tex
9189@sp 1
9190@end ifset
9191@ifclear print-postscript-figures
9192@iftex
9193@sp 1
9194@smallexample
9195@group
9196bouquet flowers
9197 | |
9198 | ___ ___ ___ ___ | ___ ___ ___ ___
9199 --> | | | | | | --> | | | | | |
9200 |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9201 | | | |
9202 | | | |
9203 --> lily --> rose --> violet --> buttercup
9204@end group
9205@end smallexample
9206@sp 1
9207@end iftex
9208@end ifclear
9209
9210@need 1200
9211@noindent
9212However, this does not change the value of the symbol
9213@code{flowers}, as you can see by evaluating the following,
9214
9215@smallexample
9216(eq (cdr (cdr bouquet)) flowers)
9217@end smallexample
9218
9219@noindent
9220which returns @code{t} for true.
9221
9222Until it is reset, @code{flowers} still has the value
9223@code{(violet buttercup)}; that is, it has the address of the cons
9224cell whose first address is of @code{violet}. Also, this does not
9225alter any of the pre-existing cons cells; they are all still there.
9226
9227Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9228of the next cons cell in the series; to get the @sc{car} of a list,
9229you get the address of the first element of the list; to @code{cons} a
9230new element on a list, you add a new cons cell to the front of the list.
9231That is all there is to it! The underlying structure of Lisp is
9232brilliantly simple!
9233
9234And what does the last address in a series of cons cells refer to? It
9235is the address of the empty list, of @code{nil}.
9236
9237In summary, when a Lisp variable is set to a value, it is provided with
9238the address of the list to which the variable refers.
9239
9240@node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9241@section Symbols as a Chest of Drawers
9242@cindex Symbols as a Chest of Drawers
9243@cindex Chest of Drawers, metaphor for a symbol
9244@cindex Drawers, Chest of, metaphor for a symbol
9245
9246In an earlier section, I suggested that you might imagine a symbol as
9247being a chest of drawers. The function definition is put in one
9248drawer, the value in another, and so on. What is put in the drawer
9249holding the value can be changed without affecting the contents of the
9250drawer holding the function definition, and vice-versa.
9251
9252Actually, what is put in each drawer is the address of the value or
9253function definition. It is as if you found an old chest in the attic,
9254and in one of its drawers you found a map giving you directions to
9255where the buried treasure lies.
9256
9257(In addition to its name, symbol definition, and variable value, a
9258symbol has a `drawer' for a @dfn{property list} which can be used to
9259record other information. Property lists are not discussed here; see
9260@ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9261Reference Manual}.)
9262
9263@need 1500
9264Here is a fanciful representation:
9265
9266@c chest-of-drawers diagram
9267@ifnottex
9268@sp 1
9269@smallexample
9270@group
9271 Chest of Drawers Contents of Drawers
9272
9273 __ o0O0o __
9274 / \
9275 ---------------------
9276 | directions to | [map to]
9277 | symbol name | bouquet
9278 | |
9279 +---------------------+
9280 | directions to |
9281 | symbol definition | [none]
9282 | |
9283 +---------------------+
9284 | directions to | [map to]
9285 | variable value | (rose violet buttercup)
9286 | |
9287 +---------------------+
9288 | directions to |
9289 | property list | [not described here]
9290 | |
9291 +---------------------+
9292 |/ \|
9293@end group
9294@end smallexample
9295@sp 1
9296@end ifnottex
9297@ifset print-postscript-figures
9298@sp 1
9299@tex
9300@image{drawers}
9301%%%% old method of including an image
9302% \input /usr/local/lib/tex/inputs/psfig.tex
9303% \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9304% \catcode`\@=0 %
9305@end tex
9306@sp 1
9307@end ifset
9308@ifclear print-postscript-figures
9309@iftex
9310@sp 1
9311@smallexample
9312@group
9313 Chest of Drawers Contents of Drawers
9314
9315 __ o0O0o __
9316 / \
9317 ---------------------
9318 | directions to | [map to]
9319 | symbol name | bouquet
9320 | |
9321 +---------------------+
9322 | directions to |
9323 | symbol definition | [none]
9324 | |
9325 +---------------------+
9326 | directions to | [map to]
9327 | variable value | (rose violet buttercup)
9328 | |
9329 +---------------------+
9330 | directions to |
9331 | property list | [not described here]
9332 | |
9333 +---------------------+
9334 |/ \|
9335@end group
9336@end smallexample
9337@sp 1
9338@end iftex
9339@end ifclear
9340
9341@node List Exercise, , Symbols as Chest, List Implementation
9342@section Exercise
9343
9344Set @code{flowers} to @code{violet} and @code{buttercup}. Cons two
9345more flowers on to this list and set this new list to
9346@code{more-flowers}. Set the @sc{car} of @code{flowers} to a fish.
9347What does the @code{more-flowers} list now contain?
9348
9349@node Yanking, Loops & Recursion, List Implementation, Top
9350@comment node-name, next, previous, up
9351@chapter Yanking Text Back
9352@findex yank
9353@findex rotate-yank-pointer
9354@cindex Text retrieval
9355@cindex Retrieving text
9356@cindex Pasting text
9357
9358Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9359you can bring it back with a `yank' command. The text that is cut out of
9360the buffer is put in the kill ring and the yank commands insert the
9361appropriate contents of the kill ring back into a buffer (not necessarily
9362the original buffer).
9363
9364A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9365the kill ring into the current buffer. If the @kbd{C-y} command is
9366followed immediately by @kbd{M-y}, the first element is replaced by
9367the second element. Successive @kbd{M-y} commands replace the second
9368element with the third, fourth, or fifth element, and so on. When the
9369last element in the kill ring is reached, it is replaced by the first
9370element and the cycle is repeated. (Thus the kill ring is called a
9371`ring' rather than just a `list'. However, the actual data structure
9372that holds the text is a list.
9373@xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9374list is handled as a ring.)
9375
9376@menu
9377* Kill Ring Overview:: The kill ring is a list.
9378* kill-ring-yank-pointer:: The @code{kill-ring-yank-pointer} variable.
9379* yank nthcdr Exercises::
9380@end menu
9381
9382@node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9383@comment node-name, next, previous, up
9384@section Kill Ring Overview
9385@cindex Kill ring overview
9386
9387The kill ring is a list of textual strings. This is what it looks like:
9388
9389@smallexample
9390("some text" "a different piece of text" "yet more text")
9391@end smallexample
9392
9393If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9394string of characters saying @samp{some text} would be inserted in this
9395buffer where my cursor is located.
9396
9397The @code{yank} command is also used for duplicating text by copying it.
9398The copied text is not cut from the buffer, but a copy of it is put on the
9399kill ring and is inserted by yanking it back.
9400
9401Three functions are used for bringing text back from the kill ring:
9402@code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9403which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9404which is used by the two other functions.
9405
9406These functions refer to the kill ring through a variable called the
9407@code{kill-ring-yank-pointer}. Indeed, the insertion code for both the
9408@code{yank} and @code{yank-pop} functions is:
9409
9410@smallexample
9411(insert (car kill-ring-yank-pointer))
9412@end smallexample
9413
9414To begin to understand how @code{yank} and @code{yank-pop} work, it is
9415first necessary to look at the @code{kill-ring-yank-pointer} variable
9416and the @code{rotate-yank-pointer} function.
9417
9418@node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9419@comment node-name, next, previous, up
9420@section The @code{kill-ring-yank-pointer} Variable
9421
9422@code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9423a variable. It points to something by being bound to the value of what
9424it points to, like any other Lisp variable.
9425
9426@need 1000
9427Thus, if the value of the kill ring is:
9428
9429@smallexample
9430("some text" "a different piece of text" "yet more text")
9431@end smallexample
9432
9433@need 1250
9434@noindent
9435and the @code{kill-ring-yank-pointer} points to the second clause, the
9436value of @code{kill-ring-yank-pointer} is:
9437
9438@smallexample
9439("a different piece of text" "yet more text")
9440@end smallexample
9441
9442As explained in the previous chapter (@pxref{List Implementation}), the
9443computer does not keep two different copies of the text being pointed to
9444by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}. The
9445words ``a different piece of text'' and ``yet more text'' are not
9446duplicated. Instead, the two Lisp variables point to the same pieces of
9447text. Here is a diagram:
9448
9449@c cons-cell-diagram #5
9450@ifnottex
9451@smallexample
9452@group
9453kill-ring kill-ring-yank-pointer
9454 | |
9455 | ___ ___ | ___ ___ ___ ___
9456 ---> | | | --> | | | | | |
9457 |___|___|----> |___|___|--> |___|___|--> nil
9458 | | |
9459 | | |
9460 | | --> "yet more text"
9461 | |
9462 | --> "a different piece of text
9463 |
9464 --> "some text"
9465@end group
9466@end smallexample
9467@sp 1
9468@end ifnottex
9469@ifset print-postscript-figures
9470@sp 1
9471@tex
9472@image{cons-5}
9473%%%% old method of including an image
9474% \input /usr/local/lib/tex/inputs/psfig.tex
9475% \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9476% \catcode`\@=0 %
9477@end tex
9478@sp 1
9479@end ifset
9480@ifclear print-postscript-figures
9481@iftex
9482@smallexample
9483@group
9484kill-ring kill-ring-yank-pointer
9485 | |
9486 | ___ ___ | ___ ___ ___ ___
9487 ---> | | | --> | | | | | |
9488 |___|___|----> |___|___|--> |___|___|--> nil
9489 | | |
9490 | | |
9491 | | --> "yet more text"
9492 | |
9493 | --> "a different piece of text
9494 |
9495 --> "some text"
9496@end group
9497@end smallexample
9498@sp 1
9499@end iftex
9500@end ifclear
9501
9502Both the variable @code{kill-ring} and the variable
9503@code{kill-ring-yank-pointer} are pointers. But the kill ring itself is
9504usually described as if it were actually what it is composed of. The
9505@code{kill-ring} is spoken of as if it were the list rather than that it
9506points to the list. Conversely, the @code{kill-ring-yank-pointer} is
9507spoken of as pointing to a list.
9508
9509These two ways of talking about the same thing sound confusing at first but
9510make sense on reflection. The kill ring is generally thought of as the
9511complete structure of data that holds the information of what has recently
9512been cut out of the Emacs buffers. The @code{kill-ring-yank-pointer}
9513on the other hand, serves to indicate---that is, to `point to'---that part
9514of the kill ring of which the first element (the @sc{car}) will be
9515inserted.
9516
9517The @code{rotate-yank-pointer} function changes the element in the
9518kill ring to which the @code{kill-ring-yank-pointer} points; when the
9519pointer is set to point to the next element beyond the end of the kill
9520ring, it automatically sets it to point to the first element of the
9521kill ring. This is how the list is transformed into a ring. The
9522@code{rotate-yank-pointer} function itself is not difficult, but
9523contains many details. It and the much simpler @code{yank} and
9524@code{yank-pop} functions are described in an appendix.
9525@xref{Kill Ring, , Handling the Kill Ring}.
9526
9527@need 1500
9528@node yank nthcdr Exercises, , kill-ring-yank-pointer, Yanking
9529@section Exercises with @code{yank} and @code{nthcdr}
9530
9531@itemize @bullet
9532@item
9533Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9534your kill ring. Add several items to your kill ring; look at its
9535value again. Using @kbd{M-y} (@code{yank-pop)}, move all the way
9536around the kill ring. How many items were in your kill ring? Find
9537the value of @code{kill-ring-max}. Was your kill ring full, or could
9538you have kept more blocks of text within it?
9539
9540@item
9541Using @code{nthcdr} and @code{car}, construct a series of expressions
9542to return the first, second, third, and fourth elements of a list.
9543@end itemize
9544
9545@node Loops & Recursion, Regexp Search, Yanking, Top
9546@comment node-name, next, previous, up
9547@chapter Loops and Recursion
9548@cindex Loops and recursion
9549@cindex Recursion and loops
9550@cindex Repetition (loops)
9551
9552Emacs Lisp has two primary ways to cause an expression, or a series of
9553expressions, to be evaluated repeatedly: one uses a @code{while}
9554loop, and the other uses @dfn{recursion}.
9555
9556Repetition can be very valuable. For example, to move forward four
9557sentences, you need only write a program that will move forward one
9558sentence and then repeat the process four times. Since a computer does
9559not get bored or tired, such repetitive action does not have the
9560deleterious effects that excessive or the wrong kinds of repetition can
9561have on humans.
9562
9563People mostly write Emacs Lisp functions using @code{while} loops and
9564their kin; but you can use recursion, which provides a very powerful
9565way to think about and then to solve problems@footnote{You can write
9566recursive functions to be frugal or wasteful of mental or computer
9567resources; as it happens, methods that people find easy---that are
9568frugal of `mental resources'---sometimes use considerable computer
9569resources. Emacs was designed to run on machines that we now consider
9570limited and its default settings are conservative. You may want to
9571increase the values of @code{max-specpdl-size} and
9572@code{max-lisp-eval-depth}. In my @file{.emacs} file, I set them to
957315 and 30 times their default value.}.
9574
9575@menu
9576* while:: Causing a stretch of code to repeat.
9577* dolist dotimes::
9578* Recursion:: Causing a function to call itself.
9579* Looping exercise::
9580@end menu
9581
9582@node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9583@comment node-name, next, previous, up
9584@section @code{while}
9585@cindex Loops
9586@findex while
9587
9588The @code{while} special form tests whether the value returned by
9589evaluating its first argument is true or false. This is similar to what
9590the Lisp interpreter does with an @code{if}; what the interpreter does
9591next, however, is different.
9592
9593In a @code{while} expression, if the value returned by evaluating the
9594first argument is false, the Lisp interpreter skips the rest of the
9595expression (the @dfn{body} of the expression) and does not evaluate it.
9596However, if the value is true, the Lisp interpreter evaluates the body
9597of the expression and then again tests whether the first argument to
9598@code{while} is true or false. If the value returned by evaluating the
9599first argument is again true, the Lisp interpreter again evaluates the
9600body of the expression.
9601
9602@need 1200
9603The template for a @code{while} expression looks like this:
9604
9605@smallexample
9606@group
9607(while @var{true-or-false-test}
9608 @var{body}@dots{})
9609@end group
9610@end smallexample
9611
9612@menu
9613* Looping with while:: Repeat so long as test returns true.
9614* Loop Example:: A @code{while} loop that uses a list.
9615* print-elements-of-list:: Uses @code{while}, @code{car}, @code{cdr}.
9616* Incrementing Loop:: A loop with an incrementing counter.
9617* Decrementing Loop:: A loop with a decrementing counter.
9618@end menu
9619
9620@node Looping with while, Loop Example, while, while
9621@ifnottex
9622@unnumberedsubsec Looping with @code{while}
9623@end ifnottex
9624
9625So long as the true-or-false-test of the @code{while} expression
9626returns a true value when it is evaluated, the body is repeatedly
9627evaluated. This process is called a loop since the Lisp interpreter
9628repeats the same thing again and again, like an airplane doing a loop.
9629When the result of evaluating the true-or-false-test is false, the
9630Lisp interpreter does not evaluate the rest of the @code{while}
9631expression and `exits the loop'.
9632
9633Clearly, if the value returned by evaluating the first argument to
9634@code{while} is always true, the body following will be evaluated
9635again and again @dots{} and again @dots{} forever. Conversely, if the
9636value returned is never true, the expressions in the body will never
9637be evaluated. The craft of writing a @code{while} loop consists of
9638choosing a mechanism such that the true-or-false-test returns true
9639just the number of times that you want the subsequent expressions to
9640be evaluated, and then have the test return false.
9641
9642The value returned by evaluating a @code{while} is the value of the
9643true-or-false-test. An interesting consequence of this is that a
9644@code{while} loop that evaluates without error will return @code{nil}
9645or false regardless of whether it has looped 1 or 100 times or none at
9646all. A @code{while} expression that evaluates successfully never
9647returns a true value! What this means is that @code{while} is always
9648evaluated for its side effects, which is to say, the consequences of
9649evaluating the expressions within the body of the @code{while} loop.
9650This makes sense. It is not the mere act of looping that is desired,
9651but the consequences of what happens when the expressions in the loop
9652are repeatedly evaluated.
9653
9654@node Loop Example, print-elements-of-list, Looping with while, while
9655@comment node-name, next, previous, up
9656@subsection A @code{while} Loop and a List
9657
9658A common way to control a @code{while} loop is to test whether a list
9659has any elements. If it does, the loop is repeated; but if it does not,
9660the repetition is ended. Since this is an important technique, we will
9661create a short example to illustrate it.
9662
9663A simple way to test whether a list has elements is to evaluate the
9664list: if it has no elements, it is an empty list and will return the
9665empty list, @code{()}, which is a synonym for @code{nil} or false. On
9666the other hand, a list with elements will return those elements when it
9667is evaluated. Since Emacs Lisp considers as true any value that is not
9668@code{nil}, a list that returns elements will test true in a
9669@code{while} loop.
9670
9671@need 1200
9672For example, you can set the variable @code{empty-list} to @code{nil} by
9673evaluating the following @code{setq} expression:
9674
9675@smallexample
9676(setq empty-list ())
9677@end smallexample
9678
9679@noindent
9680After evaluating the @code{setq} expression, you can evaluate the
9681variable @code{empty-list} in the usual way, by placing the cursor after
9682the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9683echo area:
9684
9685@smallexample
9686empty-list
9687@end smallexample
9688
9689On the other hand, if you set a variable to be a list with elements, the
9690list will appear when you evaluate the variable, as you can see by
9691evaluating the following two expressions:
9692
9693@smallexample
9694@group
9695(setq animals '(gazelle giraffe lion tiger))
9696
9697animals
9698@end group
9699@end smallexample
9700
9701Thus, to create a @code{while} loop that tests whether there are any
9702items in the list @code{animals}, the first part of the loop will be
9703written like this:
9704
9705@smallexample
9706@group
9707(while animals
9708 @dots{}
9709@end group
9710@end smallexample
9711
9712@noindent
9713When the @code{while} tests its first argument, the variable
9714@code{animals} is evaluated. It returns a list. So long as the list
9715has elements, the @code{while} considers the results of the test to be
9716true; but when the list is empty, it considers the results of the test
9717to be false.
9718
9719To prevent the @code{while} loop from running forever, some mechanism
9720needs to be provided to empty the list eventually. An oft-used
9721technique is to have one of the subsequent forms in the @code{while}
9722expression set the value of the list to be the @sc{cdr} of the list.
9723Each time the @code{cdr} function is evaluated, the list will be made
9724shorter, until eventually only the empty list will be left. At this
9725point, the test of the @code{while} loop will return false, and the
9726arguments to the @code{while} will no longer be evaluated.
9727
9728For example, the list of animals bound to the variable @code{animals}
9729can be set to be the @sc{cdr} of the original list with the
9730following expression:
9731
9732@smallexample
9733(setq animals (cdr animals))
9734@end smallexample
9735
9736@noindent
9737If you have evaluated the previous expressions and then evaluate this
9738expression, you will see @code{(giraffe lion tiger)} appear in the echo
9739area. If you evaluate the expression again, @code{(lion tiger)} will
9740appear in the echo area. If you evaluate it again and yet again,
9741@code{(tiger)} appears and then the empty list, shown by @code{nil}.
9742
9743A template for a @code{while} loop that uses the @code{cdr} function
9744repeatedly to cause the true-or-false-test eventually to test false
9745looks like this:
9746
9747@smallexample
9748@group
9749(while @var{test-whether-list-is-empty}
9750 @var{body}@dots{}
9751 @var{set-list-to-cdr-of-list})
9752@end group
9753@end smallexample
9754
9755This test and use of @code{cdr} can be put together in a function that
9756goes through a list and prints each element of the list on a line of its
9757own.
9758
9759@node print-elements-of-list, Incrementing Loop, Loop Example, while
9760@subsection An Example: @code{print-elements-of-list}
9761@findex print-elements-of-list
9762
9763The @code{print-elements-of-list} function illustrates a @code{while}
9764loop with a list.
9765
9766@cindex @file{*scratch*} buffer
9767The function requires several lines for its output. If you are
9768reading this in Emacs 21 or a later version, you can evaluate the
9769following expression inside of Info, as usual.
9770
9771If you are using an earlier version of Emacs, you need to copy the
9772necessary expressions to your @file{*scratch*} buffer and evaluate
9773them there. This is because the echo area had only one line in the
9774earlier versions.
9775
9776You can copy the expressions by marking the beginning of the region
9777with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9778the end of the region and then copying the region using @kbd{M-w}
9779(@code{copy-region-as-kill}). In the @file{*scratch*} buffer, you can
9780yank the expressions back by typing @kbd{C-y} (@code{yank}).
9781
9782After you have copied the expressions to the @file{*scratch*} buffer,
9783evaluate each expression in turn. Be sure to evaluate the last
9784expression, @code{(print-elements-of-list animals)}, by typing
9785@kbd{C-u C-x C-e}, that is, by giving an argument to
9786@code{eval-last-sexp}. This will cause the result of the evaluation
9787to be printed in the @file{*scratch*} buffer instead of being printed
9788in the echo area. (Otherwise you will see something like this in your
b15dd613 9789echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
8b096dce
EZ
9790each @samp{^J} stands for a `newline'.)
9791
9792@need 1500
9793If you are using Emacs 21 or later, you can evaluate these expressions
9794directly in the Info buffer, and the echo area will grow to show the
9795results.
9796
9797@smallexample
9798@group
9799(setq animals '(gazelle giraffe lion tiger))
9800
9801(defun print-elements-of-list (list)
9802 "Print each element of LIST on a line of its own."
9803 (while list
9804 (print (car list))
9805 (setq list (cdr list))))
9806
9807(print-elements-of-list animals)
9808@end group
9809@end smallexample
9810
9811@need 1200
9812@noindent
9813When you evaluate the three expressions in sequence, you will see
9814this:
9815
9816@smallexample
9817@group
8b096dce
EZ
9818gazelle
9819
b15dd613
RC
9820giraffe
9821
8b096dce
EZ
9822lion
9823
9824tiger
9825nil
9826@end group
9827@end smallexample
9828
9829Each element of the list is printed on a line of its own (that is what
9830the function @code{print} does) and then the value returned by the
9831function is printed. Since the last expression in the function is the
9832@code{while} loop, and since @code{while} loops always return
9833@code{nil}, a @code{nil} is printed after the last element of the list.
9834
9835@node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9836@comment node-name, next, previous, up
9837@subsection A Loop with an Incrementing Counter
9838
9839A loop is not useful unless it stops when it ought. Besides
9840controlling a loop with a list, a common way of stopping a loop is to
9841write the first argument as a test that returns false when the correct
9842number of repetitions are complete. This means that the loop must
9843have a counter---an expression that counts how many times the loop
9844repeats itself.
9845
9846The test can be an expression such as @code{(< count desired-number)}
9847which returns @code{t} for true if the value of @code{count} is less
9848than the @code{desired-number} of repetitions and @code{nil} for false if
9849the value of @code{count} is equal to or is greater than the
9850@code{desired-number}. The expression that increments the count can be
9851a simple @code{setq} such as @code{(setq count (1+ count))}, where
9852@code{1+} is a built-in function in Emacs Lisp that adds 1 to its
18432d81 9853argument. (The expression @w{@code{(1+ count)}} has the same result as
28be162e 9854@w{@code{(+ count 1)}}, but is easier for a human to read.)
8b096dce
EZ
9855
9856@need 1250
9857The template for a @code{while} loop controlled by an incrementing
9858counter looks like this:
9859
9860@smallexample
9861@group
9862@var{set-count-to-initial-value}
9863(while (< count desired-number) ; @r{true-or-false-test}
9864 @var{body}@dots{}
9865 (setq count (1+ count))) ; @r{incrementer}
9866@end group
9867@end smallexample
9868
9869@noindent
9870Note that you need to set the initial value of @code{count}; usually it
9871is set to 1.
9872
9873@menu
9874* Incrementing Example:: Counting pebbles in a triangle.
9875* Inc Example parts:: The parts of the function definition.
9876* Inc Example altogether:: Putting the function definition together.
9877@end menu
9878
9879@node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9880@unnumberedsubsubsec Example with incrementing counter
9881
9882Suppose you are playing on the beach and decide to make a triangle of
9883pebbles, putting one pebble in the first row, two in the second row,
9884three in the third row and so on, like this:
9885
9886@sp 1
9887@c pebble diagram
9888@ifnottex
9889@smallexample
9890@group
9891 *
9892 * *
9893 * * *
9894 * * * *
9895@end group
9896@end smallexample
9897@end ifnottex
9898@iftex
9899@smallexample
9900@group
9901 @bullet{}
9902 @bullet{} @bullet{}
9903 @bullet{} @bullet{} @bullet{}
9904 @bullet{} @bullet{} @bullet{} @bullet{}
9905@end group
9906@end smallexample
9907@end iftex
9908@sp 1
9909
9910@noindent
9911(About 2500 years ago, Pythagoras and others developed the beginnings of
9912number theory by considering questions such as this.)
9913
9914Suppose you want to know how many pebbles you will need to make a
9915triangle with 7 rows?
9916
9917Clearly, what you need to do is add up the numbers from 1 to 7. There
9918are two ways to do this; start with the smallest number, one, and add up
9919the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9920number and add the list going down: 7, 6, 5, 4 and so on. Because both
9921mechanisms illustrate common ways of writing @code{while} loops, we will
9922create two examples, one counting up and the other counting down. In
9923this first example, we will start with 1 and add 2, 3, 4 and so on.
9924
9925If you are just adding up a short list of numbers, the easiest way to do
9926it is to add up all the numbers at once. However, if you do not know
9927ahead of time how many numbers your list will have, or if you want to be
9928prepared for a very long list, then you need to design your addition so
9929that what you do is repeat a simple process many times instead of doing
9930a more complex process once.
9931
9932For example, instead of adding up all the pebbles all at once, what you
9933can do is add the number of pebbles in the first row, 1, to the number
9934in the second row, 2, and then add the total of those two rows to the
9935third row, 3. Then you can add the number in the fourth row, 4, to the
9936total of the first three rows; and so on.
9937
9938The critical characteristic of the process is that each repetitive
9939action is simple. In this case, at each step we add only two numbers,
9940the number of pebbles in the row and the total already found. This
9941process of adding two numbers is repeated again and again until the last
9942row has been added to the total of all the preceding rows. In a more
9943complex loop the repetitive action might not be so simple, but it will
9944be simpler than doing everything all at once.
9945
9946@node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9947@unnumberedsubsubsec The parts of the function definition
9948
9949The preceding analysis gives us the bones of our function definition:
9950first, we will need a variable that we can call @code{total} that will
9951be the total number of pebbles. This will be the value returned by
9952the function.
9953
9954Second, we know that the function will require an argument: this
9955argument will be the total number of rows in the triangle. It can be
9956called @code{number-of-rows}.
9957
9958Finally, we need a variable to use as a counter. We could call this
9959variable @code{counter}, but a better name is @code{row-number}.
9960That is because what the counter does is count rows, and a program
9961should be written to be as understandable as possible.
9962
9963When the Lisp interpreter first starts evaluating the expressions in the
9964function, the value of @code{total} should be set to zero, since we have
9965not added anything to it. Then the function should add the number of
9966pebbles in the first row to the total, and then add the number of
9967pebbles in the second to the total, and then add the number of
9968pebbles in the third row to the total, and so on, until there are no
9969more rows left to add.
9970
9971Both @code{total} and @code{row-number} are used only inside the
9972function, so they can be declared as local variables with @code{let}
9973and given initial values. Clearly, the initial value for @code{total}
9974should be 0. The initial value of @code{row-number} should be 1,
9975since we start with the first row. This means that the @code{let}
9976statement will look like this:
9977
9978@smallexample
9979@group
9980 (let ((total 0)
9981 (row-number 1))
9982 @var{body}@dots{})
9983@end group
9984@end smallexample
9985
9986After the internal variables are declared and bound to their initial
9987values, we can begin the @code{while} loop. The expression that serves
9988as the test should return a value of @code{t} for true so long as the
9989@code{row-number} is less than or equal to the @code{number-of-rows}.
9990(If the expression tests true only so long as the row number is less
9991than the number of rows in the triangle, the last row will never be
9992added to the total; hence the row number has to be either less than or
9993equal to the number of rows.)
9994
9995@need 1500
9996@findex <= @r{(less than or equal)}
9997Lisp provides the @code{<=} function that returns true if the value of
9998its first argument is less than or equal to the value of its second
9999argument and false otherwise. So the expression that the @code{while}
10000will evaluate as its test should look like this:
10001
10002@smallexample
10003(<= row-number number-of-rows)
10004@end smallexample
10005
10006The total number of pebbles can be found by repeatedly adding the number
10007of pebbles in a row to the total already found. Since the number of
10008pebbles in the row is equal to the row number, the total can be found by
10009adding the row number to the total. (Clearly, in a more complex
10010situation, the number of pebbles in the row might be related to the row
10011number in a more complicated way; if this were the case, the row number
10012would be replaced by the appropriate expression.)
10013
10014@smallexample
10015(setq total (+ total row-number))
10016@end smallexample
10017
10018@noindent
10019What this does is set the new value of @code{total} to be equal to the
10020sum of adding the number of pebbles in the row to the previous total.
10021
10022After setting the value of @code{total}, the conditions need to be
10023established for the next repetition of the loop, if there is one. This
10024is done by incrementing the value of the @code{row-number} variable,
10025which serves as a counter. After the @code{row-number} variable has
10026been incremented, the true-or-false-test at the beginning of the
10027@code{while} loop tests whether its value is still less than or equal to
10028the value of the @code{number-of-rows} and if it is, adds the new value
10029of the @code{row-number} variable to the @code{total} of the previous
10030repetition of the loop.
10031
10032@need 1200
10033The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10034@code{row-number} variable can be incremented with this expression:
10035
10036@smallexample
10037(setq row-number (1+ row-number))
10038@end smallexample
10039
10040@node Inc Example altogether, , Inc Example parts, Incrementing Loop
10041@unnumberedsubsubsec Putting the function definition together
10042
10043We have created the parts for the function definition; now we need to
10044put them together.
10045
10046@need 800
10047First, the contents of the @code{while} expression:
10048
10049@smallexample
10050@group
10051(while (<= row-number number-of-rows) ; @r{true-or-false-test}
10052 (setq total (+ total row-number))
10053 (setq row-number (1+ row-number))) ; @r{incrementer}
10054@end group
10055@end smallexample
10056
10057Along with the @code{let} expression varlist, this very nearly
10058completes the body of the function definition. However, it requires
10059one final element, the need for which is somewhat subtle.
10060
10061The final touch is to place the variable @code{total} on a line by
10062itself after the @code{while} expression. Otherwise, the value returned
10063by the whole function is the value of the last expression that is
10064evaluated in the body of the @code{let}, and this is the value
10065returned by the @code{while}, which is always @code{nil}.
10066
10067This may not be evident at first sight. It almost looks as if the
10068incrementing expression is the last expression of the whole function.
10069But that expression is part of the body of the @code{while}; it is the
10070last element of the list that starts with the symbol @code{while}.
10071Moreover, the whole of the @code{while} loop is a list within the body
10072of the @code{let}.
10073
10074@need 1250
10075In outline, the function will look like this:
10076
10077@smallexample
10078@group
10079(defun @var{name-of-function} (@var{argument-list})
10080 "@var{documentation}@dots{}"
10081 (let (@var{varlist})
10082 (while (@var{true-or-false-test})
10083 @var{body-of-while}@dots{} )
10084 @dots{} ) ; @r{Need final expression here.}
10085@end group
10086@end smallexample
10087
10088The result of evaluating the @code{let} is what is going to be returned
10089by the @code{defun} since the @code{let} is not embedded within any
10090containing list, except for the @code{defun} as a whole. However, if
10091the @code{while} is the last element of the @code{let} expression, the
10092function will always return @code{nil}. This is not what we want!
10093Instead, what we want is the value of the variable @code{total}. This
10094is returned by simply placing the symbol as the last element of the list
10095starting with @code{let}. It gets evaluated after the preceding
10096elements of the list are evaluated, which means it gets evaluated after
10097it has been assigned the correct value for the total.
10098
10099It may be easier to see this by printing the list starting with
10100@code{let} all on one line. This format makes it evident that the
10101@var{varlist} and @code{while} expressions are the second and third
10102elements of the list starting with @code{let}, and the @code{total} is
10103the last element:
10104
10105@smallexample
10106@group
10107(let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10108@end group
10109@end smallexample
10110
10111@need 1200
10112Putting everything together, the @code{triangle} function definition
10113looks like this:
10114
10115@smallexample
10116@group
10117(defun triangle (number-of-rows) ; @r{Version with}
10118 ; @r{ incrementing counter.}
10119 "Add up the number of pebbles in a triangle.
10120The first row has one pebble, the second row two pebbles,
10121the third row three pebbles, and so on.
10122The argument is NUMBER-OF-ROWS."
10123@end group
10124@group
10125 (let ((total 0)
10126 (row-number 1))
10127 (while (<= row-number number-of-rows)
10128 (setq total (+ total row-number))
10129 (setq row-number (1+ row-number)))
10130 total))
10131@end group
10132@end smallexample
10133
10134@need 1200
10135After you have installed @code{triangle} by evaluating the function, you
10136can try it out. Here are two examples:
10137
10138@smallexample
10139@group
10140(triangle 4)
10141
10142(triangle 7)
10143@end group
10144@end smallexample
10145
10146@noindent
10147The sum of the first four numbers is 10 and the sum of the first seven
10148numbers is 28.
10149
10150@node Decrementing Loop, , Incrementing Loop, while
10151@comment node-name, next, previous, up
10152@subsection Loop with a Decrementing Counter
10153
10154Another common way to write a @code{while} loop is to write the test
10155so that it determines whether a counter is greater than zero. So long
10156as the counter is greater than zero, the loop is repeated. But when
10157the counter is equal to or less than zero, the loop is stopped. For
10158this to work, the counter has to start out greater than zero and then
10159be made smaller and smaller by a form that is evaluated
10160repeatedly.
10161
10162The test will be an expression such as @code{(> counter 0)} which
10163returns @code{t} for true if the value of @code{counter} is greater
10164than zero, and @code{nil} for false if the value of @code{counter} is
10165equal to or less than zero. The expression that makes the number
10166smaller and smaller can be a simple @code{setq} such as @code{(setq
10167counter (1- counter))}, where @code{1-} is a built-in function in
10168Emacs Lisp that subtracts 1 from its argument.
10169
10170@need 1250
10171The template for a decrementing @code{while} loop looks like this:
10172
10173@smallexample
10174@group
10175(while (> counter 0) ; @r{true-or-false-test}
10176 @var{body}@dots{}
10177 (setq counter (1- counter))) ; @r{decrementer}
10178@end group
10179@end smallexample
10180
10181@menu
10182* Decrementing Example:: More pebbles on the beach.
10183* Dec Example parts:: The parts of the function definition.
10184* Dec Example altogether:: Putting the function definition together.
10185@end menu
10186
10187@node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10188@unnumberedsubsubsec Example with decrementing counter
10189
10190To illustrate a loop with a decrementing counter, we will rewrite the
10191@code{triangle} function so the counter decreases to zero.
10192
10193This is the reverse of the earlier version of the function. In this
10194case, to find out how many pebbles are needed to make a triangle with
101953 rows, add the number of pebbles in the third row, 3, to the number
10196in the preceding row, 2, and then add the total of those two rows to
10197the row that precedes them, which is 1.
10198
10199Likewise, to find the number of pebbles in a triangle with 7 rows, add
10200the number of pebbles in the seventh row, 7, to the number in the
10201preceding row, which is 6, and then add the total of those two rows to
10202the row that precedes them, which is 5, and so on. As in the previous
10203example, each addition only involves adding two numbers, the total of
10204the rows already added up and the number of pebbles in the row that is
10205being added to the total. This process of adding two numbers is
10206repeated again and again until there are no more pebbles to add.
10207
10208We know how many pebbles to start with: the number of pebbles in the
10209last row is equal to the number of rows. If the triangle has seven
10210rows, the number of pebbles in the last row is 7. Likewise, we know how
10211many pebbles are in the preceding row: it is one less than the number in
10212the row.
10213
10214@node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10215@unnumberedsubsubsec The parts of the function definition
10216
10217We start with three variables: the total number of rows in the
10218triangle; the number of pebbles in a row; and the total number of
10219pebbles, which is what we want to calculate. These variables can be
10220named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10221@code{total}, respectively.
10222
10223Both @code{total} and @code{number-of-pebbles-in-row} are used only
10224inside the function and are declared with @code{let}. The initial
10225value of @code{total} should, of course, be zero. However, the
10226initial value of @code{number-of-pebbles-in-row} should be equal to
10227the number of rows in the triangle, since the addition will start with
10228the longest row.
10229
10230@need 1250
10231This means that the beginning of the @code{let} expression will look
10232like this:
10233
10234@smallexample
10235@group
10236(let ((total 0)
10237 (number-of-pebbles-in-row number-of-rows))
10238 @var{body}@dots{})
10239@end group
10240@end smallexample
10241
10242The total number of pebbles can be found by repeatedly adding the number
10243of pebbles in a row to the total already found, that is, by repeatedly
10244evaluating the following expression:
10245
10246@smallexample
10247(setq total (+ total number-of-pebbles-in-row))
10248@end smallexample
10249
10250@noindent
10251After the @code{number-of-pebbles-in-row} is added to the @code{total},
10252the @code{number-of-pebbles-in-row} should be decremented by one, since
10253the next time the loop repeats, the preceding row will be
10254added to the total.
10255
10256The number of pebbles in a preceding row is one less than the number of
10257pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10258used to compute the number of pebbles in the preceding row. This can be
10259done with the following expression:
10260
10261@smallexample
10262@group
10263(setq number-of-pebbles-in-row
10264 (1- number-of-pebbles-in-row))
10265@end group
10266@end smallexample
10267
10268Finally, we know that the @code{while} loop should stop making repeated
10269additions when there are no pebbles in a row. So the test for
10270the @code{while} loop is simply:
10271
10272@smallexample
10273(while (> number-of-pebbles-in-row 0)
10274@end smallexample
10275
10276@node Dec Example altogether, , Dec Example parts, Decrementing Loop
10277@unnumberedsubsubsec Putting the function definition together
10278
10279We can put these expressions together to create a function definition
10280that works. However, on examination, we find that one of the local
10281variables is unneeded!
10282
10283@need 1250
10284The function definition looks like this:
10285
10286@smallexample
10287@group
10288;;; @r{First subtractive version.}
10289(defun triangle (number-of-rows)
10290 "Add up the number of pebbles in a triangle."
10291 (let ((total 0)
10292 (number-of-pebbles-in-row number-of-rows))
10293 (while (> number-of-pebbles-in-row 0)
10294 (setq total (+ total number-of-pebbles-in-row))
10295 (setq number-of-pebbles-in-row
10296 (1- number-of-pebbles-in-row)))
10297 total))
10298@end group
10299@end smallexample
10300
10301As written, this function works.
10302
10303However, we do not need @code{number-of-pebbles-in-row}.
10304
10305@cindex Argument as local variable
10306When the @code{triangle} function is evaluated, the symbol
10307@code{number-of-rows} will be bound to a number, giving it an initial
10308value. That number can be changed in the body of the function as if
10309it were a local variable, without any fear that such a change will
10310effect the value of the variable outside of the function. This is a
10311very useful characteristic of Lisp; it means that the variable
10312@code{number-of-rows} can be used anywhere in the function where
10313@code{number-of-pebbles-in-row} is used.
10314
10315@need 800
10316Here is a second version of the function written a bit more cleanly:
10317
10318@smallexample
10319@group
10320(defun triangle (number) ; @r{Second version.}
10321 "Return sum of numbers 1 through NUMBER inclusive."
10322 (let ((total 0))
10323 (while (> number 0)
10324 (setq total (+ total number))
10325 (setq number (1- number)))
10326 total))
10327@end group
10328@end smallexample
10329
10330In brief, a properly written @code{while} loop will consist of three parts:
10331
10332@enumerate
10333@item
10334A test that will return false after the loop has repeated itself the
10335correct number of times.
10336
10337@item
10338An expression the evaluation of which will return the value desired
10339after being repeatedly evaluated.
10340
10341@item
10342An expression to change the value passed to the true-or-false-test so
10343that the test returns false after the loop has repeated itself the right
10344number of times.
10345@end enumerate
10346
10347@node dolist dotimes, Recursion, while, Loops & Recursion
10348@comment node-name, next, previous, up
10349@section Save your time: @code{dolist} and @code{dotimes}
10350
10351In addition to @code{while}, both @code{dolist} and @code{dotimes}
10352provide for looping. Sometimes these are quicker to write than the
10353equivalent @code{while} loop. Both are Lisp macros. (@xref{Macros, ,
10354Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10355
10356@code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10357list': @code{dolist} automatically shortens the list each time it
10358loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10359each shorter version of the list to the first of its arguments.
10360
e601d8fd 10361@code{dotimes} loops a specific number of times: you specify the number.
8b096dce
EZ
10362
10363@menu
10364* dolist::
10365* dotimes::
10366@end menu
10367
10368@node dolist, dotimes, dolist dotimes, dolist dotimes
10369@unnumberedsubsubsec The @code{dolist} Macro
10370@findex dolist
10371
10372Suppose, for example, you want to reverse a list, so that
10373``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10374
10375@need 1250
10376In practice, you would use the @code{reverse} function, like this:
10377
10378@smallexample
10379@group
10380(setq animals '(gazelle giraffe lion tiger))
10381
10382(reverse animals)
10383@end group
10384@end smallexample
10385
10386@need 800
10387@noindent
10388Here is how you could reverse the list using a @code{while} loop:
10389
10390@smallexample
10391@group
10392(setq animals '(gazelle giraffe lion tiger))
10393
10394(defun reverse-list-with-while (list)
10395 "Using while, reverse the order of LIST."
10396 (let (value) ; make sure list starts empty
10397 (while list
10398 (setq value (cons (car list) value))
10399 (setq list (cdr list)))
10400 value))
10401
10402(reverse-list-with-while animals)
10403@end group
10404@end smallexample
10405
10406@need 800
10407@noindent
10408And here is how you could use the @code{dolist} macro:
10409
10410@smallexample
10411@group
10412(setq animals '(gazelle giraffe lion tiger))
10413
10414(defun reverse-list-with-dolist (list)
10415 "Using dolist, reverse the order of LIST."
10416 (let (value) ; make sure list starts empty
10417 (dolist (element list value)
10418 (setq value (cons element value)))))
10419
10420(reverse-list-with-dolist animals)
10421@end group
10422@end smallexample
10423
10424@need 1250
10425@noindent
10426In Info, you can place your cursor after the closing parenthesis of
10427each expression and type @kbd{C-x C-e}; in each case, you should see
10428
10429@smallexample
10430(tiger lion giraffe gazelle)
10431@end smallexample
10432
10433@noindent
10434in the echo area.
10435
10436For this example, the existing @code{reverse} function is obviously best.
10437The @code{while} loop is just like our first example (@pxref{Loop
10438Example, , A @code{while} Loop and a List}). The @code{while} first
10439checks whether the list has elements; if so, it constructs a new list
10440by adding the first element of the list to the existing list (which in
10441the first iteration of the loop is @code{nil}). Since the second
10442element is prepended in front of the first element, and the third
10443element is prepended in front of the second element, the list is reversed.
10444
10445In the expression using a @code{while} loop,
10446the @w{@code{(setq list (cdr list))}}
10447expression shortens the list, so the @code{while} loop eventually
10448stops. In addition, it provides the @code{cons} expression with a new
10449first element by creating a new and shorter list at each repetition of
10450the loop.
10451
10452The @code{dolist} expression does very much the same as the
10453@code{while} expression, except that the @code{dolist} macro does some
10454of the work you have to do when writing a @code{while} expression.
10455
10456Like a @code{while} loop, a @code{dolist} loops. What is different is
10457that it automatically shortens the list each time it loops --- it
10458`@sc{cdr}s down the list' on its own --- and it automatically binds
10459the @sc{car} of each shorter version of the list to the first of its
10460arguments.
10461
10462In the example, the @sc{car} of each shorter version of the list is
10463referred to using the symbol @samp{element}, the list itself is called
10464@samp{list}, and the value returned is called @samp{value}. The
10465remainder of the @code{dolist} expression is the body.
10466
10467The @code{dolist} expression binds the @sc{car} of each shorter
10468version of the list to @code{element} and then evaluates the body of
10469the expression; and repeats the loop. The result is returned in
10470@code{value}.
10471
10472@node dotimes, , dolist, dolist dotimes
10473@unnumberedsubsubsec The @code{dotimes} Macro
10474@findex dotimes
10475
10476The @code{dotimes} macro is similar to @code{dolist}, except that it
10477loops a specific number of times.
10478
10479The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10480and so forth each time around the loop, and the value of the third
10481argument is returned. You need to provide the value of the second
10482argument, which is how many times the macro loops.
10483
10484@need 1250
10485For example, the following binds the numbers from 0 up to, but not
10486including, the number 3 to the first argument, @var{number}, and then
10487constructs a list of the three numbers. (The first number is 0, the
10488second number is 1, and the third number is 2; this makes a total of
10489three numbers in all, starting with zero as the first number.)
10490
10491@smallexample
10492@group
10493(let (value) ; otherwise a value is a void variable
10494 (dotimes (number 3 value)
10495 (setq value (cons number value))))
10496
10497@result{} (2 1 0)
10498@end group
10499@end smallexample
10500
10501@noindent
10502@code{dotimes} returns @code{value}, so the way to use
10503@code{dotimes} is to operate on some expression @var{number} number of
10504times and then return the result, either as a list or an atom.
10505
10506@need 1250
10507Here is an example of a @code{defun} that uses @code{dotimes} to add
10508up the number of pebbles in a triangle.
10509
10510@smallexample
10511@group
10512(defun triangle-using-dotimes (number-of-rows)
10513 "Using dotimes, add up the number of pebbles in a triangle."
10514(let ((total 0)) ; otherwise a total is a void variable
10515 (dotimes (number number-of-rows total)
10516 (setq total (+ total (1+ number))))))
10517
10518(triangle-using-dotimes 4)
10519@end group
10520@end smallexample
10521
10522@node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10523@comment node-name, next, previous, up
10524@section Recursion
10525@cindex Recursion
10526
10527A recursive function contains code that tells the Lisp interpreter to
10528call a program that runs exactly like itself, but with slightly
10529different arguments. The code runs exactly the same because it has
b15dd613
RC
10530the same name. However, even though the program has the same name, it
10531is not the same entity. It is different. In the jargon, it is a
10532different `instance'.
8b096dce
EZ
10533
10534Eventually, if the program is written correctly, the `slightly
10535different arguments' will become sufficiently different from the first
10536arguments that the final instance will stop.
10537
10538@menu
10539* Building Robots:: Same model, different serial number ...
10540* Recursive Definition Parts:: Walk until you stop ...
10541* Recursion with list:: Using a list as the test whether to recurse.
10542* Recursive triangle function::
10543* Recursion with cond::
10544* Recursive Patterns:: Often used templates.
10545* No Deferment:: Don't store up work ...
10546* No deferment solution::
10547@end menu
10548
10549@node Building Robots, Recursive Definition Parts, Recursion, Recursion
10550@comment node-name, next, previous, up
10551@subsection Building Robots: Extending the Metaphor
10552@cindex Building robots
10553@cindex Robots, building
10554
10555It is sometimes helpful to think of a running program as a robot that
10556does a job. In doing its job, a recursive function calls on a second
10557robot to help it. The second robot is identical to the first in every
10558way, except that the second robot helps the first and has been
10559passed different arguments than the first.
10560
10561In a recursive function, the second robot may call a third; and the
10562third may call a fourth, and so on. Each of these is a different
10563entity; but all are clones.
10564
10565Since each robot has slightly different instructions---the arguments
10566will differ from one robot to the next---the last robot should know
10567when to stop.
10568
10569Let's expand on the metaphor in which a computer program is a robot.
10570
10571A function definition provides the blueprints for a robot. When you
10572install a function definition, that is, when you evaluate a
10573@code{defun} special form, you install the necessary equipment to
10574build robots. It is as if you were in a factory, setting up an
10575assembly line. Robots with the same name are built according to the
10576same blueprints. So they have, as it were, the same `model number',
10577but a different `serial number'.
10578
10579We often say that a recursive function `calls itself'. What we mean
10580is that the instructions in a recursive function cause the Lisp
10581interpreter to run a different function that has the same name and
10582does the same job as the first, but with different arguments.
10583
10584It is important that the arguments differ from one instance to the
10585next; otherwise, the process will never stop.
10586
10587@node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10588@comment node-name, next, previous, up
10589@subsection The Parts of a Recursive Definition
10590@cindex Parts of a Recursive Definition
10591@cindex Recursive Definition Parts
10592
10593A recursive function typically contains a conditional expression which
10594has three parts:
10595
10596@enumerate
10597@item
10598A true-or-false-test that determines whether the function is called
10599again, here called the @dfn{do-again-test}.
10600
10601@item
10602The name of the function. When this name is called, a new instance of
10603the function---a new robot, as it were---is created and told what to do.
10604
10605@item
10606An expression that returns a different value each time the function is
10607called, here called the @dfn{next-step-expression}. Consequently, the
10608argument (or arguments) passed to the new instance of the function
10609will be different from that passed to the previous instance. This
10610causes the conditional expression, the @dfn{do-again-test}, to test
10611false after the correct number of repetitions.
10612@end enumerate
10613
10614Recursive functions can be much simpler than any other kind of
10615function. Indeed, when people first start to use them, they often look
10616so mysteriously simple as to be incomprehensible. Like riding a
10617bicycle, reading a recursive function definition takes a certain knack
10618which is hard at first but then seems simple.
10619
10620@need 1200
10621There are several different common recursive patterns. A very simple
10622pattern looks like this:
10623
10624@smallexample
10625@group
10626(defun @var{name-of-recursive-function} (@var{argument-list})
10627 "@var{documentation}@dots{}"
10628 (if @var{do-again-test}
10629 @var{body}@dots{}
10630 (@var{name-of-recursive-function}
10631 @var{next-step-expression})))
10632@end group
10633@end smallexample
10634
10635Each time a recursive function is evaluated, a new instance of it is
10636created and told what to do. The arguments tell the instance what to do.
10637
10638An argument is bound to the value of the next-step-expression. Each
10639instance runs with a different value of the next-step-expression.
10640
10641The value in the next-step-expression is used in the do-again-test.
10642
10643The value returned by the next-step-expression is passed to the new
10644instance of the function, which evaluates it (or some
10645transmogrification of it) to determine whether to continue or stop.
10646The next-step-expression is designed so that the do-again-test returns
10647false when the function should no longer be repeated.
10648
10649The do-again-test is sometimes called the @dfn{stop condition},
10650since it stops the repetitions when it tests false.
10651
10652@node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10653@comment node-name, next, previous, up
10654@subsection Recursion with a List
10655
10656The example of a @code{while} loop that printed the elements of a list
10657of numbers can be written recursively. Here is the code, including
10658an expression to set the value of the variable @code{animals} to a list.
10659
10660If you are using Emacs 20 or before, this example must be copied to
10661the @file{*scratch*} buffer and each expression must be evaluated
10662there. Use @kbd{C-u C-x C-e} to evaluate the
10663@code{(print-elements-recursively animals)} expression so that the
10664results are printed in the buffer; otherwise the Lisp interpreter will
10665try to squeeze the results into the one line of the echo area.
10666
10667Also, place your cursor immediately after the last closing parenthesis
10668of the @code{print-elements-recursively} function, before the comment.
10669Otherwise, the Lisp interpreter will try to evaluate the comment.
10670
10671If you are using Emacs 21 or later, you can evaluate this expression
10672directly in Info.
10673
10674@findex print-elements-recursively
10675@smallexample
10676@group
10677(setq animals '(gazelle giraffe lion tiger))
10678
10679(defun print-elements-recursively (list)
10680 "Print each element of LIST on a line of its own.
10681Uses recursion."
10682 (if list ; @r{do-again-test}
10683 (progn
10684 (print (car list)) ; @r{body}
10685 (print-elements-recursively ; @r{recursive call}
10686 (cdr list))))) ; @r{next-step-expression}
10687
10688(print-elements-recursively animals)
10689@end group
10690@end smallexample
10691
10692The @code{print-elements-recursively} function first tests whether
10693there is any content in the list; if there is, the function prints the
10694first element of the list, the @sc{car} of the list. Then the
10695function `invokes itself', but gives itself as its argument, not the
10696whole list, but the second and subsequent elements of the list, the
10697@sc{cdr} of the list.
10698
10699Put another way, if the list is not empty, the function invokes
10700another instance of code that is similar to the initial code, but is a
10701different thread of execution, with different arguments than the first
10702instance.
10703
10704Put in yet another way, if the list is not empty, the first robot
10705assemblies a second robot and tells it what to do; the second robot is
10706a different individual from the first, but is the same model.
10707
10708When the second evaluation occurs, the @code{if} expression is
10709evaluated and if true, prints the first element of the list it
10710receives as its argument (which is the second element of the original
10711list). Then the function `calls itself' with the @sc{cdr} of the list
10712it is invoked with, which (the second time around) is the @sc{cdr} of
10713the @sc{cdr} of the original list.
10714
10715Note that although we say that the function `calls itself', what we
10716mean is that the Lisp interpreter assembles and instructs a new
10717instance of the program. The new instance is a clone of the first,
10718but is a separate individual.
10719
10720Each time the function `invokes itself', it invokes itself on a
10721shorter version of the original list. It creates a new instance that
10722works on a shorter list.
10723
10724Eventually, the function invokes itself on an empty list. It creates
10725a new instance whose argument is @code{nil}. The conditional expression
10726tests the value of @code{list}. Since the value of @code{list} is
10727@code{nil}, the @code{if} expression tests false so the then-part is
10728not evaluated. The function as a whole then returns @code{nil}.
10729
10730@need 1200
10731When you evaluate @code{(print-elements-recursively animals)} in the
10732@file{*scratch*} buffer, you see this result:
10733
10734@smallexample
10735@group
8b096dce
EZ
10736gazelle
10737
b15dd613
RC
10738giraffe
10739
8b096dce
EZ
10740lion
10741
10742tiger
10743nil
10744@end group
10745@end smallexample
10746
10747@node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10748@comment node-name, next, previous, up
10749@subsection Recursion in Place of a Counter
10750@findex triangle-recursively
10751
10752@need 1200
10753The @code{triangle} function described in a previous section can also
10754be written recursively. It looks like this:
10755
10756@smallexample
10757@group
10758(defun triangle-recursively (number)
10759 "Return the sum of the numbers 1 through NUMBER inclusive.
10760Uses recursion."
10761 (if (= number 1) ; @r{do-again-test}
10762 1 ; @r{then-part}
10763 (+ number ; @r{else-part}
10764 (triangle-recursively ; @r{recursive call}
10765 (1- number))))) ; @r{next-step-expression}
10766
10767(triangle-recursively 7)
10768@end group
10769@end smallexample
10770
10771@noindent
10772You can install this function by evaluating it and then try it by
10773evaluating @code{(triangle-recursively 7)}. (Remember to put your
10774cursor immediately after the last parenthesis of the function
10775definition, before the comment.) The function evaluates to 28.
10776
10777To understand how this function works, let's consider what happens in the
10778various cases when the function is passed 1, 2, 3, or 4 as the value of
10779its argument.
10780
10781@menu
10782* Recursive Example arg of 1 or 2::
10783* Recursive Example arg of 3 or 4::
10784@end menu
10785
10786@node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10787@ifnottex
10788@unnumberedsubsubsec An argument of 1 or 2
10789@end ifnottex
10790
10791First, what happens if the value of the argument is 1?
10792
10793The function has an @code{if} expression after the documentation
10794string. It tests whether the value of @code{number} is equal to 1; if
10795so, Emacs evaluates the then-part of the @code{if} expression, which
10796returns the number 1 as the value of the function. (A triangle with
10797one row has one pebble in it.)
10798
10799Suppose, however, that the value of the argument is 2. In this case,
10800Emacs evaluates the else-part of the @code{if} expression.
10801
10802@need 1200
10803The else-part consists of an addition, the recursive call to
10804@code{triangle-recursively} and a decrementing action; and it looks like
10805this:
10806
10807@smallexample
10808(+ number (triangle-recursively (1- number)))
10809@end smallexample
10810
10811When Emacs evaluates this expression, the innermost expression is
10812evaluated first; then the other parts in sequence. Here are the steps
10813in detail:
10814
10815@table @i
10816@item Step 1 @w{ } Evaluate the innermost expression.
10817
10818The innermost expression is @code{(1- number)} so Emacs decrements the
10819value of @code{number} from 2 to 1.
10820
10821@item Step 2 @w{ } Evaluate the @code{triangle-recursively} function.
10822
10823The Lisp interpreter creates an individual instance of
10824@code{triangle-recursively}. It does not matter that this function is
10825contained within itself. Emacs passes the result Step 1 as the
10826argument used by this instance of the @code{triangle-recursively}
10827function
10828
10829In this case, Emacs evaluates @code{triangle-recursively} with an
10830argument of 1. This means that this evaluation of
10831@code{triangle-recursively} returns 1.
10832
10833@item Step 3 @w{ } Evaluate the value of @code{number}.
10834
10835The variable @code{number} is the second element of the list that
10836starts with @code{+}; its value is 2.
10837
10838@item Step 4 @w{ } Evaluate the @code{+} expression.
10839
10840The @code{+} expression receives two arguments, the first
10841from the evaluation of @code{number} (Step 3) and the second from the
10842evaluation of @code{triangle-recursively} (Step 2).
10843
10844The result of the addition is the sum of 2 plus 1, and the number 3 is
10845returned, which is correct. A triangle with two rows has three
10846pebbles in it.
10847@end table
10848
10849@node Recursive Example arg of 3 or 4, , Recursive Example arg of 1 or 2, Recursive triangle function
10850@unnumberedsubsubsec An argument of 3 or 4
10851
10852Suppose that @code{triangle-recursively} is called with an argument of
108533.
10854
10855@table @i
10856@item Step 1 @w{ } Evaluate the do-again-test.
10857
10858The @code{if} expression is evaluated first. This is the do-again
10859test and returns false, so the else-part of the @code{if} expression
10860is evaluated. (Note that in this example, the do-again-test causes
10861the function to call itself when it tests false, not when it tests
10862true.)
10863
10864@item Step 2 @w{ } Evaluate the innermost expression of the else-part.
10865
10866The innermost expression of the else-part is evaluated, which decrements
108673 to 2. This is the next-step-expression.
10868
10869@item Step 3 @w{ } Evaluate the @code{triangle-recursively} function.
10870
10871The number 2 is passed to the @code{triangle-recursively} function.
10872
10873We know what happens when Emacs evaluates @code{triangle-recursively} with
10874an argument of 2. After going through the sequence of actions described
10875earlier, it returns a value of 3. So that is what will happen here.
10876
10877@item Step 4 @w{ } Evaluate the addition.
10878
108793 will be passed as an argument to the addition and will be added to the
10880number with which the function was called, which is 3.
10881@end table
10882
10883@noindent
10884The value returned by the function as a whole will be 6.
10885
10886Now that we know what will happen when @code{triangle-recursively} is
10887called with an argument of 3, it is evident what will happen if it is
10888called with an argument of 4:
10889
10890@quotation
10891@need 800
10892In the recursive call, the evaluation of
10893
10894@smallexample
10895(triangle-recursively (1- 4))
10896@end smallexample
10897
10898@need 800
10899@noindent
10900will return the value of evaluating
10901
10902@smallexample
10903(triangle-recursively 3)
10904@end smallexample
10905
10906@noindent
10907which is 6 and this value will be added to 4 by the addition in the
10908third line.
10909@end quotation
10910
10911@noindent
10912The value returned by the function as a whole will be 10.
10913
10914Each time @code{triangle-recursively} is evaluated, it evaluates a
10915version of itself---a different instance of itself---with a smaller
10916argument, until the argument is small enough so that it does not
10917evaluate itself.
10918
10919Note that this particular design for a recursive function
10920requires that operations be deferred.
10921
10922Before @code{(triangle-recursively 7)} can calculate its answer, it
10923must call @code{(triangle-recursively 6)}; and before
10924@code{(triangle-recursively 6)} can calculate its answer, it must call
10925@code{(triangle-recursively 5)}; and so on. That is to say, the
10926calculation that @code{(triangle-recursively 7)} makes must be
10927deferred until @code{(triangle-recursively 6)} makes its calculation;
10928and @code{(triangle-recursively 6)} must defer until
10929@code{(triangle-recursively 5)} completes; and so on.
10930
10931If each of these instances of @code{triangle-recursively} are thought
10932of as different robots, the first robot must wait for the second to
10933complete its job, which must wait until the third completes, and so
10934on.
10935
10936There is a way around this kind of waiting, which we will discuss in
10937@ref{No Deferment, , Recursion without Deferments}.
10938
10939@node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10940@comment node-name, next, previous, up
10941@subsection Recursion Example Using @code{cond}
10942@findex cond
10943
10944The version of @code{triangle-recursively} described earlier is written
10945with the @code{if} special form. It can also be written using another
10946special form called @code{cond}. The name of the special form
10947@code{cond} is an abbreviation of the word @samp{conditional}.
10948
10949Although the @code{cond} special form is not used as often in the
10950Emacs Lisp sources as @code{if}, it is used often enough to justify
10951explaining it.
10952
10953@need 800
10954The template for a @code{cond} expression looks like this:
10955
10956@smallexample
10957@group
10958(cond
10959 @var{body}@dots{})
10960@end group
10961@end smallexample
10962
10963@noindent
10964where the @var{body} is a series of lists.
10965
10966@need 800
10967Written out more fully, the template looks like this:
10968
10969@smallexample
10970@group
10971(cond
10972 (@var{first-true-or-false-test} @var{first-consequent})
10973 (@var{second-true-or-false-test} @var{second-consequent})
10974 (@var{third-true-or-false-test} @var{third-consequent})
10975 @dots{})
10976@end group
10977@end smallexample
10978
10979When the Lisp interpreter evaluates the @code{cond} expression, it
10980evaluates the first element (the @sc{car} or true-or-false-test) of
10981the first expression in a series of expressions within the body of the
10982@code{cond}.
10983
10984If the true-or-false-test returns @code{nil} the rest of that
10985expression, the consequent, is skipped and the true-or-false-test of the
10986next expression is evaluated. When an expression is found whose
10987true-or-false-test returns a value that is not @code{nil}, the
10988consequent of that expression is evaluated. The consequent can be one
10989or more expressions. If the consequent consists of more than one
10990expression, the expressions are evaluated in sequence and the value of
10991the last one is returned. If the expression does not have a consequent,
10992the value of the true-or-false-test is returned.
10993
10994If none of the true-or-false-tests test true, the @code{cond} expression
10995returns @code{nil}.
10996
10997@need 1250
10998Written using @code{cond}, the @code{triangle} function looks like this:
10999
11000@smallexample
11001@group
11002(defun triangle-using-cond (number)
11003 (cond ((<= number 0) 0)
11004 ((= number 1) 1)
11005 ((> number 1)
11006 (+ number (triangle-using-cond (1- number))))))
11007@end group
11008@end smallexample
11009
11010@noindent
11011In this example, the @code{cond} returns 0 if the number is less than or
11012equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11013number (triangle-using-cond (1- number)))} if the number is greater than
110141.
11015
11016@node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11017@comment node-name, next, previous, up
11018@subsection Recursive Patterns
11019@cindex Recursive Patterns
11020
11021Here are three common recursive patterns. Each involves a list.
11022Recursion does not need to involve lists, but Lisp is designed for lists
11023and this provides a sense of its primal capabilities.
11024
11025@menu
11026* Every::
11027* Accumulate::
11028* Keep::
11029@end menu
11030
11031@node Every, Accumulate, Recursive Patterns, Recursive Patterns
11032@comment node-name, next, previous, up
11033@unnumberedsubsubsec Recursive Pattern: @emph{every}
11034@cindex Every, type of recursive pattern
11035@cindex Recursive pattern: every
11036
11037In the @code{every} recursive pattern, an action is performed on every
11038element of a list.
11039
11040@need 1500
11041The basic pattern is:
11042
11043@itemize @bullet
11044@item
11045If a list be empty, return @code{nil}.
11046@item
11047Else, act on the beginning of the list (the @sc{car} of the list)
11048 @itemize @minus
11049 @item
11050 through a recursive call by the function on the rest (the
11051 @sc{cdr}) of the list,
11052 @item
11053 and, optionally, combine the acted-on element, using @code{cons},
11054 with the results of acting on the rest.
11055 @end itemize
11056@end itemize
11057
11058@need 1500
11059Here is example:
11060
11061@smallexample
11062@group
11063(defun square-each (numbers-list)
11064 "Square each of a NUMBERS LIST, recursively."
11065 (if (not numbers-list) ; do-again-test
11066 nil
11067 (cons
11068 (* (car numbers-list) (car numbers-list))
11069 (square-each (cdr numbers-list))))) ; next-step-expression
11070@end group
11071
11072@group
11073(square-each '(1 2 3))
11074 @result{} (1 4 9)
11075@end group
11076@end smallexample
11077
11078@need 1200
11079@noindent
11080If @code{numbers-list} is empty, do nothing. But if it has content,
11081construct a list combining the square of the first number in the list
11082with the result of the recursive call.
11083
11084(The example follows the pattern exactly: @code{nil} is returned if
11085the numbers' list is empty. In practice, you would write the
11086conditional so it carries out the action when the numbers' list is not
11087empty.)
11088
11089The @code{print-elements-recursively} function (@pxref{Recursion with
11090list, , Recursion with a List}) is another example of an @code{every}
11091pattern, except in this case, rather than bring the results together
11092using @code{cons}, we print each element of output.
11093
11094@need 1250
11095The @code{print-elements-recursively} function looks like this:
11096
11097@smallexample
11098@group
11099(setq animals '(gazelle giraffe lion tiger))
11100@end group
11101
11102@group
11103(defun print-elements-recursively (list)
11104 "Print each element of LIST on a line of its own.
11105Uses recursion."
11106 (if list ; @r{do-again-test}
11107 (progn
11108 (print (car list)) ; @r{body}
11109 (print-elements-recursively ; @r{recursive call}
11110 (cdr list))))) ; @r{next-step-expression}
11111
11112(print-elements-recursively animals)
11113@end group
11114@end smallexample
11115
11116@need 1500
11117The pattern for @code{print-elements-recursively} is:
11118
11119@itemize @bullet
11120@item
11121If the list be empty, do nothing.
11122@item
11123But if the list has at least one element,
11124 @itemize @minus
11125 @item
11126 act on the beginning of the list (the @sc{car} of the list),
11127 @item
11128 and make a recursive call on the rest (the @sc{cdr}) of the list.
11129 @end itemize
11130@end itemize
11131
11132@node Accumulate, Keep, Every, Recursive Patterns
11133@comment node-name, next, previous, up
11134@unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11135@cindex Accumulate, type of recursive pattern
11136@cindex Recursive pattern: accumulate
11137
11138Another recursive pattern is called the @code{accumulate} pattern. In
11139the @code{accumulate} recursive pattern, an action is performed on
11140every element of a list and the result of that action is accumulated
11141with the results of performing the action on the other elements.
11142
11143This is very like the `every' pattern using @code{cons}, except that
11144@code{cons} is not used, but some other combiner.
11145
11146@need 1500
11147The pattern is:
11148
11149@itemize @bullet
11150@item
11151If a list be empty, return zero or some other constant.
11152@item
11153Else, act on the beginning of the list (the @sc{car} of the list),
11154 @itemize @minus
11155 @item
11156 and combine that acted-on element, using @code{+} or
11157 some other combining function, with
11158 @item
11159 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11160 @end itemize
11161@end itemize
11162
11163@need 1500
11164Here is an example:
11165
11166@smallexample
11167@group
11168(defun add-elements (numbers-list)
11169 "Add the elements of NUMBERS-LIST together."
11170 (if (not numbers-list)
11171 0
11172 (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11173@end group
11174
11175@group
11176(add-elements '(1 2 3 4))
11177 @result{} 10
11178@end group
11179@end smallexample
11180
11181@xref{Files List, , Making a List of Files}, for an example of the
11182accumulate pattern.
11183
11184@node Keep, , Accumulate, Recursive Patterns
11185@comment node-name, next, previous, up
11186@unnumberedsubsubsec Recursive Pattern: @emph{keep}
11187@cindex Keep, type of recursive pattern
11188@cindex Recursive pattern: keep
11189
11190A third recursive pattern is called the @code{keep} pattern.
11191In the @code{keep} recursive pattern, each element of a list is tested;
11192the element is acted on and the results are kept only if the element
11193meets a criterion.
11194
11195Again, this is very like the `every' pattern, except the element is
11196skipped unless it meets a criterion.
11197
11198@need 1500
11199The pattern has three parts:
11200
11201@itemize @bullet
11202@item
11203If a list be empty, return @code{nil}.
11204@item
11205Else, if the beginning of the list (the @sc{car} of the list) passes
11206 a test
11207 @itemize @minus
11208 @item
11209 act on that element and combine it, using @code{cons} with
11210 @item
11211 a recursive call by the function on the rest (the @sc{cdr}) of the list.
11212 @end itemize
11213@item
11214Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11215the test
11216 @itemize @minus
11217 @item
11218 skip on that element,
11219 @item
11220 and, recursively call the function on the rest (the @sc{cdr}) of the list.
11221 @end itemize
11222@end itemize
11223
11224@need 1500
11225Here is an example that uses @code{cond}:
11226
11227@smallexample
11228@group
11229(defun keep-three-letter-words (word-list)
11230 "Keep three letter words in WORD-LIST."
11231 (cond
11232 ;; First do-again-test: stop-condition
11233 ((not word-list) nil)
11234
11235 ;; Second do-again-test: when to act
11236 ((eq 3 (length (symbol-name (car word-list))))
11237 ;; combine acted-on element with recursive call on shorter list
11238 (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11239
11240 ;; Third do-again-test: when to skip element;
11241 ;; recursively call shorter list with next-step expression
11242 (t (keep-three-letter-words (cdr word-list)))))
11243@end group
11244
11245@group
11246(keep-three-letter-words '(one two three four five six))
11247 @result{} (one two six)
11248@end group
11249@end smallexample
11250
11251It goes without saying that you need not use @code{nil} as the test for
11252when to stop; and you can, of course, combine these patterns.
11253
11254@node No Deferment, No deferment solution, Recursive Patterns, Recursion
11255@subsection Recursion without Deferments
11256@cindex Deferment in recursion
11257@cindex Recursion without Deferments
11258
11259Let's consider again what happens with the @code{triangle-recursively}
11260function. We will find that the intermediate calculations are
11261deferred until all can be done.
11262
11263@need 800
11264Here is the function definition:
11265
11266@smallexample
11267@group
11268(defun triangle-recursively (number)
11269 "Return the sum of the numbers 1 through NUMBER inclusive.
11270Uses recursion."
11271 (if (= number 1) ; @r{do-again-test}
11272 1 ; @r{then-part}
11273 (+ number ; @r{else-part}
11274 (triangle-recursively ; @r{recursive call}
11275 (1- number))))) ; @r{next-step-expression}
11276@end group
11277@end smallexample
11278
11279What happens when we call this function with a argument of 7?
11280
11281The first instance of the @code{triangle-recursively} function adds
11282the number 7 to the value returned by a second instance of
11283@code{triangle-recursively}, an instance that has been passed an
11284argument of 6. That is to say, the first calculation is:
11285
11286@smallexample
b15dd613 11287(+ 7 (triangle-recursively 6))
8b096dce
EZ
11288@end smallexample
11289
11290@noindent
11291The first instance of @code{triangle-recursively}---you may want to
11292think of it as a little robot---cannot complete its job. It must hand
11293off the calculation for @code{(triangle-recursively 6)} to a second
11294instance of the program, to a second robot. This second individual is
11295completely different from the first one; it is, in the jargon, a
11296`different instantiation'. Or, put another way, it is a different
11297robot. It is the same model as the first; it calculates triangle
11298numbers recursively; but it has a different serial number.
11299
11300And what does @code{(triangle-recursively 6)} return? It returns the
11301number 6 added to the value returned by evaluating
11302@code{triangle-recursively} with an argument of 5. Using the robot
11303metaphor, it asks yet another robot to help it.
11304
11305@need 800
11306Now the total is:
11307
11308@smallexample
b15dd613 11309(+ 7 6 (triangle-recursively 5))
8b096dce
EZ
11310@end smallexample
11311
11312@need 800
11313And what happens next?
11314
11315@smallexample
b15dd613 11316(+ 7 6 5 (triangle-recursively 4))
8b096dce
EZ
11317@end smallexample
11318
11319Each time @code{triangle-recursively} is called, except for the last
11320time, it creates another instance of the program---another robot---and
11321asks it to make a calculation.
11322
11323@need 800
11324Eventually, the full addition is set up and performed:
11325
11326@smallexample
11327(+ 7 6 5 4 3 2 1)
11328@end smallexample
11329
11330This design for the function defers the calculation of the first step
11331until the second can be done, and defers that until the third can be
11332done, and so on. Each deferment means the computer must remember what
11333is being waited on. This is not a problem when there are only a few
11334steps, as in this example. But it can be a problem when there are
11335more steps.
11336
11337@node No deferment solution, , No Deferment, Recursion
11338@subsection No Deferment Solution
11339@cindex No deferment solution
11340@cindex Defermentless solution
11341@cindex Solution without deferment
11342
11343The solution to the problem of deferred operations is to write in a
11344manner that does not defer operations@footnote{The phrase @dfn{tail
11345recursive} is used to describe such a process, one that uses
11346`constant space'.}. This requires
11347writing to a different pattern, often one that involves writing two
11348function definitions, an `initialization' function and a `helper'
11349function.
11350
11351The `initialization' function sets up the job; the `helper' function
11352does the work.
11353
11354@need 1200
11355Here are the two function definitions for adding up numbers. They are
11356so simple, I find them hard to understand.
11357
11358@smallexample
11359@group
11360(defun triangle-initialization (number)
11361 "Return the sum of the numbers 1 through NUMBER inclusive.
11362This is the `initialization' component of a two function
11363duo that uses recursion."
11364 (triangle-recursive-helper 0 0 number))
11365@end group
11366@end smallexample
11367
11368@smallexample
11369@group
11370(defun triangle-recursive-helper (sum counter number)
11371 "Return SUM, using COUNTER, through NUMBER inclusive.
11372This is the `helper' component of a two function duo
11373that uses recursion."
11374 (if (> counter number)
11375 sum
11376 (triangle-recursive-helper (+ sum counter) ; @r{sum}
11377 (1+ counter) ; @r{counter}
11378 number))) ; @r{number}
11379@end group
11380@end smallexample
11381
11382@need 1250
11383Install both function definitions by evaluating them, then call
11384@code{triangle-initialization} with 2 rows:
11385
11386@smallexample
11387@group
11388(triangle-initialization 2)
11389 @result{} 3
11390@end group
11391@end smallexample
11392
11393The `initialization' function calls the first instance of the `helper'
11394function with three arguments: zero, zero, and a number which is the
11395number of rows in the triangle.
11396
11397The first two arguments passed to the `helper' function are
11398initialization values. These values are changed when
11399@code{triangle-recursive-helper} invokes new instances.@footnote{The
11400jargon is mildly confusing: @code{triangle-recursive-helper} uses a
11401process that is iterative in a procedure that is recursive. The
11402process is called iterative because the computer need only record the
11403three values, @code{sum}, @code{counter}, and @code{number}; the
11404procedure is recursive because the function `calls itself'. On the
11405other hand, both the process and the procedure used by
11406@code{triangle-recursively} are called recursive. The word
11407`recursive' has different meanings in the two contexts.}
11408
11409Let's see what happens when we have a triangle that has one row. (This
11410triangle will have one pebble in it!)
11411
11412@need 1200
11413@code{triangle-initialization} will call its helper with
11414the arguments @w{@code{0 0 1}}. That function will run the conditional
11415test whether @code{(> counter number)}:
11416
11417@smallexample
11418(> 0 1)
11419@end smallexample
11420
11421@need 1200
11422@noindent
11423and find that the result is false, so it will invoke
11424the then-part of the @code{if} clause:
11425
11426@smallexample
11427@group
11428 (triangle-recursive-helper
11429 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11430 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11431 number) ; @r{number stays the same}
11432@end group
11433@end smallexample
11434
11435@need 800
11436@noindent
11437which will first compute:
11438
11439@smallexample
11440@group
11441(triangle-recursive-helper (+ 0 0) ; @r{sum}
11442 (1+ 0) ; @r{counter}
11443 1) ; @r{number}
11444@exdent which is:
11445
11446(triangle-recursive-helper 0 1 1)
11447@end group
11448@end smallexample
11449
11450Again, @code{(> counter number)} will be false, so again, the Lisp
11451interpreter will evaluate @code{triangle-recursive-helper}, creating a
11452new instance with new arguments.
11453
11454@need 800
11455This new instance will be;
11456
11457@smallexample
11458@group
11459 (triangle-recursive-helper
11460 (+ sum counter) ; @r{sum plus counter} @result{} @r{sum}
11461 (1+ counter) ; @r{increment counter} @result{} @r{counter}
11462 number) ; @r{number stays the same}
11463
11464@exdent which is:
11465
11466(triangle-recursive-helper 1 2 1)
11467@end group
11468@end smallexample
11469
11470In this case, the @code{(> counter number)} test will be true! So the
11471instance will return the value of the sum, which will be 1, as
11472expected.
11473
11474Now, let's pass @code{triangle-initialization} an argument
11475of 2, to find out how many pebbles there are in a triangle with two rows.
11476
11477That function calls @code{(triangle-recursive-helper 0 0 2)}.
11478
11479@need 800
11480In stages, the instances called will be:
11481
11482@smallexample
11483@group
11484 @r{sum counter number}
11485(triangle-recursive-helper 0 1 2)
11486
11487(triangle-recursive-helper 1 2 2)
11488
11489(triangle-recursive-helper 3 3 2)
11490@end group
11491@end smallexample
11492
11493When the last instance is called, the @code{(> counter number)} test
11494will be true, so the instance will return the value of @code{sum},
11495which will be 3.
11496
11497This kind of pattern helps when you are writing functions that can use
11498many resources in a computer.
11499
11500@need 1500
11501@node Looping exercise, , Recursion, Loops & Recursion
11502@section Looping Exercise
11503
11504@itemize @bullet
11505@item
11506Write a function similar to @code{triangle} in which each row has a
11507value which is the square of the row number. Use a @code{while} loop.
11508
11509@item
11510Write a function similar to @code{triangle} that multiplies instead of
11511adds the values.
11512
11513@item
11514Rewrite these two functions recursively. Rewrite these functions
11515using @code{cond}.
11516
11517@c comma in printed title causes problem in Info cross reference
11518@item
11519Write a function for Texinfo mode that creates an index entry at the
11520beginning of a paragraph for every @samp{@@dfn} within the paragraph.
c6f54b06
RC
11521(In a Texinfo file, @samp{@@dfn} marks a definition. This book is
11522written in Texinfo.)
11523
11524Many of the functions you will need are described in two of the
11525previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
11526Text}, and @ref{Yanking, , Yanking Text Back}. If you use
11527@code{forward-paragraph} to put the index entry at the beginning of
11528the paragraph, you will have to use @w{@kbd{C-h f}}
11529(@code{describe-function}) to find out how to make the command go
11530backwards.
11531
11532For more information, see
8b096dce 11533@ifinfo
c6f54b06 11534@ref{Indicating, , Indicating Definitions, texinfo}.
8b096dce
EZ
11535@end ifinfo
11536@ifhtml
c6f54b06
RC
11537@ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
11538a Texinfo manual in the current directory. Or, if you are on the
11539Internet, see
11540@uref{http://www.gnu.org/manual/texinfo-4.6/html_node/Indicating.html}
8b096dce
EZ
11541@end ifhtml
11542@iftex
11543``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
c6f54b06 11544Documentation Format}.
8b096dce
EZ
11545@end iftex
11546@end itemize
11547
11548@node Regexp Search, Counting Words, Loops & Recursion, Top
11549@comment node-name, next, previous, up
11550@chapter Regular Expression Searches
11551@cindex Searches, illustrating
11552@cindex Regular expression searches
11553@cindex Patterns, searching for
11554@cindex Motion by sentence and paragraph
11555@cindex Sentences, movement by
11556@cindex Paragraphs, movement by
11557
11558Regular expression searches are used extensively in GNU Emacs. The
11559two functions, @code{forward-sentence} and @code{forward-paragraph},
11560illustrate these searches well. They use regular expressions to find
11561where to move point. The phrase `regular expression' is often written
11562as `regexp'.
11563
11564Regular expression searches are described in @ref{Regexp Search, ,
11565Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11566@ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11567Manual}. In writing this chapter, I am presuming that you have at
11568least a mild acquaintance with them. The major point to remember is
11569that regular expressions permit you to search for patterns as well as
11570for literal strings of characters. For example, the code in
11571@code{forward-sentence} searches for the pattern of possible
11572characters that could mark the end of a sentence, and moves point to
11573that spot.
11574
11575Before looking at the code for the @code{forward-sentence} function, it
11576is worth considering what the pattern that marks the end of a sentence
11577must be. The pattern is discussed in the next section; following that
11578is a description of the regular expression search function,
11579@code{re-search-forward}. The @code{forward-sentence} function
11580is described in the section following. Finally, the
11581@code{forward-paragraph} function is described in the last section of
11582this chapter. @code{forward-paragraph} is a complex function that
11583introduces several new features.
11584
11585@menu
11586* sentence-end:: The regular expression for @code{sentence-end}.
11587* re-search-forward:: Very similar to @code{search-forward}.
11588* forward-sentence:: A straightforward example of regexp search.
11589* forward-paragraph:: A somewhat complex example.
11590* etags:: How to create your own @file{TAGS} table.
11591* Regexp Review::
11592* re-search Exercises::
11593@end menu
11594
11595@node sentence-end, re-search-forward, Regexp Search, Regexp Search
11596@comment node-name, next, previous, up
11597@section The Regular Expression for @code{sentence-end}
11598@findex sentence-end
11599
11600The symbol @code{sentence-end} is bound to the pattern that marks the
11601end of a sentence. What should this regular expression be?
11602
11603Clearly, a sentence may be ended by a period, a question mark, or an
11604exclamation mark. Indeed, only clauses that end with one of those three
11605characters should be considered the end of a sentence. This means that
11606the pattern should include the character set:
11607
11608@smallexample
11609[.?!]
11610@end smallexample
11611
11612However, we do not want @code{forward-sentence} merely to jump to a
11613period, a question mark, or an exclamation mark, because such a character
11614might be used in the middle of a sentence. A period, for example, is
11615used after abbreviations. So other information is needed.
11616
11617According to convention, you type two spaces after every sentence, but
11618only one space after a period, a question mark, or an exclamation mark in
11619the body of a sentence. So a period, a question mark, or an exclamation
11620mark followed by two spaces is a good indicator of an end of sentence.
11621However, in a file, the two spaces may instead be a tab or the end of a
11622line. This means that the regular expression should include these three
11623items as alternatives.
11624
11625@need 800
11626This group of alternatives will look like this:
11627
11628@smallexample
11629@group
11630\\($\\| \\| \\)
11631 ^ ^^
11632 TAB SPC
11633@end group
11634@end smallexample
11635
11636@noindent
11637Here, @samp{$} indicates the end of the line, and I have pointed out
11638where the tab and two spaces are inserted in the expression. Both are
11639inserted by putting the actual characters into the expression.
11640
11641Two backslashes, @samp{\\}, are required before the parentheses and
11642vertical bars: the first backslash quotes the following backslash in
11643Emacs; and the second indicates that the following character, the
11644parenthesis or the vertical bar, is special.
11645
11646@need 1000
11647Also, a sentence may be followed by one or more carriage returns, like
11648this:
11649
11650@smallexample
11651@group
11652[
11653]*
11654@end group
11655@end smallexample
11656
11657@noindent
11658Like tabs and spaces, a carriage return is inserted into a regular
11659expression by inserting it literally. The asterisk indicates that the
11660@key{RET} is repeated zero or more times.
11661
11662But a sentence end does not consist only of a period, a question mark or
11663an exclamation mark followed by appropriate space: a closing quotation
11664mark or a closing brace of some kind may precede the space. Indeed more
11665than one such mark or brace may precede the space. These require a
11666expression that looks like this:
11667
11668@smallexample
11669[]\"')@}]*
11670@end smallexample
11671
11672In this expression, the first @samp{]} is the first character in the
11673expression; the second character is @samp{"}, which is preceded by a
11674@samp{\} to tell Emacs the @samp{"} is @emph{not} special. The last
11675three characters are @samp{'}, @samp{)}, and @samp{@}}.
11676
11677All this suggests what the regular expression pattern for matching the
11678end of a sentence should be; and, indeed, if we evaluate
11679@code{sentence-end} we find that it returns the following value:
11680
11681@smallexample
11682@group
11683sentence-end
11684 @result{} "[.?!][]\"')@}]*\\($\\| \\| \\)[
11685]*"
11686@end group
11687@end smallexample
11688
11689@ignore
11690
11691@noindent
11692(Note that here the @key{TAB}, two spaces, and @key{RET} are shown
11693literally in the pattern.)
11694
11695This regular expression can be decyphered as follows:
11696
11697@table @code
11698@item [.?!]
11699The first part of the pattern is the three characters, a period, a question
11700mark and an exclamation mark, within square brackets. The pattern must
11701begin with one or other of these characters.
11702
11703@item []\"')@}]*
11704The second part of the pattern is the group of closing braces and
11705quotation marks, which can appear zero or more times. These may follow
11706the period, question mark or exclamation mark. In a regular expression,
11707the backslash, @samp{\}, followed by the double quotation mark,
11708@samp{"}, indicates the class of string-quote characters. Usually, the
11709double quotation mark is the only character in this class. The
11710asterisk, @samp{*}, indicates that the items in the previous group (the
11711group surrounded by square brackets, @samp{[]}) may be repeated zero or
11712more times.
11713
11714@item \\($\\| \\| \\)
11715The third part of the pattern is one or other of: either the end of a
11716line, or two blank spaces, or a tab. The double back-slashes are used
11717to prevent Emacs from reading the parentheses and vertical bars as part
11718of the search pattern; the parentheses are used to mark the group and
11719the vertical bars are used to indicated that the patterns to either side
11720of them are alternatives. The dollar sign is used to indicate the end
11721of a line and both the two spaces and the tab are each inserted as is to
11722indicate what they are.
11723
11724@item [@key{RET}]*
11725Finally, the last part of the pattern indicates that the end of the line
11726or the whitespace following the period, question mark or exclamation
11727mark may, but need not, be followed by one or more carriage returns. In
11728the pattern, the carriage return is inserted as an actual carriage
11729return between square brackets but here it is shown as @key{RET}.
11730@end table
11731
11732@end ignore
11733
11734@node re-search-forward, forward-sentence, sentence-end, Regexp Search
11735@comment node-name, next, previous, up
11736@section The @code{re-search-forward} Function
11737@findex re-search-forward
11738
11739The @code{re-search-forward} function is very like the
11740@code{search-forward} function. (@xref{search-forward, , The
11741@code{search-forward} Function}.)
11742
11743@code{re-search-forward} searches for a regular expression. If the
11744search is successful, it leaves point immediately after the last
11745character in the target. If the search is backwards, it leaves point
11746just before the first character in the target. You may tell
11747@code{re-search-forward} to return @code{t} for true. (Moving point
11748is therefore a `side effect'.)
11749
11750Like @code{search-forward}, the @code{re-search-forward} function takes
11751four arguments:
11752
11753@enumerate
11754@item
11755The first argument is the regular expression that the function searches
11756for. The regular expression will be a string between quotations marks.
11757
11758@item
11759The optional second argument limits how far the function will search; it is a
11760bound, which is specified as a position in the buffer.
11761
11762@item
11763The optional third argument specifies how the function responds to
11764failure: @code{nil} as the third argument causes the function to
11765signal an error (and print a message) when the search fails; any other
11766value causes it to return @code{nil} if the search fails and @code{t}
11767if the search succeeds.
11768
11769@item
11770The optional fourth argument is the repeat count. A negative repeat
11771count causes @code{re-search-forward} to search backwards.
11772@end enumerate
11773
11774@need 800
11775The template for @code{re-search-forward} looks like this:
11776
11777@smallexample
11778@group
11779(re-search-forward "@var{regular-expression}"
11780 @var{limit-of-search}
11781 @var{what-to-do-if-search-fails}
11782 @var{repeat-count})
11783@end group
11784@end smallexample
11785
11786The second, third, and fourth arguments are optional. However, if you
11787want to pass a value to either or both of the last two arguments, you
11788must also pass a value to all the preceding arguments. Otherwise, the
11789Lisp interpreter will mistake which argument you are passing the value
11790to.
11791
11792@need 1200
11793In the @code{forward-sentence} function, the regular expression will be
11794the value of the variable @code{sentence-end}, namely:
11795
11796@smallexample
11797@group
11798"[.?!][]\"')@}]*\\($\\| \\| \\)[
11799]*"
11800@end group
11801@end smallexample
11802
11803@noindent
11804The limit of the search will be the end of the paragraph (since a
11805sentence cannot go beyond a paragraph). If the search fails, the
11806function will return @code{nil}; and the repeat count will be provided
11807by the argument to the @code{forward-sentence} function.
11808
11809@node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11810@comment node-name, next, previous, up
11811@section @code{forward-sentence}
11812@findex forward-sentence
11813
11814The command to move the cursor forward a sentence is a straightforward
11815illustration of how to use regular expression searches in Emacs Lisp.
11816Indeed, the function looks longer and more complicated than it is; this
11817is because the function is designed to go backwards as well as forwards;
11818and, optionally, over more than one sentence. The function is usually
11819bound to the key command @kbd{M-e}.
11820
11821@menu
11822* Complete forward-sentence::
11823* fwd-sentence while loops:: Two @code{while} loops.
11824* fwd-sentence re-search:: A regular expression search.
11825@end menu
11826
11827@node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11828@ifnottex
11829@unnumberedsubsec Complete @code{forward-sentence} function definition
11830@end ifnottex
11831
11832@need 1250
11833Here is the code for @code{forward-sentence}:
11834
11835@smallexample
11836@group
11837(defun forward-sentence (&optional arg)
11838 "Move forward to next sentence-end. With argument, repeat.
11839With negative argument, move backward repeatedly to sentence-beginning.
11840Sentence ends are identified by the value of sentence-end
11841treated as a regular expression. Also, every paragraph boundary
11842terminates sentences as well."
11843@end group
11844@group
11845 (interactive "p")
11846 (or arg (setq arg 1))
11847 (while (< arg 0)
11848 (let ((par-beg
11849 (save-excursion (start-of-paragraph-text) (point))))
11850 (if (re-search-backward
11851 (concat sentence-end "[^ \t\n]") par-beg t)
11852 (goto-char (1- (match-end 0)))
11853 (goto-char par-beg)))
11854 (setq arg (1+ arg)))
11855 (while (> arg 0)
11856 (let ((par-end
11857 (save-excursion (end-of-paragraph-text) (point))))
11858 (if (re-search-forward sentence-end par-end t)
11859 (skip-chars-backward " \t\n")
11860 (goto-char par-end)))
11861 (setq arg (1- arg))))
11862@end group
11863@end smallexample
11864
11865The function looks long at first sight and it is best to look at its
11866skeleton first, and then its muscle. The way to see the skeleton is to
11867look at the expressions that start in the left-most columns:
11868
11869@smallexample
11870@group
11871(defun forward-sentence (&optional arg)
11872 "@var{documentation}@dots{}"
11873 (interactive "p")
11874 (or arg (setq arg 1))
11875 (while (< arg 0)
11876 @var{body-of-while-loop}
11877 (while (> arg 0)
11878 @var{body-of-while-loop}
11879@end group
11880@end smallexample
11881
11882This looks much simpler! The function definition consists of
11883documentation, an @code{interactive} expression, an @code{or}
11884expression, and @code{while} loops.
11885
11886Let's look at each of these parts in turn.
11887
11888We note that the documentation is thorough and understandable.
11889
11890The function has an @code{interactive "p"} declaration. This means
11891that the processed prefix argument, if any, is passed to the
11892function as its argument. (This will be a number.) If the function
11893is not passed an argument (it is optional) then the argument
11894@code{arg} will be bound to 1. When @code{forward-sentence} is called
11895non-interactively without an argument, @code{arg} is bound to
11896@code{nil}.
11897
11898The @code{or} expression handles the prefix argument. What it does is
11899either leave the value of @code{arg} as it is, but only if @code{arg}
11900is bound to a value; or it sets the value of @code{arg} to 1, in the
11901case when @code{arg} is bound to @code{nil}.
11902
11903@node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11904@unnumberedsubsec The @code{while} loops
11905
11906Two @code{while} loops follow the @code{or} expression. The first
11907@code{while} has a true-or-false-test that tests true if the prefix
11908argument for @code{forward-sentence} is a negative number. This is for
11909going backwards. The body of this loop is similar to the body of the
11910second @code{while} clause, but it is not exactly the same. We will
11911skip this @code{while} loop and concentrate on the second @code{while}
11912loop.
11913
11914@need 1500
11915The second @code{while} loop is for moving point forward. Its skeleton
11916looks like this:
11917
11918@smallexample
11919@group
11920(while (> arg 0) ; @r{true-or-false-test}
11921 (let @var{varlist}
11922 (if (@var{true-or-false-test})
11923 @var{then-part}
11924 @var{else-part}
11925 (setq arg (1- arg)))) ; @code{while} @r{loop decrementer}
11926@end group
11927@end smallexample
11928
11929The @code{while} loop is of the decrementing kind.
11930(@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.) It
11931has a true-or-false-test that tests true so long as the counter (in
11932this case, the variable @code{arg}) is greater than zero; and it has a
11933decrementer that subtracts 1 from the value of the counter every time
11934the loop repeats.
11935
11936If no prefix argument is given to @code{forward-sentence}, which is
11937the most common way the command is used, this @code{while} loop will
11938run once, since the value of @code{arg} will be 1.
11939
11940The body of the @code{while} loop consists of a @code{let} expression,
11941which creates and binds a local variable, and has, as its body, an
11942@code{if} expression.
11943
11944@need 1250
11945The body of the @code{while} loop looks like this:
11946
11947@smallexample
11948@group
11949(let ((par-end
11950 (save-excursion (end-of-paragraph-text) (point))))
11951 (if (re-search-forward sentence-end par-end t)
11952 (skip-chars-backward " \t\n")
11953 (goto-char par-end)))
11954@end group
11955@end smallexample
11956
11957The @code{let} expression creates and binds the local variable
11958@code{par-end}. As we shall see, this local variable is designed to
11959provide a bound or limit to the regular expression search. If the
11960search fails to find a proper sentence ending in the paragraph, it will
11961stop on reaching the end of the paragraph.
11962
11963But first, let us examine how @code{par-end} is bound to the value of
11964the end of the paragraph. What happens is that the @code{let} sets the
11965value of @code{par-end} to the value returned when the Lisp interpreter
11966evaluates the expression
11967
11968@smallexample
11969@group
11970(save-excursion (end-of-paragraph-text) (point))
11971@end group
11972@end smallexample
11973
11974@noindent
11975In this expression, @code{(end-of-paragraph-text)} moves point to the
11976end of the paragraph, @code{(point)} returns the value of point, and then
11977@code{save-excursion} restores point to its original position. Thus,
11978the @code{let} binds @code{par-end} to the value returned by the
11979@code{save-excursion} expression, which is the position of the end of
11980the paragraph. (The @code{(end-of-paragraph-text)} function uses
11981@code{forward-paragraph}, which we will discuss shortly.)
11982
11983@need 1200
11984Emacs next evaluates the body of the @code{let}, which is an @code{if}
11985expression that looks like this:
11986
11987@smallexample
11988@group
11989(if (re-search-forward sentence-end par-end t) ; @r{if-part}
11990 (skip-chars-backward " \t\n") ; @r{then-part}
11991 (goto-char par-end))) ; @r{else-part}
11992@end group
11993@end smallexample
11994
11995The @code{if} tests whether its first argument is true and if so,
11996evaluates its then-part; otherwise, the Emacs Lisp interpreter
11997evaluates the else-part. The true-or-false-test of the @code{if}
11998expression is the regular expression search.
11999
12000It may seem odd to have what looks like the `real work' of
12001the @code{forward-sentence} function buried here, but this is a common
12002way this kind of operation is carried out in Lisp.
12003
12004@node fwd-sentence re-search, , fwd-sentence while loops, forward-sentence
12005@unnumberedsubsec The regular expression search
12006
12007The @code{re-search-forward} function searches for the end of the
12008sentence, that is, for the pattern defined by the @code{sentence-end}
12009regular expression. If the pattern is found---if the end of the sentence is
12010found---then the @code{re-search-forward} function does two things:
12011
12012@enumerate
12013@item
12014The @code{re-search-forward} function carries out a side effect, which
12015is to move point to the end of the occurrence found.
12016
12017@item
12018The @code{re-search-forward} function returns a value of true. This is
12019the value received by the @code{if}, and means that the search was
12020successful.
12021@end enumerate
12022
12023@noindent
12024The side effect, the movement of point, is completed before the
12025@code{if} function is handed the value returned by the successful
12026conclusion of the search.
12027
12028When the @code{if} function receives the value of true from a successful
12029call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12030which is the expression @code{(skip-chars-backward " \t\n")}. This
12031expression moves backwards over any blank spaces, tabs or carriage
12032returns until a printed character is found and then leaves point after
12033the character. Since point has already been moved to the end of the
12034pattern that marks the end of the sentence, this action leaves point
12035right after the closing printed character of the sentence, which is
12036usually a period.
12037
12038On the other hand, if the @code{re-search-forward} function fails to
12039find a pattern marking the end of the sentence, the function returns
12040false. The false then causes the @code{if} to evaluate its third
12041argument, which is @code{(goto-char par-end)}: it moves point to the
12042end of the paragraph.
12043
12044Regular expression searches are exceptionally useful and the pattern
12045illustrated by @code{re-search-forward}, in which the search is the
12046test of an @code{if} expression, is handy. You will see or write code
12047incorporating this pattern often.
12048
12049@node forward-paragraph, etags, forward-sentence, Regexp Search
12050@comment node-name, next, previous, up
12051@section @code{forward-paragraph}: a Goldmine of Functions
12052@findex forward-paragraph
12053
12054The @code{forward-paragraph} function moves point forward to the end
12055of the paragraph. It is usually bound to @kbd{M-@}} and makes use of a
12056number of functions that are important in themselves, including
12057@code{let*}, @code{match-beginning}, and @code{looking-at}.
12058
12059The function definition for @code{forward-paragraph} is considerably
12060longer than the function definition for @code{forward-sentence}
12061because it works with a paragraph, each line of which may begin with a
12062fill prefix.
12063
12064A fill prefix consists of a string of characters that are repeated at
12065the beginning of each line. For example, in Lisp code, it is a
12066convention to start each line of a paragraph-long comment with
12067@samp{;;; }. In Text mode, four blank spaces make up another common
12068fill prefix, creating an indented paragraph. (@xref{Fill Prefix, , ,
12069emacs, The GNU Emacs Manual}, for more information about fill
12070prefixes.)
12071
12072The existence of a fill prefix means that in addition to being able to
12073find the end of a paragraph whose lines begin on the left-most
12074column, the @code{forward-paragraph} function must be able to find the
12075end of a paragraph when all or many of the lines in the buffer begin
12076with the fill prefix.
12077
12078Moreover, it is sometimes practical to ignore a fill prefix that
12079exists, especially when blank lines separate paragraphs.
12080This is an added complication.
12081
12082@menu
12083* forward-paragraph in brief:: Key parts of the function definition.
12084* fwd-para let:: The @code{let*} expression.
12085* fwd-para while:: The forward motion @code{while} loop.
12086* fwd-para between paragraphs:: Movement between paragraphs.
12087* fwd-para within paragraph:: Movement within paragraphs.
12088* fwd-para no fill prefix:: When there is no fill prefix.
12089* fwd-para with fill prefix:: When there is a fill prefix.
12090* fwd-para summary:: Summary of @code{forward-paragraph} code.
12091@end menu
12092
12093@node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12094@ifnottex
12095@unnumberedsubsec Shortened @code{forward-paragraph} function definition
12096@end ifnottex
12097
12098Rather than print all of the @code{forward-paragraph} function, we
12099will only print parts of it. Read without preparation, the function
12100can be daunting!
12101
12102@need 800
12103In outline, the function looks like this:
12104
12105@smallexample
12106@group
12107(defun forward-paragraph (&optional arg)
12108 "@var{documentation}@dots{}"
12109 (interactive "p")
12110 (or arg (setq arg 1))
12111 (let*
12112 @var{varlist}
12113 (while (< arg 0) ; @r{backward-moving-code}
12114 @dots{}
12115 (setq arg (1+ arg)))
12116 (while (> arg 0) ; @r{forward-moving-code}
12117 @dots{}
12118 (setq arg (1- arg)))))
12119@end group
12120@end smallexample
12121
12122The first parts of the function are routine: the function's argument
12123list consists of one optional argument. Documentation follows.
12124
12125The lower case @samp{p} in the @code{interactive} declaration means
12126that the processed prefix argument, if any, is passed to the function.
12127This will be a number, and is the repeat count of how many paragraphs
12128point will move. The @code{or} expression in the next line handles
12129the common case when no argument is passed to the function, which occurs
12130if the function is called from other code rather than interactively.
12131This case was described earlier. (@xref{forward-sentence, The
12132@code{forward-sentence} function}.) Now we reach the end of the
12133familiar part of this function.
12134
12135@node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12136@unnumberedsubsec The @code{let*} expression
12137
12138The next line of the @code{forward-paragraph} function begins a
12139@code{let*} expression. This is a different kind of expression than
12140we have seen so far. The symbol is @code{let*} not @code{let}.
12141
12142The @code{let*} special form is like @code{let} except that Emacs sets
12143each variable in sequence, one after another, and variables in the
12144latter part of the varlist can make use of the values to which Emacs
12145set variables in the earlier part of the varlist.
12146
12147In the @code{let*} expression in this function, Emacs binds two
12148variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12149The value to which @code{paragraph-separate} is bound depends on the
12150value of @code{fill-prefix-regexp}.
12151
12152@need 1200
12153Let's look at each in turn. The symbol @code{fill-prefix-regexp} is
12154set to the value returned by evaluating the following list:
12155
12156@smallexample
12157@group
12158(and fill-prefix
12159 (not (equal fill-prefix ""))
12160 (not paragraph-ignore-fill-prefix)
12161 (regexp-quote fill-prefix))
12162@end group
12163@end smallexample
12164
12165@noindent
12166This is an expression whose first element is the @code{and} special form.
12167
12168As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12169function}), the @code{and} special form evaluates each of its
12170arguments until one of the arguments returns a value of @code{nil}, in
12171which case the @code{and} expression returns @code{nil}; however, if
12172none of the arguments returns a value of @code{nil}, the value
12173resulting from evaluating the last argument is returned. (Since such
12174a value is not @code{nil}, it is considered true in Lisp.) In other
12175words, an @code{and} expression returns a true value only if all its
12176arguments are true.
12177@findex and
12178
12179In this case, the variable @code{fill-prefix-regexp} is bound to a
12180non-@code{nil} value only if the following four expressions produce a
12181true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12182@code{fill-prefix-regexp} is bound to @code{nil}.
12183
12184@table @code
12185@item fill-prefix
12186When this variable is evaluated, the value of the fill prefix, if any,
12187is returned. If there is no fill prefix, this variable returns
12188@code{nil}.
12189
12190@item (not (equal fill-prefix "")
12191This expression checks whether an existing fill prefix is an empty
12192string, that is, a string with no characters in it. An empty string is
12193not a useful fill prefix.
12194
12195@item (not paragraph-ignore-fill-prefix)
12196This expression returns @code{nil} if the variable
12197@code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12198true value such as @code{t}.
12199
12200@item (regexp-quote fill-prefix)
12201This is the last argument to the @code{and} special form. If all the
12202arguments to the @code{and} are true, the value resulting from
12203evaluating this expression will be returned by the @code{and} expression
12204and bound to the variable @code{fill-prefix-regexp},
12205@end table
12206
12207@findex regexp-quote
12208@noindent
12209The result of evaluating this @code{and} expression successfully is that
12210@code{fill-prefix-regexp} will be bound to the value of
12211@code{fill-prefix} as modified by the @code{regexp-quote} function.
12212What @code{regexp-quote} does is read a string and return a regular
12213expression that will exactly match the string and match nothing else.
12214This means that @code{fill-prefix-regexp} will be set to a value that
12215will exactly match the fill prefix if the fill prefix exists.
12216Otherwise, the variable will be set to @code{nil}.
12217
12218The second local variable in the @code{let*} expression is
12219@code{paragraph-separate}. It is bound to the value returned by
12220evaluating the expression:
12221
12222@smallexample
12223@group
12224(if fill-prefix-regexp
12225 (concat paragraph-separate
12226 "\\|^" fill-prefix-regexp "[ \t]*$")
12227 paragraph-separate)))
12228@end group
12229@end smallexample
12230
12231This expression shows why @code{let*} rather than @code{let} was used.
12232The true-or-false-test for the @code{if} depends on whether the variable
12233@code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12234
12235If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12236the else-part of the @code{if} expression and binds
12237@code{paragraph-separate} to its local value.
12238(@code{paragraph-separate} is a regular expression that matches what
12239separates paragraphs.)
12240
12241But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12242the then-part of the @code{if} expression and binds
12243@code{paragraph-separate} to a regular expression that includes the
12244@code{fill-prefix-regexp} as part of the pattern.
12245
12246Specifically, @code{paragraph-separate} is set to the original value
12247of the paragraph separate regular expression concatenated with an
12248alternative expression that consists of the @code{fill-prefix-regexp}
12249followed by a blank line. The @samp{^} indicates that the
12250@code{fill-prefix-regexp} must begin a line, and the optional
12251whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12252The @samp{\\|} defines this portion of the regexp as an alternative to
12253@code{paragraph-separate}.
12254
12255Now we get into the body of the @code{let*}. The first part of the body
12256of the @code{let*} deals with the case when the function is given a
12257negative argument and is therefore moving backwards. We will skip this
12258section.
12259
12260@node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12261@unnumberedsubsec The forward motion @code{while} loop
12262
12263The second part of the body of the @code{let*} deals with forward
12264motion. It is a @code{while} loop that repeats itself so long as the
12265value of @code{arg} is greater than zero. In the most common use of
12266the function, the value of the argument is 1, so the body of the
12267@code{while} loop is evaluated exactly once, and the cursor moves
12268forward one paragraph.
12269
12270This part handles three situations: when point is between paragraphs,
12271when point is within a paragraph and there is a fill prefix, and
12272when point is within a paragraph and there is no fill prefix.
12273
12274@need 800
12275The @code{while} loop looks like this:
12276
12277@smallexample
12278@group
12279(while (> arg 0)
12280 (beginning-of-line)
12281
12282 ;; @r{between paragraphs}
12283 (while (prog1 (and (not (eobp))
12284 (looking-at paragraph-separate))
12285 (forward-line 1)))
12286@end group
12287
12288@group
12289 ;; @r{within paragraphs, with a fill prefix}
12290 (if fill-prefix-regexp
12291 ;; @r{There is a fill prefix; it overrides paragraph-start.}
12292 (while (and (not (eobp))
12293 (not (looking-at paragraph-separate))
12294 (looking-at fill-prefix-regexp))
12295 (forward-line 1))
12296@end group
12297
12298@group
12299 ;; @r{within paragraphs, no fill prefix}
12300 (if (re-search-forward paragraph-start nil t)
12301 (goto-char (match-beginning 0))
12302 (goto-char (point-max))))
12303
12304 (setq arg (1- arg)))
12305@end group
12306@end smallexample
12307
12308We can see immediately that this is a decrementing counter @code{while}
12309loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12310
12311@need 800
12312The body of the loop consists of three expressions:
12313
12314@smallexample
12315@group
12316;; @r{between paragraphs}
12317(beginning-of-line)
12318(while
12319 @var{body-of-while})
12320@end group
12321
12322@group
12323;; @r{within paragraphs, with fill prefix}
12324(if @var{true-or-false-test}
12325 @var{then-part}
12326@end group
12327
12328@group
12329;; @r{within paragraphs, no fill prefix}
12330 @var{else-part}
12331@end group
12332@end smallexample
12333
12334@noindent
12335When the Emacs Lisp interpreter evaluates the body of the
12336@code{while} loop, the first thing it does is evaluate the
12337@code{(beginning-of-line)} expression and move point to the beginning
12338of the line. Then there is an inner @code{while} loop. This
12339@code{while} loop is designed to move the cursor out of the blank
12340space between paragraphs, if it should happen to be there. Finally,
12341there is an @code{if} expression that actually moves point to the end
12342of the paragraph.
12343
12344@node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12345@unnumberedsubsec Between paragraphs
12346
12347First, let us look at the inner @code{while} loop. This loop handles
12348the case when point is between paragraphs; it uses three functions
12349that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12350@findex prog1
12351@findex eobp
12352@findex looking-at
12353
12354@itemize @bullet
12355@item
12356@code{prog1} is similar to the @code{progn} special form,
12357except that @code{prog1} evaluates its arguments in sequence and then
12358returns the value of its first argument as the value of the whole
12359expression. (@code{progn} returns the value of its last argument as the
12360value of the expression.) The second and subsequent arguments to
12361@code{prog1} are evaluated only for their side effects.
12362
12363@item
12364@code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12365function that returns true if point is at the end of the buffer.
12366
12367@item
12368@code{looking-at} is a function that returns true if the text following
12369point matches the regular expression passed @code{looking-at} as its
12370argument.
12371@end itemize
12372
12373@need 800
12374The @code{while} loop we are studying looks like this:
12375
12376@smallexample
12377@group
12378(while (prog1 (and (not (eobp))
12379 (looking-at paragraph-separate))
12380 (forward-line 1)))
12381@end group
12382@end smallexample
12383
12384@need 1200
12385@noindent
12386This is a @code{while} loop with no body! The true-or-false-test of the
12387loop is the expression:
12388
12389@smallexample
12390@group
12391(prog1 (and (not (eobp))
12392 (looking-at paragraph-separate))
12393 (forward-line 1))
12394@end group
12395@end smallexample
12396
12397@noindent
12398The first argument to the @code{prog1} is the @code{and} expression. It
12399has within in it a test of whether point is at the end of the buffer and
12400also a test of whether the pattern following point matches the regular
12401expression for separating paragraphs.
12402
12403If the cursor is not at the end of the buffer and if the characters
12404following the cursor mark the separation between two paragraphs, then
12405the @code{and} expression is true. After evaluating the @code{and}
12406expression, the Lisp interpreter evaluates the second argument to
12407@code{prog1}, which is @code{forward-line}. This moves point forward
12408one line. The value returned by the @code{prog1} however, is the
12409value of its first argument, so the @code{while} loop continues so
12410long as point is not at the end of the buffer and is between
12411paragraphs. When, finally, point is moved to a paragraph, the
12412@code{and} expression tests false. Note however, that the
12413@code{forward-line} command is carried out anyhow. This means that
12414when point is moved from between paragraphs to a paragraph, it is left
12415at the beginning of the second line of the paragraph.
12416
12417@node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12418@unnumberedsubsec Within paragraphs
12419
12420The next expression in the outer @code{while} loop is an @code{if}
12421expression. The Lisp interpreter evaluates the then-part of the
12422@code{if} when the @code{fill-prefix-regexp} variable has a value other
12423than @code{nil}, and it evaluates the else-part when the value of
12424@code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12425fill prefix.
12426
12427@node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12428@unnumberedsubsec No fill prefix
12429
12430It is simplest to look at the code for the case when there is no fill
12431prefix first. This code consists of yet another inner @code{if}
12432expression, and reads as follows:
12433
12434@smallexample
12435@group
12436(if (re-search-forward paragraph-start nil t)
12437 (goto-char (match-beginning 0))
12438 (goto-char (point-max)))
12439@end group
12440@end smallexample
12441
12442@noindent
12443This expression actually does the work that most people think of as
12444the primary purpose of the @code{forward-paragraph} command: it causes
12445a regular expression search to occur that searches forward to the
12446start of the next paragraph and if it is found, moves point there; but
12447if the start of another paragraph if not found, it moves point to the
12448end of the accessible region of the buffer.
12449
12450The only unfamiliar part of this is the use of @code{match-beginning}.
12451This is another function that is new to us. The
12452@code{match-beginning} function returns a number specifying the
12453location of the start of the text that was matched by the last regular
12454expression search.
12455
12456The @code{match-beginning} function is used here because of a
12457characteristic of a forward search: a successful forward search,
12458regardless of whether it is a plain search or a regular expression
12459search, will move point to the end of the text that is found. In this
12460case, a successful search will move point to the end of the pattern for
12461@code{paragraph-start}, which will be the beginning of the next
12462paragraph rather than the end of the current one.
12463
12464However, we want to put point at the end of the current paragraph, not at
12465the beginning of the next one. The two positions may be different,
12466because there may be several blank lines between paragraphs.
12467
12468@findex match-beginning
12469When given an argument of 0, @code{match-beginning} returns the position
12470that is the start of the text that the most recent regular
12471expression search matched. In this case, the most recent regular
12472expression search is the one looking for @code{paragraph-start}, so
12473@code{match-beginning} returns the beginning position of the pattern,
12474rather than the end of the pattern. The beginning position is the end
12475of the paragraph.
12476
12477(Incidentally, when passed a positive number as an argument, the
12478@code{match-beginning} function will place point at that parenthesized
12479expression in the last regular expression. It is a useful function.)
12480
12481@node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12482@unnumberedsubsec With a fill prefix
12483
12484The inner @code{if} expression just discussed is the else-part of an enclosing
12485@code{if} expression which tests whether there is a fill prefix. If
12486there is a fill prefix, the then-part of this @code{if} is evaluated.
12487It looks like this:
12488
12489@smallexample
12490@group
12491(while (and (not (eobp))
12492 (not (looking-at paragraph-separate))
12493 (looking-at fill-prefix-regexp))
12494 (forward-line 1))
12495@end group
12496@end smallexample
12497
12498@noindent
12499What this expression does is move point forward line by line so long
12500as three conditions are true:
12501
12502@enumerate
12503@item
12504Point is not at the end of the buffer.
12505
12506@item
12507The text following point does not separate paragraphs.
12508
12509@item
12510The pattern following point is the fill prefix regular expression.
12511@end enumerate
12512
12513The last condition may be puzzling, until you remember that point was
12514moved to the beginning of the line early in the @code{forward-paragraph}
12515function. This means that if the text has a fill prefix, the
12516@code{looking-at} function will see it.
12517
12518@node fwd-para summary, , fwd-para with fill prefix, forward-paragraph
12519@unnumberedsubsec Summary
12520
12521In summary, when moving forward, the @code{forward-paragraph} function
12522does the following:
12523
12524@itemize @bullet
12525@item
12526Move point to the beginning of the line.
12527
12528@item
12529Skip over lines between paragraphs.
12530
12531@item
12532Check whether there is a fill prefix, and if there is:
12533
12534@itemize ---
12535
12536@item
12537Go forward line by line so long as the line is not a paragraph
12538separating line.
12539@end itemize
12540
12541@item
12542But if there is no fill prefix,
12543
12544@itemize ---
12545
12546@item
12547Search for the next paragraph start pattern.
12548
12549@item
12550Go to the beginning of the paragraph start pattern, which will be the
12551end of the previous paragraph.
12552
12553@item
12554Or else go to the end of the accessible portion of the buffer.
12555@end itemize
12556@end itemize
12557
12558@need 1200
12559For review, here is the code we have just been discussing, formatted
12560for clarity:
12561
12562@smallexample
12563@group
12564(interactive "p")
12565(or arg (setq arg 1))
12566(let* (
12567 (fill-prefix-regexp
12568 (and fill-prefix (not (equal fill-prefix ""))
12569 (not paragraph-ignore-fill-prefix)
12570 (regexp-quote fill-prefix)))
12571@end group
12572
12573@group
12574 (paragraph-separate
12575 (if fill-prefix-regexp
12576 (concat paragraph-separate
12577 "\\|^"
12578 fill-prefix-regexp
12579 "[ \t]*$")
12580 paragraph-separate)))
12581
12582 @var{omitted-backward-moving-code} @dots{}
12583@end group
12584
12585@group
12586 (while (> arg 0) ; @r{forward-moving-code}
12587 (beginning-of-line)
12588
12589 (while (prog1 (and (not (eobp))
12590 (looking-at paragraph-separate))
12591 (forward-line 1)))
12592@end group
12593
12594@group
12595 (if fill-prefix-regexp
12596 (while (and (not (eobp)) ; @r{then-part}
12597 (not (looking-at paragraph-separate))
12598 (looking-at fill-prefix-regexp))
12599 (forward-line 1))
12600@end group
12601@group
12602 ; @r{else-part: the inner-if}
12603 (if (re-search-forward paragraph-start nil t)
12604 (goto-char (match-beginning 0))
12605 (goto-char (point-max))))
12606
12607 (setq arg (1- arg))))) ; @r{decrementer}
12608@end group
12609@end smallexample
12610
12611The full definition for the @code{forward-paragraph} function not only
12612includes this code for going forwards, but also code for going backwards.
12613
12614If you are reading this inside of GNU Emacs and you want to see the
12615whole function, you can type @kbd{C-h f} (@code{describe-function})
12616and the name of the function. This gives you the function
12617documentation and the name of the library containing the function's
12618source. Place point over the name of the library and press the RET
12619key; you will be taken directly to the source. (Be sure to install
12620your sources! Without them, you are like a person who tries to drive
12621a car with his eyes shut!)
12622
12623@c !!! again, 21.0.100 tags table location in this paragraph
12624Or -- a good habit to get into -- you can type @kbd{M-.}
12625(@code{find-tag}) and the name of the function when prompted for it.
12626This will take you directly to the source. If the @code{find-tag}
12627function first asks you for the name of a @file{TAGS} table, give it
12628the name of the @file{TAGS} file such as
12629@file{/usr/local/share/emacs/21.0.100/lisp/TAGS}. (The exact path to your
12630@file{TAGS} file depends on how your copy of Emacs was installed.)
12631
12632You can also create your own @file{TAGS} file for directories that
12633lack one.
12634@ifnottex
12635@xref{etags, , Create Your Own @file{TAGS} File}.
12636@end ifnottex
12637
12638@node etags, Regexp Review, forward-paragraph, Regexp Search
12639@section Create Your Own @file{TAGS} File
12640@findex etags
12641@cindex @file{TAGS} file, create own
12642
12643The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12644source for a function, variable, node, or other source. The function
12645depends on tags tables to tell it where to go.
12646
12647You often need to build and install tags tables yourself. They are
12648not built automatically. A tags table is called a @file{TAGS} file;
12649the name is in upper case letters.
12650
12651You can create a @file{TAGS} file by calling the @code{etags} program
12652that comes as a part of the Emacs distribution. Usually, @code{etags}
12653is compiled and installed when Emacs is built. (@code{etags} is not
12654an Emacs Lisp function or a part of Emacs; it is a C program.)
12655
12656@need 1250
12657To create a @file{TAGS} file, first switch to the directory in which
12658you want to create the file. In Emacs you can do this with the
12659@kbd{M-x cd} command, or by visiting a file in the directory, or by
12660listing the directory with @kbd{C-x d} (@code{dired}). Then run the
12661compile command, with @w{@code{etags *.el}} as the command to execute
12662
12663@smallexample
12664M-x compile RET etags *.el RET
12665@end smallexample
12666
12667@noindent
12668to create a @file{TAGS} file.
12669
12670For example, if you have a large number of files in your
12671@file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12672of which I load 12---you can create a @file{TAGS} file for the Emacs
12673Lisp files in that directory.
12674
12675@need 1250
12676The @code{etags} program takes all the
12677usual shell `wildcards'. For example, if you have two directories for
12678which you want a single @file{TAGS file}, type
12679@w{@code{etags *.el ../elisp/*.el}},
12680where @file{../elisp/} is the second directory:
12681
12682@smallexample
12683M-x compile RET etags *.el ../elisp/*.el RET
12684@end smallexample
12685
12686@need 1250
12687Type
12688
12689@smallexample
12690M-x compile RET etags --help RET
12691@end smallexample
12692
12693@noindent
12694to see a list of the options accepted by @code{etags} as well as a
12695list of supported languages.
12696
12697The @code{etags} program handles more than 20 languages, including
12698Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12699Pascal, Perl, Python, Texinfo, makefiles, and most assemblers. The
12700program has no switches for specifying the language; it recognizes the
12701language in an input file according to its file name and contents.
12702
12703@file{etags} is very helpful when you are writing code yourself and
12704want to refer back to functions you have already written. Just run
12705@code{etags} again at intervals as you write new functions, so they
12706become part of the @file{TAGS} file.
12707
12708If you think an appropriate @file{TAGS} file already exists for what
12709you want, but do not know where it is, you can use the @code{locate}
12710program to attempt to find it.
12711
12712Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12713full path names of all your @file{TAGS} files. On my system, this
12714command lists 34 @file{TAGS} files. On the other hand, a `plain
12715vanilla' system I recently installed did not contain any @file{TAGS}
12716files.
12717
12718If the tags table you want has been created, you can use the @code{M-x
12719visit-tags-table} command to specify it. Otherwise, you will need to
12720create the tag table yourself and then use @code{M-x
12721visit-tags-table}.
12722
12723@subsubheading Building Tags in the Emacs sources
12724@cindex Building Tags in the Emacs sources
12725@cindex Tags in the Emacs sources
12726@findex make tags
12727
12728The GNU Emacs sources come with a @file{Makefile} that contains a
12729sophisticated @code{etags} command that creates, collects, and merges
12730tags tables from all over the Emacs sources and puts the information
12731into one @file{TAGS} file in the @file{src/} directory below the top
12732level of your Emacs source directory.
12733
12734@need 1250
12735To build this @file{TAGS} file, go to the top level of your Emacs
12736source directory and run the compile command @code{make tags}:
12737
12738@smallexample
12739M-x compile RET make tags RET
12740@end smallexample
12741
12742@noindent
12743(The @code{make tags} command works well with the GNU Emacs sources,
12744as well as with some other source packages.)
12745
12746For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12747Manual}.
12748
12749@node Regexp Review, re-search Exercises, etags, Regexp Search
12750@comment node-name, next, previous, up
12751@section Review
12752
12753Here is a brief summary of some recently introduced functions.
12754
12755@table @code
12756@item while
12757Repeatedly evaluate the body of the expression so long as the first
12758element of the body tests true. Then return @code{nil}. (The
12759expression is evaluated only for its side effects.)
12760
12761@need 1250
12762For example:
12763
12764@smallexample
12765@group
12766(let ((foo 2))
12767 (while (> foo 0)
12768 (insert (format "foo is %d.\n" foo))
12769 (setq foo (1- foo))))
12770
12771 @result{} foo is 2.
12772 foo is 1.
12773 nil
12774@end group
12775@end smallexample
12776@noindent
12777(The @code{insert} function inserts its arguments at point; the
12778@code{format} function returns a string formatted from its arguments
12779the way @code{message} formats its arguments; @code{\n} produces a new
12780line.)
12781
12782@item re-search-forward
12783Search for a pattern, and if the pattern is found, move point to rest
12784just after it.
12785
12786@noindent
12787Takes four arguments, like @code{search-forward}:
12788
12789@enumerate
12790@item
12791A regular expression that specifies the pattern to search for.
12792
12793@item
12794Optionally, the limit of the search.
12795
12796@item
12797Optionally, what to do if the search fails, return @code{nil} or an
12798error message.
12799
12800@item
12801Optionally, how many times to repeat the search; if negative, the
12802search goes backwards.
12803@end enumerate
12804
12805@item let*
12806Bind some variables locally to particular values,
12807and then evaluate the remaining arguments, returning the value of the
12808last one. While binding the local variables, use the local values of
12809variables bound earlier, if any.
12810
12811@need 1250
12812For example:
12813
12814@smallexample
12815@group
12816(let* ((foo 7)
12817 (bar (* 3 foo)))
12818 (message "`bar' is %d." bar))
12819 @result{} `bar' is 21.
12820@end group
12821@end smallexample
12822
12823@item match-beginning
12824Return the position of the start of the text found by the last regular
12825expression search.
12826
12827@item looking-at
12828Return @code{t} for true if the text after point matches the argument,
12829which should be a regular expression.
12830
12831@item eobp
12832Return @code{t} for true if point is at the end of the accessible part
12833of a buffer. The end of the accessible part is the end of the buffer
12834if the buffer is not narrowed; it is the end of the narrowed part if
12835the buffer is narrowed.
12836
12837@item prog1
12838Evaluate each argument in sequence and then return the value of the
12839@emph{first}.
12840
12841@need 1250
12842For example:
12843
12844@smallexample
12845@group
12846(prog1 1 2 3 4)
12847 @result{} 1
12848@end group
12849@end smallexample
12850@end table
12851
12852@need 1500
12853@node re-search Exercises, , Regexp Review, Regexp Search
12854@section Exercises with @code{re-search-forward}
12855
12856@itemize @bullet
12857@item
12858Write a function to search for a regular expression that matches two
12859or more blank lines in sequence.
12860
12861@item
12862Write a function to search for duplicated words, such as `the the'.
12863@xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12864Manual}, for information on how to write a regexp (a regular
12865expression) to match a string that is composed of two identical
12866halves. You can devise several regexps; some are better than others.
12867The function I use is described in an appendix, along with several
12868regexps. @xref{the-the, , @code{the-the} Duplicated Words Function}.
12869@end itemize
12870
12871@node Counting Words, Words in a defun, Regexp Search, Top
12872@chapter Counting: Repetition and Regexps
12873@cindex Repetition for word counting
12874@cindex Regular expressions for word counting
12875
12876Repetition and regular expression searches are powerful tools that you
12877often use when you write code in Emacs Lisp. This chapter illustrates
12878the use of regular expression searches through the construction of
12879word count commands using @code{while} loops and recursion.
12880
12881@menu
12882* Why Count Words::
12883* count-words-region:: Use a regexp, but find a problem.
12884* recursive-count-words:: Start with case of no words in region.
12885* Counting Exercise::
12886@end menu
12887
12888@node Why Count Words, count-words-region, Counting Words, Counting Words
12889@ifnottex
12890@unnumberedsec Counting words
12891@end ifnottex
12892
12893The standard Emacs distribution contains a function for counting the
12894number of lines within a region. However, there is no corresponding
12895function for counting words.
12896
12897Certain types of writing ask you to count words. Thus, if you write
12898an essay, you may be limited to 800 words; if you write a novel, you
12899may discipline yourself to write 1000 words a day. It seems odd to me
12900that Emacs lacks a word count command. Perhaps people use Emacs
12901mostly for code or types of documentation that do not require word
12902counts; or perhaps they restrict themselves to the operating system
12903word count command, @code{wc}. Alternatively, people may follow
12904the publishers' convention and compute a word count by dividing the
12905number of characters in a document by five. In any event, here are
12906commands to count words.
12907
12908@node count-words-region, recursive-count-words, Why Count Words, Counting Words
12909@comment node-name, next, previous, up
12910@section The @code{count-words-region} Function
12911@findex count-words-region
12912
12913A word count command could count words in a line, paragraph, region,
12914or buffer. What should the command cover? You could design the
12915command to count the number of words in a complete buffer. However,
12916the Emacs tradition encourages flexibility---you may want to count
12917words in just a section, rather than all of a buffer. So it makes
12918more sense to design the command to count the number of words in a
12919region. Once you have a @code{count-words-region} command, you can,
12920if you wish, count words in a whole buffer by marking it with @kbd{C-x
12921h} (@code{mark-whole-buffer}).
12922
12923Clearly, counting words is a repetitive act: starting from the
12924beginning of the region, you count the first word, then the second
12925word, then the third word, and so on, until you reach the end of the
12926region. This means that word counting is ideally suited to recursion
12927or to a @code{while} loop.
12928
12929@menu
12930* Design count-words-region:: The definition using a @code{while} loop.
12931* Whitespace Bug:: The Whitespace Bug in @code{count-words-region}.
12932@end menu
12933
12934@node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12935@ifnottex
12936@unnumberedsubsec Designing @code{count-words-region}
12937@end ifnottex
12938
12939First, we will implement the word count command with a @code{while}
12940loop, then with recursion. The command will, of course, be
12941interactive.
12942
12943@need 800
12944The template for an interactive function definition is, as always:
12945
12946@smallexample
12947@group
12948(defun @var{name-of-function} (@var{argument-list})
12949 "@var{documentation}@dots{}"
12950 (@var{interactive-expression}@dots{})
12951 @var{body}@dots{})
12952@end group
12953@end smallexample
12954
12955What we need to do is fill in the slots.
12956
12957The name of the function should be self-explanatory and similar to the
12958existing @code{count-lines-region} name. This makes the name easier
12959to remember. @code{count-words-region} is a good choice.
12960
12961The function counts words within a region. This means that the
12962argument list must contain symbols that are bound to the two
12963positions, the beginning and end of the region. These two positions
12964can be called @samp{beginning} and @samp{end} respectively. The first
12965line of the documentation should be a single sentence, since that is
12966all that is printed as documentation by a command such as
12967@code{apropos}. The interactive expression will be of the form
12968@samp{(interactive "r")}, since that will cause Emacs to pass the
12969beginning and end of the region to the function's argument list. All
12970this is routine.
12971
12972The body of the function needs to be written to do three tasks:
12973first, to set up conditions under which the @code{while} loop can
12974count words, second, to run the @code{while} loop, and third, to send
12975a message to the user.
12976
12977When a user calls @code{count-words-region}, point may be at the
12978beginning or the end of the region. However, the counting process
12979must start at the beginning of the region. This means we will want
12980to put point there if it is not already there. Executing
12981@code{(goto-char beginning)} ensures this. Of course, we will want to
12982return point to its expected position when the function finishes its
12983work. For this reason, the body must be enclosed in a
12984@code{save-excursion} expression.
12985
12986The central part of the body of the function consists of a
12987@code{while} loop in which one expression jumps point forward word by
12988word, and another expression counts those jumps. The true-or-false-test
12989of the @code{while} loop should test true so long as point should jump
12990forward, and false when point is at the end of the region.
12991
12992We could use @code{(forward-word 1)} as the expression for moving point
12993forward word by word, but it is easier to see what Emacs identifies as a
12994`word' if we use a regular expression search.
12995
12996A regular expression search that finds the pattern for which it is
12997searching leaves point after the last character matched. This means
12998that a succession of successful word searches will move point forward
12999word by word.
13000
13001As a practical matter, we want the regular expression search to jump
13002over whitespace and punctuation between words as well as over the
13003words themselves. A regexp that refuses to jump over interword
13004whitespace would never jump more than one word! This means that
13005the regexp should include the whitespace and punctuation that follows
13006a word, if any, as well as the word itself. (A word may end a buffer
13007and not have any following whitespace or punctuation, so that part of
13008the regexp must be optional.)
13009
13010Thus, what we want for the regexp is a pattern defining one or more
13011word constituent characters followed, optionally, by one or more
13012characters that are not word constituents. The regular expression for
13013this is:
13014
13015@smallexample
13016\w+\W*
13017@end smallexample
13018
13019@noindent
13020The buffer's syntax table determines which characters are and are not
13021word constituents. (@xref{Syntax, , What Constitutes a Word or
13022Symbol?}, for more about syntax. Also, see @ref{Syntax, Syntax, The
13023Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
13024Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13025
13026@need 800
13027The search expression looks like this:
13028
13029@smallexample
13030(re-search-forward "\\w+\\W*")
13031@end smallexample
13032
13033@noindent
13034(Note that paired backslashes precede the @samp{w} and @samp{W}. A
13035single backslash has special meaning to the Emacs Lisp interpreter. It
13036indicates that the following character is interpreted differently than
13037usual. For example, the two characters, @samp{\n}, stand for
13038@samp{newline}, rather than for a backslash followed by @samp{n}. Two
13039backslashes in a row stand for an ordinary, `unspecial' backslash.)
13040
13041We need a counter to count how many words there are; this variable
13042must first be set to 0 and then incremented each time Emacs goes
13043around the @code{while} loop. The incrementing expression is simply:
13044
13045@smallexample
13046(setq count (1+ count))
13047@end smallexample
13048
13049Finally, we want to tell the user how many words there are in the
13050region. The @code{message} function is intended for presenting this
13051kind of information to the user. The message has to be phrased so
13052that it reads properly regardless of how many words there are in the
13053region: we don't want to say that ``there are 1 words in the region''.
13054The conflict between singular and plural is ungrammatical. We can
13055solve this problem by using a conditional expression that evaluates
13056different messages depending on the number of words in the region.
13057There are three possibilities: no words in the region, one word in the
13058region, and more than one word. This means that the @code{cond}
13059special form is appropriate.
13060
13061@need 1500
13062All this leads to the following function definition:
13063
13064@smallexample
13065@group
13066;;; @r{First version; has bugs!}
13067(defun count-words-region (beginning end)
13068 "Print number of words in the region.
13069Words are defined as at least one word-constituent
13070character followed by at least one character that
13071is not a word-constituent. The buffer's syntax
13072table determines which characters these are."
13073 (interactive "r")
13074 (message "Counting words in region ... ")
13075@end group
13076
13077@group
13078;;; @r{1. Set up appropriate conditions.}
13079 (save-excursion
13080 (goto-char beginning)
13081 (let ((count 0))
13082@end group
13083
13084@group
13085;;; @r{2. Run the} while @r{loop.}
13086 (while (< (point) end)
13087 (re-search-forward "\\w+\\W*")
13088 (setq count (1+ count)))
13089@end group
13090
13091@group
13092;;; @r{3. Send a message to the user.}
13093 (cond ((zerop count)
13094 (message
13095 "The region does NOT have any words."))
13096 ((= 1 count)
13097 (message
13098 "The region has 1 word."))
13099 (t
13100 (message
13101 "The region has %d words." count))))))
13102@end group
13103@end smallexample
13104
13105@noindent
13106As written, the function works, but not in all circumstances.
13107
13108@node Whitespace Bug, , Design count-words-region, count-words-region
13109@comment node-name, next, previous, up
13110@subsection The Whitespace Bug in @code{count-words-region}
13111
13112The @code{count-words-region} command described in the preceding
13113section has two bugs, or rather, one bug with two manifestations.
13114First, if you mark a region containing only whitespace in the middle
13115of some text, the @code{count-words-region} command tells you that the
13116region contains one word! Second, if you mark a region containing
13117only whitespace at the end of the buffer or the accessible portion of
13118a narrowed buffer, the command displays an error message that looks
13119like this:
13120
13121@smallexample
13122Search failed: "\\w+\\W*"
13123@end smallexample
13124
13125If you are reading this in Info in GNU Emacs, you can test for these
13126bugs yourself.
13127
13128First, evaluate the function in the usual manner to install it.
13129@ifinfo
13130Here is a copy of the definition. Place your cursor after the closing
13131parenthesis and type @kbd{C-x C-e} to install it.
13132
13133@smallexample
13134@group
13135;; @r{First version; has bugs!}
13136(defun count-words-region (beginning end)
13137 "Print number of words in the region.
13138Words are defined as at least one word-constituent character followed
13139by at least one character that is not a word-constituent. The buffer's
13140syntax table determines which characters these are."
13141@end group
13142@group
13143 (interactive "r")
13144 (message "Counting words in region ... ")
13145@end group
13146
13147@group
13148;;; @r{1. Set up appropriate conditions.}
13149 (save-excursion
13150 (goto-char beginning)
13151 (let ((count 0))
13152@end group
13153
13154@group
13155;;; @r{2. Run the} while @r{loop.}
13156 (while (< (point) end)
13157 (re-search-forward "\\w+\\W*")
13158 (setq count (1+ count)))
13159@end group
13160
13161@group
13162;;; @r{3. Send a message to the user.}
13163 (cond ((zerop count)
13164 (message "The region does NOT have any words."))
13165 ((= 1 count) (message "The region has 1 word."))
13166 (t (message "The region has %d words." count))))))
13167@end group
13168@end smallexample
13169@end ifinfo
13170
13171@need 1000
13172If you wish, you can also install this keybinding by evaluating it:
13173
13174@smallexample
13175(global-set-key "\C-c=" 'count-words-region)
13176@end smallexample
13177
13178To conduct the first test, set mark and point to the beginning and end
13179of the following line and then type @kbd{C-c =} (or @kbd{M-x
13180count-words-region} if you have not bound @kbd{C-c =}):
13181
13182@smallexample
13183 one two three
13184@end smallexample
13185
13186@noindent
13187Emacs will tell you, correctly, that the region has three words.
13188
13189Repeat the test, but place mark at the beginning of the line and place
13190point just @emph{before} the word @samp{one}. Again type the command
13191@kbd{C-c =} (or @kbd{M-x count-words-region}). Emacs should tell you
13192that the region has no words, since it is composed only of the
13193whitespace at the beginning of the line. But instead Emacs tells you
13194that the region has one word!
13195
13196For the third test, copy the sample line to the end of the
13197@file{*scratch*} buffer and then type several spaces at the end of the
13198line. Place mark right after the word @samp{three} and point at the
13199end of line. (The end of the line will be the end of the buffer.)
13200Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13201Again, Emacs should tell you that the region has no words, since it is
13202composed only of the whitespace at the end of the line. Instead,
13203Emacs displays an error message saying @samp{Search failed}.
13204
13205The two bugs stem from the same problem.
13206
13207Consider the first manifestation of the bug, in which the command
13208tells you that the whitespace at the beginning of the line contains
13209one word. What happens is this: The @code{M-x count-words-region}
13210command moves point to the beginning of the region. The @code{while}
13211tests whether the value of point is smaller than the value of
13212@code{end}, which it is. Consequently, the regular expression search
13213looks for and finds the first word. It leaves point after the word.
13214@code{count} is set to one. The @code{while} loop repeats; but this
13215time the value of point is larger than the value of @code{end}, the
13216loop is exited; and the function displays a message saying the number
13217of words in the region is one. In brief, the regular expression
13218search looks for and finds the word even though it is outside
13219the marked region.
13220
13221In the second manifestation of the bug, the region is whitespace at
13222the end of the buffer. Emacs says @samp{Search failed}. What happens
13223is that the true-or-false-test in the @code{while} loop tests true, so
13224the search expression is executed. But since there are no more words
13225in the buffer, the search fails.
13226
13227In both manifestations of the bug, the search extends or attempts to
13228extend outside of the region.
13229
13230The solution is to limit the search to the region---this is a fairly
13231simple action, but as you may have come to expect, it is not quite as
13232simple as you might think.
13233
13234As we have seen, the @code{re-search-forward} function takes a search
13235pattern as its first argument. But in addition to this first,
13236mandatory argument, it accepts three optional arguments. The optional
13237second argument bounds the search. The optional third argument, if
13238@code{t}, causes the function to return @code{nil} rather than signal
13239an error if the search fails. The optional fourth argument is a
13240repeat count. (In Emacs, you can see a function's documentation by
13241typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13242
13243In the @code{count-words-region} definition, the value of the end of
13244the region is held by the variable @code{end} which is passed as an
13245argument to the function. Thus, we can add @code{end} as an argument
13246to the regular expression search expression:
13247
13248@smallexample
13249(re-search-forward "\\w+\\W*" end)
13250@end smallexample
13251
13252However, if you make only this change to the @code{count-words-region}
13253definition and then test the new version of the definition on a
13254stretch of whitespace, you will receive an error message saying
13255@samp{Search failed}.
13256
13257What happens is this: the search is limited to the region, and fails
13258as you expect because there are no word-constituent characters in the
13259region. Since it fails, we receive an error message. But we do not
13260want to receive an error message in this case; we want to receive the
13261message that "The region does NOT have any words."
13262
13263The solution to this problem is to provide @code{re-search-forward}
13264with a third argument of @code{t}, which causes the function to return
13265@code{nil} rather than signal an error if the search fails.
13266
13267However, if you make this change and try it, you will see the message
13268``Counting words in region ... '' and @dots{} you will keep on seeing
13269that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13270
13271Here is what happens: the search is limited to the region, as before,
13272and it fails because there are no word-constituent characters in the
13273region, as expected. Consequently, the @code{re-search-forward}
13274expression returns @code{nil}. It does nothing else. In particular,
13275it does not move point, which it does as a side effect if it finds the
13276search target. After the @code{re-search-forward} expression returns
13277@code{nil}, the next expression in the @code{while} loop is evaluated.
13278This expression increments the count. Then the loop repeats. The
13279true-or-false-test tests true because the value of point is still less
13280than the value of end, since the @code{re-search-forward} expression
13281did not move point. @dots{} and the cycle repeats @dots{}
13282
13283The @code{count-words-region} definition requires yet another
13284modification, to cause the true-or-false-test of the @code{while} loop
13285to test false if the search fails. Put another way, there are two
13286conditions that must be satisfied in the true-or-false-test before the
13287word count variable is incremented: point must still be within the
13288region and the search expression must have found a word to count.
13289
13290Since both the first condition and the second condition must be true
13291together, the two expressions, the region test and the search
13292expression, can be joined with an @code{and} special form and embedded in
13293the @code{while} loop as the true-or-false-test, like this:
13294
13295@smallexample
13296(and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13297@end smallexample
13298
13299@c colon in printed section title causes problem in Info cross reference
13300@c also trouble with an overfull hbox
13301@iftex
13302@noindent
13303(For information about @code{and}, see
13304@ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13305Functions}.)
13306@end iftex
13307@ifinfo
13308@noindent
13309(@xref{forward-paragraph}, for information about @code{and}.)
13310@end ifinfo
13311
13312The @code{re-search-forward} expression returns @code{t} if the search
13313succeeds and as a side effect moves point. Consequently, as words are
13314found, point is moved through the region. When the search
13315expression fails to find another word, or when point reaches the end
13316of the region, the true-or-false-test tests false, the @code{while}
13317loop exists, and the @code{count-words-region} function displays one
13318or other of its messages.
13319
13320After incorporating these final changes, the @code{count-words-region}
13321works without bugs (or at least, without bugs that I have found!).
13322Here is what it looks like:
13323
13324@smallexample
13325@group
13326;;; @r{Final version:} @code{while}
13327(defun count-words-region (beginning end)
13328 "Print number of words in the region."
13329 (interactive "r")
13330 (message "Counting words in region ... ")
13331@end group
13332
13333@group
13334;;; @r{1. Set up appropriate conditions.}
13335 (save-excursion
13336 (let ((count 0))
13337 (goto-char beginning)
13338@end group
13339
13340@group
13341;;; @r{2. Run the} while @r{loop.}
13342 (while (and (< (point) end)
13343 (re-search-forward "\\w+\\W*" end t))
13344 (setq count (1+ count)))
13345@end group
13346
13347@group
13348;;; @r{3. Send a message to the user.}
13349 (cond ((zerop count)
13350 (message
13351 "The region does NOT have any words."))
13352 ((= 1 count)
13353 (message
13354 "The region has 1 word."))
13355 (t
13356 (message
13357 "The region has %d words." count))))))
13358@end group
13359@end smallexample
13360
13361@node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13362@comment node-name, next, previous, up
13363@section Count Words Recursively
13364@cindex Count words recursively
13365@cindex Recursively counting words
13366@cindex Words, counted recursively
13367
13368You can write the function for counting words recursively as well as
13369with a @code{while} loop. Let's see how this is done.
13370
13371First, we need to recognize that the @code{count-words-region}
13372function has three jobs: it sets up the appropriate conditions for
13373counting to occur; it counts the words in the region; and it sends a
13374message to the user telling how many words there are.
13375
13376If we write a single recursive function to do everything, we will
13377receive a message for every recursive call. If the region contains 13
13378words, we will receive thirteen messages, one right after the other.
13379We don't want this! Instead, we must write two functions to do the
13380job, one of which (the recursive function) will be used inside of the
13381other. One function will set up the conditions and display the
13382message; the other will return the word count.
13383
13384Let us start with the function that causes the message to be displayed.
13385We can continue to call this @code{count-words-region}.
13386
13387This is the function that the user will call. It will be interactive.
13388Indeed, it will be similar to our previous versions of this
13389function, except that it will call @code{recursive-count-words} to
13390determine how many words are in the region.
13391
13392@need 1250
13393We can readily construct a template for this function, based on our
13394previous versions:
13395
13396@smallexample
13397@group
13398;; @r{Recursive version; uses regular expression search}
13399(defun count-words-region (beginning end)
13400 "@var{documentation}@dots{}"
13401 (@var{interactive-expression}@dots{})
13402@end group
13403@group
13404
13405;;; @r{1. Set up appropriate conditions.}
13406 (@var{explanatory message})
13407 (@var{set-up functions}@dots{}
13408@end group
13409@group
13410
13411;;; @r{2. Count the words.}
13412 @var{recursive call}
13413@end group
13414@group
13415
13416;;; @r{3. Send a message to the user.}
13417 @var{message providing word count}))
13418@end group
13419@end smallexample
13420
13421The definition looks straightforward, except that somehow the count
13422returned by the recursive call must be passed to the message
13423displaying the word count. A little thought suggests that this can be
13424done by making use of a @code{let} expression: we can bind a variable
13425in the varlist of a @code{let} expression to the number of words in
13426the region, as returned by the recursive call; and then the
13427@code{cond} expression, using binding, can display the value to the
13428user.
13429
13430Often, one thinks of the binding within a @code{let} expression as
13431somehow secondary to the `primary' work of a function. But in this
13432case, what you might consider the `primary' job of the function,
13433counting words, is done within the @code{let} expression.
13434
13435@need 1250
13436Using @code{let}, the function definition looks like this:
13437
13438@smallexample
13439@group
13440(defun count-words-region (beginning end)
13441 "Print number of words in the region."
13442 (interactive "r")
13443@end group
13444
13445@group
13446;;; @r{1. Set up appropriate conditions.}
13447 (message "Counting words in region ... ")
13448 (save-excursion
13449 (goto-char beginning)
13450@end group
13451
13452@group
13453;;; @r{2. Count the words.}
13454 (let ((count (recursive-count-words end)))
13455@end group
13456
13457@group
13458;;; @r{3. Send a message to the user.}
13459 (cond ((zerop count)
13460 (message
13461 "The region does NOT have any words."))
13462 ((= 1 count)
13463 (message
13464 "The region has 1 word."))
13465 (t
13466 (message
13467 "The region has %d words." count))))))
13468@end group
13469@end smallexample
13470
13471Next, we need to write the recursive counting function.
13472
13473A recursive function has at least three parts: the `do-again-test', the
13474`next-step-expression', and the recursive call.
13475
13476The do-again-test determines whether the function will or will not be
13477called again. Since we are counting words in a region and can use a
13478function that moves point forward for every word, the do-again-test
13479can check whether point is still within the region. The do-again-test
13480should find the value of point and determine whether point is before,
13481at, or after the value of the end of the region. We can use the
13482@code{point} function to locate point. Clearly, we must pass the
13483value of the end of the region to the recursive counting function as an
13484argument.
13485
13486In addition, the do-again-test should also test whether the search finds a
13487word. If it does not, the function should not call itself again.
13488
13489The next-step-expression changes a value so that when the recursive
13490function is supposed to stop calling itself, it stops. More
13491precisely, the next-step-expression changes a value so that at the
13492right time, the do-again-test stops the recursive function from
13493calling itself again. In this case, the next-step-expression can be
13494the expression that moves point forward, word by word.
13495
13496The third part of a recursive function is the recursive call.
13497
13498Somewhere, also, we also need a part that does the `work' of the
13499function, a part that does the counting. A vital part!
13500
13501@need 1250
13502But already, we have an outline of the recursive counting function:
13503
13504@smallexample
13505@group
13506(defun recursive-count-words (region-end)
13507 "@var{documentation}@dots{}"
13508 @var{do-again-test}
13509 @var{next-step-expression}
13510 @var{recursive call})
13511@end group
13512@end smallexample
13513
13514Now we need to fill in the slots. Let's start with the simplest cases
13515first: if point is at or beyond the end of the region, there cannot
13516be any words in the region, so the function should return zero.
13517Likewise, if the search fails, there are no words to count, so the
13518function should return zero.
13519
13520On the other hand, if point is within the region and the search
13521succeeds, the function should call itself again.
13522
13523@need 800
13524Thus, the do-again-test should look like this:
13525
13526@smallexample
13527@group
13528(and (< (point) region-end)
13529 (re-search-forward "\\w+\\W*" region-end t))
13530@end group
13531@end smallexample
13532
13533Note that the search expression is part of the do-again-test---the
13534function returns @code{t} if its search succeeds and @code{nil} if it
13535fails. (@xref{Whitespace Bug, , The Whitespace Bug in
13536@code{count-words-region}}, for an explanation of how
13537@code{re-search-forward} works.)
13538
13539The do-again-test is the true-or-false test of an @code{if} clause.
13540Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13541clause should call the function again; but if it fails, the else-part
13542should return zero since either point is outside the region or the
13543search failed because there were no words to find.
13544
13545But before considering the recursive call, we need to consider the
13546next-step-expression. What is it? Interestingly, it is the search
13547part of the do-again-test.
13548
13549In addition to returning @code{t} or @code{nil} for the
13550do-again-test, @code{re-search-forward} moves point forward as a side
13551effect of a successful search. This is the action that changes the
13552value of point so that the recursive function stops calling itself
13553when point completes its movement through the region. Consequently,
13554the @code{re-search-forward} expression is the next-step-expression.
13555
13556@need 1200
13557In outline, then, the body of the @code{recursive-count-words}
13558function looks like this:
13559
13560@smallexample
13561@group
13562(if @var{do-again-test-and-next-step-combined}
13563 ;; @r{then}
13564 @var{recursive-call-returning-count}
13565 ;; @r{else}
13566 @var{return-zero})
13567@end group
13568@end smallexample
13569
13570How to incorporate the mechanism that counts?
13571
13572If you are not used to writing recursive functions, a question like
13573this can be troublesome. But it can and should be approached
13574systematically.
13575
13576We know that the counting mechanism should be associated in some way
13577with the recursive call. Indeed, since the next-step-expression moves
13578point forward by one word, and since a recursive call is made for
13579each word, the counting mechanism must be an expression that adds one
13580to the value returned by a call to @code{recursive-count-words}.
13581
13582Consider several cases:
13583
13584@itemize @bullet
13585@item
13586If there are two words in the region, the function should return
13587a value resulting from adding one to the value returned when it counts
13588the first word, plus the number returned when it counts the remaining
13589words in the region, which in this case is one.
13590
13591@item
13592If there is one word in the region, the function should return
13593a value resulting from adding one to the value returned when it counts
13594that word, plus the number returned when it counts the remaining
13595words in the region, which in this case is zero.
13596
13597@item
13598If there are no words in the region, the function should return zero.
13599@end itemize
13600
13601From the sketch we can see that the else-part of the @code{if} returns
13602zero for the case of no words. This means that the then-part of the
13603@code{if} must return a value resulting from adding one to the value
13604returned from a count of the remaining words.
13605
13606@need 1200
13607The expression will look like this, where @code{1+} is a function that
13608adds one to its argument.
13609
13610@smallexample
13611(1+ (recursive-count-words region-end))
13612@end smallexample
13613
13614@need 1200
13615The whole @code{recursive-count-words} function will then look like
13616this:
13617
13618@smallexample
13619@group
13620(defun recursive-count-words (region-end)
13621 "@var{documentation}@dots{}"
13622
13623;;; @r{1. do-again-test}
13624 (if (and (< (point) region-end)
13625 (re-search-forward "\\w+\\W*" region-end t))
13626@end group
13627
13628@group
13629;;; @r{2. then-part: the recursive call}
13630 (1+ (recursive-count-words region-end))
13631
13632;;; @r{3. else-part}
13633 0))
13634@end group
13635@end smallexample
13636
13637@need 1250
13638Let's examine how this works:
13639
13640If there are no words in the region, the else part of the @code{if}
13641expression is evaluated and consequently the function returns zero.
13642
13643If there is one word in the region, the value of point is less than
13644the value of @code{region-end} and the search succeeds. In this case,
13645the true-or-false-test of the @code{if} expression tests true, and the
13646then-part of the @code{if} expression is evaluated. The counting
13647expression is evaluated. This expression returns a value (which will
13648be the value returned by the whole function) that is the sum of one
13649added to the value returned by a recursive call.
13650
13651Meanwhile, the next-step-expression has caused point to jump over the
13652first (and in this case only) word in the region. This means that
13653when @code{(recursive-count-words region-end)} is evaluated a second
13654time, as a result of the recursive call, the value of point will be
13655equal to or greater than the value of region end. So this time,
13656@code{recursive-count-words} will return zero. The zero will be added
13657to one, and the original evaluation of @code{recursive-count-words}
13658will return one plus zero, which is one, which is the correct amount.
13659
13660Clearly, if there are two words in the region, the first call to
13661@code{recursive-count-words} returns one added to the value returned
13662by calling @code{recursive-count-words} on a region containing the
13663remaining word---that is, it adds one to one, producing two, which is
13664the correct amount.
13665
13666Similarly, if there are three words in the region, the first call to
13667@code{recursive-count-words} returns one added to the value returned
13668by calling @code{recursive-count-words} on a region containing the
13669remaining two words---and so on and so on.
13670
13671@need 1250
13672@noindent
13673With full documentation the two functions look like this:
13674
13675@need 1250
13676@noindent
13677The recursive function:
13678
13679@findex recursive-count-words
13680@smallexample
13681@group
13682(defun recursive-count-words (region-end)
13683 "Number of words between point and REGION-END."
13684@end group
13685
13686@group
13687;;; @r{1. do-again-test}
13688 (if (and (< (point) region-end)
13689 (re-search-forward "\\w+\\W*" region-end t))
13690@end group
13691
13692@group
13693;;; @r{2. then-part: the recursive call}
13694 (1+ (recursive-count-words region-end))
13695
13696;;; @r{3. else-part}
13697 0))
13698@end group
13699@end smallexample
13700
13701@need 800
13702@noindent
13703The wrapper:
13704
13705@smallexample
13706@group
13707;;; @r{Recursive version}
13708(defun count-words-region (beginning end)
13709 "Print number of words in the region.
13710@end group
13711
13712@group
13713Words are defined as at least one word-constituent
13714character followed by at least one character that is
13715not a word-constituent. The buffer's syntax table
13716determines which characters these are."
13717@end group
13718@group
13719 (interactive "r")
13720 (message "Counting words in region ... ")
13721 (save-excursion
13722 (goto-char beginning)
13723 (let ((count (recursive-count-words end)))
13724@end group
13725@group
13726 (cond ((zerop count)
13727 (message
13728 "The region does NOT have any words."))
13729@end group
13730@group
13731 ((= 1 count)
13732 (message "The region has 1 word."))
13733 (t
13734 (message
13735 "The region has %d words." count))))))
13736@end group
13737@end smallexample
13738
13739@node Counting Exercise, , recursive-count-words, Counting Words
13740@section Exercise: Counting Punctuation
13741
13742Using a @code{while} loop, write a function to count the number of
13743punctuation marks in a region---period, comma, semicolon, colon,
13744exclamation mark, and question mark. Do the same using recursion.
13745
13746@node Words in a defun, Readying a Graph, Counting Words, Top
13747@chapter Counting Words in a @code{defun}
13748@cindex Counting words in a @code{defun}
13749@cindex Word counting in a @code{defun}
13750
13751Our next project is to count the number of words in a function
13752definition. Clearly, this can be done using some variant of
13753@code{count-word-region}. @xref{Counting Words, , Counting Words:
13754Repetition and Regexps}. If we are just going to count the words in
13755one definition, it is easy enough to mark the definition with the
13756@kbd{C-M-h} (@code{mark-defun}) command, and then call
13757@code{count-word-region}.
13758
13759However, I am more ambitious: I want to count the words and symbols in
13760every definition in the Emacs sources and then print a graph that
13761shows how many functions there are of each length: how many contain 40
13762to 49 words or symbols, how many contain 50 to 59 words or symbols,
13763and so on. I have often been curious how long a typical function is,
13764and this will tell.
13765
13766@menu
13767* Divide and Conquer::
13768* Words and Symbols:: What to count?
13769* Syntax:: What constitutes a word or symbol?
13770* count-words-in-defun:: Very like @code{count-words}.
13771* Several defuns:: Counting several defuns in a file.
13772* Find a File:: Do you want to look at a file?
13773* lengths-list-file:: A list of the lengths of many definitions.
13774* Several files:: Counting in definitions in different files.
13775* Several files recursively:: Recursively counting in different files.
13776* Prepare the data:: Prepare the data for display in a graph.
13777@end menu
13778
13779@node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13780@ifnottex
13781@unnumberedsec Divide and Conquer
13782@end ifnottex
13783
13784Described in one phrase, the histogram project is daunting; but
13785divided into numerous small steps, each of which we can take one at a
13786time, the project becomes less fearsome. Let us consider what the
13787steps must be:
13788
13789@itemize @bullet
13790@item
13791First, write a function to count the words in one definition. This
13792includes the problem of handling symbols as well as words.
13793
13794@item
13795Second, write a function to list the numbers of words in each function
13796in a file. This function can use the @code{count-words-in-defun}
13797function.
13798
13799@item
13800Third, write a function to list the numbers of words in each function
13801in each of several files. This entails automatically finding the
13802various files, switching to them, and counting the words in the
13803definitions within them.
13804
13805@item
13806Fourth, write a function to convert the list of numbers that we
13807created in step three to a form that will be suitable for printing as
13808a graph.
13809
13810@item
13811Fifth, write a function to print the results as a graph.
13812@end itemize
13813
13814This is quite a project! But if we take each step slowly, it will not
13815be difficult.
13816
13817@node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13818@section What to Count?
13819@cindex Words and symbols in defun
13820
13821When we first start thinking about how to count the words in a
13822function definition, the first question is (or ought to be) what are
13823we going to count? When we speak of `words' with respect to a Lisp
13824function definition, we are actually speaking, in large part, of
13825`symbols'. For example, the following @code{multiply-by-seven}
13826function contains the five symbols @code{defun},
13827@code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}. In
13828addition, in the documentation string, it contains the four words
13829@samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}. The
13830symbol @samp{number} is repeated, so the definition contains a total
13831of ten words and symbols.
13832
13833@smallexample
13834@group
13835(defun multiply-by-seven (number)
13836 "Multiply NUMBER by seven."
13837 (* 7 number))
13838@end group
13839@end smallexample
13840
13841@noindent
13842However, if we mark the @code{multiply-by-seven} definition with
13843@kbd{C-M-h} (@code{mark-defun}), and then call
13844@code{count-words-region} on it, we will find that
13845@code{count-words-region} claims the definition has eleven words, not
13846ten! Something is wrong!
13847
13848The problem is twofold: @code{count-words-region} does not count the
13849@samp{*} as a word, and it counts the single symbol,
13850@code{multiply-by-seven}, as containing three words. The hyphens are
13851treated as if they were interword spaces rather than intraword
13852connectors: @samp{multiply-by-seven} is counted as if it were written
13853@samp{multiply by seven}.
13854
13855The cause of this confusion is the regular expression search within
13856the @code{count-words-region} definition that moves point forward word
13857by word. In the canonical version of @code{count-words-region}, the
13858regexp is:
13859
13860@smallexample
13861"\\w+\\W*"
13862@end smallexample
13863
13864@noindent
13865This regular expression is a pattern defining one or more word
13866constituent characters possibly followed by one or more characters
13867that are not word constituents. What is meant by `word constituent
13868characters' brings us to the issue of syntax, which is worth a section
13869of its own.
13870
13871@node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13872@section What Constitutes a Word or Symbol?
13873@cindex Syntax categories and tables
13874
13875Emacs treats different characters as belonging to different
13876@dfn{syntax categories}. For example, the regular expression,
13877@samp{\\w+}, is a pattern specifying one or more @emph{word
13878constituent} characters. Word constituent characters are members of
13879one syntax category. Other syntax categories include the class of
13880punctuation characters, such as the period and the comma, and the
13881class of whitespace characters, such as the blank space and the tab
13882character. (For more information, see @ref{Syntax, Syntax, The Syntax
13883Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13884Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13885
13886Syntax tables specify which characters belong to which categories.
13887Usually, a hyphen is not specified as a `word constituent character'.
13888Instead, it is specified as being in the `class of characters that are
13889part of symbol names but not words.' This means that the
13890@code{count-words-region} function treats it in the same way it treats
13891an interword white space, which is why @code{count-words-region}
13892counts @samp{multiply-by-seven} as three words.
13893
13894There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13895one symbol: modify the syntax table or modify the regular expression.
13896
13897We could redefine a hyphen as a word constituent character by
13898modifying the syntax table that Emacs keeps for each mode. This
13899action would serve our purpose, except that a hyphen is merely the
13900most common character within symbols that is not typically a word
13901constituent character; there are others, too.
13902
13903Alternatively, we can redefine the regular expression used in the
13904@code{count-words} definition so as to include symbols. This
13905procedure has the merit of clarity, but the task is a little tricky.
13906
13907@need 1200
13908The first part is simple enough: the pattern must match ``at least one
13909character that is a word or symbol constituent''. Thus:
13910
13911@smallexample
13912"\\(\\w\\|\\s_\\)+"
13913@end smallexample
13914
13915@noindent
13916The @samp{\\(} is the first part of the grouping construct that
13917includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13918by the @samp{\\|}. The @samp{\\w} matches any word-constituent
13919character and the @samp{\\s_} matches any character that is part of a
13920symbol name but not a word-constituent character. The @samp{+}
13921following the group indicates that the word or symbol constituent
13922characters must be matched at least once.
13923
13924However, the second part of the regexp is more difficult to design.
13925What we want is to follow the first part with ``optionally one or more
13926characters that are not constituents of a word or symbol''. At first,
13927I thought I could define this with the following:
13928
13929@smallexample
13930"\\(\\W\\|\\S_\\)*"
13931@end smallexample
13932
13933@noindent
13934The upper case @samp{W} and @samp{S} match characters that are
13935@emph{not} word or symbol constituents. Unfortunately, this
13936expression matches any character that is either not a word constituent
13937or not a symbol constituent. This matches any character!
13938
13939I then noticed that every word or symbol in my test region was
13940followed by white space (blank space, tab, or newline). So I tried
13941placing a pattern to match one or more blank spaces after the pattern
13942for one or more word or symbol constituents. This failed, too. Words
13943and symbols are often separated by whitespace, but in actual code
13944parentheses may follow symbols and punctuation may follow words. So
13945finally, I designed a pattern in which the word or symbol constituents
13946are followed optionally by characters that are not white space and
13947then followed optionally by white space.
13948
13949@need 800
13950Here is the full regular expression:
13951
13952@smallexample
13953"\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13954@end smallexample
13955
13956@node count-words-in-defun, Several defuns, Syntax, Words in a defun
13957@section The @code{count-words-in-defun} Function
13958@cindex Counting words in a @code{defun}
13959
13960We have seen that there are several ways to write a
13961@code{count-word-region} function. To write a
13962@code{count-words-in-defun}, we need merely adapt one of these
13963versions.
13964
13965The version that uses a @code{while} loop is easy to understand, so I
13966am going to adapt that. Because @code{count-words-in-defun} will be
13967part of a more complex program, it need not be interactive and it need
13968not display a message but just return the count. These considerations
13969simplify the definition a little.
13970
13971On the other hand, @code{count-words-in-defun} will be used within a
13972buffer that contains function definitions. Consequently, it is
13973reasonable to ask that the function determine whether it is called
13974when point is within a function definition, and if it is, to return
13975the count for that definition. This adds complexity to the
13976definition, but saves us from needing to pass arguments to the
13977function.
13978
13979@need 1250
13980These considerations lead us to prepare the following template:
13981
13982@smallexample
13983@group
13984(defun count-words-in-defun ()
13985 "@var{documentation}@dots{}"
13986 (@var{set up}@dots{}
13987 (@var{while loop}@dots{})
13988 @var{return count})
13989@end group
13990@end smallexample
13991
13992@noindent
13993As usual, our job is to fill in the slots.
13994
13995First, the set up.
13996
13997We are presuming that this function will be called within a buffer
13998containing function definitions. Point will either be within a
13999function definition or not. For @code{count-words-in-defun} to work,
14000point must move to the beginning of the definition, a counter must
14001start at zero, and the counting loop must stop when point reaches the
14002end of the definition.
14003
14004The @code{beginning-of-defun} function searches backwards for an
14005opening delimiter such as a @samp{(} at the beginning of a line, and
14006moves point to that position, or else to the limit of the search. In
14007practice, this means that @code{beginning-of-defun} moves point to the
14008beginning of an enclosing or preceding function definition, or else to
14009the beginning of the buffer. We can use @code{beginning-of-defun} to
14010place point where we wish to start.
14011
14012The @code{while} loop requires a counter to keep track of the words or
14013symbols being counted. A @code{let} expression can be used to create
14014a local variable for this purpose, and bind it to an initial value of zero.
14015
14016The @code{end-of-defun} function works like @code{beginning-of-defun}
14017except that it moves point to the end of the definition.
14018@code{end-of-defun} can be used as part of an expression that
14019determines the position of the end of the definition.
14020
14021The set up for @code{count-words-in-defun} takes shape rapidly: first
14022we move point to the beginning of the definition, then we create a
14023local variable to hold the count, and finally, we record the position
14024of the end of the definition so the @code{while} loop will know when to stop
14025looping.
14026
14027@need 1250
14028The code looks like this:
14029
14030@smallexample
14031@group
14032(beginning-of-defun)
14033(let ((count 0)
14034 (end (save-excursion (end-of-defun) (point))))
14035@end group
14036@end smallexample
14037
14038@noindent
14039The code is simple. The only slight complication is likely to concern
14040@code{end}: it is bound to the position of the end of the definition
14041by a @code{save-excursion} expression that returns the value of point
14042after @code{end-of-defun} temporarily moves it to the end of the
14043definition.
14044
14045The second part of the @code{count-words-in-defun}, after the set up,
14046is the @code{while} loop.
14047
14048The loop must contain an expression that jumps point forward word by
14049word and symbol by symbol, and another expression that counts the
14050jumps. The true-or-false-test for the @code{while} loop should test
14051true so long as point should jump forward, and false when point is at
14052the end of the definition. We have already redefined the regular
14053expression for this (@pxref{Syntax}), so the loop is straightforward:
14054
14055@smallexample
14056@group
14057(while (and (< (point) end)
14058 (re-search-forward
14059 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14060 (setq count (1+ count)))
14061@end group
14062@end smallexample
14063
14064The third part of the function definition returns the count of words
14065and symbols. This part is the last expression within the body of the
14066@code{let} expression, and can be, very simply, the local variable
14067@code{count}, which when evaluated returns the count.
14068
14069@need 1250
14070Put together, the @code{count-words-in-defun} definition looks like this:
14071
14072@findex count-words-in-defun
14073@smallexample
14074@group
14075(defun count-words-in-defun ()
14076 "Return the number of words and symbols in a defun."
14077 (beginning-of-defun)
14078 (let ((count 0)
14079 (end (save-excursion (end-of-defun) (point))))
14080@end group
14081@group
14082 (while
14083 (and (< (point) end)
14084 (re-search-forward
14085 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14086 end t))
14087 (setq count (1+ count)))
14088 count))
14089@end group
14090@end smallexample
14091
14092How to test this? The function is not interactive, but it is easy to
14093put a wrapper around the function to make it interactive; we can use
14094almost the same code as for the recursive version of
14095@code{count-words-region}:
14096
14097@smallexample
14098@group
14099;;; @r{Interactive version.}
14100(defun count-words-defun ()
14101 "Number of words and symbols in a function definition."
14102 (interactive)
14103 (message
14104 "Counting words and symbols in function definition ... ")
14105@end group
14106@group
14107 (let ((count (count-words-in-defun)))
14108 (cond
14109 ((zerop count)
14110 (message
14111 "The definition does NOT have any words or symbols."))
14112@end group
14113@group
14114 ((= 1 count)
14115 (message
14116 "The definition has 1 word or symbol."))
14117 (t
14118 (message
14119 "The definition has %d words or symbols." count)))))
14120@end group
14121@end smallexample
14122
14123@need 800
14124@noindent
14125Let's re-use @kbd{C-c =} as a convenient keybinding:
14126
14127@smallexample
14128(global-set-key "\C-c=" 'count-words-defun)
14129@end smallexample
14130
14131Now we can try out @code{count-words-defun}: install both
14132@code{count-words-in-defun} and @code{count-words-defun}, and set the
14133keybinding, and then place the cursor within the following definition:
14134
14135@smallexample
14136@group
14137(defun multiply-by-seven (number)
14138 "Multiply NUMBER by seven."
14139 (* 7 number))
14140 @result{} 10
14141@end group
14142@end smallexample
14143
14144@noindent
14145Success! The definition has 10 words and symbols.
14146
14147The next problem is to count the numbers of words and symbols in
14148several definitions within a single file.
14149
14150@node Several defuns, Find a File, count-words-in-defun, Words in a defun
14151@section Count Several @code{defuns} Within a File
14152
14153A file such as @file{simple.el} may have 80 or more function
14154definitions within it. Our long term goal is to collect statistics on
14155many files, but as a first step, our immediate goal is to collect
14156statistics on one file.
14157
14158The information will be a series of numbers, each number being the
14159length of a function definition. We can store the numbers in a list.
14160
14161We know that we will want to incorporate the information regarding one
14162file with information about many other files; this means that the
14163function for counting definition lengths within one file need only
14164return the list of lengths. It need not and should not display any
14165messages.
14166
14167The word count commands contain one expression to jump point forward
14168word by word and another expression to count the jumps. The function
14169to return the lengths of definitions can be designed to work the same
14170way, with one expression to jump point forward definition by
14171definition and another expression to construct the lengths' list.
14172
14173This statement of the problem makes it elementary to write the
14174function definition. Clearly, we will start the count at the
14175beginning of the file, so the first command will be @code{(goto-char
14176(point-min))}. Next, we start the @code{while} loop; and the
14177true-or-false test of the loop can be a regular expression search for
14178the next function definition---so long as the search succeeds, point
14179is moved forward and then the body of the loop is evaluated. The body
14180needs an expression that constructs the lengths' list. @code{cons},
14181the list construction command, can be used to create the list. That
14182is almost all there is to it.
14183
14184@need 800
14185Here is what this fragment of code looks like:
14186
14187@smallexample
14188@group
14189(goto-char (point-min))
14190(while (re-search-forward "^(defun" nil t)
14191 (setq lengths-list
14192 (cons (count-words-in-defun) lengths-list)))
14193@end group
14194@end smallexample
14195
14196What we have left out is the mechanism for finding the file that
14197contains the function definitions.
14198
14199In previous examples, we either used this, the Info file, or we
14200switched back and forth to some other buffer, such as the
14201@file{*scratch*} buffer.
14202
14203Finding a file is a new process that we have not yet discussed.
14204
14205@node Find a File, lengths-list-file, Several defuns, Words in a defun
14206@comment node-name, next, previous, up
14207@section Find a File
14208@cindex Find a File
14209
14210To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14211command. This command is almost, but not quite right for the lengths
14212problem.
14213
14214@need 1200
14215Let's look at the source for @code{find-file} (you can use the
14216@code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14217find the source of a function):
14218
14219@smallexample
14220@group
14221(defun find-file (filename)
14222 "Edit file FILENAME.
14223Switch to a buffer visiting file FILENAME,
14224creating one if none already exists."
14225 (interactive "FFind file: ")
14226 (switch-to-buffer (find-file-noselect filename)))
14227@end group
14228@end smallexample
14229
14230The definition possesses short but complete documentation and an
14231interactive specification that prompts you for a file name when you
14232use the command interactively. The body of the definition contains
14233two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14234
14235According to its documentation as shown by @kbd{C-h f} (the
14236@code{describe-function} command), the @code{find-file-noselect}
14237function reads the named file into a buffer and returns the buffer.
14238However, the buffer is not selected. Emacs does not switch its
14239attention (or yours if you are using @code{find-file-noselect}) to the
14240named buffer. That is what @code{switch-to-buffer} does: it switches
14241the buffer to which Emacs attention is directed; and it switches the
14242buffer displayed in the window to the new buffer. We have discussed
14243buffer switching elsewhere. (@xref{Switching Buffers}.)
14244
14245In this histogram project, we do not need to display each file on the
14246screen as the program determines the length of each definition within
14247it. Instead of employing @code{switch-to-buffer}, we can work with
14248@code{set-buffer}, which redirects the attention of the computer
14249program to a different buffer but does not redisplay it on the screen.
14250So instead of calling on @code{find-file} to do the job, we must write
14251our own expression.
14252
14253The task is easy: use @code{find-file-noselect} and @code{set-buffer}.
14254
14255@node lengths-list-file, Several files, Find a File, Words in a defun
14256@section @code{lengths-list-file} in Detail
14257
14258The core of the @code{lengths-list-file} function is a @code{while}
14259loop containing a function to move point forward `defun by defun' and
14260a function to count the number of words and symbols in each defun.
14261This core must be surrounded by functions that do various other tasks,
14262including finding the file, and ensuring that point starts out at the
14263beginning of the file. The function definition looks like this:
14264@findex lengths-list-file
14265
14266@smallexample
14267@group
14268(defun lengths-list-file (filename)
14269 "Return list of definitions' lengths within FILE.
14270The returned list is a list of numbers.
14271Each number is the number of words or
14272symbols in one function definition."
14273@end group
14274@group
14275 (message "Working on `%s' ... " filename)
14276 (save-excursion
14277 (let ((buffer (find-file-noselect filename))
14278 (lengths-list))
14279 (set-buffer buffer)
14280 (setq buffer-read-only t)
14281 (widen)
14282 (goto-char (point-min))
14283 (while (re-search-forward "^(defun" nil t)
14284 (setq lengths-list
14285 (cons (count-words-in-defun) lengths-list)))
14286 (kill-buffer buffer)
14287 lengths-list)))
14288@end group
14289@end smallexample
14290
14291@noindent
14292The function is passed one argument, the name of the file on which it
14293will work. It has four lines of documentation, but no interactive
14294specification. Since people worry that a computer is broken if they
14295don't see anything going on, the first line of the body is a
14296message.
14297
14298The next line contains a @code{save-excursion} that returns Emacs'
14299attention to the current buffer when the function completes. This is
14300useful in case you embed this function in another function that
14301presumes point is restored to the original buffer.
14302
14303In the varlist of the @code{let} expression, Emacs finds the file and
14304binds the local variable @code{buffer} to the buffer containing the
14305file. At the same time, Emacs creates @code{lengths-list} as a local
14306variable.
14307
14308Next, Emacs switches its attention to the buffer.
14309
14310In the following line, Emacs makes the buffer read-only. Ideally,
14311this line is not necessary. None of the functions for counting words
14312and symbols in a function definition should change the buffer.
14313Besides, the buffer is not going to be saved, even if it were changed.
14314This line is entirely the consequence of great, perhaps excessive,
14315caution. The reason for the caution is that this function and those
14316it calls work on the sources for Emacs and it is very inconvenient if
14317they are inadvertently modified. It goes without saying that I did
14318not realize a need for this line until an experiment went awry and
14319started to modify my Emacs source files @dots{}
14320
14321Next comes a call to widen the buffer if it is narrowed. This
14322function is usually not needed---Emacs creates a fresh buffer if none
14323already exists; but if a buffer visiting the file already exists Emacs
14324returns that one. In this case, the buffer may be narrowed and must
14325be widened. If we wanted to be fully `user-friendly', we would
14326arrange to save the restriction and the location of point, but we
14327won't.
14328
14329The @code{(goto-char (point-min))} expression moves point to the
14330beginning of the buffer.
14331
14332Then comes a @code{while} loop in which the `work' of the function is
14333carried out. In the loop, Emacs determines the length of each
14334definition and constructs a lengths' list containing the information.
14335
14336Emacs kills the buffer after working through it. This is to save
14337space inside of Emacs. My version of Emacs 19 contained over 300
14338source files of interest; Emacs 21 contains over 800 source files.
14339Another function will apply @code{lengths-list-file} to each of the
14340files.
14341
14342Finally, the last expression within the @code{let} expression is the
14343@code{lengths-list} variable; its value is returned as the value of
14344the whole function.
14345
14346You can try this function by installing it in the usual fashion. Then
14347place your cursor after the following expression and type @kbd{C-x
14348C-e} (@code{eval-last-sexp}).
14349
14350@c !!! 21.0.100 lisp sources location here
14351@smallexample
14352(lengths-list-file
14353 "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14354@end smallexample
14355
14356@c was: (lengths-list-file "../lisp/debug.el")
14357@c !!! as of 21, Info file is in
14358@c /usr/share/info/emacs-lisp-intro.info.gz
14359@c but debug.el is in /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14360
14361@noindent
14362(You may need to change the pathname of the file; the one here worked
14363with GNU Emacs version 21.0.100. To change the expression, copy it to
14364the @file{*scratch*} buffer and edit it.
14365
14366@need 1200
14367@noindent
14368(Also, to see the full length of the list, rather than a truncated
14369version, you may have to evaluate the following:
14370
14371@smallexample
14372(custom-set-variables '(eval-expression-print-length nil))
14373@end smallexample
14374
14375@noindent
14376(@xref{defcustom, , Setting Variables with @code{defcustom}}.
14377Then evaluate the @code{lengths-list-file} expression.)
14378
14379@need 1200
14380The lengths' list for @file{debug.el} takes less than a second to
14381produce and looks like this:
14382
14383@smallexample
14384(77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14385@end smallexample
14386
14387@need 1500
14388(Using my old machine, the version 19 lengths' list for @file{debug.el}
14389took seven seconds to produce and looked like this:
14390
14391@smallexample
14392(75 41 80 62 20 45 44 68 45 12 34 235)
14393@end smallexample
14394
14395(The newer version of @file{debug.el} contains more defuns than the
14396earlier one; and my new machine is much faster than the old one.)
14397
14398Note that the length of the last definition in the file is first in
14399the list.
14400
14401@node Several files, Several files recursively, lengths-list-file, Words in a defun
14402@section Count Words in @code{defuns} in Different Files
14403
14404In the previous section, we created a function that returns a list of
14405the lengths of each definition in a file. Now, we want to define a
14406function to return a master list of the lengths of the definitions in
14407a list of files.
14408
14409Working on each of a list of files is a repetitious act, so we can use
14410either a @code{while} loop or recursion.
14411
14412@menu
14413* lengths-list-many-files:: Return a list of the lengths of defuns.
14414* append:: Attach one list to another.
14415@end menu
14416
14417@node lengths-list-many-files, append, Several files, Several files
14418@ifnottex
14419@unnumberedsubsec Determine the lengths of @code{defuns}
14420@end ifnottex
14421
14422The design using a @code{while} loop is routine. The argument passed
14423the function is a list of files. As we saw earlier (@pxref{Loop
14424Example}), you can write a @code{while} loop so that the body of the
14425loop is evaluated if such a list contains elements, but to exit the
14426loop if the list is empty. For this design to work, the body of the
14427loop must contain an expression that shortens the list each time the
14428body is evaluated, so that eventually the list is empty. The usual
14429technique is to set the value of the list to the value of the @sc{cdr}
14430of the list each time the body is evaluated.
14431
14432@need 800
14433The template looks like this:
14434
14435@smallexample
14436@group
14437(while @var{test-whether-list-is-empty}
14438 @var{body}@dots{}
14439 @var{set-list-to-cdr-of-list})
14440@end group
14441@end smallexample
14442
14443Also, we remember that a @code{while} loop returns @code{nil} (the
14444result of evaluating the true-or-false-test), not the result of any
14445evaluation within its body. (The evaluations within the body of the
14446loop are done for their side effects.) However, the expression that
14447sets the lengths' list is part of the body---and that is the value
14448that we want returned by the function as a whole. To do this, we
14449enclose the @code{while} loop within a @code{let} expression, and
14450arrange that the last element of the @code{let} expression contains
14451the value of the lengths' list. (@xref{Incrementing Example, , Loop
14452Example with an Incrementing Counter}.)
14453
14454@findex lengths-list-many-files
14455@need 1250
14456These considerations lead us directly to the function itself:
14457
14458@smallexample
14459@group
14460;;; @r{Use @code{while} loop.}
14461(defun lengths-list-many-files (list-of-files)
14462 "Return list of lengths of defuns in LIST-OF-FILES."
14463@end group
14464@group
14465 (let (lengths-list)
14466
14467;;; @r{true-or-false-test}
14468 (while list-of-files
14469 (setq lengths-list
14470 (append
14471 lengths-list
14472
14473;;; @r{Generate a lengths' list.}
14474 (lengths-list-file
14475 (expand-file-name (car list-of-files)))))
14476@end group
14477
14478@group
14479;;; @r{Make files' list shorter.}
14480 (setq list-of-files (cdr list-of-files)))
14481
14482;;; @r{Return final value of lengths' list.}
14483 lengths-list))
14484@end group
14485@end smallexample
14486
14487@code{expand-file-name} is a built-in function that converts a file
14488name to the absolute, long, path name form of the directory in which
14489the function is called.
14490
14491@c !!! 21.0.100 lisp sources location here
14492@need 1500
14493Thus, if @code{expand-file-name} is called on @code{debug.el} when
14494Emacs is visiting the
14495@file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14496
14497@smallexample
14498debug.el
14499@end smallexample
14500
14501@need 800
14502@noindent
14503becomes
14504
14505@c !!! 21.0.100 lisp sources location here
14506@smallexample
14507/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14508@end smallexample
14509
14510The only other new element of this function definition is the as yet
14511unstudied function @code{append}, which merits a short section for
14512itself.
14513
14514@node append, , lengths-list-many-files, Several files
14515@subsection The @code{append} Function
14516
14517@need 800
14518The @code{append} function attaches one list to another. Thus,
14519
14520@smallexample
14521(append '(1 2 3 4) '(5 6 7 8))
14522@end smallexample
14523
14524@need 800
14525@noindent
14526produces the list
14527
14528@smallexample
14529(1 2 3 4 5 6 7 8)
14530@end smallexample
14531
14532This is exactly how we want to attach two lengths' lists produced by
14533@code{lengths-list-file} to each other. The results contrast with
14534@code{cons},
14535
14536@smallexample
14537(cons '(1 2 3 4) '(5 6 7 8))
14538@end smallexample
14539
14540@need 1250
14541@noindent
14542which constructs a new list in which the first argument to @code{cons}
14543becomes the first element of the new list:
14544
14545@smallexample
14546((1 2 3 4) 5 6 7 8)
14547@end smallexample
14548
14549@node Several files recursively, Prepare the data, Several files, Words in a defun
14550@section Recursively Count Words in Different Files
14551
14552Besides a @code{while} loop, you can work on each of a list of files
14553with recursion. A recursive version of @code{lengths-list-many-files}
14554is short and simple.
14555
14556The recursive function has the usual parts: the `do-again-test', the
14557`next-step-expression', and the recursive call. The `do-again-test'
14558determines whether the function should call itself again, which it
14559will do if the @code{list-of-files} contains any remaining elements;
14560the `next-step-expression' resets the @code{list-of-files} to the
14561@sc{cdr} of itself, so eventually the list will be empty; and the
14562recursive call calls itself on the shorter list. The complete
14563function is shorter than this description!
14564@findex recursive-lengths-list-many-files
14565
14566@smallexample
14567@group
14568(defun recursive-lengths-list-many-files (list-of-files)
14569 "Return list of lengths of each defun in LIST-OF-FILES."
14570 (if list-of-files ; @r{do-again-test}
14571 (append
14572 (lengths-list-file
14573 (expand-file-name (car list-of-files)))
14574 (recursive-lengths-list-many-files
14575 (cdr list-of-files)))))
14576@end group
14577@end smallexample
14578
14579@noindent
14580In a sentence, the function returns the lengths' list for the first of
14581the @code{list-of-files} appended to the result of calling itself on
14582the rest of the @code{list-of-files}.
14583
14584Here is a test of @code{recursive-lengths-list-many-files}, along with
14585the results of running @code{lengths-list-file} on each of the files
14586individually.
14587
14588Install @code{recursive-lengths-list-many-files} and
14589@code{lengths-list-file}, if necessary, and then evaluate the
14590following expressions. You may need to change the files' pathnames;
14591those here work when this Info file and the Emacs sources are located
14592in their customary places. To change the expressions, copy them to
14593the @file{*scratch*} buffer, edit them, and then evaluate them.
14594
14595The results are shown after the @samp{@result{}}. (These results are
14596for files from Emacs Version 21.0.100; files from other versions of
14597Emacs may produce different results.)
14598
14599@c !!! 21.0.100 lisp sources location here
14600@smallexample
14601@group
14602(cd "/usr/local/share/emacs/21.0.100/")
14603
14604(lengths-list-file "./lisp/macros.el")
14605 @result{} (273 263 456 90)
14606@end group
14607
14608@group
14609(lengths-list-file "./lisp/mail/mailalias.el")
14610 @result{} (38 32 26 77 174 180 321 198 324)
14611@end group
14612
14613@group
14614(lengths-list-file "./lisp/makesum.el")
14615 @result{} (85 181)
14616@end group
14617
14618@group
14619(recursive-lengths-list-many-files
14620 '("./lisp/macros.el"
14621 "./lisp/mail/mailalias.el"
14622 "./lisp/makesum.el"))
14623 @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14624@end group
14625@end smallexample
14626
14627The @code{recursive-lengths-list-many-files} function produces the
14628output we want.
14629
14630The next step is to prepare the data in the list for display in a graph.
14631
14632@node Prepare the data, , Several files recursively, Words in a defun
14633@section Prepare the Data for Display in a Graph
14634
14635The @code{recursive-lengths-list-many-files} function returns a list
14636of numbers. Each number records the length of a function definition.
14637What we need to do now is transform this data into a list of numbers
14638suitable for generating a graph. The new list will tell how many
14639functions definitions contain less than 10 words and
14640symbols, how many contain between 10 and 19 words and symbols, how
14641many contain between 20 and 29 words and symbols, and so on.
14642
14643In brief, we need to go through the lengths' list produced by the
14644@code{recursive-lengths-list-many-files} function and count the number
14645of defuns within each range of lengths, and produce a list of those
14646numbers.
14647
14648Based on what we have done before, we can readily foresee that it
14649should not be too hard to write a function that `@sc{cdr}s' down the
14650lengths' list, looks at each element, determines which length range it
14651is in, and increments a counter for that range.
14652
14653However, before beginning to write such a function, we should consider
14654the advantages of sorting the lengths' list first, so the numbers are
14655ordered from smallest to largest. First, sorting will make it easier
14656to count the numbers in each range, since two adjacent numbers will
14657either be in the same length range or in adjacent ranges. Second, by
14658inspecting a sorted list, we can discover the highest and lowest
14659number, and thereby determine the largest and smallest length range
14660that we will need.
14661
14662@menu
14663* Sorting:: Sorting lists.
14664* Files List:: Making a list of files.
14665* Counting function definitions::
14666@end menu
14667
14668@node Sorting, Files List, Prepare the data, Prepare the data
14669@subsection Sorting Lists
14670@findex sort
14671
14672Emacs contains a function to sort lists, called (as you might guess)
14673@code{sort}. The @code{sort} function takes two arguments, the list
14674to be sorted, and a predicate that determines whether the first of
14675two list elements is ``less'' than the second.
14676
14677As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14678Type Object as an Argument}), a predicate is a function that
14679determines whether some property is true or false. The @code{sort}
14680function will reorder a list according to whatever property the
14681predicate uses; this means that @code{sort} can be used to sort
14682non-numeric lists by non-numeric criteria---it can, for example,
14683alphabetize a list.
14684
14685@need 1250
14686The @code{<} function is used when sorting a numeric list. For example,
14687
14688@smallexample
14689(sort '(4 8 21 17 33 7 21 7) '<)
14690@end smallexample
14691
14692@need 800
14693@noindent
14694produces this:
14695
14696@smallexample
14697(4 7 7 8 17 21 21 33)
14698@end smallexample
14699
14700@noindent
14701(Note that in this example, both the arguments are quoted so that the
14702symbols are not evaluated before being passed to @code{sort} as
14703arguments.)
14704
14705Sorting the list returned by the
14706@code{recursive-lengths-list-many-files} function is straightforward;
14707it uses the @code{<} function:
14708
14709@smallexample
14710@group
14711(sort
14712 (recursive-lengths-list-many-files
14713 '("../lisp/macros.el"
14714 "../lisp/mailalias.el"
14715 "../lisp/makesum.el"))
c6f54b06 14716 '<)
8b096dce
EZ
14717@end group
14718@end smallexample
14719
14720@need 800
14721@noindent
14722which produces:
14723
14724@smallexample
14725(85 86 116 122 154 176 179 265)
14726@end smallexample
14727
14728@noindent
14729(Note that in this example, the first argument to @code{sort} is not
14730quoted, since the expression must be evaluated so as to produce the
14731list that is passed to @code{sort}.)
14732
14733@node Files List, Counting function definitions, Sorting, Prepare the data
14734@subsection Making a List of Files
14735
14736The @code{recursive-lengths-list-many-files} function requires a list
14737of files as its argument. For our test examples, we constructed such
14738a list by hand; but the Emacs Lisp source directory is too large for
14739us to do for that. Instead, we will write a function to do the job
14740for us. In this function, we will use both a @code{while} loop and a
14741recursive call.
14742
14743@findex directory-files
14744We did not have to write a function like this for older versions of
14745GNU Emacs, since they placed all the @samp{.el} files in one
14746directory. Instead, we were able to use the @code{directory-files}
14747function, which lists the names of files that match a specified
14748pattern within a single directory.
14749
14750However, recent versions of Emacs place Emacs Lisp files in
14751sub-directories of the top level @file{lisp} directory. This
14752re-arrangement eases navigation. For example, all the mail related
14753files are in a @file{lisp} sub-directory called @file{mail}. But at
14754the same time, this arrangement forces us to create a file listing
14755function that descends into the sub-directories.
14756
14757@findex files-in-below-directory
14758We can create this function, called @code{files-in-below-directory},
14759using familiar functions such as @code{car}, @code{nthcdr}, and
14760@code{substring} in conjunction with an existing function called
14761@code{directory-files-and-attributes}. This latter function not only
14762lists all the filenames in a directory, including the names
14763of sub-directories, but also their attributes.
14764
14765To restate our goal: to create a function that will enable us
14766to feed filenames to @code{recursive-lengths-list-many-files}
14767as a list that looks like this (but with more elements):
14768
14769@smallexample
14770@group
14771("../lisp/macros.el"
14772 "../lisp/mail/rmail.el"
14773 "../lisp/makesum.el")
14774@end group
14775@end smallexample
14776
14777The @code{directory-files-and-attributes} function returns a list of
14778lists. Each of the lists within the main list consists of 13
14779elements. The first element is a string that contains the name of the
14780file -- which, in GNU/Linux, may be a `directory file', that is to
14781say, a file with the special attributes of a directory. The second
14782element of the list is @code{t} for a directory, a string
14783for symbolic link (the string is the name linked to), or @code{nil}.
14784
14785For example, the first @samp{.el} file in the @file{lisp/} directory
14786is @file{abbrev.el}. Its name is
14787@file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14788directory or a symbolic link.
14789
14790@need 1000
14791This is how @code{directory-files-and-attributes} lists that file and
14792its attributes:
14793
14794@smallexample
14795@group
14796("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14797nil
147981
147991000
14800100
14801@end group
14802@group
14803(15019 32380)
14804(14883 48041)
14805(15214 49336)
1480611583
14807"-rw-rw-r--"
14808@end group
14809@group
14810t
14811341385
14812776)
14813@end group
14814@end smallexample
14815
14816@need 1200
14817On the other hand, @file{mail/} is a directory within the @file{lisp/}
14818directory. The beginning of its listing looks like this:
14819
14820@smallexample
14821@group
14822("/usr/local/share/emacs/21.0.100/lisp/mail"
14823t
14824@dots{}
14825)
14826@end group
14827@end smallexample
14828
14829(Look at the documentation of @code{file-attributes} to learn about
14830the different attributes. Bear in mind that the
14831@code{file-attributes} function does not list the filename, so its
14832first element is @code{directory-files-and-attributes}'s second
14833element.)
14834
14835We will want our new function, @code{files-in-below-directory}, to
14836list the @samp{.el} files in the directory it is told to check, and in
14837any directories below that directory.
14838
14839This gives us a hint on how to construct
14840@code{files-in-below-directory}: within a directory, the function
14841should add @samp{.el} filenames to a list; and if, within a directory,
14842the function comes upon a sub-directory, it should go into that
14843sub-directory and repeat its actions.
14844
14845However, we should note that every directory contains a name that
14846refers to itself, called @file{.}, (``dot'') and a name that refers to
14847its parent directory, called @file{..} (``double dot''). (In
14848@file{/}, the root directory, @file{..} refers to itself, since
14849@file{/} has no parent.) Clearly, we do not want our
14850@code{files-in-below-directory} function to enter those directories,
14851since they always lead us, directly or indirectly, to the current
14852directory.
14853
14854Consequently, our @code{files-in-below-directory} function must do
14855several tasks:
14856
14857@itemize @bullet
14858@item
14859Check to see whether it is looking at a filename that ends in
14860@samp{.el}; and if so, add its name to a list.
14861
14862@item
14863Check to see whether it is looking at a filename that is the name of a
14864directory; and if so,
14865
14866@itemize @minus
14867@item
14868Check to see whether it is looking at @file{.} or @file{..}; and if
14869so skip it.
14870
14871@item
14872Or else, go into that directory and repeat the process.
14873@end itemize
14874@end itemize
14875
14876Let's write a function definition to do these tasks. We will use a
14877@code{while} loop to move from one filename to another within a
14878directory, checking what needs to be done; and we will use a recursive
14879call to repeat the actions on each sub-directory. The recursive
14880pattern is `accumulate'
14881(@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14882using @code{append} as the combiner.
14883
14884@ignore
14885(directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14886(shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14887@end ignore
14888
14889@c /usr/local/share/emacs/21.0.100/lisp/
14890
14891@need 800
14892Here is the function:
14893
14894@smallexample
14895@group
14896(defun files-in-below-directory (directory)
14897 "List the .el files in DIRECTORY and in its sub-directories."
14898 ;; Although the function will be used non-interactively,
14899 ;; it will be easier to test if we make it interactive.
14900 ;; The directory will have a name such as
14901 ;; "/usr/local/share/emacs/21.0.100/lisp/"
14902 (interactive "DDirectory name: ")
14903@end group
14904@group
14905 (let (el-files-list
14906 (current-directory-list
14907 (directory-files-and-attributes directory t)))
14908 ;; while we are in the current directory
14909 (while current-directory-list
14910@end group
14911@group
14912 (cond
14913 ;; check to see whether filename ends in `.el'
14914 ;; and if so, append its name to a list.
14915 ((equal ".el" (substring (car (car current-directory-list)) -3))
14916 (setq el-files-list
14917 (cons (car (car current-directory-list)) el-files-list)))
14918@end group
14919@group
14920 ;; check whether filename is that of a directory
14921 ((eq t (car (cdr (car current-directory-list))))
14922 ;; decide whether to skip or recurse
14923 (if
14924 (equal (or "." "..")
14925 (substring (car (car current-directory-list)) -1))
14926 ;; then do nothing if filename is that of
14927 ;; current directory or parent
14928 ()
14929@end group
14930@group
14931 ;; else descend into the directory and repeat the process
14932 (setq el-files-list
14933 (append
14934 (files-in-below-directory
14935 (car (car current-directory-list)))
14936 el-files-list)))))
14937 ;; move to the next filename in the list; this also
14938 ;; shortens the list so the while loop eventually comes to an end
14939 (setq current-directory-list (cdr current-directory-list)))
14940 ;; return the filenames
14941 el-files-list))
14942@end group
14943@end smallexample
14944
14945@c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14946
14947The @code{files-in-below-directory} @code{directory-files} function
14948takes one argument, the name of a directory.
14949
14950@need 1250
14951Thus, on my system,
14952
14953@c !!! 21.0.100 lisp sources location here
14954@smallexample
14955@group
14956(length
14957 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14958@end group
14959@end smallexample
14960
14961@noindent
14962tells me that my version 21.0.100 Lisp sources directory contains 754
14963@samp{.el} files.
14964
14965@code{files-in-below-directory} returns a list in reverse alphabetical
14966order. An expression to sort the list in alphabetical order looks
14967like this:
14968
14969@smallexample
14970@group
14971(sort
14972 (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14973 'string-lessp)
14974@end group
14975@end smallexample
14976
14977@ignore
14978(defun test ()
14979 "Test how long it takes to find lengths of all elisp defuns."
14980 (insert "\n" (current-time-string) "\n")
14981 (sit-for 0)
14982 (sort
14983 (recursive-lengths-list-many-files
14984 '("../lisp/macros.el"
14985 "../lisp/mailalias.el"
14986 "../lisp/makesum.el"))
14987 '<)
14988 (insert (format "%s" (current-time-string))))
14989
14990@end ignore
14991
14992@node Counting function definitions, , Files List, Prepare the data
14993@subsection Counting function definitions
14994
14995Our immediate goal is to generate a list that tells us how many
14996function definitions contain fewer than 10 words and symbols, how many
14997contain between 10 and 19 words and symbols, how many contain between
1499820 and 29 words and symbols, and so on.
14999
15000With a sorted list of numbers, this is easy: count how many elements
15001of the list are smaller than 10, then, after moving past the numbers
15002just counted, count how many are smaller than 20, then, after moving
15003past the numbers just counted, count how many are smaller than 30, and
15004so on. Each of the numbers, 10, 20, 30, 40, and the like, is one
15005larger than the top of that range. We can call the list of such
15006numbers the @code{top-of-ranges} list.
15007
15008@need 1200
15009If we wished, we could generate this list automatically, but it is
15010simpler to write a list manually. Here it is:
15011@vindex top-of-ranges
15012
15013@smallexample
15014@group
15015(defvar top-of-ranges
15016 '(10 20 30 40 50
15017 60 70 80 90 100
15018 110 120 130 140 150
15019 160 170 180 190 200
15020 210 220 230 240 250
15021 260 270 280 290 300)
15022 "List specifying ranges for `defuns-per-range'.")
15023@end group
15024@end smallexample
15025
15026To change the ranges, we edit this list.
15027
15028Next, we need to write the function that creates the list of the
15029number of definitions within each range. Clearly, this function must
15030take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15031as arguments.
15032
15033The @code{defuns-per-range} function must do two things again and
15034again: it must count the number of definitions within a range
15035specified by the current top-of-range value; and it must shift to the
15036next higher value in the @code{top-of-ranges} list after counting the
15037number of definitions in the current range. Since each of these
15038actions is repetitive, we can use @code{while} loops for the job.
15039One loop counts the number of definitions in the range defined by the
15040current top-of-range value, and the other loop selects each of the
15041top-of-range values in turn.
15042
15043Several entries of the @code{sorted-lengths} list are counted for each
15044range; this means that the loop for the @code{sorted-lengths} list
15045will be inside the loop for the @code{top-of-ranges} list, like a
15046small gear inside a big gear.
15047
15048The inner loop counts the number of definitions within the range. It
15049is a simple counting loop of the type we have seen before.
15050(@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15051The true-or-false test of the loop tests whether the value from the
15052@code{sorted-lengths} list is smaller than the current value of the
15053top of the range. If it is, the function increments the counter and
15054tests the next value from the @code{sorted-lengths} list.
15055
15056@need 1250
15057The inner loop looks like this:
15058
15059@smallexample
15060@group
15061(while @var{length-element-smaller-than-top-of-range}
15062 (setq number-within-range (1+ number-within-range))
15063 (setq sorted-lengths (cdr sorted-lengths)))
15064@end group
15065@end smallexample
15066
15067The outer loop must start with the lowest value of the
15068@code{top-of-ranges} list, and then be set to each of the succeeding
15069higher values in turn. This can be done with a loop like this:
15070
15071@smallexample
15072@group
15073(while top-of-ranges
15074 @var{body-of-loop}@dots{}
15075 (setq top-of-ranges (cdr top-of-ranges)))
15076@end group
15077@end smallexample
15078
15079@need 1200
15080Put together, the two loops look like this:
15081
15082@smallexample
15083@group
15084(while top-of-ranges
15085
15086 ;; @r{Count the number of elements within the current range.}
15087 (while @var{length-element-smaller-than-top-of-range}
15088 (setq number-within-range (1+ number-within-range))
15089 (setq sorted-lengths (cdr sorted-lengths)))
15090
15091 ;; @r{Move to next range.}
15092 (setq top-of-ranges (cdr top-of-ranges)))
15093@end group
15094@end smallexample
15095
15096In addition, in each circuit of the outer loop, Emacs should record
15097the number of definitions within that range (the value of
15098@code{number-within-range}) in a list. We can use @code{cons} for
15099this purpose. (@xref{cons, , @code{cons}}.)
15100
15101The @code{cons} function works fine, except that the list it
15102constructs will contain the number of definitions for the highest
15103range at its beginning and the number of definitions for the lowest
15104range at its end. This is because @code{cons} attaches new elements
15105of the list to the beginning of the list, and since the two loops are
15106working their way through the lengths' list from the lower end first,
15107the @code{defuns-per-range-list} will end up largest number first.
15108But we will want to print our graph with smallest values first and the
15109larger later. The solution is to reverse the order of the
15110@code{defuns-per-range-list}. We can do this using the
15111@code{nreverse} function, which reverses the order of a list.
15112@findex nreverse
15113
15114@need 800
15115For example,
15116
15117@smallexample
15118(nreverse '(1 2 3 4))
15119@end smallexample
15120
15121@need 800
15122@noindent
15123produces:
15124
15125@smallexample
15126(4 3 2 1)
15127@end smallexample
15128
15129Note that the @code{nreverse} function is ``destructive''---that is,
15130it changes the list to which it is applied; this contrasts with the
15131@code{car} and @code{cdr} functions, which are non-destructive. In
15132this case, we do not want the original @code{defuns-per-range-list},
15133so it does not matter that it is destroyed. (The @code{reverse}
15134function provides a reversed copy of a list, leaving the original list
15135as is.)
15136@findex reverse
15137
15138@need 1250
15139Put all together, the @code{defuns-per-range} looks like this:
15140
15141@smallexample
15142@group
15143(defun defuns-per-range (sorted-lengths top-of-ranges)
15144 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15145 (let ((top-of-range (car top-of-ranges))
15146 (number-within-range 0)
15147 defuns-per-range-list)
15148@end group
15149
15150@group
15151 ;; @r{Outer loop.}
15152 (while top-of-ranges
15153@end group
15154
15155@group
15156 ;; @r{Inner loop.}
15157 (while (and
15158 ;; @r{Need number for numeric test.}
15159 (car sorted-lengths)
15160 (< (car sorted-lengths) top-of-range))
15161@end group
15162
15163@group
15164 ;; @r{Count number of definitions within current range.}
15165 (setq number-within-range (1+ number-within-range))
15166 (setq sorted-lengths (cdr sorted-lengths)))
15167
15168 ;; @r{Exit inner loop but remain within outer loop.}
15169@end group
15170
15171@group
15172 (setq defuns-per-range-list
15173 (cons number-within-range defuns-per-range-list))
15174 (setq number-within-range 0) ; @r{Reset count to zero.}
15175@end group
15176
15177@group
15178 ;; @r{Move to next range.}
15179 (setq top-of-ranges (cdr top-of-ranges))
15180 ;; @r{Specify next top of range value.}
15181 (setq top-of-range (car top-of-ranges)))
15182@end group
15183
15184@group
15185 ;; @r{Exit outer loop and count the number of defuns larger than}
15186 ;; @r{ the largest top-of-range value.}
15187 (setq defuns-per-range-list
15188 (cons
15189 (length sorted-lengths)
15190 defuns-per-range-list))
15191@end group
15192
15193@group
15194 ;; @r{Return a list of the number of definitions within each range,}
15195 ;; @r{ smallest to largest.}
15196 (nreverse defuns-per-range-list)))
15197@end group
15198@end smallexample
15199
15200@need 1200
15201@noindent
15202The function is straightforward except for one subtle feature. The
15203true-or-false test of the inner loop looks like this:
15204
15205@smallexample
15206@group
15207(and (car sorted-lengths)
15208 (< (car sorted-lengths) top-of-range))
15209@end group
15210@end smallexample
15211
15212@need 800
15213@noindent
15214instead of like this:
15215
15216@smallexample
15217(< (car sorted-lengths) top-of-range)
15218@end smallexample
15219
15220The purpose of the test is to determine whether the first item in the
15221@code{sorted-lengths} list is less than the value of the top of the
15222range.
15223
15224The simple version of the test works fine unless the
15225@code{sorted-lengths} list has a @code{nil} value. In that case, the
15226@code{(car sorted-lengths)} expression function returns
15227@code{nil}. The @code{<} function cannot compare a number to
15228@code{nil}, which is an empty list, so Emacs signals an error and
15229stops the function from attempting to continue to execute.
15230
15231The @code{sorted-lengths} list always becomes @code{nil} when the
15232counter reaches the end of the list. This means that any attempt to
15233use the @code{defuns-per-range} function with the simple version of
15234the test will fail.
15235
15236We solve the problem by using the @code{(car sorted-lengths)}
15237expression in conjunction with the @code{and} expression. The
15238@code{(car sorted-lengths)} expression returns a non-@code{nil}
15239value so long as the list has at least one number within it, but
15240returns @code{nil} if the list is empty. The @code{and} expression
15241first evaluates the @code{(car sorted-lengths)} expression, and
15242if it is @code{nil}, returns false @emph{without} evaluating the
15243@code{<} expression. But if the @code{(car sorted-lengths)}
15244expression returns a non-@code{nil} value, the @code{and} expression
15245evaluates the @code{<} expression, and returns that value as the value
15246of the @code{and} expression.
15247
15248@c colon in printed section title causes problem in Info cross reference
15249This way, we avoid an error.
15250@iftex
15251@xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15252Functions}, for more information about @code{and}.
15253@end iftex
15254@ifinfo
15255@xref{forward-paragraph}, for more information about @code{and}.
15256@end ifinfo
15257
15258Here is a short test of the @code{defuns-per-range} function. First,
15259evaluate the expression that binds (a shortened)
15260@code{top-of-ranges} list to the list of values, then evaluate the
15261expression for binding the @code{sorted-lengths} list, and then
15262evaluate the @code{defuns-per-range} function.
15263
15264@smallexample
15265@group
15266;; @r{(Shorter list than we will use later.)}
15267(setq top-of-ranges
15268 '(110 120 130 140 150
15269 160 170 180 190 200))
15270
15271(setq sorted-lengths
15272 '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15273
15274(defuns-per-range sorted-lengths top-of-ranges)
15275@end group
15276@end smallexample
15277
15278@need 800
15279@noindent
15280The list returned looks like this:
15281
15282@smallexample
15283(2 2 2 0 0 1 0 2 0 0 4)
15284@end smallexample
15285
15286@noindent
15287Indeed, there are two elements of the @code{sorted-lengths} list
15288smaller than 110, two elements between 110 and 119, two elements
15289between 120 and 129, and so on. There are four elements with a value
15290of 200 or larger.
15291
15292@c The next step is to turn this numbers' list into a graph.
15293
15294@node Readying a Graph, Emacs Initialization, Words in a defun, Top
15295@chapter Readying a Graph
15296@cindex Readying a graph
15297@cindex Graph prototype
15298@cindex Prototype graph
15299@cindex Body of graph
15300
15301Our goal is to construct a graph showing the numbers of function
15302definitions of various lengths in the Emacs lisp sources.
15303
15304As a practical matter, if you were creating a graph, you would
15305probably use a program such as @code{gnuplot} to do the job.
15306(@code{gnuplot} is nicely integrated into GNU Emacs.) In this case,
15307however, we create one from scratch, and in the process we will
15308re-acquaint ourselves with some of what we learned before and learn
15309more.
15310
15311In this chapter, we will first write a simple graph printing function.
15312This first definition will be a @dfn{prototype}, a rapidly written
15313function that enables us to reconnoiter this unknown graph-making
15314territory. We will discover dragons, or find that they are myth.
15315After scouting the terrain, we will feel more confident and enhance
15316the function to label the axes automatically.
15317
15318@menu
15319* Columns of a graph::
15320* graph-body-print:: How to print the body of a graph.
15321* recursive-graph-body-print::
15322* Printed Axes::
15323* Line Graph Exercise::
15324@end menu
15325
15326@node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15327@ifnottex
15328@unnumberedsec Printing the Columns of a Graph
15329@end ifnottex
15330
15331Since Emacs is designed to be flexible and work with all kinds of
15332terminals, including character-only terminals, the graph will need to
15333be made from one of the `typewriter' symbols. An asterisk will do; as
15334we enhance the graph-printing function, we can make the choice of
15335symbol a user option.
15336
15337We can call this function @code{graph-body-print}; it will take a
15338@code{numbers-list} as its only argument. At this stage, we will not
15339label the graph, but only print its body.
15340
15341The @code{graph-body-print} function inserts a vertical column of
15342asterisks for each element in the @code{numbers-list}. The height of
15343each line is determined by the value of that element of the
15344@code{numbers-list}.
15345
15346Inserting columns is a repetitive act; that means that this function can
15347be written either with a @code{while} loop or recursively.
15348
15349Our first challenge is to discover how to print a column of asterisks.
15350Usually, in Emacs, we print characters onto a screen horizontally,
15351line by line, by typing. We have two routes we can follow: write our
15352own column-insertion function or discover whether one exists in Emacs.
15353
15354To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15355command. This command is like the @kbd{C-h a} (command-apropos)
15356command, except that the latter finds only those functions that are
15357commands. The @kbd{M-x apropos} command lists all symbols that match
15358a regular expression, including functions that are not interactive.
15359@findex apropos
15360
15361What we want to look for is some command that prints or inserts
15362columns. Very likely, the name of the function will contain either
15363the word `print' or the word `insert' or the word `column'.
15364Therefore, we can simply type @kbd{M-x apropos RET
15365print\|insert\|column RET} and look at the result. On my system, this
15366command takes quite some time, and then produces a list of 79
15367functions and variables. Scanning down the list, the only function
15368that looks as if it might do the job is @code{insert-rectangle}.
15369
15370@need 1200
15371Indeed, this is the function we want; its documentation says:
15372
15373@smallexample
15374@group
15375insert-rectangle:
15376Insert text of RECTANGLE with upper left corner at point.
15377RECTANGLE's first line is inserted at point,
15378its second line is inserted at a point vertically under point, etc.
15379RECTANGLE should be a list of strings.
15380@end group
15381@end smallexample
15382
15383We can run a quick test, to make sure it does what we expect of it.
15384
15385Here is the result of placing the cursor after the
15386@code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15387(@code{eval-last-sexp}). The function inserts the strings
15388@samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15389point. Also the function returns @code{nil}.
15390
15391@smallexample
15392@group
15393(insert-rectangle '("first" "second" "third"))first
15394 second
15395 third
15396nil
15397@end group
15398@end smallexample
15399
15400@noindent
15401Of course, we won't be inserting the text of the
15402@code{insert-rectangle} expression itself into the buffer in which we
15403are making the graph, but will call the function from our program. We
15404shall, however, have to make sure that point is in the buffer at the
15405place where the @code{insert-rectangle} function will insert its
15406column of strings.
15407
15408If you are reading this in Info, you can see how this works by
15409switching to another buffer, such as the @file{*scratch*} buffer,
15410placing point somewhere in the buffer, typing @kbd{M-:},
15411typing the @code{insert-rectangle} expression into the minibuffer at
15412the prompt, and then typing @key{RET}. This causes Emacs to evaluate
15413the expression in the minibuffer, but to use as the value of point the
15414position of point in the @file{*scratch*} buffer. (@kbd{M-:}
15415is the keybinding for @code{eval-expression}.)
15416
15417We find when we do this that point ends up at the end of the last
15418inserted line---that is to say, this function moves point as a
15419side-effect. If we were to repeat the command, with point at this
15420position, the next insertion would be below and to the right of the
15421previous insertion. We don't want this! If we are going to make a
15422bar graph, the columns need to be beside each other.
15423
15424So we discover that each cycle of the column-inserting @code{while}
15425loop must reposition point to the place we want it, and that place
15426will be at the top, not the bottom, of the column. Moreover, we
15427remember that when we print a graph, we do not expect all the columns
15428to be the same height. This means that the top of each column may be
15429at a different height from the previous one. We cannot simply
15430reposition point to the same line each time, but moved over to the
15431right---or perhaps we can@dots{}
15432
15433We are planning to make the columns of the bar graph out of asterisks.
15434The number of asterisks in the column is the number specified by the
15435current element of the @code{numbers-list}. We need to construct a
15436list of asterisks of the right length for each call to
15437@code{insert-rectangle}. If this list consists solely of the requisite
15438number of asterisks, then we will have position point the right number
15439of lines above the base for the graph to print correctly. This could
15440be difficult.
15441
15442Alternatively, if we can figure out some way to pass
15443@code{insert-rectangle} a list of the same length each time, then we
15444can place point on the same line each time, but move it over one
15445column to the right for each new column. If we do this, however, some
15446of the entries in the list passed to @code{insert-rectangle} must be
15447blanks rather than asterisks. For example, if the maximum height of
15448the graph is 5, but the height of the column is 3, then
15449@code{insert-rectangle} requires an argument that looks like this:
15450
15451@smallexample
15452(" " " " "*" "*" "*")
15453@end smallexample
15454
15455This last proposal is not so difficult, so long as we can determine
15456the column height. There are two ways for us to specify the column
15457height: we can arbitrarily state what it will be, which would work
15458fine for graphs of that height; or we can search through the list of
15459numbers and use the maximum height of the list as the maximum height
15460of the graph. If the latter operation were difficult, then the former
15461procedure would be easiest, but there is a function built into Emacs
15462that determines the maximum of its arguments. We can use that
15463function. The function is called @code{max} and it returns the
15464largest of all its arguments, which must be numbers. Thus, for
15465example,
15466
15467@smallexample
15468(max 3 4 6 5 7 3)
15469@end smallexample
15470
15471@noindent
15472returns 7. (A corresponding function called @code{min} returns the
15473smallest of all its arguments.)
15474@findex max
15475@findex min
15476
15477However, we cannot simply call @code{max} on the @code{numbers-list};
15478the @code{max} function expects numbers as its argument, not a list of
15479numbers. Thus, the following expression,
15480
15481@smallexample
15482(max '(3 4 6 5 7 3))
15483@end smallexample
15484
15485@need 800
15486@noindent
15487produces the following error message;
15488
15489@smallexample
15490Wrong type of argument: number-or-marker-p, (3 4 6 5 7 3)
15491@end smallexample
15492
15493@findex apply
15494We need a function that passes a list of arguments to a function.
15495This function is @code{apply}. This function `applies' its first
15496argument (a function) to its remaining arguments, the last of which
15497may be a list.
15498
15499@need 1250
15500For example,
15501
15502@smallexample
15503(apply 'max 3 4 7 3 '(4 8 5))
15504@end smallexample
15505
15506@noindent
15507returns 8.
15508
15509(Incidentally, I don't know how you would learn of this function
15510without a book such as this. It is possible to discover other
15511functions, like @code{search-forward} or @code{insert-rectangle}, by
15512guessing at a part of their names and then using @code{apropos}. Even
15513though its base in metaphor is clear---`apply' its first argument to
15514the rest---I doubt a novice would come up with that particular word
15515when using @code{apropos} or other aid. Of course, I could be wrong;
15516after all, the function was first named by someone who had to invent
15517it.)
15518
15519The second and subsequent arguments to @code{apply} are optional, so
15520we can use @code{apply} to call a function and pass the elements of a
15521list to it, like this, which also returns 8:
15522
15523@smallexample
15524(apply 'max '(4 8 5))
15525@end smallexample
15526
15527This latter way is how we will use @code{apply}. The
15528@code{recursive-lengths-list-many-files} function returns a numbers'
15529list to which we can apply @code{max} (we could also apply @code{max} to
15530the sorted numbers' list; it does not matter whether the list is
15531sorted or not.)
15532
15533@need 800
15534Hence, the operation for finding the maximum height of the graph is this:
15535
15536@smallexample
15537(setq max-graph-height (apply 'max numbers-list))
15538@end smallexample
15539
15540Now we can return to the question of how to create a list of strings
15541for a column of the graph. Told the maximum height of the graph
15542and the number of asterisks that should appear in the column, the
15543function should return a list of strings for the
15544@code{insert-rectangle} command to insert.
15545
15546Each column is made up of asterisks or blanks. Since the function is
15547passed the value of the height of the column and the number of
15548asterisks in the column, the number of blanks can be found by
15549subtracting the number of asterisks from the height of the column.
15550Given the number of blanks and the number of asterisks, two
15551@code{while} loops can be used to construct the list:
15552
15553@smallexample
15554@group
15555;;; @r{First version.}
15556(defun column-of-graph (max-graph-height actual-height)
15557 "Return list of strings that is one column of a graph."
15558 (let ((insert-list nil)
15559 (number-of-top-blanks
15560 (- max-graph-height actual-height)))
15561@end group
15562
15563@group
15564 ;; @r{Fill in asterisks.}
15565 (while (> actual-height 0)
15566 (setq insert-list (cons "*" insert-list))
15567 (setq actual-height (1- actual-height)))
15568@end group
15569
15570@group
15571 ;; @r{Fill in blanks.}
15572 (while (> number-of-top-blanks 0)
15573 (setq insert-list (cons " " insert-list))
15574 (setq number-of-top-blanks
15575 (1- number-of-top-blanks)))
15576@end group
15577
15578@group
15579 ;; @r{Return whole list.}
15580 insert-list))
15581@end group
15582@end smallexample
15583
15584If you install this function and then evaluate the following
15585expression you will see that it returns the list as desired:
15586
15587@smallexample
15588(column-of-graph 5 3)
15589@end smallexample
15590
15591@need 800
15592@noindent
15593returns
15594
15595@smallexample
15596(" " " " "*" "*" "*")
15597@end smallexample
15598
15599As written, @code{column-of-graph} contains a major flaw: the symbols
15600used for the blank and for the marked entries in the column are
15601`hard-coded' as a space and asterisk. This is fine for a prototype,
15602but you, or another user, may wish to use other symbols. For example,
15603in testing the graph function, you many want to use a period in place
15604of the space, to make sure the point is being repositioned properly
15605each time the @code{insert-rectangle} function is called; or you might
15606want to substitute a @samp{+} sign or other symbol for the asterisk.
15607You might even want to make a graph-column that is more than one
15608display column wide. The program should be more flexible. The way to
15609do that is to replace the blank and the asterisk with two variables
15610that we can call @code{graph-blank} and @code{graph-symbol} and define
15611those variables separately.
15612
15613Also, the documentation is not well written. These considerations
15614lead us to the second version of the function:
15615
15616@smallexample
15617@group
15618(defvar graph-symbol "*"
15619 "String used as symbol in graph, usually an asterisk.")
15620@end group
15621
15622@group
15623(defvar graph-blank " "
15624 "String used as blank in graph, usually a blank space.
15625graph-blank must be the same number of columns wide
15626as graph-symbol.")
15627@end group
15628@end smallexample
15629
15630@noindent
15631(For an explanation of @code{defvar}, see
15632@ref{defvar, , Initializing a Variable with @code{defvar}}.)
15633
15634@smallexample
15635@group
15636;;; @r{Second version.}
15637(defun column-of-graph (max-graph-height actual-height)
15638 "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15639
15640@end group
15641@group
15642The graph-symbols are contiguous entries at the end
15643of the list.
15644The list will be inserted as one column of a graph.
15645The strings are either graph-blank or graph-symbol."
15646@end group
15647
15648@group
15649 (let ((insert-list nil)
15650 (number-of-top-blanks
15651 (- max-graph-height actual-height)))
15652@end group
15653
15654@group
15655 ;; @r{Fill in @code{graph-symbols}.}
15656 (while (> actual-height 0)
15657 (setq insert-list (cons graph-symbol insert-list))
15658 (setq actual-height (1- actual-height)))
15659@end group
15660
15661@group
15662 ;; @r{Fill in @code{graph-blanks}.}
15663 (while (> number-of-top-blanks 0)
15664 (setq insert-list (cons graph-blank insert-list))
15665 (setq number-of-top-blanks
15666 (1- number-of-top-blanks)))
15667
15668 ;; @r{Return whole list.}
15669 insert-list))
15670@end group
15671@end smallexample
15672
15673If we wished, we could rewrite @code{column-of-graph} a third time to
15674provide optionally for a line graph as well as for a bar graph. This
15675would not be hard to do. One way to think of a line graph is that it
15676is no more than a bar graph in which the part of each bar that is
15677below the top is blank. To construct a column for a line graph, the
15678function first constructs a list of blanks that is one shorter than
15679the value, then it uses @code{cons} to attach a graph symbol to the
15680list; then it uses @code{cons} again to attach the `top blanks' to
15681the list.
15682
15683It is easy to see how to write such a function, but since we don't
15684need it, we will not do it. But the job could be done, and if it were
15685done, it would be done with @code{column-of-graph}. Even more
15686important, it is worth noting that few changes would have to be made
15687anywhere else. The enhancement, if we ever wish to make it, is
15688simple.
15689
15690Now, finally, we come to our first actual graph printing function.
15691This prints the body of a graph, not the labels for the vertical and
15692horizontal axes, so we can call this @code{graph-body-print}.
15693
15694@node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15695@section The @code{graph-body-print} Function
15696@findex graph-body-print
15697
15698After our preparation in the preceding section, the
15699@code{graph-body-print} function is straightforward. The function
15700will print column after column of asterisks and blanks, using the
15701elements of a numbers' list to specify the number of asterisks in each
15702column. This is a repetitive act, which means we can use a
15703decrementing @code{while} loop or recursive function for the job. In
15704this section, we will write the definition using a @code{while} loop.
15705
15706The @code{column-of-graph} function requires the height of the graph
15707as an argument, so we should determine and record that as a local variable.
15708
15709This leads us to the following template for the @code{while} loop
15710version of this function:
15711
15712@smallexample
15713@group
15714(defun graph-body-print (numbers-list)
15715 "@var{documentation}@dots{}"
15716 (let ((height @dots{}
15717 @dots{}))
15718@end group
15719
15720@group
15721 (while numbers-list
15722 @var{insert-columns-and-reposition-point}
15723 (setq numbers-list (cdr numbers-list)))))
15724@end group
15725@end smallexample
15726
15727@noindent
15728We need to fill in the slots of the template.
15729
15730Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15731determine the height of the graph.
15732
15733The @code{while} loop will cycle through the @code{numbers-list} one
15734element at a time. As it is shortened by the @code{(setq numbers-list
15735(cdr numbers-list))} expression, the @sc{car} of each instance of the
15736list is the value of the argument for @code{column-of-graph}.
15737
15738At each cycle of the @code{while} loop, the @code{insert-rectangle}
15739function inserts the list returned by @code{column-of-graph}. Since
15740the @code{insert-rectangle} function moves point to the lower right of
15741the inserted rectangle, we need to save the location of point at the
15742time the rectangle is inserted, move back to that position after the
15743rectangle is inserted, and then move horizontally to the next place
15744from which @code{insert-rectangle} is called.
15745
15746If the inserted columns are one character wide, as they will be if
15747single blanks and asterisks are used, the repositioning command is
15748simply @code{(forward-char 1)}; however, the width of a column may be
15749greater than one. This means that the repositioning command should be
15750written @code{(forward-char symbol-width)}. The @code{symbol-width}
15751itself is the length of a @code{graph-blank} and can be found using
15752the expression @code{(length graph-blank)}. The best place to bind
15753the @code{symbol-width} variable to the value of the width of graph
15754column is in the varlist of the @code{let} expression.
15755
15756@need 1250
15757These considerations lead to the following function definition:
15758
15759@smallexample
15760@group
15761(defun graph-body-print (numbers-list)
15762 "Print a bar graph of the NUMBERS-LIST.
15763The numbers-list consists of the Y-axis values."
15764
15765 (let ((height (apply 'max numbers-list))
15766 (symbol-width (length graph-blank))
15767 from-position)
15768@end group
15769
15770@group
15771 (while numbers-list
15772 (setq from-position (point))
15773 (insert-rectangle
15774 (column-of-graph height (car numbers-list)))
15775 (goto-char from-position)
15776 (forward-char symbol-width)
15777@end group
15778@group
15779 ;; @r{Draw graph column by column.}
15780 (sit-for 0)
15781 (setq numbers-list (cdr numbers-list)))
15782@end group
15783@group
15784 ;; @r{Place point for X axis labels.}
15785 (forward-line height)
15786 (insert "\n")
15787))
15788@end group
15789@end smallexample
15790
15791@noindent
15792The one unexpected expression in this function is the
15793@w{@code{(sit-for 0)}} expression in the @code{while} loop. This
15794expression makes the graph printing operation more interesting to
15795watch than it would be otherwise. The expression causes Emacs to
15796`sit' or do nothing for a zero length of time and then redraw the
15797screen. Placed here, it causes Emacs to redraw the screen column by
15798column. Without it, Emacs would not redraw the screen until the
15799function exits.
15800
15801We can test @code{graph-body-print} with a short list of numbers.
15802
15803@enumerate
15804@item
15805Install @code{graph-symbol}, @code{graph-blank},
15806@code{column-of-graph}, which are in
475dc40a
EZ
15807@iftex
15808@ref{Readying a Graph, , Readying a Graph},
15809@end iftex
15810@ifinfo
15811@ref{Columns of a graph},
15812@end ifinfo
8b096dce
EZ
15813and @code{graph-body-print}.
15814
15815@need 800
15816@item
15817Copy the following expression:
15818
15819@smallexample
15820(graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15821@end smallexample
15822
15823@item
15824Switch to the @file{*scratch*} buffer and place the cursor where you
15825want the graph to start.
15826
15827@item
15828Type @kbd{M-:} (@code{eval-expression}).
15829
15830@item
15831Yank the @code{graph-body-print} expression into the minibuffer
15832with @kbd{C-y} (@code{yank)}.
15833
15834@item
15835Press @key{RET} to evaluate the @code{graph-body-print} expression.
15836@end enumerate
15837
15838@need 800
15839Emacs will print a graph like this:
15840
15841@smallexample
15842@group
15843 *
15844 * **
15845 * ****
15846 *** ****
15847 ********* *
15848 ************
15849 *************
15850@end group
15851@end smallexample
15852
15853@node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15854@section The @code{recursive-graph-body-print} Function
15855@findex recursive-graph-body-print
15856
15857The @code{graph-body-print} function may also be written recursively.
15858The recursive solution is divided into two parts: an outside `wrapper'
15859that uses a @code{let} expression to determine the values of several
15860variables that need only be found once, such as the maximum height of
15861the graph, and an inside function that is called recursively to print
15862the graph.
15863
15864@need 1250
15865The `wrapper' is uncomplicated:
15866
15867@smallexample
15868@group
15869(defun recursive-graph-body-print (numbers-list)
15870 "Print a bar graph of the NUMBERS-LIST.
15871The numbers-list consists of the Y-axis values."
15872 (let ((height (apply 'max numbers-list))
15873 (symbol-width (length graph-blank))
15874 from-position)
15875 (recursive-graph-body-print-internal
15876 numbers-list
15877 height
15878 symbol-width)))
15879@end group
15880@end smallexample
15881
15882The recursive function is a little more difficult. It has four parts:
15883the `do-again-test', the printing code, the recursive call, and the
15884`next-step-expression'. The `do-again-test' is an @code{if}
15885expression that determines whether the @code{numbers-list} contains
15886any remaining elements; if it does, the function prints one column of
15887the graph using the printing code and calls itself again. The
15888function calls itself again according to the value produced by the
15889`next-step-expression' which causes the call to act on a shorter
15890version of the @code{numbers-list}.
15891
15892@smallexample
15893@group
15894(defun recursive-graph-body-print-internal
15895 (numbers-list height symbol-width)
15896 "Print a bar graph.
15897Used within recursive-graph-body-print function."
15898@end group
15899
15900@group
15901 (if numbers-list
15902 (progn
15903 (setq from-position (point))
15904 (insert-rectangle
15905 (column-of-graph height (car numbers-list)))
15906@end group
15907@group
15908 (goto-char from-position)
15909 (forward-char symbol-width)
15910 (sit-for 0) ; @r{Draw graph column by column.}
15911 (recursive-graph-body-print-internal
15912 (cdr numbers-list) height symbol-width))))
15913@end group
15914@end smallexample
15915
15916@need 1250
15917After installation, this expression can be tested; here is a sample:
15918
15919@smallexample
15920(recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15921@end smallexample
15922
15923@need 800
15924Here is what @code{recursive-graph-body-print} produces:
15925
15926@smallexample
15927@group
15928 *
15929 ** *
15930 **** *
15931 **** ***
15932 * *********
15933 ************
15934 *************
15935@end group
15936@end smallexample
15937
15938Either of these two functions, @code{graph-body-print} or
15939@code{recursive-graph-body-print}, create the body of a graph.
15940
15941@node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15942@section Need for Printed Axes
15943
15944A graph needs printed axes, so you can orient yourself. For a do-once
15945project, it may be reasonable to draw the axes by hand using Emacs'
15946Picture mode; but a graph drawing function may be used more than once.
15947
15948For this reason, I have written enhancements to the basic
15949@code{print-graph-body} function that automatically print labels for
15950the horizontal and vertical axes. Since the label printing functions
15951do not contain much new material, I have placed their description in
15952an appendix. @xref{Full Graph, , A Graph with Labelled Axes}.
15953
15954@node Line Graph Exercise, , Printed Axes, Readying a Graph
15955@section Exercise
15956
15957Write a line graph version of the graph printing functions.
15958
15959@node Emacs Initialization, Debugging, Readying a Graph, Top
15960@chapter Your @file{.emacs} File
15961@cindex @file{.emacs} file
15962@cindex Customizing your @file{.emacs} file
15963@cindex Initialization file
15964
15965``You don't have to like Emacs to like it'' -- this seemingly
15966paradoxical statement is the secret of GNU Emacs. The plain, `out of
15967the box' Emacs is a generic tool. Most people who use it, customize
15968it to suit themselves.
15969
15970GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15971expressions in Emacs Lisp you can change or extend Emacs.
15972
15973@menu
15974* Default Configuration::
15975* Site-wide Init:: You can write site-wide init files.
15976* defcustom:: Emacs will write code for you.
15977* Beginning a .emacs File:: How to write a @code{.emacs file}.
15978* Text and Auto-fill:: Automatically wrap lines.
15979* Mail Aliases:: Use abbreviations for email addresses.
15980* Indent Tabs Mode:: Don't use tabs with @TeX{}
15981* Keybindings:: Create some personal keybindings.
15982* Keymaps:: More about key binding.
15983* Loading Files:: Load (i.e., evaluate) files automatically.
15984* Autoload:: Make functions available.
15985* Simple Extension:: Define a function; bind it to a key.
15986* X11 Colors:: Colors in version 19 in X.
15987* Miscellaneous::
15988* Mode Line:: How to customize your mode line.
15989@end menu
15990
15991@node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15992@ifnottex
15993@unnumberedsec Emacs' Default Configuration
15994@end ifnottex
15995
15996There are those who appreciate Emacs' default configuration. After
15997all, Emacs starts you in C mode when you edit a C file, starts you in
15998Fortran mode when you edit a Fortran file, and starts you in
15999Fundamental mode when you edit an unadorned file. This all makes
16000sense, if you do not know who is going to use Emacs. Who knows what a
16001person hopes to do with an unadorned file? Fundamental mode is the
16002right default for such a file, just as C mode is the right default for
16003editing C code. But when you do know who is going to use Emacs---you,
16004yourself---then it makes sense to customize Emacs.
16005
16006For example, I seldom want Fundamental mode when I edit an
16007otherwise undistinguished file; I want Text mode. This is why I
16008customize Emacs: so it suits me.
16009
16010You can customize and extend Emacs by writing or adapting a
16011@file{~/.emacs} file. This is your personal initialization file; its
16012contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16013may also add @file{.el} to @file{~/.emacs} and call it a
16014@file{~/.emacs.el} file. In the past, you were forbidden to type the
16015extra keystrokes that the name @file{~/.emacs.el} requires, but now
16016you may. The new format is consistent with the Emacs Lisp file
16017naming conventions; the old format saves typing.}
16018
16019A @file{~/.emacs} file contains Emacs Lisp code. You can write this
16020code yourself; or you can use Emacs' @code{customize} feature to write
16021the code for you. You can combine your own expressions and
16022auto-written Customize expressions in your @file{.emacs} file.
16023
16024(I myself prefer to write my own expressions, except for those,
16025particularly fonts, that I find easier to manipulate using the
16026@code{customize} command. I combine the two methods.)
16027
16028Most of this chapter is about writing expressions yourself. It
16029describes a simple @file{.emacs} file; for more information, see
16030@ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16031@ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16032Manual}.
16033
16034@node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16035@section Site-wide Initialization Files
16036
16037@cindex @file{default.el} init file
16038@cindex @file{site-init.el} init file
16039@cindex @file{site-load.el} init file
16040In addition to your personal initialization file, Emacs automatically
16041loads various site-wide initialization files, if they exist. These
16042have the same form as your @file{.emacs} file, but are loaded by
16043everyone.
16044
16045Two site-wide initialization files, @file{site-load.el} and
16046@file{site-init.el}, are loaded into Emacs and then `dumped' if a
16047`dumped' version of Emacs is created, as is most common. (Dumped
16048copies of Emacs load more quickly. However, once a file is loaded and
16049dumped, a change to it does not lead to a change in Emacs unless you
16050load it yourself or re-dump Emacs. @xref{Building Emacs, , Building
16051Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16052@file{INSTALL} file.)
16053
16054Three other site-wide initialization files are loaded automatically
16055each time you start Emacs, if they exist. These are
16056@file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16057file, and @file{default.el}, and the terminal type file, which are both
16058loaded @emph{after} your @file{.emacs} file.
16059
16060Settings and definitions in your @file{.emacs} file will overwrite
16061conflicting settings and definitions in a @file{site-start.el} file,
16062if it exists; but the settings and definitions in a @file{default.el}
16063or terminal type file will overwrite those in your @file{.emacs} file.
16064(You can prevent interference from a terminal type file by setting
16065@code{term-file-prefix} to @code{nil}. @xref{Simple Extension, , A
16066Simple Extension}.)
16067
16068@c Rewritten to avoid overfull hbox.
16069The @file{INSTALL} file that comes in the distribution contains
16070descriptions of the @file{site-init.el} and @file{site-load.el} files.
16071
16072The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16073control loading. These files are in the @file{lisp} directory of the
16074Emacs distribution and are worth perusing.
16075
16076The @file{loaddefs.el} file contains a good many suggestions as to
16077what to put into your own @file{.emacs} file, or into a site-wide
16078initialization file.
16079
16080@node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16081@section Specifying Variables using @code{defcustom}
16082@findex defcustom
16083
16084You can specify variables using @code{defcustom} so that you and
e601d8fd 16085others can then use Emacs' @code{customize} feature to set their
8b096dce
EZ
16086values. (You cannot use @code{customize} to write function
16087definitions; but you can write @code{defuns} in your @file{.emacs}
16088file. Indeed, you can write any Lisp expression in your @file{.emacs}
16089file.)
16090
16091The @code{customize} feature depends on the @code{defcustom} special
16092form. Although you can use @code{defvar} or @code{setq} for variables
16093that users set, the @code{defcustom} special form is designed for the
16094job.
16095
16096You can use your knowledge of @code{defvar} for writing the
16097first three arguments for @code{defcustom}. The first argument to
16098@code{defcustom} is the name of the variable. The second argument is
16099the variable's initial value, if any; and this value is set only if
16100the value has not already been set. The third argument is the
16101documentation.
16102
16103The fourth and subsequent arguments to @code{defcustom} specify types
16104and options; these are not featured in @code{defvar}. (These
16105arguments are optional.)
16106
16107Each of these arguments consists of a keyword followed by a value.
c6f54b06 16108Each keyword starts with the colon character @samp{:}.
8b096dce
EZ
16109
16110@need 1250
16111For example, the customizable user option variable
16112@code{text-mode-hook} looks like this:
16113
16114@smallexample
16115@group
16116(defcustom text-mode-hook nil
16117 "Normal hook run when entering Text mode and many related modes."
16118 :type 'hook
16119 :options '(turn-on-auto-fill flyspell-mode)
16120 :group 'data)
16121@end group
16122@end smallexample
16123
16124@noindent
16125The name of the variable is @code{text-mode-hook}; it has no default
16126value; and its documentation string tells you what it does.
16127
16128The @code{:type} keyword tells Emacs what kind of data
16129@code{text-mode-hook} should be set to and how to display the value in
16130a Customization buffer.
16131
16132The @code{:options} keyword specifies a suggested list of values for
16133the variable. Currently, you can use @code{:options} only for a hook.
16134The list is only a suggestion; it is not exclusive; a person who sets
16135the variable may set it to other values; the list shown following the
16136@code{:options} keyword is intended to offer convenient choices to a
16137user.
16138
16139Finally, the @code{:group} keyword tells the Emacs Customization
16140command in which group the variable is located. This tells where to
16141find it.
16142
16143For more information, see @ref{Customization, , Writing Customization
16144Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16145
16146Consider @code{text-mode-hook} as an example.
16147
16148There are two ways to customize this variable. You can use the
16149customization command or write the appropriate expressions yourself.
16150
16151@need 800
16152Using the customization command, you can type:
16153
16154@smallexample
16155M-x customize
16156@end smallexample
16157
16158@noindent
16159and find that the group for editing files of data is called `data'.
16160Enter that group. Text Mode Hook is the first member. You can click
16161on its various options to set the values. After you click on the
16162button to
16163
16164@smallexample
16165Save for Future Sessions
16166@end smallexample
16167
16168@noindent
16169Emacs will write an expression into your @file{.emacs} file.
16170It will look like this:
16171
16172@smallexample
16173@group
16174(custom-set-variables
16175 ;; custom-set-variables was added by Custom --
16176 ;; don't edit or cut/paste it!
16177 ;; Your init file should contain only one such instance.
16178 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16179@end group
16180@end smallexample
16181
16182@noindent
16183(The @code{text-mode-hook-identify} function tells
16184@code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16185
16186In spite of the warning, you certainly may edit, cut, and paste the
16187expression! I do all time. The purpose of the warning is to scare
16188those who do not know what they are doing, so they do not
16189inadvertently generate an error.
16190
c6f54b06
RC
16191The @code{custom-set-variables} function works somewhat differently
16192than a @code{setq}. While I have never learned the differences, I do
16193modify the @code{custom-set-variables} expressions in my @file{.emacs}
16194file by hand: I make the changes in what appears to me to be a
16195reasonable manner and have not had any problems. Others prefer to use
16196the Customization command and let Emacs do the work for them.
8b096dce
EZ
16197
16198Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16199This function sets the various font faces. Over time, I have set a
16200considerable number of faces. Some of the time, I re-set them using
16201@code{customize}; other times, I simply edit the
16202@code{custom-set-faces} expression in my @file{.emacs} file itself.
16203
16204The second way to customize your @code{text-mode-hook} is to set it
16205yourself in your @file{.emacs} file using code that has nothing to do
16206with the @code{custom-set-@dots{}} functions.
16207
16208@need 800
16209When you do this, and later use @code{customize}, you will see a
16210message that says
16211
16212@smallexample
16213this option has been changed outside the customize buffer.
16214@end smallexample
16215
16216@need 800
16217This message is only a warning. If you click on the button to
16218
16219@smallexample
16220Save for Future Sessions
16221@end smallexample
16222
16223@noindent
16224Emacs will write a @code{custom-set-@dots{}} expression near the end
16225of your @file{.emacs} file that will be evaluated after your
16226hand-written expression. It will, therefore, overrule your
16227hand-written expression. No harm will be done. When you do this,
16228however, be careful to remember which expression is active; if you
16229forget, you may confuse yourself.
16230
16231So long as you remember where the values are set, you will have no
16232trouble. In any event, the values are always set in your
16233initialization file, which is usually called @file{.emacs}.
16234
16235I myself use @code{customize} for hardly anything. Mostly, I write
16236expressions myself.
16237
16238@node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16239@section Beginning a @file{.emacs} File
16240@cindex @file{.emacs} file, beginning of
16241
16242When you start Emacs, it loads your @file{.emacs} file unless you tell
16243it not to by specifying @samp{-q} on the command line. (The
16244@code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16245
16246A @file{.emacs} file contains Lisp expressions. Often, these are no
16247more than expressions to set values; sometimes they are function
16248definitions.
16249
16250@xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16251Manual}, for a short description of initialization files.
16252
16253This chapter goes over some of the same ground, but is a walk among
16254extracts from a complete, long-used @file{.emacs} file---my own.
16255
16256The first part of the file consists of comments: reminders to myself.
16257By now, of course, I remember these things, but when I started, I did
16258not.
16259
c6f54b06 16260@need 1200
8b096dce
EZ
16261@smallexample
16262@group
16263;;;; Bob's .emacs file
16264; Robert J. Chassell
16265; 26 September 1985
16266@end group
16267@end smallexample
16268
16269@noindent
16270Look at that date! I started this file a long time ago. I have been
16271adding to it ever since.
16272
16273@smallexample
16274@group
16275; Each section in this file is introduced by a
16276; line beginning with four semicolons; and each
16277; entry is introduced by a line beginning with
16278; three semicolons.
16279@end group
16280@end smallexample
16281
16282@noindent
16283This describes the usual conventions for comments in Emacs Lisp.
16284Everything on a line that follows a semicolon is a comment. Two,
16285three, and four semicolons are used as section and subsection
16286markers. (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16287Manual}, for more about comments.)
16288
16289@smallexample
16290@group
16291;;;; The Help Key
16292; Control-h is the help key;
16293; after typing control-h, type a letter to
16294; indicate the subject about which you want help.
16295; For an explanation of the help facility,
16296; type control-h two times in a row.
16297@end group
16298@end smallexample
16299
16300@noindent
16301Just remember: type @kbd{C-h} two times for help.
16302
16303@smallexample
16304@group
16305; To find out about any mode, type control-h m
16306; while in that mode. For example, to find out
16307; about mail mode, enter mail mode and then type
16308; control-h m.
16309@end group
16310@end smallexample
16311
16312@noindent
16313`Mode help', as I call this, is very helpful. Usually, it tells you
16314all you need to know.
16315
16316Of course, you don't need to include comments like these in your
16317@file{.emacs} file. I included them in mine because I kept forgetting
16318about Mode help or the conventions for comments---but I was able to
16319remember to look here to remind myself.
16320
16321@node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16322@section Text and Auto Fill Mode
16323
16324Now we come to the part that `turns on' Text mode and
16325Auto Fill mode.
16326
16327@smallexample
16328@group
16329;;; Text mode and Auto Fill mode
16330; The next three lines put Emacs into Text mode
16331; and Auto Fill mode, and are for writers who
16332; want to start writing prose rather than code.
16333
16334(setq default-major-mode 'text-mode)
16335(add-hook 'text-mode-hook 'text-mode-hook-identify)
16336(add-hook 'text-mode-hook 'turn-on-auto-fill)
16337@end group
16338@end smallexample
16339
16340Here is the first part of this @file{.emacs} file that does something
16341besides remind a forgetful human!
16342
16343The first of the two lines in parentheses tells Emacs to turn on Text
16344mode when you find a file, @emph{unless} that file should go into some
16345other mode, such as C mode.
16346
16347@cindex Per-buffer, local variables list
16348@cindex Local variables list, per-buffer,
16349@cindex Automatic mode selection
16350@cindex Mode selection, automatic
16351When Emacs reads a file, it looks at the extension to the file name,
16352if any. (The extension is the part that comes after a @samp{.}.) If
16353the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16354on C mode. Also, Emacs looks at first nonblank line of the file; if
16355the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode. Emacs
16356possesses a list of extensions and specifications that it uses
16357automatically. In addition, Emacs looks near the last page for a
16358per-buffer, ``local variables list'', if any.
16359
16360@ifinfo
16361@xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16362Emacs Manual}.
16363
16364@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16365Manual}.
16366@end ifinfo
16367@iftex
16368See sections ``How Major Modes are Chosen'' and ``Local Variables in
16369Files'' in @cite{The GNU Emacs Manual}.
16370@end iftex
16371
16372Now, back to the @file{.emacs} file.
16373
16374@need 800
16375Here is the line again; how does it work?
16376
16377@cindex Text Mode turned on
16378@smallexample
16379(setq default-major-mode 'text-mode)
16380@end smallexample
16381
16382@noindent
16383This line is a short, but complete Emacs Lisp expression.
16384
16385We are already familiar with @code{setq}. It sets the following variable,
16386@code{default-major-mode}, to the subsequent value, which is
16387@code{text-mode}. The single quote mark before @code{text-mode} tells
16388Emacs to deal directly with the @code{text-mode} variable, not with
16389whatever it might stand for. @xref{set & setq, , Setting the Value of
16390a Variable}, for a reminder of how @code{setq} works. The main point
16391is that there is no difference between the procedure you use to set
16392a value in your @file{.emacs} file and the procedure you use anywhere
16393else in Emacs.
16394
16395@need 800
16396Here are the next two lines:
16397
16398@cindex Auto Fill mode turned on
16399@findex add-hook
16400@smallexample
16401(add-hook 'text-mode-hook 'text-mode-hook-identify)
16402(add-hook 'text-mode-hook 'turn-on-auto-fill)
16403@end smallexample
16404
16405@noindent
16406In these two lines, the @code{add-hook} command first adds
16407@code{text-mode-hook-identify} to the variable called
16408@code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16409variable.
16410
16411@code{turn-on-auto-fill} is the name of a program, that, you guessed
16412it!, turns on Auto Fill mode. @code{text-mode-hook-identify} is a
16413function that tells @code{toggle-text-mode-auto-fill} which buffers
16414are in Text mode.
16415
16416Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16417onto Text mode. So every time Emacs turns on Text mode, Emacs also
16418turns on Auto Fill mode.
16419
16420In brief, the first line causes Emacs to enter Text mode when you edit
16421a file, unless the file name extension, first non-blank line, or local
16422variables tell Emacs otherwise.
16423
16424Text mode among other actions, sets the syntax table to work
16425conveniently for writers. In Text mode, Emacs considers an apostrophe
16426as part of a word like a letter; but Emacs does not consider a period
16427or a space as part of a word. Thus, @kbd{M-f} moves you over
16428@samp{it's}. On the other hand, in C mode, @kbd{M-f} stops just after
16429the @samp{t} of @samp{it's}.
16430
16431The second and third lines causes Emacs to turn on Auto Fill mode when
16432it turns on Text mode. In Auto Fill mode, Emacs automatically breaks
16433a line that is too wide and brings the excessively wide part of the
16434line down to the next line. Emacs breaks lines between words, not
16435within them.
16436
16437When Auto Fill mode is turned off, lines continue to the right as you
16438type them. Depending on how you set the value of
16439@code{truncate-lines}, the words you type either disappear off the
16440right side of the screen, or else are shown, in a rather ugly and
16441unreadable manner, as a continuation line on the screen.
16442
16443@need 1250
16444In addition, in this part of my @file{.emacs} file, I tell the Emacs
16445fill commands to insert two spaces after a colon:
16446
16447@smallexample
16448(setq colon-double-space t)
16449@end smallexample
16450
16451@node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16452@section Mail Aliases
16453
16454Here is a @code{setq} that `turns on' mail aliases, along with more
16455reminders.
16456
16457@smallexample
16458@group
16459;;; Mail mode
16460; To enter mail mode, type `C-x m'
16461; To enter RMAIL (for reading mail),
16462; type `M-x rmail'
16463
16464(setq mail-aliases t)
16465@end group
16466@end smallexample
16467
16468@cindex Mail aliases
16469@noindent
16470This @code{setq} command sets the value of the variable
16471@code{mail-aliases} to @code{t}. Since @code{t} means true, the line
16472says, in effect, ``Yes, use mail aliases.''
16473
16474Mail aliases are convenient short names for long email addresses or
16475for lists of email addresses. The file where you keep your `aliases'
16476is @file{~/.mailrc}. You write an alias like this:
16477
16478@smallexample
16479alias geo george@@foobar.wiz.edu
16480@end smallexample
16481
16482@noindent
16483When you write a message to George, address it to @samp{geo}; the
16484mailer will automatically expand @samp{geo} to the full address.
16485
16486@node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16487@section Indent Tabs Mode
16488@cindex Tabs, preventing
16489@findex indent-tabs-mode
16490
16491By default, Emacs inserts tabs in place of multiple spaces when it
16492formats a region. (For example, you might indent many lines of text
16493all at once with the @code{indent-region} command.) Tabs look fine on
16494a terminal or with ordinary printing, but they produce badly indented
16495output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16496
16497@need 1250
16498The following turns off Indent Tabs mode:
16499
16500@smallexample
16501@group
16502;;; Prevent Extraneous Tabs
16503(setq-default indent-tabs-mode nil)
16504@end group
16505@end smallexample
16506
16507Note that this line uses @code{setq-default} rather than the
16508@code{setq} command that we have seen before. The @code{setq-default}
16509command sets values only in buffers that do not have their own local
16510values for the variable.
16511
16512@ifinfo
16513@xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16514
16515@xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16516Manual}.
16517@end ifinfo
16518@iftex
16519See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16520Files'' in @cite{The GNU Emacs Manual}.
16521@end iftex
16522
16523@node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16524@section Some Keybindings
16525
16526Now for some personal keybindings:
16527
16528@smallexample
16529@group
16530;;; Compare windows
16531(global-set-key "\C-cw" 'compare-windows)
16532@end group
16533@end smallexample
16534
16535@findex compare-windows
16536@code{compare-windows} is a nifty command that compares the text in
16537your current window with text in the next window. It makes the
16538comparison by starting at point in each window, moving over text in
16539each window as far as they match. I use this command all the time.
16540
16541This also shows how to set a key globally, for all modes.
16542
16543@cindex Setting a key globally
16544@cindex Global set key
16545@cindex Key setting globally
16546@findex global-set-key
16547The command is @code{global-set-key}. It is followed by the
16548keybinding. In a @file{.emacs} file, the keybinding is written as
16549shown: @code{\C-c} stands for `control-c', which means `press the
16550control key and the @kbd{c} key at the same time'. The @code{w} means
16551`press the @kbd{w} key'. The keybinding is surrounded by double
16552quotation marks. In documentation, you would write this as @kbd{C-c
16553w}. (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16554than a @key{CTL} key, you would write @code{\M-c}. @xref{Init
16555Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16556Manual}, for details.)
16557
16558The command invoked by the keys is @code{compare-windows}. Note that
16559@code{compare-windows} is preceded by a single quote; otherwise, Emacs
16560would first try to evaluate the symbol to determine its value.
16561
16562These three things, the double quotation marks, the backslash before
16563the @samp{C}, and the single quote mark are necessary parts of
16564keybinding that I tend to forget. Fortunately, I have come to
16565remember that I should look at my existing @file{.emacs} file, and
16566adapt what is there.
16567
16568As for the keybinding itself: @kbd{C-c w}. This combines the prefix
16569key, @kbd{C-c}, with a single character, in this case, @kbd{w}. This
16570set of keys, @kbd{C-c} followed by a single character, is strictly
16571reserved for individuals' own use. (I call these `own' keys, since
16572these are for my own use.) You should always be able to create such a
16573keybinding for your own use without stomping on someone else's
16574keybinding. If you ever write an extension to Emacs, please avoid
16575taking any of these keys for public use. Create a key like @kbd{C-c
16576C-w} instead. Otherwise, we will run out of `own' keys.
16577
16578@need 1250
16579Here is another keybinding, with a comment:
16580
16581@smallexample
16582@group
16583;;; Keybinding for `occur'
16584; I use occur a lot, so let's bind it to a key:
16585(global-set-key "\C-co" 'occur)
16586@end group
16587@end smallexample
16588
16589@findex occur
16590The @code{occur} command shows all the lines in the current buffer
16591that contain a match for a regular expression. Matching lines are
16592shown in a buffer called @file{*Occur*}. That buffer serves as a menu
16593to jump to occurrences.
16594
16595@findex global-unset-key
16596@cindex Unbinding key
16597@cindex Key unbinding
16598@need 1250
16599Here is how to unbind a key, so it does not
16600work:
16601
16602@smallexample
16603@group
16604;;; Unbind `C-x f'
16605(global-unset-key "\C-xf")
16606@end group
16607@end smallexample
16608
16609There is a reason for this unbinding: I found I inadvertently typed
16610@w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}. Rather than find a
16611file, as I intended, I accidentally set the width for filled text,
16612almost always to a width I did not want. Since I hardly ever reset my
16613default width, I simply unbound the key.
16614
16615@findex list-buffers, @r{rebound}
16616@findex buffer-menu, @r{bound to key}
16617@need 1250
16618The following rebinds an existing key:
16619
16620@smallexample
16621@group
16622;;; Rebind `C-x C-b' for `buffer-menu'
16623(global-set-key "\C-x\C-b" 'buffer-menu)
16624@end group
16625@end smallexample
16626
16627By default, @kbd{C-x C-b} runs the
16628@code{list-buffers} command. This command lists
16629your buffers in @emph{another} window. Since I
16630almost always want to do something in that
16631window, I prefer the @code{buffer-menu}
16632command, which not only lists the buffers,
16633but moves point into that window.
16634
16635@node Keymaps, Loading Files, Keybindings, Emacs Initialization
16636@section Keymaps
16637@cindex Keymaps
16638@cindex Rebinding keys
16639
16640Emacs uses @dfn{keymaps} to record which keys call which commands.
16641When you use @code{global-set-key} to set the keybinding for a single
16642command in all parts of Emacs, you are specifying the keybinding in
16643@code{current-global-map}.
16644
16645Specific modes, such as C mode or Text mode, have their own keymaps;
16646the mode-specific keymaps override the global map that is shared by
16647all buffers.
16648
16649The @code{global-set-key} function binds, or rebinds, the global
16650keymap. For example, the following binds the key @kbd{C-x C-b} to the
16651function @code{buffer-menu}:
16652
16653@smallexample
16654(global-set-key "\C-x\C-b" 'buffer-menu)
16655@end smallexample
16656
16657Mode-specific keymaps are bound using the @code{define-key} function,
16658which takes a specific keymap as an argument, as well as the key and
16659the command. For example, my @file{.emacs} file contains the
16660following expression to bind the @code{texinfo-insert-@@group} command
16661to @kbd{C-c C-c g}:
16662
16663@smallexample
16664@group
16665(define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16666@end group
16667@end smallexample
16668
16669@noindent
16670The @code{texinfo-insert-@@group} function itself is a little extension
16671to Texinfo mode that inserts @samp{@@group} into a Texinfo file. I
16672use this command all the time and prefer to type the three strokes
16673@kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16674(@samp{@@group} and its matching @samp{@@end group} are commands that
16675keep all enclosed text together on one page; many multi-line examples
16676in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16677
16678@need 1250
16679Here is the @code{texinfo-insert-@@group} function definition:
16680
16681@smallexample
16682@group
16683(defun texinfo-insert-@@group ()
16684 "Insert the string @@group in a Texinfo buffer."
16685 (interactive)
16686 (beginning-of-line)
16687 (insert "@@group\n"))
16688@end group
16689@end smallexample
16690
16691(Of course, I could have used Abbrev mode to save typing, rather than
16692write a function to insert a word; but I prefer key strokes consistent
16693with other Texinfo mode key bindings.)
16694
16695You will see numerous @code{define-key} expressions in
16696@file{loaddefs.el} as well as in the various mode libraries, such as
16697@file{cc-mode.el} and @file{lisp-mode.el}.
16698
16699@xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16700Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16701Reference Manual}, for more information about keymaps.
16702
16703@node Loading Files, Autoload, Keymaps, Emacs Initialization
16704@section Loading Files
16705@cindex Loading files
16706@c findex load
16707
16708Many people in the GNU Emacs community have written extensions to
16709Emacs. As time goes by, these extensions are often included in new
16710releases. For example, the Calendar and Diary packages are now part
c6f54b06 16711of the standard GNU Emacs, as is Calc.
8b096dce
EZ
16712
16713You can use a @code{load} command to evaluate a complete file and
16714thereby install all the functions and variables in the file into Emacs.
16715For example:
16716
16717@c (auto-compression-mode t)
16718
16719@smallexample
16720(load "~/emacs/slowsplit")
16721@end smallexample
16722
16723This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16724exists, the faster, byte compiled @file{slowsplit.elc} file from the
16725@file{emacs} sub-directory of your home directory. The file contains
16726the function @code{split-window-quietly}, which John Robinson wrote in
167271989.
16728
16729The @code{split-window-quietly} function splits a window with the
16730minimum of redisplay. I installed it in 1989 because it worked well
16731with the slow 1200 baud terminals I was then using. Nowadays, I only
16732occasionally come across such a slow connection, but I continue to use
16733the function because I like the way it leaves the bottom half of a
16734buffer in the lower of the new windows and the top half in the upper
16735window.
16736
16737@need 1250
16738To replace the key binding for the default
16739@code{split-window-vertically}, you must also unset that key and bind
16740the keys to @code{split-window-quietly}, like this:
16741
16742@smallexample
16743@group
16744(global-unset-key "\C-x2")
16745(global-set-key "\C-x2" 'split-window-quietly)
16746@end group
16747@end smallexample
16748
16749@vindex load-path
16750If you load many extensions, as I do, then instead of specifying the
16751exact location of the extension file, as shown above, you can specify
16752that directory as part of Emacs' @code{load-path}. Then, when Emacs
16753loads a file, it will search that directory as well as its default
16754list of directories. (The default list is specified in @file{paths.h}
16755when Emacs is built.)
16756
16757@need 1250
16758The following command adds your @file{~/emacs} directory to the
16759existing load path:
16760
16761@smallexample
16762@group
16763;;; Emacs Load Path
16764(setq load-path (cons "~/emacs" load-path))
16765@end group
16766@end smallexample
16767
16768Incidentally, @code{load-library} is an interactive interface to the
16769@code{load} function. The complete function looks like this:
16770
16771@findex load-library
16772@smallexample
16773@group
16774(defun load-library (library)
16775 "Load the library named LIBRARY.
16776This is an interface to the function `load'."
16777 (interactive "sLoad library: ")
16778 (load library))
16779@end group
16780@end smallexample
16781
16782The name of the function, @code{load-library}, comes from the use of
16783`library' as a conventional synonym for `file'. The source for the
16784@code{load-library} command is in the @file{files.el} library.
16785
16786Another interactive command that does a slightly different job is
16787@code{load-file}. @xref{Lisp Libraries, , Libraries of Lisp Code for
16788Emacs, emacs, The GNU Emacs Manual}, for information on the
16789distinction between @code{load-library} and this command.
16790
16791@node Autoload, Simple Extension, Loading Files, Emacs Initialization
16792@section Autoloading
16793@findex autoload
16794
16795Instead of installing a function by loading the file that contains it,
16796or by evaluating the function definition, you can make the function
16797available but not actually install it until it is first called. This
16798is called @dfn{autoloading}.
16799
16800When you execute an autoloaded function, Emacs automatically evaluates
16801the file that contains the definition, and then calls the function.
16802
16803Emacs starts quicker with autoloaded functions, since their libraries
16804are not loaded right away; but you need to wait a moment when you
16805first use such a function, while its containing file is evaluated.
16806
16807Rarely used functions are frequently autoloaded. The
16808@file{loaddefs.el} library contains hundreds of autoloaded functions,
16809from @code{bookmark-set} to @code{wordstar-mode}. Of course, you may
16810come to use a `rare' function frequently. When you do, you should
16811load that function's file with a @code{load} expression in your
16812@file{.emacs} file.
16813
16814In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16815that contain functions that would otherwise be autoloaded. (Actually,
16816it would have been better to include these files in my `dumped' Emacs
16817when I built it, but I forgot. @xref{Building Emacs, , Building
16818Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16819file for more about dumping.)
16820
16821You may also want to include autoloaded expressions in your @file{.emacs}
16822file. @code{autoload} is a built-in function that takes up to five
16823arguments, the final three of which are optional. The first argument
16824is the name of the function to be autoloaded; the second is the name
16825of the file to be loaded. The third argument is documentation for the
16826function, and the fourth tells whether the function can be called
16827interactively. The fifth argument tells what type of
16828object---@code{autoload} can handle a keymap or macro as well as a
16829function (the default is a function).
16830
16831@need 800
16832Here is a typical example:
16833
16834@smallexample
16835@group
16836(autoload 'html-helper-mode
16837 "html-helper-mode" "Edit HTML documents" t)
16838@end group
16839@end smallexample
16840
16841@noindent
16842(@code{html-helper-mode} is an alternative to @code{html-mode}, which
16843is a standard part of the distribution).
16844
16845@noindent
16846This expression autoloads the @code{html-helper-mode} function. It
16847takes it from the @file{html-helper-mode.el} file (or from the byte
16848compiled file @file{html-helper-mode.elc}, if it exists.) The file
16849must be located in a directory specified by @code{load-path}. The
16850documentation says that this is a mode to help you edit documents
16851written in the HyperText Markup Language. You can call this mode
16852interactively by typing @kbd{M-x html-helper-mode}. (You need to
16853duplicate the function's regular documentation in the autoload
16854expression because the regular function is not yet loaded, so its
16855documentation is not available.)
16856
16857@xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16858Manual}, for more information.
16859
16860@node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16861@section A Simple Extension: @code{line-to-top-of-window}
16862@findex line-to-top-of-window
16863@cindex Simple extension in @file{.emacs} file
16864
16865Here is a simple extension to Emacs that moves the line point is on to
16866the top of the window. I use this all the time, to make text easier
16867to read.
16868
16869You can put the following code into a separate file and then load it
16870from your @file{.emacs} file, or you can include it within your
16871@file{.emacs} file.
16872
16873@need 1250
16874Here is the definition:
16875
16876@smallexample
16877@group
16878;;; Line to top of window;
16879;;; replace three keystroke sequence C-u 0 C-l
16880(defun line-to-top-of-window ()
16881 "Move the line point is on to top of window."
16882 (interactive)
16883 (recenter 0))
16884@end group
16885@end smallexample
16886
16887@need 1250
16888Now for the keybinding.
16889
16890Nowadays, function keys as well as mouse button events and
16891non-@sc{ascii} characters are written within square brackets, without
16892quotation marks. (In Emacs version 18 and before, you had to write
16893different function key bindings for each different make of terminal.)
16894
16895I bind @code{line-to-top-of-window} to my @key{F6} function key like
16896this:
16897
16898@smallexample
16899(global-set-key [f6] 'line-to-top-of-window)
16900@end smallexample
16901
16902For more information, see @ref{Init Rebinding, , Rebinding Keys in
16903Your Init File, emacs, The GNU Emacs Manual}.
16904
16905@cindex Conditional 'twixt two versions of Emacs
16906@cindex Version of Emacs, choosing
16907@cindex Emacs version, choosing
16908If you run two versions of GNU Emacs, such as versions 20 and 21, and
16909use one @file{.emacs} file, you can select which code to evaluate with
16910the following conditional:
16911
16912@smallexample
16913@group
16914(cond
16915 ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16916 ;; evaluate version 20 code
16917 ( @dots{} ))
16918 ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16919 ;; evaluate version 21 code
16920 ( @dots{} )))
16921@end group
16922@end smallexample
16923
16924For example, in contrast to version 20, version 21 blinks its cursor
16925by default. I hate such blinking, as well as some other features in
16926version 21, so I placed the following in my @file{.emacs}
16927file@footnote{When I start instances of Emacs that do not load my
16928@file{.emacs} file or any site file, I also turn off blinking:
16929
16930@smallexample
16931emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16932@end smallexample
16933}:
16934
16935@smallexample
16936@group
16937(if (string-equal "21" (substring (emacs-version) 10 12))
16938 (progn
16939 (blink-cursor-mode 0)
16940 ;; Insert newline when you press `C-n' (next-line)
16941 ;; at the end of the buffer
16942 (setq next-line-add-newlines t)
16943@end group
16944@group
16945 ;; Turn on image viewing
16946 (auto-image-file-mode t)
16947@end group
16948@group
16949 ;; Turn on menu bar (this bar has text)
16950 ;; (Use numeric argument to turn on)
16951 (menu-bar-mode 1)
16952@end group
16953@group
16954 ;; Turn off tool bar (this bar has icons)
16955 ;; (Use numeric argument to turn on)
16956 (tool-bar-mode nil)
16957@end group
16958@group
16959 ;; Turn off tooltip mode for tool bar
16960 ;; (This mode causes icon explanations to pop up)
16961 ;; (Use numeric argument to turn on)
16962 (tooltip-mode nil)
16963 ;; If tooltips turned on, make tips appear promptly
16964 (setq tooltip-delay 0.1) ; default is one second
16965 ))
16966@end group
16967@end smallexample
16968
16969@noindent
16970(You will note that instead of typing @code{(number-to-string 21)}, I
16971decided to save typing and wrote `21' as a string, @code{"21"}, rather
16972than convert it from an integer to a string. In this instance, this
16973expression is better than the longer, but more general
16974@code{(number-to-string 21)}. However, if you do not know ahead of
16975time what type of information will be returned, then the
16976@code{number-to-string} function will be needed.)
16977
16978@node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16979@section X11 Colors
16980
16981You can specify colors when you use Emacs with the MIT X Windowing
16982system.
16983
16984I dislike the default colors and specify my own.
16985
16986@need 1250
16987Here are the expressions in my @file{.emacs}
16988file that set values:
16989
16990@smallexample
16991@group
16992;; Set cursor color
16993(set-cursor-color "white")
16994
16995;; Set mouse color
16996(set-mouse-color "white")
16997
16998;; Set foreground and background
16999(set-foreground-color "white")
17000(set-background-color "darkblue")
17001@end group
17002
17003@group
17004;;; Set highlighting colors for isearch and drag
17005(set-face-foreground 'highlight "white")
17006(set-face-background 'highlight "blue")
17007@end group
17008
17009@group
17010(set-face-foreground 'region "cyan")
17011(set-face-background 'region "blue")
17012@end group
17013
17014@group
17015(set-face-foreground 'secondary-selection "skyblue")
17016(set-face-background 'secondary-selection "darkblue")
17017@end group
17018
17019@group
17020;; Set calendar highlighting colors
17021(setq calendar-load-hook
17022 '(lambda ()
17023 (set-face-foreground 'diary-face "skyblue")
17024 (set-face-background 'holiday-face "slate blue")
17025 (set-face-foreground 'holiday-face "white")))
17026@end group
17027@end smallexample
17028
17029The various shades of blue soothe my eye and prevent me from seeing
17030the screen flicker.
17031
17032Alternatively, I could have set my specifications in various X
17033initialization files. For example, I could set the foreground,
17034background, cursor, and pointer (i.e., mouse) colors in my
17035@file{~/.Xresources} file like this:
17036
17037@smallexample
17038@group
17039Emacs*foreground: white
17040Emacs*background: darkblue
17041Emacs*cursorColor: white
17042Emacs*pointerColor: white
17043@end group
17044@end smallexample
17045
17046In any event, since it is not part of Emacs, I set the root color of
17047my X window in my @file{~/.xinitrc} file, like this@footnote{I
17048occasionally run more modern window managers, such as Sawfish with
17049GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17050image rather than a plain color.}:
17051
17052@smallexample
17053@group
17054# I use TWM for window manager.
17055xsetroot -solid Navy -fg white &
17056@end group
17057@end smallexample
17058
17059@node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17060@section Miscellaneous Settings for a @file{.emacs} File
17061
17062Here are a few miscellaneous settings:
17063@sp 1
17064
17065@itemize @minus
17066@item
17067Set the shape and color of the mouse cursor:
17068@smallexample
17069@group
17070; Cursor shapes are defined in
17071; `/usr/include/X11/cursorfont.h';
17072; for example, the `target' cursor is number 128;
17073; the `top_left_arrow' cursor is number 132.
17074@end group
17075
17076@group
17077(let ((mpointer (x-get-resource "*mpointer"
17078 "*emacs*mpointer")))
17079 ;; If you have not set your mouse pointer
17080 ;; then set it, otherwise leave as is:
17081 (if (eq mpointer nil)
17082 (setq mpointer "132")) ; top_left_arrow
17083@end group
17084@group
17085 (setq x-pointer-shape (string-to-int mpointer))
17086 (set-mouse-color "white"))
17087@end group
17088@end smallexample
c6f54b06
RC
17089
17090@item
17091Convert @kbd{@key{CTL}-h} into @key{DEL} and @key{DEL}
17092into @kbd{@key{CTL}-h}.@*
17093(Some olders keyboards needed this, although I have not seen the
17094problem recently.)
17095
17096@smallexample
17097@group
17098;; Translate `C-h' to <DEL>.
17099; (keyboard-translate ?\C-h ?\C-?)
17100
17101;; Translate <DEL> to `C-h'.
17102(keyboard-translate ?\C-? ?\C-h)
17103@end group
17104@end smallexample
17105
17106@item Turn off a blinking cursor!
17107
17108@smallexample
17109@group
17110(if (fboundp 'blink-cursor-mode)
17111 (blink-cursor-mode -1))
17112@end group
17113@end smallexample
17114
17115@item Ignore case when using `grep'@*
17116@samp{-n}@w{ } Prefix each line of output with line number@*
17117@samp{-i}@w{ } Ignore case distinctions@*
17118@samp{-e}@w{ } Protect patterns beginning with a hyphen character, @samp{-}
17119
17120@smallexample
17121(setq grep-command "grep -n -i -e ")
17122@end smallexample
17123
17124@item Automatically uncompress compressed files when visiting them
17125
17126@smallexample
17127(load "uncompress")
17128@end smallexample
17129
17130@item Find an existing buffer, even if it has a different name@*
17131This avoids problems with symbolic links.
17132
17133@smallexample
17134(setq find-file-existing-other-name t)
17135@end smallexample
17136
17137@item Set your language environment and default input method
17138
17139@smallexample
17140@group
17141(set-language-environment "latin-1")
17142;; Remember you can enable or disable multilingual text input
17143;; with the @code{toggle-input-method'} (@kbd{C-\}) command
17144(setq default-input-method "latin-1-prefix")
17145@end group
17146@end smallexample
17147
17148If you want to write with Chinese `GB' characters, set this instead:
17149
17150@smallexample
17151@group
17152(set-language-environment "Chinese-GB")
17153(setq default-input-method "chinese-tonepy")
17154@end group
17155@end smallexample
8b096dce
EZ
17156@end itemize
17157
c6f54b06
RC
17158@subsubheading Fixing Unpleasant Key Bindings
17159@cindex Key bindings, fixing
17160@cindex Bindings, key, fixing unpleasant
17161
17162Some systems bind keys unpleasantly. Sometimes, for example, the
17163@key{CTL} key appears in an awkward spot rather than at the far left
17164of the home row.
17165
17166Usually, when people fix these sorts of keybindings, they do not
17167change their @file{~/.emacs} file. Instead, they bind the proper keys
17168on their consoles with the @code{loadkeys} or @code{install-keymap}
17169commands in their boot script and then include @code{xmodmap} commands
17170in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
17171
17172@need 1250
17173@noindent
17174For a boot script:
17175
17176@smallexample
17177@group
17178loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
17179
17180@exdent or
17181
17182install-keymap emacs2
17183@end group
17184@end smallexample
17185
17186@need 1250
17187@noindent
17188For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
17189Lock} key is at the far left of the home row:
17190
17191@smallexample
17192@group
17193# Bind the key labeled `Caps Lock' to `Control'
17194# (Such a broken user interface suggests that keyboard manufacturers
17195# think that computers are typewriters from 1885.)
17196
17197xmodmap -e "clear Lock"
17198xmodmap -e "add Control = Caps_Lock"
17199@end group
17200@end smallexample
17201
17202@need 1250
17203@noindent
17204In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
17205key to a @key{META} key:
17206
17207@smallexample
17208@group
17209# Some ill designed keyboards have a key labeled ALT and no Meta
17210xmodmap -e "keysym Alt_L = Meta_L Alt_L"
17211@end group
17212@end smallexample
17213
8b096dce
EZ
17214@node Mode Line, , Miscellaneous, Emacs Initialization
17215@section A Modified Mode Line
17216@vindex default-mode-line-format
17217@cindex Mode line format
17218
17219Finally, a feature I really like: a modified mode line.
17220
17221When I work over a network, I forget which machine I am using. Also,
17222I tend to I lose track of where I am, and which line point is on.
17223
17224So I reset my mode line to look like this:
17225
17226@smallexample
17227-:-- foo.texi rattlesnake:/home/bob/ Line 1 (Texinfo Fill) Top
17228@end smallexample
17229
17230I am visiting a file called @file{foo.texi}, on my machine
17231@file{rattlesnake} in my @file{/home/bob} buffer. I am on line 1, in
17232Texinfo mode, and am at the top of the buffer.
17233
17234@need 1200
17235My @file{.emacs} file has a section that looks like this:
17236
17237@smallexample
17238@group
17239;; Set a Mode Line that tells me which machine, which directory,
17240;; and which line I am on, plus the other customary information.
17241(setq default-mode-line-format
17242 (quote
17243 (#("-" 0 1
17244 (help-echo
17245 "mouse-1: select window, mouse-2: delete others ..."))
17246 mode-line-mule-info
17247 mode-line-modified
17248 mode-line-frame-identification
17249 " "
17250@end group
17251@group
17252 mode-line-buffer-identification
17253 " "
17254 (:eval (substring
17255 (system-name) 0 (string-match "\\..+" (system-name))))
17256 ":"
17257 default-directory
17258 #(" " 0 1
17259 (help-echo
17260 "mouse-1: select window, mouse-2: delete others ..."))
17261 (line-number-mode " Line %l ")
17262 global-mode-string
17263@end group
17264@group
17265 #(" %[(" 0 6
17266 (help-echo
17267 "mouse-1: select window, mouse-2: delete others ..."))
17268 (:eval (mode-line-mode-name))
17269 mode-line-process
17270 minor-mode-alist
17271 #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17272 ")%] "
17273 (-3 . "%P")
17274 ;; "-%-"
17275 )))
17276@end group
17277@end smallexample
17278
17279@noindent
17280Here, I redefine the default mode line. Most of the parts are from
17281the original; but I make a few changes. I set the @emph{default} mode
17282line format so as to permit various modes, such as Info, to override
17283it.
17284
17285Many elements in the list are self-explanatory:
17286@code{mode-line-modified} is a variable that tells whether the buffer
17287has been modified, @code{mode-name} tells the name of the mode, and so
17288on. However, the format looks complicated because of two features we
17289have not discussed.
17290
c6f54b06 17291@cindex Properties, in mode line example
8b096dce
EZ
17292The first string in the mode line is a dash or hyphen, @samp{-}. In
17293the old days, it would have been specified simply as @code{"-"}. But
17294nowadays, Emacs can add properties to a string, such as highlighting
17295or, as in this case, a help feature. If you place your mouse cursor
c6f54b06 17296over the hyphen, some help information appears (By default, you must
8b096dce
EZ
17297wait one second before the information appears. You can change that
17298timing by changing the value of @code{tooltip-delay}.)
17299
17300@need 1000
17301The new string format has a special syntax:
17302
17303@smallexample
17304#("-" 0 1 (help-echo "mouse-1: select window, ..."))
17305@end smallexample
17306
17307@noindent
17308The @code{#(} begins a list. The first element of the list is the
17309string itself, just one @samp{-}. The second and third
17310elements specify the range over which the fourth element applies. A
17311range starts @emph{after} a character, so a zero means the range
17312starts just before the first character; a 1 means that the range ends
17313just after the first character. The third element is the property for
17314the range. It consists of a property list, a
17315property name, in this case, @samp{help-echo}, followed by a value, in this
17316case, a string. The second, third, and fourth elements of this new
17317string format can be repeated.
17318
c6f54b06
RC
17319@xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
17320Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
17321elisp, The GNU Emacs Lisp Reference Manual}, for more information.
8b096dce
EZ
17322
17323@code{mode-line-buffer-identification}
17324displays the current buffer name. It is a list
17325beginning @code{(#("%12b" 0 4 @dots{}}.
17326The @code{#(} begins the list.
17327
17328The @samp{"%12b"} displays the current buffer name, using the
17329@code{buffer-name} function with which we are familiar; the `12'
17330specifies the maximum number of characters that will be displayed.
17331When a name has fewer characters, whitespace is added to fill out to
17332this number. (Buffer names can and often should be longer than 12
17333characters; this length works well in a typical 80 column wide
17334window.)
17335
17336@code{:eval} is a new feature in GNU Emacs version 21. It says to
17337evaluate the following form and use the result as a string to display.
17338In this case, the expression displays the first component of the full
17339system name. The end of the first component is a @samp{.} (`period'),
17340so I use the @code{string-match} function to tell me the length of the
17341first component. The substring from the zeroth character to that
17342length is the name of the machine.
17343
17344@need 1250
17345This is the expression:
17346
17347@smallexample
17348@group
17349(:eval (substring
17350 (system-name) 0 (string-match "\\..+" (system-name))))
17351@end group
17352@end smallexample
17353
17354@samp{%[} and @samp{%]} cause a pair of square brackets
17355to appear for each recursive editing level. @samp{%n} says `Narrow'
17356when narrowing is in effect. @samp{%P} tells you the percentage of
17357the buffer that is above the bottom of the window, or `Top', `Bottom',
17358or `All'. (A lower case @samp{p} tell you the percentage above the
17359@emph{top} of the window.) @samp{%-} inserts enough dashes to fill
17360out the line.
17361
17362Remember, ``You don't have to like Emacs to like it'' --- your own
17363Emacs can have different colors, different commands, and different
17364keys than a default Emacs.
17365
17366On the other hand, if you want to bring up a plain `out of the box'
17367Emacs, with no customization, type:
17368
17369@smallexample
17370emacs -q
17371@end smallexample
17372
17373@noindent
17374This will start an Emacs that does @emph{not} load your
17375@file{~/.emacs} initialization file. A plain, default Emacs. Nothing
17376more.
17377
17378@node Debugging, Conclusion, Emacs Initialization, Top
17379@chapter Debugging
17380@cindex debugging
17381
17382GNU Emacs has two debuggers, @code{debug} and @code{edebug}. The
17383first is built into the internals of Emacs and is always with you;
17384the second requires that you instrument a function before you can use it.
17385
17386Both debuggers are described extensively in @ref{Debugging, ,
17387Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17388In this chapter, I will walk through a short example of each.
17389
17390@menu
17391* debug:: How to use the built-in debugger.
17392* debug-on-entry:: Start debugging when you call a function.
17393* debug-on-quit:: Start debugging when you quit with @kbd{C-g}.
17394* edebug:: How to use Edebug, a source level debugger.
17395* Debugging Exercises::
17396@end menu
17397
17398@node debug, debug-on-entry, Debugging, Debugging
17399@section @code{debug}
17400@findex debug
17401
17402Suppose you have written a function definition that is intended to
17403return the sum of the numbers 1 through a given number. (This is the
17404@code{triangle} function discussed earlier. @xref{Decrementing
17405Example, , Example with Decrementing Counter}, for a discussion.)
17406@c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17407
17408However, your function definition has a bug. You have mistyped
17409@samp{1=} for @samp{1-}. Here is the broken definition:
17410
17411@findex triangle-bugged
17412@smallexample
17413@group
17414(defun triangle-bugged (number)
17415 "Return sum of numbers 1 through NUMBER inclusive."
17416 (let ((total 0))
17417 (while (> number 0)
17418 (setq total (+ total number))
17419 (setq number (1= number))) ; @r{Error here.}
17420 total))
17421@end group
17422@end smallexample
17423
17424If you are reading this in Info, you can evaluate this definition in
17425the normal fashion. You will see @code{triangle-bugged} appear in the
17426echo area.
17427
17428@need 1250
17429Now evaluate the @code{triangle-bugged} function with an
17430argument of 4:
17431
17432@smallexample
17433(triangle-bugged 4)
17434@end smallexample
17435
17436@noindent
17437In GNU Emacs version 21, you will create and enter a
17438@file{*Backtrace*} buffer that says:
17439
17440@noindent
17441@smallexample
17442@group
17443---------- Buffer: *Backtrace* ----------
17444Debugger entered--Lisp error: (void-function 1=)
17445 (1= number)
17446 (setq number (1= number))
17447 (while (> number 0) (setq total (+ total number))
17448 (setq number (1= number)))
17449 (let ((total 0)) (while (> number 0) (setq total ...)
17450 (setq number ...)) total)
17451 triangle-bugged(4)
17452@end group
17453@group
17454 eval((triangle-bugged 4))
17455 eval-last-sexp-1(nil)
17456 eval-last-sexp(nil)
17457 call-interactively(eval-last-sexp)
17458---------- Buffer: *Backtrace* ----------
17459@end group
17460@end smallexample
17461
17462@noindent
17463(I have reformatted this example slightly; the debugger does not fold
17464long lines. As usual, you can quit the debugger by typing @kbd{q} in
17465the @file{*Backtrace*} buffer.)
17466
17467In practice, for a bug as simple as this, the `Lisp error' line will
17468tell you what you need to know to correct the definition. The
17469function @code{1=} is `void'.
17470
17471@need 800
17472In GNU Emacs 20 and before, you will see:
17473
17474@smallexample
17475Symbol's function definition is void:@: 1=
17476@end smallexample
17477
17478@noindent
17479which has the same meaning as the @file{*Backtrace*} buffer line in
17480version 21.
17481
17482However, suppose you are not quite certain what is going on?
17483You can read the complete backtrace.
17484
17485In this case, you need to run GNU Emacs 21, which automatically starts
17486the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17487you need to start the debugger manually as described below.
17488
17489Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17490what Emacs did that led to the error. Emacs made an interactive call
17491to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17492of the @code{triangle-bugged} expression. Each line above tells you
17493what the Lisp interpreter evaluated next.
17494
17495@need 1250
17496The third line from the top of the buffer is
17497
17498@smallexample
17499(setq number (1= number))
17500@end smallexample
17501
17502@noindent
17503Emacs tried to evaluate this expression; in order to do so, it tried
17504to evaluate the inner expression shown on the second line from the
17505top:
17506
17507@smallexample
17508(1= number)
17509@end smallexample
17510
17511@need 1250
17512@noindent
17513This is where the error occurred; as the top line says:
17514
17515@smallexample
17516Debugger entered--Lisp error: (void-function 1=)
17517@end smallexample
17518
17519@noindent
17520You can correct the mistake, re-evaluate the function definition, and
17521then run your test again.
17522
17523@node debug-on-entry, debug-on-quit, debug, Debugging
17524@section @code{debug-on-entry}
17525@findex debug-on-entry
17526
17527GNU Emacs 21 starts the debugger automatically when your function has
17528an error. GNU Emacs version 20 and before did not; it simply
17529presented you with an error message. You had to start the debugger
17530manually.
17531
17532You can start the debugger manually for all versions of Emacs; the
17533advantage is that the debugger runs even if you do not have a bug in
17534your code. Sometimes your code will be free of bugs!
17535
17536You can enter the debugger when you call the function by calling
17537@code{debug-on-entry}.
17538
17539@need 1250
17540@noindent
17541Type:
17542
17543@smallexample
17544M-x debug-on-entry RET triangle-bugged RET
17545@end smallexample
17546
17547@need 1250
17548@noindent
17549Now, evaluate the following:
17550
17551@smallexample
17552(triangle-bugged 5)
17553@end smallexample
17554
17555@noindent
17556All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17557you that it is beginning to evaluate the @code{triangle-bugged}
17558function:
17559
17560@smallexample
17561@group
17562---------- Buffer: *Backtrace* ----------
17563Debugger entered--entering a function:
17564* triangle-bugged(5)
17565 eval((triangle-bugged 5))
17566@end group
17567@group
17568 eval-last-sexp-1(nil)
17569 eval-last-sexp(nil)
17570 call-interactively(eval-last-sexp)
17571---------- Buffer: *Backtrace* ----------
17572@end group
17573@end smallexample
17574
17575In the @file{*Backtrace*} buffer, type @kbd{d}. Emacs will evaluate
17576the first expression in @code{triangle-bugged}; the buffer will look
17577like this:
17578
17579@smallexample
17580@group
17581---------- Buffer: *Backtrace* ----------
17582Debugger entered--beginning evaluation of function call form:
17583* (let ((total 0)) (while (> number 0) (setq total ...)
17584 (setq number ...)) total)
17585* triangle-bugged(5)
17586 eval((triangle-bugged 5))
17587@end group
17588@group
17589 eval-last-sexp-1(nil)
17590 eval-last-sexp(nil)
17591 call-interactively(eval-last-sexp)
17592---------- Buffer: *Backtrace* ----------
17593@end group
17594@end smallexample
17595
17596@noindent
17597Now, type @kbd{d} again, eight times, slowly. Each time you type
17598@kbd{d}, Emacs will evaluate another expression in the function
17599definition.
17600
17601@need 1750
17602Eventually, the buffer will look like this:
17603
17604@smallexample
17605@group
17606---------- Buffer: *Backtrace* ----------
17607Debugger entered--beginning evaluation of function call form:
17608* (setq number (1= number))
17609* (while (> number 0) (setq total (+ total number))
17610 (setq number (1= number)))
17611@group
17612@end group
17613* (let ((total 0)) (while (> number 0) (setq total ...)
17614 (setq number ...)) total)
17615* triangle-bugged(5)
17616 eval((triangle-bugged 5))
17617@group
17618@end group
17619 eval-last-sexp-1(nil)
17620 eval-last-sexp(nil)
17621 call-interactively(eval-last-sexp)
17622---------- Buffer: *Backtrace* ----------
17623@end group
17624@end smallexample
17625
c6f54b06 17626@need 1500
8b096dce
EZ
17627@noindent
17628Finally, after you type @kbd{d} two more times, Emacs will reach the
17629error, and the top two lines of the @file{*Backtrace*} buffer will look
17630like this:
17631
17632@smallexample
17633@group
17634---------- Buffer: *Backtrace* ----------
17635Debugger entered--Lisp error: (void-function 1=)
17636* (1= number)
17637@dots{}
17638---------- Buffer: *Backtrace* ----------
17639@end group
17640@end smallexample
17641
17642By typing @kbd{d}, you were able to step through the function.
17643
17644You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17645quits the trace, but does not cancel @code{debug-on-entry}.
17646
17647@findex cancel-debug-on-entry
17648To cancel the effect of @code{debug-on-entry}, call
17649@code{cancel-debug-on-entry} and the name of the function, like this:
17650
17651@smallexample
17652M-x cancel-debug-on-entry RET triangle-bugged RET
17653@end smallexample
17654
17655@noindent
17656(If you are reading this in Info, cancel @code{debug-on-entry} now.)
17657
17658@node debug-on-quit, edebug, debug-on-entry, Debugging
17659@section @code{debug-on-quit} and @code{(debug)}
17660
17661In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17662there are two other ways to start @code{debug}.
17663
17664@findex debug-on-quit
17665You can start @code{debug} whenever you type @kbd{C-g}
17666(@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17667@code{t}. This is useful for debugging infinite loops.
17668
17669@need 1500
17670@cindex @code{(debug)} in code
17671Or, you can insert a line that says @code{(debug)} into your code
17672where you want the debugger to start, like this:
17673
17674@smallexample
17675@group
17676(defun triangle-bugged (number)
17677 "Return sum of numbers 1 through NUMBER inclusive."
17678 (let ((total 0))
17679 (while (> number 0)
17680 (setq total (+ total number))
17681 (debug) ; @r{Start debugger.}
17682 (setq number (1= number))) ; @r{Error here.}
17683 total))
17684@end group
17685@end smallexample
17686
17687The @code{debug} function is described in detail in @ref{Debugger, ,
17688The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17689
17690@node edebug, Debugging Exercises, debug-on-quit, Debugging
17691@section The @code{edebug} Source Level Debugger
17692@cindex Source level debugger
17693@findex edebug
17694
17695Edebug is a source level debugger. Edebug normally displays the
17696source of the code you are debugging, with an arrow at the left that
17697shows which line you are currently executing.
17698
17699You can walk through the execution of a function, line by line, or run
17700quickly until reaching a @dfn{breakpoint} where execution stops.
17701
17702Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17703Lisp Reference Manual}.
17704
c6f54b06 17705@need 1250
8b096dce
EZ
17706Here is a bugged function definition for @code{triangle-recursively}.
17707@xref{Recursive triangle function, , Recursion in place of a counter},
17708for a review of it.
17709
17710@smallexample
17711@group
17712(defun triangle-recursively-bugged (number)
17713 "Return sum of numbers 1 through NUMBER inclusive.
17714Uses recursion."
17715 (if (= number 1)
17716 1
17717 (+ number
17718 (triangle-recursively-bugged
17719 (1= number))))) ; @r{Error here.}
17720@end group
17721@end smallexample
17722
17723@noindent
17724Normally, you would install this definition by positioning your cursor
17725after the function's closing parenthesis and typing @kbd{C-x C-e}
17726(@code{eval-last-sexp}) or else by positioning your cursor within the
17727definition and typing @kbd{C-M-x} (@code{eval-defun}). (By default,
17728the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17729Interactive mode.)
17730
17731@need 1500
17732However, to prepare this function definition for Edebug, you must
17733first @dfn{instrument} the code using a different command. You can do
17734this by positioning your cursor within the definition and typing
17735
17736@smallexample
17737M-x edebug-defun RET
17738@end smallexample
17739
17740@noindent
17741This will cause Emacs to load Edebug automatically if it is not
17742already loaded, and properly instrument the function.
17743
17744After instrumenting the function, place your cursor after the
17745following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17746
17747@smallexample
17748(triangle-recursively-bugged 3)
17749@end smallexample
17750
17751@noindent
17752You will be jumped back to the source for
17753@code{triangle-recursively-bugged} and the cursor positioned at the
17754beginning of the @code{if} line of the function. Also, you will see
17755an arrowhead at the left hand side of that line. The arrowhead marks
17756the line where the function is executing. (In the following examples,
17757we show the arrowhead with @samp{=>}; in a windowing system, you may
17758see the arrowhead as a solid triangle in the window `fringe'.)
17759
17760@smallexample
17761=>@point{}(if (= number 1)
17762@end smallexample
17763
17764@noindent
17765@iftex
17766In the example, the location of point is displayed with a star,
17767@samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17768@end iftex
17769@ifnottex
17770In the example, the location of point is displayed as @samp{@point{}}
17771(in a printed book, it is displayed with a five pointed star).
17772@end ifnottex
17773
17774If you now press @key{SPC}, point will move to the next expression to
17775be executed; the line will look like this:
17776
17777@smallexample
17778=>(if @point{}(= number 1)
17779@end smallexample
17780
17781@noindent
17782As you continue to press @key{SPC}, point will move from expression to
17783expression. At the same time, whenever an expression returns a value,
17784that value will be displayed in the echo area. For example, after you
17785move point past @code{number}, you will see the following:
17786
17787@smallexample
17788Result: 3 = C-c
17789@end smallexample
17790
17791@noindent
17792This means the value of @code{number} is 3, which is @sc{ascii}
c6f54b06
RC
17793`control-c' (the third letter of the alphabet, in case you need to
17794know this information).
8b096dce
EZ
17795
17796You can continue moving through the code until you reach the line with
17797the error. Before evaluation, that line looks like this:
17798
17799@smallexample
17800=> @point{}(1= number))))) ; @r{Error here.}
17801@end smallexample
17802
17803@need 1250
17804@noindent
17805When you press @key{SPC} once again, you will produce an error message
17806that says:
17807
17808@smallexample
17809Symbol's function definition is void:@: 1=
17810@end smallexample
17811
17812@noindent
17813This is the bug.
17814
17815Press @kbd{q} to quit Edebug.
17816
17817To remove instrumentation from a function definition, simply
17818re-evaluate it with a command that does not instrument it.
17819For example, you could place your cursor after the definition's
17820closing parenthesis and type @kbd{C-x C-e}.
17821
17822Edebug does a great deal more than walk with you through a function.
17823You can set it so it races through on its own, stopping only at an
17824error or at specified stopping points; you can cause it to display the
17825changing values of various expressions; you can find out how many
17826times a function is called, and more.
17827
17828Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17829Lisp Reference Manual}.
17830
17831@need 1500
17832@node Debugging Exercises, , edebug, Debugging
17833@section Debugging Exercises
17834
17835@itemize @bullet
17836@item
17837Install the @code{count-words-region} function and then cause it to
17838enter the built-in debugger when you call it. Run the command on a
17839region containing two words. You will need to press @kbd{d} a
17840remarkable number of times. On your system, is a `hook' called after
17841the command finishes? (For information on hooks, see @ref{Command
17842Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17843Manual}.)
17844
17845@item
17846Copy @code{count-words-region} into the @file{*scratch*} buffer,
17847instrument the function for Edebug, and walk through its execution.
17848The function does not need to have a bug, although you can introduce
17849one if you wish. If the function lacks a bug, the walk-through
17850completes without problems.
17851
17852@item
17853While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17854(The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17855@kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17856for commands made outside of the Edebug debugging buffer.)
17857
17858@item
17859In the Edebug debugging buffer, use the @kbd{p}
17860(@code{edebug-bounce-point}) command to see where in the region the
17861@code{count-words-region} is working.
17862
17863@item
17864Move point to some spot further down function and then type the
17865@kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17866
17867@item
17868Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17869walk through the function on its own; use an upper case @kbd{T} for
17870@code{edebug-Trace-fast-mode}.
17871
17872@item
17873Set a breakpoint, then run Edebug in Trace mode until it reaches the
17874stopping point.
17875@end itemize
17876
17877@node Conclusion, the-the, Debugging, Top
17878@chapter Conclusion
17879
17880We have now reached the end of this Introduction. You have now
17881learned enough about programming in Emacs Lisp to set values, to write
17882simple @file{.emacs} files for yourself and your friends, and write
17883simple customizations and extensions to Emacs.
17884
17885This is a place to stop. Or, if you wish, you can now go onward, and
17886teach yourself.
17887
17888You have learned some of the basic nuts and bolts of programming. But
17889only some. There are a great many more brackets and hinges that are
17890easy to use that we have not touched.
17891
17892A path you can follow right now lies among the sources to GNU Emacs
17893and in
17894@ifnotinfo
17895@cite{The GNU Emacs Lisp Reference Manual}.
17896@end ifnotinfo
17897@ifinfo
17898@ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17899Emacs Lisp Reference Manual}.
17900@end ifinfo
17901
17902The Emacs Lisp sources are an adventure. When you read the sources and
17903come across a function or expression that is unfamiliar, you need to
17904figure out or find out what it does.
17905
17906Go to the Reference Manual. It is a thorough, complete, and fairly
17907easy-to-read description of Emacs Lisp. It is written not only for
17908experts, but for people who know what you know. (The @cite{Reference
17909Manual} comes with the standard GNU Emacs distribution. Like this
17910introduction, it comes as a Texinfo source file, so you can read it
17911on-line and as a typeset, printed book.)
17912
17913Go to the other on-line help that is part of GNU Emacs: the on-line
17914documentation for all functions, and @code{find-tags}, the program
17915that takes you to sources.
17916
17917Here is an example of how I explore the sources. Because of its name,
17918@file{simple.el} is the file I looked at first, a long time ago. As
17919it happens some of the functions in @file{simple.el} are complicated,
17920or at least look complicated at first sight. The @code{open-line}
17921function, for example, looks complicated.
17922
17923You may want to walk through this function slowly, as we did with the
17924@code{forward-sentence} function.
17925@ifnottex
17926(@xref{forward-sentence}.)
17927@end ifnottex
17928@iftex
17929(@xref{forward-sentence, , @code{forward-sentence}}.)
17930@end iftex
17931Or you may want to skip that function and look at another, such as
17932@code{split-line}. You don't need to read all the functions.
17933According to @code{count-words-in-defun}, the @code{split-line}
17934function contains 27 words and symbols.
17935
17936Even though it is short, @code{split-line} contains four expressions
17937we have not studied: @code{skip-chars-forward}, @code{indent-to},
17938@code{current-column} and @samp{?\n}.
17939
17940Consider the @code{skip-chars-forward} function. (It is part of the
17941function definition for @code{back-to-indentation}, which is shown in
17942@ref{Review, , Review}.)
17943
17944In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17945typing @kbd{C-h f} (@code{describe-function}) and the name of the
17946function. This gives you the function documentation.
17947
17948You may be able to guess what is done by a well named function such as
17949@code{indent-to}; or you can look it up, too. Incidentally, the
17950@code{describe-function} function itself is in @file{help.el}; it is
17951one of those long, but decipherable functions. You can look up
17952@code{describe-function} using the @kbd{C-h f} command!
17953
17954In this instance, since the code is Lisp, the @file{*Help*} buffer
17955contains the name of the library containing the function's source.
17956You can put point over the name of the library and press the RET key,
17957which in this situation is bound to @code{help-follow}, and be taken
17958directly to the source, in the same way as @kbd{M-.}
17959(@code{find-tag}).
17960
17961The definition for @code{describe-function} illustrates how to
17962customize the @code{interactive} expression without using the standard
17963character codes; and it shows how to create a temporary buffer.
17964
17965(The @code{indent-to} function is written in C rather than Emacs Lisp;
17966it is a `built-in' function. @code{help-follow} only provides you
17967with the documentation of a built-in function; it does not take you to
17968the source. But @code{find-tag} will take you to the source, if
17969properly set up.)
17970
17971You can look at a function's source using @code{find-tag}, which is
17972bound to @kbd{M-.} Finally, you can find out what the Reference
17973Manual has to say by visiting the manual in Info, and typing @kbd{i}
17974(@code{Info-index}) and the name of the function, or by looking up
17975@code{skip-chars-forward} in the index to a printed copy of the
17976manual.
17977
17978Similarly, you can find out what is meant by @samp{?\n}. You can try
17979using @code{Info-index} with @samp{?\n}. It turns out that this
17980action won't help; but don't give up. If you search the index for
17981@samp{\n} without the @samp{?}, you will be taken directly to the
17982relevant section of the manual. (@xref{Character Type, , Character
17983Type, elisp, The GNU Emacs Lisp Reference Manual}. @samp{?\n} stands
17984for the newline character.)
17985
17986Other interesting source files include @file{paragraphs.el},
17987@file{loaddefs.el}, and @file{loadup.el}. The @file{paragraphs.el}
17988file includes short, easily understood functions as well as longer
17989ones. The @file{loaddefs.el} file contains the many standard
17990autoloads and many keymaps. I have never looked at it all; only at
17991parts. @file{loadup.el} is the file that loads the standard parts of
17992Emacs; it tells you a great deal about how Emacs is built.
17993(@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17994Reference Manual}, for more about building.)
17995
17996As I said, you have learned some nuts and bolts; however, and very
17997importantly, we have hardly touched major aspects of programming; I
17998have said nothing about how to sort information, except to use the
17999predefined @code{sort} function; I have said nothing about how to store
18000information, except to use variables and lists; I have said nothing
18001about how to write programs that write programs. These are topics for
18002another, and different kind of book, a different kind of learning.
18003
18004What you have done is learn enough for much practical work with GNU
18005Emacs. What you have done is get started. This is the end of a
18006beginning.
18007
18008@c ================ Appendix ================
18009
18010@node the-the, Kill Ring, Conclusion, Top
18011@appendix The @code{the-the} Function
18012@findex the-the
18013@cindex Duplicated words function
18014@cindex Words, duplicated
18015
18016Sometimes when you you write text, you duplicate words---as with ``you
18017you'' near the beginning of this sentence. I find that most
18018frequently, I duplicate ``the'; hence, I call the function for
18019detecting duplicated words, @code{the-the}.
18020
18021@need 1250
18022As a first step, you could use the following regular expression to
18023search for duplicates:
18024
18025@smallexample
18026\\(\\w+[ \t\n]+\\)\\1
18027@end smallexample
18028
18029@noindent
18030This regexp matches one or more word-constituent characters followed
18031by one or more spaces, tabs, or newlines. However, it does not detect
18032duplicated words on different lines, since the ending of the first
18033word, the end of the line, is different from the ending of the second
18034word, a space. (For more information about regular expressions, see
18035@ref{Regexp Search, , Regular Expression Searches}, as well as
18036@ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18037Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18038The GNU Emacs Lisp Reference Manual}.)
18039
18040You might try searching just for duplicated word-constituent
18041characters but that does not work since the pattern detects doubles
18042such as the two occurrences of `th' in `with the'.
18043
18044Another possible regexp searches for word-constituent characters
18045followed by non-word-constituent characters, reduplicated. Here,
18046@w{@samp{\\w+}} matches one or more word-constituent characters and
18047@w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18048
18049@smallexample
18050\\(\\(\\w+\\)\\W*\\)\\1
18051@end smallexample
18052
18053@noindent
18054Again, not useful.
18055
18056Here is the pattern that I use. It is not perfect, but good enough.
18057@w{@samp{\\b}} matches the empty string, provided it is at the beginning
18058or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18059any characters that are @emph{not} an @@-sign, space, newline, or tab.
18060
18061@smallexample
18062\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18063@end smallexample
18064
18065One can write more complicated expressions, but I found that this
18066expression is good enough, so I use it.
18067
18068Here is the @code{the-the} function, as I include it in my
18069@file{.emacs} file, along with a handy global key binding:
18070
18071@smallexample
18072@group
18073(defun the-the ()
18074 "Search forward for for a duplicated word."
18075 (interactive)
18076 (message "Searching for for duplicated words ...")
18077 (push-mark)
18078@end group
18079@group
18080 ;; This regexp is not perfect
18081 ;; but is fairly good over all:
18082 (if (re-search-forward
18083 "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
18084 (message "Found duplicated word.")
18085 (message "End of buffer")))
18086@end group
18087
18088@group
18089;; Bind `the-the' to C-c \
18090(global-set-key "\C-c\\" 'the-the)
18091@end group
18092@end smallexample
18093
18094@sp 1
18095Here is test text:
18096
18097@smallexample
18098@group
18099one two two three four five
18100five six seven
18101@end group
18102@end smallexample
18103
18104You can substitute the other regular expressions shown above in the
18105function definition and try each of them on this list.
18106
18107@node Kill Ring, Full Graph, the-the, Top
18108@appendix Handling the Kill Ring
18109@cindex Kill ring handling
18110@cindex Handling the kill ring
18111@cindex Ring, making a list like a
18112
18113The kill ring is a list that is transformed into a ring by the
18114workings of the @code{rotate-yank-pointer} function. The @code{yank}
18115and @code{yank-pop} commands use the @code{rotate-yank-pointer}
18116function. This appendix describes the @code{rotate-yank-pointer}
18117function as well as both the @code{yank} and the @code{yank-pop}
18118commands.
18119
18120@menu
18121* rotate-yank-pointer:: Move a pointer along a list and around.
18122* yank:: Paste a copy of a clipped element.
18123* yank-pop:: Insert first element pointed to.
c6f54b06 18124* ring file::
8b096dce
EZ
18125@end menu
18126
18127@node rotate-yank-pointer, yank, Kill Ring, Kill Ring
18128@comment node-name, next, previous, up
18129@appendixsec The @code{rotate-yank-pointer} Function
18130@findex rotate-yank-pointer
18131
18132The @code{rotate-yank-pointer} function changes the element in the kill
18133ring to which @code{kill-ring-yank-pointer} points. For example, it can
18134change @code{kill-ring-yank-pointer} from pointing to the second
18135element to point to the third element.
18136
18137@need 800
18138Here is the code for @code{rotate-yank-pointer}:
18139
18140@smallexample
18141@group
18142(defun rotate-yank-pointer (arg)
18143 "Rotate the yanking point in the kill ring."
18144 (interactive "p")
18145 (let ((length (length kill-ring)))
18146@end group
18147@group
18148 (if (zerop length)
18149 ;; @r{then-part}
18150 (error "Kill ring is empty")
18151@end group
18152@group
18153 ;; @r{else-part}
18154 (setq kill-ring-yank-pointer
18155 (nthcdr (% (+ arg
18156 (- length
18157 (length
18158 kill-ring-yank-pointer)))
18159 length)
18160 kill-ring)))))
18161@end group
18162@end smallexample
18163
18164@menu
18165* Understanding rotate-yk-ptr::
18166* rotate-yk-ptr body:: The body of @code{rotate-yank-pointer}.
18167@end menu
18168
18169@node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18170@ifnottex
18171@unnumberedsubsec @code{rotate-yank-pointer} in Outline
18172@end ifnottex
18173
18174The @code{rotate-yank-pointer} function looks complex, but as usual,
18175it can be understood by taking it apart piece by piece. First look at
18176it in skeletal form:
18177
18178@smallexample
18179@group
18180(defun rotate-yank-pointer (arg)
18181 "Rotate the yanking point in the kill ring."
18182 (interactive "p")
18183 (let @var{varlist}
18184 @var{body}@dots{})
18185@end group
18186@end smallexample
18187
18188This function takes one argument, called @code{arg}. It has a brief
18189documentation string; and it is interactive with a small @samp{p}, which
18190means that the argument must be a processed prefix passed to the
18191function as a number.
18192
18193The body of the function definition is a @code{let} expression, which
18194itself has a body as well as a @var{varlist}.
18195
18196The @code{let} expression declares a variable that will be only usable
18197within the bounds of this function. This variable is called
18198@code{length} and is bound to a value that is equal to the number of
18199items in the kill ring. This is done by using the function called
18200@code{length}. (Note that this function has the same name as the
18201variable called @code{length}; but one use of the word is to name the
18202function and the other is to name the variable. The two are quite
18203distinct. Similarly, an English speaker will distinguish between the
18204meanings of the word @samp{ship} when he says: "I must ship this package
18205immediately." and "I must get aboard the ship immediately.")
18206
18207The function @code{length} tells the number of items there are in a list,
18208so @code{(length kill-ring)} returns the number of items there are in the
18209kill ring.
18210
18211@node rotate-yk-ptr body, , Understanding rotate-yk-ptr, rotate-yank-pointer
18212@comment node-name, next, previous, up
18213@appendixsubsec The Body of @code{rotate-yank-pointer}
18214
18215The body of @code{rotate-yank-pointer} is a @code{let} expression and
18216the body of the @code{let} expression is an @code{if} expression.
18217
18218The purpose of the @code{if} expression is to find out whether there is
18219anything in the kill ring. If the kill ring is empty, the @code{error}
18220function stops evaluation of the function and prints a message in the
18221echo area. On the other hand, if the kill ring has something in it, the
18222work of the function is done.
18223
18224Here is the if-part and then-part of the @code{if} expression:
18225
18226@findex zerop
18227@findex error
18228@smallexample
18229@group
18230(if (zerop length) ; @r{if-part}
18231 (error "Kill ring is empty") ; @r{then-part}
18232 @dots{}
18233@end group
18234@end smallexample
18235
18236@noindent
18237If there is not anything in the kill ring, its length must be zero and
18238an error message sent to the user: @samp{Kill ring is empty}. The
18239@code{if} expression uses the function @code{zerop} which returns true
18240if the value it is testing is zero. When @code{zerop} tests true, the
18241then-part of the @code{if} is evaluated. The then-part is a list
18242starting with the function @code{error}, which is a function that is
18243similar to the @code{message} function (@pxref{message}), in that it
18244prints a one-line message in the echo area. However, in addition to
18245printing a message, @code{error} also stops evaluation of the function
18246within which it is embedded. This means that the rest of the function
18247will not be evaluated if the length of the kill ring is zero.
18248
18249@menu
18250* Digression concerning error:: How to mislead humans, but not computers.
18251* rotate-yk-ptr else-part:: The else-part of the @code{if} expression.
18252* Remainder Function:: The remainder, @code{%}, function.
18253* rotate-yk-ptr remainder:: Using @code{%} in @code{rotate-yank-pointer}.
18254* kill-rng-yk-ptr last elt:: Pointing to the last element.
18255@end menu
18256
18257@node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18258@ifnottex
18259@unnumberedsubsubsec Digression about the word `error'
18260@end ifnottex
18261
18262(In my opinion, it is slightly misleading, at least to humans, to use
18263the term `error' as the name of the @code{error} function. A better
18264term would be `cancel'. Strictly speaking, of course, you cannot
18265point to, much less rotate a pointer to a list that has no length, so
18266from the point of view of the computer, the word `error' is correct.
18267But a human expects to attempt this sort of thing, if only to find out
18268whether the kill ring is full or empty. This is an act of
18269exploration.
18270
18271(From the human point of view, the act of exploration and discovery is
18272not necessarily an error, and therefore should not be labelled as one,
18273even in the bowels of a computer. As it is, the code in Emacs implies
18274that a human who is acting virtuously, by exploring his or her
18275environment, is making an error. This is bad. Even though the computer
18276takes the same steps as it does when there is an `error', a term such as
18277`cancel' would have a clearer connotation.)
18278
18279@node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18280@unnumberedsubsubsec The else-part of the @code{if} expression
18281
18282The else-part of the @code{if} expression is dedicated to setting the
18283value of @code{kill-ring-yank-pointer} when the kill ring has something
18284in it. The code looks like this:
18285
18286@smallexample
18287@group
18288(setq kill-ring-yank-pointer
18289 (nthcdr (% (+ arg
18290 (- length
18291 (length kill-ring-yank-pointer)))
18292 length)
18293 kill-ring)))))
18294@end group
18295@end smallexample
18296
18297This needs some examination. Clearly, @code{kill-ring-yank-pointer}
18298is being set to be equal to some @sc{cdr} of the kill ring, using the
18299@code{nthcdr} function that is described in an earlier section.
18300(@xref{copy-region-as-kill}.) But exactly how does it do this?
18301
18302Before looking at the details of the code let's first consider the
18303purpose of the @code{rotate-yank-pointer} function.
18304
18305The @code{rotate-yank-pointer} function changes what
18306@code{kill-ring-yank-pointer} points to. If
18307@code{kill-ring-yank-pointer} starts by pointing to the first element
18308of a list, a call to @code{rotate-yank-pointer} causes it to point to
18309the second element; and if @code{kill-ring-yank-pointer} points to the
18310second element, a call to @code{rotate-yank-pointer} causes it to
18311point to the third element. (And if @code{rotate-yank-pointer} is
18312given an argument greater than 1, it jumps the pointer that many
18313elements.)
18314
18315The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18316the @code{kill-ring-yank-pointer} points to. If
18317@code{kill-ring-yank-pointer} points to the first element of the kill
18318ring, then, in the simplest case, the @code{rotate-yank-pointer}
18319function must cause it to point to the second element. Put another
18320way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18321to the @sc{cdr} of the kill ring.
18322
18323@need 1250
18324That is, under these circumstances,
18325
18326@smallexample
18327@group
18328(setq kill-ring-yank-pointer
18329 ("some text" "a different piece of text" "yet more text"))
18330
18331(setq kill-ring
18332 ("some text" "a different piece of text" "yet more text"))
18333@end group
18334@end smallexample
18335
18336@need 800
18337@noindent
18338the code should do this:
18339
18340@smallexample
18341(setq kill-ring-yank-pointer (cdr kill-ring))
18342@end smallexample
18343
18344@need 1000
18345@noindent
18346As a result, the @code{kill-ring-yank-pointer} will look like this:
18347
18348@smallexample
18349@group
18350kill-ring-yank-pointer
18351 @result{} ("a different piece of text" "yet more text"))
18352@end group
18353@end smallexample
18354
18355The actual @code{setq} expression uses the @code{nthcdr} function to do
18356the job.
18357
18358As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18359works by repeatedly taking the @sc{cdr} of a list---it takes the
18360@sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18361
18362@need 800
18363The two following expressions produce the same result:
18364
18365@smallexample
18366@group
18367(setq kill-ring-yank-pointer (cdr kill-ring))
18368
18369(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18370@end group
18371@end smallexample
18372
18373In the @code{rotate-yank-pointer} function, however, the first
18374argument to @code{nthcdr} is a rather complex looking expression with
18375lots of arithmetic inside of it:
18376
18377@smallexample
18378@group
18379(% (+ arg
18380 (- length
18381 (length kill-ring-yank-pointer)))
18382 length)
18383@end group
18384@end smallexample
18385
18386As usual, we need to look at the most deeply embedded expression first
18387and then work our way towards the light.
18388
18389The most deeply embedded expression is @code{(length
18390kill-ring-yank-pointer)}. This finds the length of the current value of
18391the @code{kill-ring-yank-pointer}. (Remember that the
18392@code{kill-ring-yank-pointer} is the name of a variable whose value is a
18393list.)
18394
18395@need 800
18396The measurement of the length is inside the expression:
18397
18398@smallexample
18399(- length (length kill-ring-yank-pointer))
18400@end smallexample
18401
18402@noindent
18403In this expression, the first @code{length} is the variable that was
18404assigned the length of the kill ring in the @code{let} statement at the
18405beginning of the function. (One might think this function would be
18406clearer if the variable @code{length} were named
18407@code{length-of-kill-ring} instead; but if you look at the text of the
18408whole function, you will see that it is so short that naming this
18409variable @code{length} is not a bother, unless you are pulling the
18410function apart into very tiny pieces as we are doing here.)
18411
18412So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18413difference between the length of the kill ring and the length of the list
18414whose name is @code{kill-ring-yank-pointer}.
18415
18416To see how all this fits into the @code{rotate-yank-pointer}
18417function, let's begin by analyzing the case where
18418@code{kill-ring-yank-pointer} points to the first element of the kill
18419ring, just as @code{kill-ring} does, and see what happens when
18420@code{rotate-yank-pointer} is called with an argument of 1.
18421
18422The variable @code{length} and the value of the expression
18423@code{(length kill-ring-yank-pointer)} will be the same since the
18424variable @code{length} is the length of the kill ring and the
18425@code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18426Consequently, the value of
18427
18428@smallexample
18429(- length (length kill-ring-yank-pointer))
18430@end smallexample
18431
18432@noindent
18433will be zero. Since the value of @code{arg} will be 1, this will mean
18434that the value of the whole expression
18435
18436@smallexample
18437(+ arg (- length (length kill-ring-yank-pointer)))
18438@end smallexample
18439
18440@noindent
18441will be 1.
18442
c6f54b06 18443@need 1200
8b096dce
EZ
18444Consequently, the argument to @code{nthcdr} will be found as the result of
18445the expression
18446
18447@smallexample
18448(% 1 length)
18449@end smallexample
18450
18451@node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18452@unnumberedsubsubsec The @code{%} remainder function
18453
18454To understand @code{(% 1 length)}, we need to understand @code{%}.
18455According to its documentation (which I just found by typing @kbd{C-h
18456f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18457its first argument divided by its second argument. For example, the
18458remainder of 5 divided by 2 is 1. (2 goes into 5 twice with a
18459remainder of 1.)
18460
18461What surprises people who don't often do arithmetic is that a smaller
18462number can be divided by a larger number and have a remainder. In the
18463example we just used, 5 was divided by 2. We can reverse that and ask,
18464what is the result of dividing 2 by 5? If you can use fractions, the
18465answer is obviously 2/5 or .4; but if, as here, you can only use whole
18466numbers, the result has to be something different. Clearly, 5 can go into
184672 zero times, but what of the remainder? To see what the answer is,
18468consider a case that has to be familiar from childhood:
18469
18470@itemize @bullet
18471@item
184725 divided by 5 is 1 with a remainder of 0;
18473
18474@item
184756 divided by 5 is 1 with a remainder of 1;
18476
18477@item
184787 divided by 5 is 1 with a remainder of 2.
18479
18480@item
18481Similarly, 10 divided by 5 is 2 with a remainder of 0;
18482
18483@item
1848411 divided by 5 is 2 with a remainder of 1;
18485
18486@item
1848712 divided by 5 is 1 with a remainder of 2.
18488@end itemize
18489
18490@need 1250
18491@noindent
18492By considering the cases as parallel, we can see that
18493
18494@itemize @bullet
18495@item
18496zero divided by 5 must be zero with a remainder of zero;
18497
18498@item
184991 divided by 5 must be zero with a remainder of 1;
18500
18501@item
185022 divided by 5 must be zero with a remainder of 2;
18503@end itemize
18504
18505@noindent
18506and so on.
18507
18508@need 1250
18509So, in this code, if the value of @code{length} is 5, then the result of
18510evaluating
18511
18512@smallexample
18513(% 1 5)
18514@end smallexample
18515
18516@noindent
18517is 1. (I just checked this by placing the cursor after the expression
18518and typing @kbd{C-x C-e}. Indeed, 1 is printed in the echo area.)
18519
c6f54b06 18520@need 2000
8b096dce
EZ
18521@node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18522@unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18523
18524When the @code{kill-ring-yank-pointer} points to the
18525beginning of the kill ring, and the argument passed to
18526@code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18527
18528@smallexample
18529@group
18530(- length (length kill-ring-yank-pointer))
18531 @result{} 0
18532@end group
18533@end smallexample
18534
18535@need 1250
18536@noindent
18537therefore,
18538
18539@smallexample
18540@group
18541(+ arg (- length (length kill-ring-yank-pointer)))
18542 @result{} 1
18543@end group
18544@end smallexample
18545
18546@need 1250
18547@noindent
18548and consequently:
18549
18550@smallexample
18551@group
18552(% (+ arg (- length (length kill-ring-yank-pointer)))
18553 length)
18554 @result{} 1
18555@end group
18556@end smallexample
18557
18558@noindent
18559regardless of the value of @code{length}.
18560
18561@need 1250
18562@noindent
18563As a result of this, the @code{setq kill-ring-yank-pointer} expression
18564simplifies to:
18565
18566@smallexample
18567(setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18568@end smallexample
18569
18570@noindent
18571What it does is now easy to understand. Instead of pointing as it did
18572to the first element of the kill ring, the
18573@code{kill-ring-yank-pointer} is set to point to the second element.
18574
18575Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18576the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18577and so on for different values of the argument.
18578
18579Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18580the second element of the kill ring, its length is shorter than the
18581length of the kill ring by 1, so the computation of the remainder is
18582based on the expression @code{(% (+ arg 1) length)}. This means that
18583the @code{kill-ring-yank-pointer} is moved from the second element of
18584the kill ring to the third element if the argument passed to
18585@code{rotate-yank-pointer} is 1.
18586
18587@node kill-rng-yk-ptr last elt, , rotate-yk-ptr remainder, rotate-yk-ptr body
18588@unnumberedsubsubsec Pointing to the last element
18589
18590The final question is, what happens if the @code{kill-ring-yank-pointer}
18591is set to the @emph{last} element of the kill ring? Will a call to
18592@code{rotate-yank-pointer} mean that nothing more can be taken from the
18593kill ring? The answer is no. What happens is different and useful.
18594The @code{kill-ring-yank-pointer} is set to point to the beginning of
18595the kill ring instead.
18596
18597Let's see how this works by looking at the code, assuming the length of the
18598kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18599When the @code{kill-ring-yank-pointer} points to the last element of
18600the kill ring, its length is 1. The code looks like this:
18601
18602@smallexample
18603(% (+ arg (- length (length kill-ring-yank-pointer))) length)
18604@end smallexample
18605
18606@need 1250
18607When the variables are replaced by their numeric values, the expression
18608looks like this:
18609
18610@smallexample
18611(% (+ 1 (- 5 1)) 5)
18612@end smallexample
18613
18614@noindent
18615This expression can be evaluated by looking at the most embedded inner
18616expression first and working outwards: The value of @code{(- 5 1)} is 4;
18617the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18618zero. So what @code{rotate-yank-pointer} will do is
18619
18620@smallexample
18621(setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18622@end smallexample
18623
18624@noindent
18625which will set the @code{kill-ring-yank-pointer} to point to the beginning
18626of the kill ring.
18627
18628So what happens with successive calls to @code{rotate-yank-pointer} is that
18629it moves the @code{kill-ring-yank-pointer} from element to element in the
18630kill ring until it reaches the end; then it jumps back to the beginning.
18631And this is why the kill ring is called a ring, since by jumping back to
18632the beginning, it is as if the list has no end! (And what is a ring, but
18633an entity with no end?)
18634
18635@node yank, yank-pop, rotate-yank-pointer, Kill Ring
18636@comment node-name, next, previous, up
18637@appendixsec @code{yank}
18638@findex yank
18639
18640After learning about @code{rotate-yank-pointer}, the code for the
18641@code{yank} function is almost easy. It has only one tricky part, which is
18642the computation of the argument to be passed to @code{rotate-yank-pointer}.
18643
18644@need 1250
18645The code looks like this:
18646
18647@smallexample
18648@group
18649(defun yank (&optional arg)
18650 "Reinsert the last stretch of killed text.
18651More precisely, reinsert the stretch of killed text most
18652recently killed OR yanked.
18653With just C-U as argument, same but put point in front
18654(and mark at end). With argument n, reinsert the nth
18655most recently killed stretch of killed text.
18656See also the command \\[yank-pop]."
18657@end group
18658@group
18659
18660 (interactive "*P")
18661 (rotate-yank-pointer (if (listp arg) 0
18662 (if (eq arg '-) -1
18663 (1- arg))))
18664 (push-mark (point))
18665 (insert (car kill-ring-yank-pointer))
18666 (if (consp arg)
18667 (exchange-point-and-mark)))
18668@end group
18669@end smallexample
18670
18671Glancing over this code, we can understand the last few lines readily
18672enough. The mark is pushed, that is, remembered; then the first element
18673(the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18674inserted; and then, if the argument passed the function is a
18675@code{cons}, point and mark are exchanged so the point is put in the
18676front of the inserted text rather than at the end. This option is
18677explained in the documentation. The function itself is interactive with
18678@code{"*P"}. This means it will not work on a read-only buffer, and that
18679the unprocessed prefix argument is passed to the function.
18680
18681@menu
18682* rotate-yk-ptr arg:: Pass the argument to @code{rotate-yank-pointer}.
18683* rotate-yk-ptr negative arg:: Pass a negative argument.
18684@end menu
18685
18686@node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18687@unnumberedsubsubsec Passing the argument
18688
18689The hard part of @code{yank} is understanding the computation that
18690determines the value of the argument passed to
18691@code{rotate-yank-pointer}. Fortunately, it is not so difficult as it
18692looks at first sight.
18693
18694What happens is that the result of evaluating one or both of the
18695@code{if} expressions will be a number and that number will be the
18696argument passed to @code{rotate-yank-pointer}.
18697
18698@need 1250
18699Laid out with comments, the code looks like this:
18700
18701@smallexample
18702@group
18703(if (listp arg) ; @r{if-part}
18704 0 ; @r{then-part}
18705 (if (eq arg '-) ; @r{else-part, inner if}
18706 -1 ; @r{inner if's then-part}
18707 (1- arg)))) ; @r{inner if's else-part}
18708@end group
18709@end smallexample
18710
18711@noindent
18712This code consists of two @code{if} expression, one the else-part of
18713the other.
18714
18715The first or outer @code{if} expression tests whether the argument
18716passed to @code{yank} is a list. Oddly enough, this will be true if
18717@code{yank} is called without an argument---because then it will be
18718passed the value of @code{nil} for the optional argument and an
18719evaluation of @code{(listp nil)} returns true! So, if no argument is
18720passed to @code{yank}, the argument passed to
18721@code{rotate-yank-pointer} inside of @code{yank} is zero. This means
18722the pointer is not moved and the first element to which
18723@code{kill-ring-yank-pointer} points is inserted, as we expect.
18724Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18725read as a list, so again, a zero will be passed to
18726@code{rotate-yank-pointer}. (@kbd{C-u} produces an unprocessed prefix
18727argument of @code{(4)}, which is a list of one element.) At the same
18728time, later in the function, this argument will be read as a
18729@code{cons} so point will be put in the front and mark at the end of
18730the insertion. (The @code{P} argument to @code{interactive} is
18731designed to provide these values for the case when an optional
18732argument is not provided or when it is @kbd{C-u}.)
18733
18734The then-part of the outer @code{if} expression handles the case when
18735there is no argument or when it is @kbd{C-u}. The else-part handles the
18736other situations. The else-part is itself another @code{if} expression.
18737
18738The inner @code{if} expression tests whether the argument is a minus
18739sign. (This is done by pressing the @key{META} and @kbd{-} keys at the
18740same time, or the @key{ESC} key and then the @kbd{-} key). In this
18741case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18742argument. This moves the @code{kill-ring-yank-pointer} backwards, which
18743is what is desired.
18744
18745If the true-or-false-test of the inner @code{if} expression is false
18746(that is, if the argument is not a minus sign), the else-part of the
18747expression is evaluated. This is the expression @code{(1- arg)}.
18748Because of the two @code{if} expressions, it will only occur when the
18749argument is a positive number or when it is a negative number (not
18750just a minus sign on its own). What @code{(1- arg)} does is decrement
18751the number and return it. (The @code{1-} function subtracts one from
18752its argument.) This means that if the argument to
18753@code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18754the first element to which @code{kill-ring-yank-pointer} points is
18755yanked back, as you would expect.
18756
18757@node rotate-yk-ptr negative arg, , rotate-yk-ptr arg, yank
18758@unnumberedsubsubsec Passing a negative argument
18759
18760Finally, the question arises, what happens if either the remainder
18761function, @code{%}, or the @code{nthcdr} function is passed a negative
18762argument, as they quite well may?
18763
18764The answers can be found by a quick test. When @code{(% -1 5)} is
18765evaluated, a negative number is returned; and if @code{nthcdr} is
18766called with a negative number, it returns the same value as if it were
e601d8fd 18767called with a first argument of zero. This can be seen by evaluating
8b096dce
EZ
18768the following code.
18769
18770Here the @samp{@result{}} points to the result of evaluating the code
18771preceding it. This was done by positioning the cursor after the code
18772and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18773You can do this if you are reading this in Info inside of GNU Emacs.
18774
18775@smallexample
18776@group
18777(% -1 5)
18778 @result{} -1
18779@end group
18780
18781@group
18782(setq animals '(cats dogs elephants))
18783 @result{} (cats dogs elephants)
18784@end group
18785
18786@group
18787(nthcdr 1 animals)
18788 @result{} (dogs elephants)
18789@end group
18790
18791@group
18792(nthcdr 0 animals)
18793 @result{} (cats dogs elephants)
18794@end group
18795
18796@group
18797(nthcdr -1 animals)
18798 @result{} (cats dogs elephants)
18799@end group
18800@end smallexample
18801
18802So, if a minus sign or a negative number is passed to @code{yank}, the
18803@code{kill-ring-yank-point} is rotated backwards until it reaches the
18804beginning of the list. Then it stays there. Unlike the other case,
18805when it jumps from the end of the list to the beginning of the list,
18806making a ring, it stops. This makes sense. You often want to get back
18807to the most recently clipped out piece of text, but you don't usually
18808want to insert text from as many as thirty kill commands ago. So you
18809need to work through the ring to get to the end, but won't cycle around
18810it inadvertently if you are trying to come back to the beginning.
18811
18812Incidentally, any number passed to @code{yank} with a minus sign
18813preceding it will be treated as @minus{}1. This is evidently a
18814simplification for writing the program. You don't need to jump back
18815towards the beginning of the kill ring more than one place at a time
18816and doing this is easier than writing a function to determine the
18817magnitude of the number that follows the minus sign.
18818
c6f54b06 18819@node yank-pop, ring file, yank, Kill Ring
8b096dce
EZ
18820@comment node-name, next, previous, up
18821@appendixsec @code{yank-pop}
18822@findex yank-pop
18823
18824After understanding @code{yank}, the @code{yank-pop} function is easy.
18825Leaving out the documentation to save space, it looks like this:
18826
18827@smallexample
18828@group
18829(defun yank-pop (arg)
18830 (interactive "*p")
18831 (if (not (eq last-command 'yank))
18832 (error "Previous command was not a yank"))
18833@end group
18834@group
18835 (setq this-command 'yank)
18836 (let ((before (< (point) (mark))))
18837 (delete-region (point) (mark))
18838 (rotate-yank-pointer arg)
18839@end group
18840@group
18841 (set-mark (point))
18842 (insert (car kill-ring-yank-pointer))
18843 (if before (exchange-point-and-mark))))
18844@end group
18845@end smallexample
18846
18847The function is interactive with a small @samp{p} so the prefix
18848argument is processed and passed to the function. The command can
18849only be used after a previous yank; otherwise an error message is
18850sent. This check uses the variable @code{last-command} which is
18851discussed elsewhere. (@xref{copy-region-as-kill}.)
18852
18853The @code{let} clause sets the variable @code{before} to true or false
18854depending whether point is before or after mark and then the region
18855between point and mark is deleted. This is the region that was just
18856inserted by the previous yank and it is this text that will be
18857replaced. Next the @code{kill-ring-yank-pointer} is rotated so that
18858the previously inserted text is not reinserted yet again. Mark is set
18859at the beginning of the place the new text will be inserted and then
18860the first element to which @code{kill-ring-yank-pointer} points is
18861inserted. This leaves point after the new text. If in the previous
18862yank, point was left before the inserted text, point and mark are now
18863exchanged so point is again left in front of the newly inserted text.
18864That is all there is to it!
18865
c6f54b06
RC
18866@node ring file, , yank-pop, Kill Ring
18867@comment node-name, next, previous, up
18868@appendixsec The @file{ring.el} File
18869@cindex @file{ring.el} file
18870
18871Interestingly, GNU Emacs posses a file called @file{ring.el} that
18872provides many of the features we just discussed. But functions such
18873as @code{kill-ring-yank-pointer} do not use this library, possibly
18874because they were written earlier.
18875
18876@node Full Graph, Free Software and Free Manuals, Kill Ring, Top
8b096dce
EZ
18877@appendix A Graph with Labelled Axes
18878
18879Printed axes help you understand a graph. They convey scale. In an
18880earlier chapter (@pxref{Readying a Graph, , Readying a Graph}), we
18881wrote the code to print the body of a graph. Here we write the code
18882for printing and labelling vertical and horizontal axes, along with the
18883body itself.
18884
18885@menu
18886* Labelled Example::
18887* print-graph Varlist:: @code{let} expression in @code{print-graph}.
18888* print-Y-axis:: Print a label for the vertical axis.
18889* print-X-axis:: Print a horizontal label.
18890* Print Whole Graph:: The function to print a complete graph.
18891@end menu
18892
18893@node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18894@ifnottex
18895@unnumberedsec Labelled Example Graph
18896@end ifnottex
18897
18898Since insertions fill a buffer to the right and below point, the new
18899graph printing function should first print the Y or vertical axis,
18900then the body of the graph, and finally the X or horizontal axis.
18901This sequence lays out for us the contents of the function:
18902
18903@enumerate
18904@item
18905Set up code.
18906
18907@item
18908Print Y axis.
18909
18910@item
18911Print body of graph.
18912
18913@item
18914Print X axis.
18915@end enumerate
18916
18917@need 800
18918Here is an example of how a finished graph should look:
18919
18920@smallexample
18921@group
18922 10 -
18923 *
18924 * *
18925 * **
18926 * ***
18927 5 - * *******
18928 * *** *******
18929 *************
18930 ***************
18931 1 - ****************
18932 | | | |
18933 1 5 10 15
18934@end group
18935@end smallexample
18936
18937@noindent
18938In this graph, both the vertical and the horizontal axes are labelled
18939with numbers. However, in some graphs, the horizontal axis is time
18940and would be better labelled with months, like this:
18941
18942@smallexample
18943@group
18944 5 - *
18945 * ** *
18946 *******
18947 ********** **
18948 1 - **************
18949 | ^ |
18950 Jan June Jan
18951@end group
18952@end smallexample
18953
18954Indeed, with a little thought, we can easily come up with a variety of
18955vertical and horizontal labelling schemes. Our task could become
18956complicated. But complications breed confusion. Rather than permit
18957this, it is better choose a simple labelling scheme for our first
18958effort, and to modify or replace it later.
18959
18960@need 1200
18961These considerations suggest the following outline for the
18962@code{print-graph} function:
18963
18964@smallexample
18965@group
18966(defun print-graph (numbers-list)
18967 "@var{documentation}@dots{}"
18968 (let ((height @dots{}
18969 @dots{}))
18970@end group
18971@group
18972 (print-Y-axis height @dots{} )
18973 (graph-body-print numbers-list)
18974 (print-X-axis @dots{} )))
18975@end group
18976@end smallexample
18977
18978We can work on each part of the @code{print-graph} function definition
18979in turn.
18980
18981@node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18982@comment node-name, next, previous, up
18983@appendixsec The @code{print-graph} Varlist
18984@cindex @code{print-graph} varlist
18985
18986In writing the @code{print-graph} function, the first task is to write
18987the varlist in the @code{let} expression. (We will leave aside for the
18988moment any thoughts about making the function interactive or about the
18989contents of its documentation string.)
18990
18991The varlist should set several values. Clearly, the top of the label
18992for the vertical axis must be at least the height of the graph, which
18993means that we must obtain this information here. Note that the
18994@code{print-graph-body} function also requires this information. There
18995is no reason to calculate the height of the graph in two different
18996places, so we should change @code{print-graph-body} from the way we
18997defined it earlier to take advantage of the calculation.
18998
18999Similarly, both the function for printing the X axis labels and the
19000@code{print-graph-body} function need to learn the value of the width of
19001each symbol. We can perform the calculation here and change the
19002definition for @code{print-graph-body} from the way we defined it in the
19003previous chapter.
19004
19005The length of the label for the horizontal axis must be at least as long
19006as the graph. However, this information is used only in the function
19007that prints the horizontal axis, so it does not need to be calculated here.
19008
19009These thoughts lead us directly to the following form for the varlist
19010in the @code{let} for @code{print-graph}:
19011
19012@smallexample
19013@group
19014(let ((height (apply 'max numbers-list)) ; @r{First version.}
19015 (symbol-width (length graph-blank)))
19016@end group
19017@end smallexample
19018
19019@noindent
19020As we shall see, this expression is not quite right.
19021
c6f54b06 19022@need 2000
8b096dce
EZ
19023@node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
19024@comment node-name, next, previous, up
19025@appendixsec The @code{print-Y-axis} Function
19026@cindex Axis, print vertical
19027@cindex Y axis printing
19028@cindex Vertical axis printing
19029@cindex Print vertical axis
19030
19031The job of the @code{print-Y-axis} function is to print a label for
19032the vertical axis that looks like this:
19033
19034@smallexample
19035@group
19036 10 -
19037
19038
19039
19040
19041 5 -
19042
19043
19044
19045 1 -
19046@end group
19047@end smallexample
19048
19049@noindent
19050The function should be passed the height of the graph, and then should
19051construct and insert the appropriate numbers and marks.
19052
19053It is easy enough to see in the figure what the Y axis label should
19054look like; but to say in words, and then to write a function
19055definition to do the job is another matter. It is not quite true to
19056say that we want a number and a tic every five lines: there are only
19057three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19058but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19059and 9). It is better to say that we want a number and a tic mark on
19060the base line (number 1) and then that we want a number and a tic on
19061the fifth line from the bottom and on every line that is a multiple of
19062five.
19063
19064@menu
19065* Height of label:: What height for the Y axis?
19066* Compute a Remainder:: How to compute the remainder of a division.
19067* Y Axis Element:: Construct a line for the Y axis.
19068* Y-axis-column:: Generate a list of Y axis labels.
19069* print-Y-axis Penultimate:: A not quite final version.
19070@end menu
19071
19072@node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
19073@ifnottex
19074@unnumberedsubsec What height should the label be?
19075@end ifnottex
19076
19077The next issue is what height the label should be? Suppose the maximum
19078height of tallest column of the graph is seven. Should the highest
19079label on the Y axis be @samp{5 -}, and should the graph stick up above
19080the label? Or should the highest label be @samp{7 -}, and mark the peak
19081of the graph? Or should the highest label be @code{10 -}, which is a
19082multiple of five, and be higher than the topmost value of the graph?
19083
19084The latter form is preferred. Most graphs are drawn within rectangles
19085whose sides are an integral number of steps long---5, 10, 15, and so
19086on for a step distance of five. But as soon as we decide to use a
19087step height for the vertical axis, we discover that the simple
19088expression in the varlist for computing the height is wrong. The
19089expression is @code{(apply 'max numbers-list)}. This returns the
19090precise height, not the maximum height plus whatever is necessary to
19091round up to the nearest multiple of five. A more complex expression
19092is required.
19093
19094As usual in cases like this, a complex problem becomes simpler if it is
19095divided into several smaller problems.
19096
19097First, consider the case when the highest value of the graph is an
c6f54b06 19098integral multiple of five---when it is 5, 10, 15, or some higher
8b096dce
EZ
19099multiple of five. We can use this value as the Y axis height.
19100
19101A fairly simply way to determine whether a number is a multiple of
19102five is to divide it by five and see if the division results in a
19103remainder. If there is no remainder, the number is a multiple of
19104five. Thus, seven divided by five has a remainder of two, and seven
19105is not an integral multiple of five. Put in slightly different
19106language, more reminiscent of the classroom, five goes into seven
19107once, with a remainder of two. However, five goes into ten twice,
19108with no remainder: ten is an integral multiple of five.
19109
19110@node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
19111@appendixsubsec Side Trip: Compute a Remainder
19112
19113@findex % @r{(remainder function)}
19114@cindex Remainder function, @code{%}
19115In Lisp, the function for computing a remainder is @code{%}. The
19116function returns the remainder of its first argument divided by its
19117second argument. As it happens, @code{%} is a function in Emacs Lisp
19118that you cannot discover using @code{apropos}: you find nothing if you
19119type @kbd{M-x apropos @key{RET} remainder @key{RET}}. The only way to
19120learn of the existence of @code{%} is to read about it in a book such
19121as this or in the Emacs Lisp sources. The @code{%} function is used
19122in the code for @code{rotate-yank-pointer}, which is described in an
19123appendix. (@xref{rotate-yk-ptr body, , The Body of
19124@code{rotate-yank-pointer}}.)
19125
19126You can try the @code{%} function by evaluating the following two
19127expressions:
19128
19129@smallexample
19130@group
19131(% 7 5)
19132
19133(% 10 5)
19134@end group
19135@end smallexample
19136
19137@noindent
19138The first expression returns 2 and the second expression returns 0.
19139
19140To test whether the returned value is zero or some other number, we
19141can use the @code{zerop} function. This function returns @code{t} if
19142its argument, which must be a number, is zero.
19143
19144@smallexample
19145@group
19146(zerop (% 7 5))
19147 @result{} nil
19148
19149(zerop (% 10 5))
19150 @result{} t
19151@end group
19152@end smallexample
19153
19154Thus, the following expression will return @code{t} if the height
19155of the graph is evenly divisible by five:
19156
19157@smallexample
19158(zerop (% height 5))
19159@end smallexample
19160
19161@noindent
19162(The value of @code{height}, of course, can be found from @code{(apply
19163'max numbers-list)}.)
19164
19165On the other hand, if the value of @code{height} is not a multiple of
19166five, we want to reset the value to the next higher multiple of five.
19167This is straightforward arithmetic using functions with which we are
19168already familiar. First, we divide the value of @code{height} by five
19169to determine how many times five goes into the number. Thus, five
19170goes into twelve twice. If we add one to this quotient and multiply by
19171five, we will obtain the value of the next multiple of five that is
19172larger than the height. Five goes into twelve twice. Add one to two,
19173and multiply by five; the result is fifteen, which is the next multiple
19174of five that is higher than twelve. The Lisp expression for this is:
19175
19176@smallexample
19177(* (1+ (/ height 5)) 5)
19178@end smallexample
19179
19180@noindent
19181For example, if you evaluate the following, the result is 15:
19182
19183@smallexample
19184(* (1+ (/ 12 5)) 5)
19185@end smallexample
19186
19187All through this discussion, we have been using `five' as the value
19188for spacing labels on the Y axis; but we may want to use some other
19189value. For generality, we should replace `five' with a variable to
19190which we can assign a value. The best name I can think of for this
19191variable is @code{Y-axis-label-spacing}.
19192
19193@need 1250
19194Using this term, and an @code{if} expression, we produce the
19195following:
19196
19197@smallexample
19198@group
19199(if (zerop (% height Y-axis-label-spacing))
19200 height
19201 ;; @r{else}
19202 (* (1+ (/ height Y-axis-label-spacing))
19203 Y-axis-label-spacing))
19204@end group
19205@end smallexample
19206
19207@noindent
19208This expression returns the value of @code{height} itself if the height
19209is an even multiple of the value of the @code{Y-axis-label-spacing} or
19210else it computes and returns a value of @code{height} that is equal to
19211the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19212
19213We can now include this expression in the @code{let} expression of the
19214@code{print-graph} function (after first setting the value of
19215@code{Y-axis-label-spacing}):
19216@vindex Y-axis-label-spacing
19217
19218@smallexample
19219@group
19220(defvar Y-axis-label-spacing 5
19221 "Number of lines from one Y axis label to next.")
19222@end group
19223
19224@group
19225@dots{}
19226(let* ((height (apply 'max numbers-list))
19227 (height-of-top-line
19228 (if (zerop (% height Y-axis-label-spacing))
19229 height
19230@end group
19231@group
19232 ;; @r{else}
19233 (* (1+ (/ height Y-axis-label-spacing))
19234 Y-axis-label-spacing)))
19235 (symbol-width (length graph-blank))))
19236@dots{}
19237@end group
19238@end smallexample
19239
19240@noindent
19241(Note use of the @code{let*} function: the initial value of height is
19242computed once by the @code{(apply 'max numbers-list)} expression and
19243then the resulting value of @code{height} is used to compute its
19244final value. @xref{fwd-para let, , The @code{let*} expression}, for
19245more about @code{let*}.)
19246
19247@node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19248@appendixsubsec Construct a Y Axis Element
19249
19250When we print the vertical axis, we want to insert strings such as
19251@w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19252Moreover, we want the numbers and dashes to line up, so shorter
19253numbers must be padded with leading spaces. If some of the strings
19254use two digit numbers, the strings with single digit numbers must
19255include a leading blank space before the number.
19256
19257@findex number-to-string
19258To figure out the length of the number, the @code{length} function is
19259used. But the @code{length} function works only with a string, not with
19260a number. So the number has to be converted from being a number to
19261being a string. This is done with the @code{number-to-string} function.
19262For example,
19263
19264@smallexample
19265@group
19266(length (number-to-string 35))
19267 @result{} 2
19268
19269(length (number-to-string 100))
19270 @result{} 3
19271@end group
19272@end smallexample
19273
19274@noindent
19275(@code{number-to-string} is also called @code{int-to-string}; you will
19276see this alternative name in various sources.)
19277
19278In addition, in each label, each number is followed by a string such
19279as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19280This variable is defined with @code{defvar}:
19281
19282@vindex Y-axis-tic
19283@smallexample
19284@group
19285(defvar Y-axis-tic " - "
19286 "String that follows number in a Y axis label.")
19287@end group
19288@end smallexample
19289
19290The length of the Y label is the sum of the length of the Y axis tic
19291mark and the length of the number of the top of the graph.
19292
19293@smallexample
19294(length (concat (number-to-string height) Y-axis-tic)))
19295@end smallexample
19296
19297This value will be calculated by the @code{print-graph} function in
19298its varlist as @code{full-Y-label-width} and passed on. (Note that we
19299did not think to include this in the varlist when we first proposed it.)
19300
19301To make a complete vertical axis label, a tic mark is concatenated
19302with a number; and the two together may be preceded by one or more
19303spaces depending on how long the number is. The label consists of
19304three parts: the (optional) leading spaces, the number, and the tic
19305mark. The function is passed the value of the number for the specific
19306row, and the value of the width of the top line, which is calculated
19307(just once) by @code{print-graph}.
19308
19309@smallexample
19310@group
19311(defun Y-axis-element (number full-Y-label-width)
19312 "Construct a NUMBERed label element.
19313A numbered element looks like this ` 5 - ',
19314and is padded as needed so all line up with
19315the element for the largest number."
19316@end group
19317@group
19318 (let* ((leading-spaces
19319 (- full-Y-label-width
19320 (length
19321 (concat (number-to-string number)
19322 Y-axis-tic)))))
19323@end group
19324@group
19325 (concat
19326 (make-string leading-spaces ? )
19327 (number-to-string number)
19328 Y-axis-tic)))
19329@end group
19330@end smallexample
19331
19332The @code{Y-axis-element} function concatenates together the leading
19333spaces, if any; the number, as a string; and the tic mark.
19334
19335To figure out how many leading spaces the label will need, the
19336function subtracts the actual length of the label---the length of the
19337number plus the length of the tic mark---from the desired label width.
19338
19339@findex make-string
19340Blank spaces are inserted using the @code{make-string} function. This
19341function takes two arguments: the first tells it how long the string
19342will be and the second is a symbol for the character to insert, in a
19343special format. The format is a question mark followed by a blank
19344space, like this, @samp{? }. @xref{Character Type, , Character Type,
19345elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19346syntax for characters.
19347
19348The @code{number-to-string} function is used in the concatenation
19349expression, to convert the number to a string that is concatenated
19350with the leading spaces and the tic mark.
19351
19352@node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19353@appendixsubsec Create a Y Axis Column
19354
19355The preceding functions provide all the tools needed to construct a
19356function that generates a list of numbered and blank strings to insert
19357as the label for the vertical axis:
19358
19359@findex Y-axis-column
19360@smallexample
19361@group
19362(defun Y-axis-column (height width-of-label)
19363 "Construct list of Y axis labels and blank strings.
19364For HEIGHT of line above base and WIDTH-OF-LABEL."
19365 (let (Y-axis)
19366@group
19367@end group
19368 (while (> height 1)
19369 (if (zerop (% height Y-axis-label-spacing))
19370 ;; @r{Insert label.}
19371 (setq Y-axis
19372 (cons
19373 (Y-axis-element height width-of-label)
19374 Y-axis))
19375@group
19376@end group
19377 ;; @r{Else, insert blanks.}
19378 (setq Y-axis
19379 (cons
19380 (make-string width-of-label ? )
19381 Y-axis)))
19382 (setq height (1- height)))
19383 ;; @r{Insert base line.}
19384 (setq Y-axis
19385 (cons (Y-axis-element 1 width-of-label) Y-axis))
19386 (nreverse Y-axis)))
19387@end group
19388@end smallexample
19389
19390In this function, we start with the value of @code{height} and
19391repetitively subtract one from its value. After each subtraction, we
19392test to see whether the value is an integral multiple of the
19393@code{Y-axis-label-spacing}. If it is, we construct a numbered label
19394using the @code{Y-axis-element} function; if not, we construct a
19395blank label using the @code{make-string} function. The base line
19396consists of the number one followed by a tic mark.
19397
c6f54b06 19398@need 2000
8b096dce
EZ
19399@node print-Y-axis Penultimate, , Y-axis-column, print-Y-axis
19400@appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19401
19402The list constructed by the @code{Y-axis-column} function is passed to
19403the @code{print-Y-axis} function, which inserts the list as a column.
19404
19405@findex print-Y-axis
19406@smallexample
19407@group
19408(defun print-Y-axis (height full-Y-label-width)
19409 "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19410Height must be the maximum height of the graph.
19411Full width is the width of the highest label element."
19412;; Value of height and full-Y-label-width
19413;; are passed by `print-graph'.
19414@end group
19415@group
19416 (let ((start (point)))
19417 (insert-rectangle
19418 (Y-axis-column height full-Y-label-width))
19419 ;; @r{Place point ready for inserting graph.}
19420 (goto-char start)
19421 ;; @r{Move point forward by value of} full-Y-label-width
19422 (forward-char full-Y-label-width)))
19423@end group
19424@end smallexample
19425
19426The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19427insert the Y axis labels created by the @code{Y-axis-column} function.
19428In addition, it places point at the correct position for printing the body of
19429the graph.
19430
19431You can test @code{print-Y-axis}:
19432
19433@enumerate
19434@item
19435Install
19436
19437@smallexample
19438@group
19439Y-axis-label-spacing
19440Y-axis-tic
19441Y-axis-element
19442Y-axis-column
19443print-Y-axis
19444@end group
19445@end smallexample
19446
19447@item
19448Copy the following expression:
19449
19450@smallexample
19451(print-Y-axis 12 5)
19452@end smallexample
19453
19454@item
19455Switch to the @file{*scratch*} buffer and place the cursor where you
19456want the axis labels to start.
19457
19458@item
19459Type @kbd{M-:} (@code{eval-expression}).
19460
19461@item
19462Yank the @code{graph-body-print} expression into the minibuffer
19463with @kbd{C-y} (@code{yank)}.
19464
19465@item
19466Press @key{RET} to evaluate the expression.
19467@end enumerate
19468
19469Emacs will print labels vertically, the top one being
19470@w{@samp{10 -@w{ }}}. (The @code{print-graph} function
19471will pass the value of @code{height-of-top-line}, which
19472in this case would end up as 15.)
19473
c6f54b06 19474@need 2000
8b096dce
EZ
19475@node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19476@appendixsec The @code{print-X-axis} Function
19477@cindex Axis, print horizontal
19478@cindex X axis printing
19479@cindex Print horizontal axis
19480@cindex Horizontal axis printing
19481
19482X axis labels are much like Y axis labels, except that the tics are on a
19483line above the numbers. Labels should look like this:
19484
19485@smallexample
19486@group
19487 | | | |
19488 1 5 10 15
19489@end group
19490@end smallexample
19491
19492The first tic is under the first column of the graph and is preceded by
19493several blank spaces. These spaces provide room in rows above for the Y
19494axis labels. The second, third, fourth, and subsequent tics are all
19495spaced equally, according to the value of @code{X-axis-label-spacing}.
19496
19497The second row of the X axis consists of numbers, preceded by several
19498blank spaces and also separated according to the value of the variable
19499@code{X-axis-label-spacing}.
19500
19501The value of the variable @code{X-axis-label-spacing} should itself be
19502measured in units of @code{symbol-width}, since you may want to change
19503the width of the symbols that you are using to print the body of the
19504graph without changing the ways the graph is labelled.
19505
19506@menu
19507* Similarities differences:: Much like @code{print-Y-axis}, but not exactly.
19508* X Axis Tic Marks:: Create tic marks for the horizontal axis.
19509@end menu
19510
19511@node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19512@ifnottex
19513@unnumberedsubsec Similarities and differences
19514@end ifnottex
19515
19516The @code{print-X-axis} function is constructed in more or less the
19517same fashion as the @code{print-Y-axis} function except that it has
19518two lines: the line of tic marks and the numbers. We will write a
19519separate function to print each line and then combine them within the
19520@code{print-X-axis} function.
19521
19522This is a three step process:
19523
19524@enumerate
19525@item
19526Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19527
19528@item
19529Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19530
19531@item
19532Write a function to print both lines, the @code{print-X-axis} function,
19533using @code{print-X-axis-tic-line} and
19534@code{print-X-axis-numbered-line}.
19535@end enumerate
19536
19537@node X Axis Tic Marks, , Similarities differences, print-X-axis
19538@appendixsubsec X Axis Tic Marks
19539
19540The first function should print the X axis tic marks. We must specify
19541the tic marks themselves and their spacing:
19542
19543@smallexample
19544@group
19545(defvar X-axis-label-spacing
19546 (if (boundp 'graph-blank)
19547 (* 5 (length graph-blank)) 5)
19548 "Number of units from one X axis label to next.")
19549@end group
19550@end smallexample
19551
19552@noindent
19553(Note that the value of @code{graph-blank} is set by another
19554@code{defvar}. The @code{boundp} predicate checks whether it has
19555already been set; @code{boundp} returns @code{nil} if it has not.
19556If @code{graph-blank} were unbound and we did not use this conditional
19557construction, in GNU Emacs 21, we would enter the debugger and see an
19558error message saying
19559@samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19560
19561@need 1200
19562Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19563
19564@smallexample
19565@group
19566(defvar X-axis-tic-symbol "|"
19567 "String to insert to point to a column in X axis.")
19568@end group
19569@end smallexample
19570
19571@need 1250
19572The goal is to make a line that looks like this:
19573
19574@smallexample
19575 | | | |
19576@end smallexample
19577
19578The first tic is indented so that it is under the first column, which is
19579indented to provide space for the Y axis labels.
19580
19581A tic element consists of the blank spaces that stretch from one tic to
19582the next plus a tic symbol. The number of blanks is determined by the
19583width of the tic symbol and the @code{X-axis-label-spacing}.
19584
19585@need 1250
19586The code looks like this:
19587
19588@smallexample
19589@group
19590;;; X-axis-tic-element
19591@dots{}
19592(concat
19593 (make-string
19594 ;; @r{Make a string of blanks.}
19595 (- (* symbol-width X-axis-label-spacing)
19596 (length X-axis-tic-symbol))
19597 ? )
19598 ;; @r{Concatenate blanks with tic symbol.}
19599 X-axis-tic-symbol)
19600@dots{}
19601@end group
19602@end smallexample
19603
19604Next, we determine how many blanks are needed to indent the first tic
19605mark to the first column of the graph. This uses the value of
19606@code{full-Y-label-width} passed it by the @code{print-graph} function.
19607
19608@need 1250
19609The code to make @code{X-axis-leading-spaces}
19610looks like this:
19611
19612@smallexample
19613@group
19614;; X-axis-leading-spaces
19615@dots{}
19616(make-string full-Y-label-width ? )
19617@dots{}
19618@end group
19619@end smallexample
19620
19621We also need to determine the length of the horizontal axis, which is
19622the length of the numbers list, and the number of tics in the horizontal
19623axis:
19624
19625@smallexample
19626@group
19627;; X-length
19628@dots{}
19629(length numbers-list)
19630@end group
19631
19632@group
19633;; tic-width
19634@dots{}
19635(* symbol-width X-axis-label-spacing)
19636@end group
19637
19638@group
19639;; number-of-X-tics
19640(if (zerop (% (X-length tic-width)))
19641 (/ (X-length tic-width))
19642 (1+ (/ (X-length tic-width))))
19643@end group
19644@end smallexample
19645
19646@need 1250
19647All this leads us directly to the function for printing the X axis tic line:
19648
19649@findex print-X-axis-tic-line
19650@smallexample
19651@group
19652(defun print-X-axis-tic-line
19653 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19654 "Print tics for X axis."
19655 (insert X-axis-leading-spaces)
19656 (insert X-axis-tic-symbol) ; @r{Under first column.}
19657@end group
19658@group
19659 ;; @r{Insert second tic in the right spot.}
19660 (insert (concat
19661 (make-string
19662 (- (* symbol-width X-axis-label-spacing)
19663 ;; @r{Insert white space up to second tic symbol.}
19664 (* 2 (length X-axis-tic-symbol)))
19665 ? )
19666 X-axis-tic-symbol))
19667@end group
19668@group
19669 ;; @r{Insert remaining tics.}
19670 (while (> number-of-X-tics 1)
19671 (insert X-axis-tic-element)
19672 (setq number-of-X-tics (1- number-of-X-tics))))
19673@end group
19674@end smallexample
19675
19676The line of numbers is equally straightforward:
19677
19678@need 1250
19679First, we create a numbered element with blank spaces before each number:
19680
19681@findex X-axis-element
19682@smallexample
19683@group
19684(defun X-axis-element (number)
19685 "Construct a numbered X axis element."
19686 (let ((leading-spaces
19687 (- (* symbol-width X-axis-label-spacing)
19688 (length (number-to-string number)))))
19689 (concat (make-string leading-spaces ? )
19690 (number-to-string number))))
19691@end group
19692@end smallexample
19693
19694Next, we create the function to print the numbered line, starting with
19695the number ``1'' under the first column:
19696
19697@findex print-X-axis-numbered-line
19698@smallexample
19699@group
19700(defun print-X-axis-numbered-line
19701 (number-of-X-tics X-axis-leading-spaces)
19702 "Print line of X-axis numbers"
19703 (let ((number X-axis-label-spacing))
19704 (insert X-axis-leading-spaces)
19705 (insert "1")
19706@end group
19707@group
19708 (insert (concat
19709 (make-string
19710 ;; @r{Insert white space up to next number.}
19711 (- (* symbol-width X-axis-label-spacing) 2)
19712 ? )
19713 (number-to-string number)))
19714@end group
19715@group
19716 ;; @r{Insert remaining numbers.}
19717 (setq number (+ number X-axis-label-spacing))
19718 (while (> number-of-X-tics 1)
19719 (insert (X-axis-element number))
19720 (setq number (+ number X-axis-label-spacing))
19721 (setq number-of-X-tics (1- number-of-X-tics)))))
19722@end group
19723@end smallexample
19724
19725Finally, we need to write the @code{print-X-axis} that uses
19726@code{print-X-axis-tic-line} and
19727@code{print-X-axis-numbered-line}.
19728
19729The function must determine the local values of the variables used by both
19730@code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19731then it must call them. Also, it must print the carriage return that
19732separates the two lines.
19733
19734The function consists of a varlist that specifies five local variables,
19735and calls to each of the two line printing functions:
19736
19737@findex print-X-axis
19738@smallexample
19739@group
19740(defun print-X-axis (numbers-list)
19741 "Print X axis labels to length of NUMBERS-LIST."
19742 (let* ((leading-spaces
19743 (make-string full-Y-label-width ? ))
19744@end group
19745@group
19746 ;; symbol-width @r{is provided by} graph-body-print
19747 (tic-width (* symbol-width X-axis-label-spacing))
19748 (X-length (length numbers-list))
19749@end group
19750@group
19751 (X-tic
19752 (concat
19753 (make-string
19754@end group
19755@group
19756 ;; @r{Make a string of blanks.}
19757 (- (* symbol-width X-axis-label-spacing)
19758 (length X-axis-tic-symbol))
19759 ? )
19760@end group
19761@group
19762 ;; @r{Concatenate blanks with tic symbol.}
19763 X-axis-tic-symbol))
19764@end group
19765@group
19766 (tic-number
19767 (if (zerop (% X-length tic-width))
19768 (/ X-length tic-width)
19769 (1+ (/ X-length tic-width)))))
19770@end group
19771@group
19772 (print-X-axis-tic-line tic-number leading-spaces X-tic)
19773 (insert "\n")
19774 (print-X-axis-numbered-line tic-number leading-spaces)))
19775@end group
19776@end smallexample
19777
19778@need 1250
19779You can test @code{print-X-axis}:
19780
19781@enumerate
19782@item
19783Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19784@code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19785@code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19786
19787@item
19788Copy the following expression:
19789
19790@smallexample
19791@group
19792(progn
19793 (let ((full-Y-label-width 5)
19794 (symbol-width 1))
19795 (print-X-axis
19796 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19797@end group
19798@end smallexample
19799
19800@item
19801Switch to the @file{*scratch*} buffer and place the cursor where you
19802want the axis labels to start.
19803
19804@item
19805Type @kbd{M-:} (@code{eval-expression}).
19806
19807@item
19808Yank the test expression into the minibuffer
19809with @kbd{C-y} (@code{yank)}.
19810
19811@item
19812Press @key{RET} to evaluate the expression.
19813@end enumerate
19814
19815@need 1250
19816Emacs will print the horizontal axis like this:
c6f54b06 19817@sp 1
8b096dce
EZ
19818
19819@smallexample
19820@group
19821 | | | | |
19822 1 5 10 15 20
19823@end group
19824@end smallexample
19825
19826@node Print Whole Graph, , print-X-axis, Full Graph
19827@appendixsec Printing the Whole Graph
19828@cindex Printing the whole graph
19829@cindex Whole graph printing
19830@cindex Graph, printing all
19831
19832Now we are nearly ready to print the whole graph.
19833
19834The function to print the graph with the proper labels follows the
19835outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19836Axes}), but with additions.
19837
19838@need 1250
19839Here is the outline:
19840
19841@smallexample
19842@group
19843(defun print-graph (numbers-list)
19844 "@var{documentation}@dots{}"
19845 (let ((height @dots{}
19846 @dots{}))
19847@end group
19848@group
19849 (print-Y-axis height @dots{} )
19850 (graph-body-print numbers-list)
19851 (print-X-axis @dots{} )))
19852@end group
19853@end smallexample
19854
19855@menu
19856* The final version:: A few changes.
19857* Test print-graph:: Run a short test.
19858* Graphing words in defuns:: Executing the final code.
19859* lambda:: How to write an anonymous function.
19860* mapcar:: Apply a function to elements of a list.
19861* Another Bug:: Yet another bug @dots{} most insidious.
19862* Final printed graph:: The graph itself!
19863@end menu
19864
19865@node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19866@ifnottex
19867@unnumberedsubsec Changes for the Final Version
19868@end ifnottex
19869
19870The final version is different from what we planned in two ways:
19871first, it contains additional values calculated once in the varlist;
19872second, it carries an option to specify the labels' increment per row.
19873This latter feature turns out to be essential; otherwise, a graph may
19874have more rows than fit on a display or on a sheet of paper.
19875
19876@need 1500
19877This new feature requires a change to the @code{Y-axis-column}
19878function, to add @code{vertical-step} to it. The function looks like
19879this:
19880
19881@findex Y-axis-column @r{Final version.}
19882@smallexample
19883@group
19884;;; @r{Final version.}
19885(defun Y-axis-column
19886 (height width-of-label &optional vertical-step)
19887 "Construct list of labels for Y axis.
19888HEIGHT is maximum height of graph.
19889WIDTH-OF-LABEL is maximum width of label.
19890VERTICAL-STEP, an option, is a positive integer
19891that specifies how much a Y axis label increments
19892for each line. For example, a step of 5 means
19893that each line is five units of the graph."
19894@end group
19895@group
19896 (let (Y-axis
19897 (number-per-line (or vertical-step 1)))
19898 (while (> height 1)
19899 (if (zerop (% height Y-axis-label-spacing))
19900@end group
19901@group
19902 ;; @r{Insert label.}
19903 (setq Y-axis
19904 (cons
19905 (Y-axis-element
19906 (* height number-per-line)
19907 width-of-label)
19908 Y-axis))
19909@end group
19910@group
19911 ;; @r{Else, insert blanks.}
19912 (setq Y-axis
19913 (cons
19914 (make-string width-of-label ? )
19915 Y-axis)))
19916 (setq height (1- height)))
19917@end group
19918@group
19919 ;; @r{Insert base line.}
19920 (setq Y-axis (cons (Y-axis-element
19921 (or vertical-step 1)
19922 width-of-label)
19923 Y-axis))
19924 (nreverse Y-axis)))
19925@end group
19926@end smallexample
19927
19928The values for the maximum height of graph and the width of a symbol
19929are computed by @code{print-graph} in its @code{let} expression; so
19930@code{graph-body-print} must be changed to accept them.
19931
19932@findex graph-body-print @r{Final version.}
19933@smallexample
19934@group
19935;;; @r{Final version.}
19936(defun graph-body-print (numbers-list height symbol-width)
19937 "Print a bar graph of the NUMBERS-LIST.
19938The numbers-list consists of the Y-axis values.
19939HEIGHT is maximum height of graph.
19940SYMBOL-WIDTH is number of each column."
19941@end group
19942@group
19943 (let (from-position)
19944 (while numbers-list
19945 (setq from-position (point))
19946 (insert-rectangle
19947 (column-of-graph height (car numbers-list)))
19948 (goto-char from-position)
19949 (forward-char symbol-width)
19950@end group
19951@group
19952 ;; @r{Draw graph column by column.}
19953 (sit-for 0)
19954 (setq numbers-list (cdr numbers-list)))
19955 ;; @r{Place point for X axis labels.}
19956 (forward-line height)
19957 (insert "\n")))
19958@end group
19959@end smallexample
19960
19961@need 1250
19962Finally, the code for the @code{print-graph} function:
19963
19964@findex print-graph @r{Final version.}
19965@smallexample
19966@group
19967;;; @r{Final version.}
19968(defun print-graph
19969 (numbers-list &optional vertical-step)
19970 "Print labelled bar graph of the NUMBERS-LIST.
19971The numbers-list consists of the Y-axis values.
19972@end group
19973
19974@group
19975Optionally, VERTICAL-STEP, a positive integer,
19976specifies how much a Y axis label increments for
19977each line. For example, a step of 5 means that
19978each row is five units."
19979@end group
19980@group
19981 (let* ((symbol-width (length graph-blank))
19982 ;; @code{height} @r{is both the largest number}
19983 ;; @r{and the number with the most digits.}
19984 (height (apply 'max numbers-list))
19985@end group
19986@group
19987 (height-of-top-line
19988 (if (zerop (% height Y-axis-label-spacing))
19989 height
19990 ;; @r{else}
19991 (* (1+ (/ height Y-axis-label-spacing))
19992 Y-axis-label-spacing)))
19993@end group
19994@group
19995 (vertical-step (or vertical-step 1))
19996 (full-Y-label-width
19997 (length
19998@end group
19999@group
20000 (concat
20001 (number-to-string
20002 (* height-of-top-line vertical-step))
20003 Y-axis-tic))))
20004@end group
20005
20006@group
20007 (print-Y-axis
20008 height-of-top-line full-Y-label-width vertical-step)
20009@end group
20010@group
20011 (graph-body-print
20012 numbers-list height-of-top-line symbol-width)
20013 (print-X-axis numbers-list)))
20014@end group
20015@end smallexample
20016
20017@node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
20018@appendixsubsec Testing @code{print-graph}
20019
20020@need 1250
20021We can test the @code{print-graph} function with a short list of numbers:
20022
20023@enumerate
20024@item
20025Install the final versions of @code{Y-axis-column},
20026@code{graph-body-print}, and @code{print-graph} (in addition to the
20027rest of the code.)
20028
20029@item
20030Copy the following expression:
20031
20032@smallexample
20033(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20034@end smallexample
20035
20036@item
20037Switch to the @file{*scratch*} buffer and place the cursor where you
20038want the axis labels to start.
20039
20040@item
20041Type @kbd{M-:} (@code{eval-expression}).
20042
20043@item
20044Yank the test expression into the minibuffer
20045with @kbd{C-y} (@code{yank)}.
20046
20047@item
20048Press @key{RET} to evaluate the expression.
20049@end enumerate
20050
20051@need 1250
20052Emacs will print a graph that looks like this:
20053
20054@smallexample
20055@group
2005610 -
20057
20058
20059 *
20060 ** *
20061 5 - **** *
20062 **** ***
20063 * *********
20064 ************
20065 1 - *************
20066
20067 | | | |
20068 1 5 10 15
20069@end group
20070@end smallexample
20071
c6f54b06 20072@need 1200
8b096dce
EZ
20073On the other hand, if you pass @code{print-graph} a
20074@code{vertical-step} value of 2, by evaluating this expression:
20075
20076@smallexample
20077(print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20078@end smallexample
20079
20080@need 1250
20081@noindent
20082The graph looks like this:
20083
20084@smallexample
20085@group
2008620 -
20087
20088
20089 *
20090 ** *
2009110 - **** *
20092 **** ***
20093 * *********
20094 ************
20095 2 - *************
20096
20097 | | | |
20098 1 5 10 15
20099@end group
20100@end smallexample
20101
20102@noindent
20103(A question: is the `2' on the bottom of the vertical axis a bug or a
20104feature? If you think it is a bug, and should be a `1' instead, (or
20105even a `0'), you can modify the sources.)
20106
20107@node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
20108@appendixsubsec Graphing Numbers of Words and Symbols
20109
20110Now for the graph for which all this code was written: a graph that
20111shows how many function definitions contain fewer than 10 words and
20112symbols, how many contain between 10 and 19 words and symbols, how
20113many contain between 20 and 29 words and symbols, and so on.
20114
20115This is a multi-step process. First make sure you have loaded all the
20116requisite code.
20117
20118@need 1500
20119It is a good idea to reset the value of @code{top-of-ranges} in case
20120you have set it to some different value. You can evaluate the
20121following:
20122
20123@smallexample
20124@group
20125(setq top-of-ranges
20126 '(10 20 30 40 50
20127 60 70 80 90 100
20128 110 120 130 140 150
20129 160 170 180 190 200
20130 210 220 230 240 250
20131 260 270 280 290 300)
20132@end group
20133@end smallexample
20134
20135@noindent
20136Next create a list of the number of words and symbols in each range.
20137
20138@need 1500
20139@noindent
20140Evaluate the following:
20141
20142@smallexample
20143@group
20144(setq list-for-graph
20145 (defuns-per-range
20146 (sort
20147 (recursive-lengths-list-many-files
20148 (directory-files "/usr/local/emacs/lisp"
20149 t ".+el$"))
20150 '<)
20151 top-of-ranges))
20152@end group
20153@end smallexample
20154
20155@noindent
c6f54b06 20156On my old machine, this took about an hour. It looked though 303 Lisp
8b096dce 20157files in my copy of Emacs version 19.23. After all that computing,
c6f54b06 20158the @code{list-for-graph} had this value:
8b096dce
EZ
20159
20160@smallexample
20161@group
20162(537 1027 955 785 594 483 349 292 224 199 166 120 116 99
2016390 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20164@end group
20165@end smallexample
20166
20167@noindent
c6f54b06 20168This means that my copy of Emacs had 537 function definitions with
8b096dce
EZ
20169fewer than 10 words or symbols in them, 1,027 function definitions
20170with 10 to 19 words or symbols in them, 955 function definitions with
2017120 to 29 words or symbols in them, and so on.
20172
20173Clearly, just by looking at this list we can see that most function
20174definitions contain ten to thirty words and symbols.
20175
20176Now for printing. We do @emph{not} want to print a graph that is
201771,030 lines high @dots{} Instead, we should print a graph that is
20178fewer than twenty-five lines high. A graph that height can be
20179displayed on almost any monitor, and easily printed on a sheet of paper.
20180
20181This means that each value in @code{list-for-graph} must be reduced to
20182one-fiftieth its present value.
20183
20184Here is a short function to do just that, using two functions we have
20185not yet seen, @code{mapcar} and @code{lambda}.
20186
20187@smallexample
20188@group
20189(defun one-fiftieth (full-range)
20190 "Return list, each number one-fiftieth of previous."
20191 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20192@end group
20193@end smallexample
20194
20195@node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20196@appendixsubsec A @code{lambda} Expression: Useful Anonymity
20197@cindex Anonymous function
20198@findex lambda
20199
20200@code{lambda} is the symbol for an anonymous function, a function
20201without a name. Every time you use an anonymous function, you need to
20202include its whole body.
20203
20204@need 1250
20205@noindent
20206Thus,
20207
20208@smallexample
20209(lambda (arg) (/ arg 50))
20210@end smallexample
20211
20212@noindent
20213is a function definition that says `return the value resulting from
20214dividing whatever is passed to me as @code{arg} by 50'.
20215
c6f54b06 20216@need 1200
8b096dce
EZ
20217Earlier, for example, we had a function @code{multiply-by-seven}; it
20218multiplied its argument by 7. This function is similar, except it
20219divides its argument by 50; and, it has no name. The anonymous
20220equivalent of @code{multiply-by-seven} is:
20221
20222@smallexample
20223(lambda (number) (* 7 number))
20224@end smallexample
20225
20226@noindent
20227(@xref{defun, , The @code{defun} Special Form}.)
20228
20229@need 1250
20230@noindent
20231If we want to multiply 3 by 7, we can write:
20232
20233@c !!! Clear print-postscript-figures if the computer formatting this
20234@c document is too small and cannot handle all the diagrams and figures.
20235@c clear print-postscript-figures
20236@c set print-postscript-figures
20237@c lambda example diagram #1
20238@ifnottex
20239@smallexample
20240@group
20241(multiply-by-seven 3)
20242 \_______________/ ^
20243 | |
20244 function argument
20245@end group
20246@end smallexample
20247@end ifnottex
20248@ifset print-postscript-figures
20249@sp 1
20250@tex
20251@image{lambda-1}
20252%%%% old method of including an image
20253% \input /usr/local/lib/tex/inputs/psfig.tex
20254% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20255% \catcode`\@=0 %
20256@end tex
20257@sp 1
20258@end ifset
20259@ifclear print-postscript-figures
20260@iftex
20261@smallexample
20262@group
20263(multiply-by-seven 3)
20264 \_______________/ ^
20265 | |
20266 function argument
20267@end group
20268@end smallexample
20269@end iftex
20270@end ifclear
20271
20272@noindent
20273This expression returns 21.
20274
20275@need 1250
20276@noindent
20277Similarly, we can write:
20278
20279@c lambda example diagram #2
20280@ifnottex
20281@smallexample
20282@group
20283((lambda (number) (* 7 number)) 3)
20284 \____________________________/ ^
20285 | |
20286 anonymous function argument
20287@end group
20288@end smallexample
20289@end ifnottex
20290@ifset print-postscript-figures
20291@sp 1
20292@tex
20293@image{lambda-2}
20294%%%% old method of including an image
20295% \input /usr/local/lib/tex/inputs/psfig.tex
20296% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20297% \catcode`\@=0 %
20298@end tex
20299@sp 1
20300@end ifset
20301@ifclear print-postscript-figures
20302@iftex
20303@smallexample
20304@group
20305((lambda (number) (* 7 number)) 3)
20306 \____________________________/ ^
20307 | |
20308 anonymous function argument
20309@end group
20310@end smallexample
20311@end iftex
20312@end ifclear
20313
20314@need 1250
20315@noindent
20316If we want to divide 100 by 50, we can write:
20317
20318@c lambda example diagram #3
20319@ifnottex
20320@smallexample
20321@group
20322((lambda (arg) (/ arg 50)) 100)
20323 \______________________/ \_/
20324 | |
20325 anonymous function argument
20326@end group
20327@end smallexample
20328@end ifnottex
20329@ifset print-postscript-figures
20330@sp 1
20331@tex
20332@image{lambda-3}
20333%%%% old method of including an image
20334% \input /usr/local/lib/tex/inputs/psfig.tex
20335% \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20336% \catcode`\@=0 %
20337@end tex
20338@sp 1
20339@end ifset
20340@ifclear print-postscript-figures
20341@iftex
20342@smallexample
20343@group
20344((lambda (arg) (/ arg 50)) 100)
20345 \______________________/ \_/
20346 | |
20347 anonymous function argument
20348@end group
20349@end smallexample
20350@end iftex
20351@end ifclear
20352
20353@noindent
20354This expression returns 2. The 100 is passed to the function, which
20355divides that number by 50.
20356
20357@xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20358Lisp Reference Manual}, for more about @code{lambda}. Lisp and lambda
20359expressions derive from the Lambda Calculus.
20360
20361@node mapcar, Another Bug, lambda, Print Whole Graph
20362@appendixsubsec The @code{mapcar} Function
20363@findex mapcar
20364
20365@code{mapcar} is a function that calls its first argument with each
20366element of its second argument, in turn. The second argument must be
20367a sequence.
20368
20369The @samp{map} part of the name comes from the mathematical phrase,
20370`mapping over a domain', meaning to apply a function to each of the
20371elements in a domain. The mathematical phrase is based on the
20372metaphor of a surveyor walking, one step at a time, over an area he is
20373mapping. And @samp{car}, of course, comes from the Lisp notion of the
20374first of a list.
20375
20376@need 1250
20377@noindent
20378For example,
20379
20380@smallexample
20381@group
20382(mapcar '1+ '(2 4 6))
20383 @result{} (3 5 7)
20384@end group
20385@end smallexample
20386
20387@noindent
20388The function @code{1+} which adds one to its argument, is executed on
20389@emph{each} element of the list, and a new list is returned.
20390
20391Contrast this with @code{apply}, which applies its first argument to
20392all the remaining.
20393(@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20394@code{apply}.)
20395
20396@need 1250
20397In the definition of @code{one-fiftieth}, the first argument is the
20398anonymous function:
20399
20400@smallexample
20401(lambda (arg) (/ arg 50))
20402@end smallexample
20403
20404@noindent
20405and the second argument is @code{full-range}, which will be bound to
20406@code{list-for-graph}.
20407
20408@need 1250
20409The whole expression looks like this:
20410
20411@smallexample
20412(mapcar '(lambda (arg) (/ arg 50)) full-range))
20413@end smallexample
20414
20415@xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20416Lisp Reference Manual}, for more about @code{mapcar}.
20417
20418Using the @code{one-fiftieth} function, we can generate a list in
20419which each element is one-fiftieth the size of the corresponding
20420element in @code{list-for-graph}.
20421
20422@smallexample
20423@group
20424(setq fiftieth-list-for-graph
20425 (one-fiftieth list-for-graph))
20426@end group
20427@end smallexample
20428
20429@need 1250
20430The resulting list looks like this:
20431
20432@smallexample
20433@group
20434(10 20 19 15 11 9 6 5 4 3 3 2 2
204351 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20436@end group
20437@end smallexample
20438
20439@noindent
20440This, we are almost ready to print! (We also notice the loss of
20441information: many of the higher ranges are 0, meaning that fewer than
2044250 defuns had that many words or symbols---but not necessarily meaning
20443that none had that many words or symbols.)
20444
20445@node Another Bug, Final printed graph, mapcar, Print Whole Graph
20446@appendixsubsec Another Bug @dots{} Most Insidious
20447@cindex Bug, most insidious type
20448@cindex Insidious type of bug
20449
20450I said `almost ready to print'! Of course, there is a bug in the
20451@code{print-graph} function @dots{} It has a @code{vertical-step}
20452option, but not a @code{horizontal-step} option. The
20453@code{top-of-range} scale goes from 10 to 300 by tens. But the
20454@code{print-graph} function will print only by ones.
20455
20456This is a classic example of what some consider the most insidious
20457type of bug, the bug of omission. This is not the kind of bug you can
20458find by studying the code, for it is not in the code; it is an omitted
20459feature. Your best actions are to try your program early and often;
20460and try to arrange, as much as you can, to write code that is easy to
20461understand and easy to change. Try to be aware, whenever you can,
20462that whatever you have written, @emph{will} be rewritten, if not soon,
20463eventually. A hard maxim to follow.
20464
20465It is the @code{print-X-axis-numbered-line} function that needs the
20466work; and then the @code{print-X-axis} and the @code{print-graph}
20467functions need to be adapted. Not much needs to be done; there is one
20468nicety: the numbers ought to line up under the tic marks. This takes
20469a little thought.
20470
20471@need 1250
20472Here is the corrected @code{print-X-axis-numbered-line}:
20473
20474@smallexample
20475@group
20476(defun print-X-axis-numbered-line
20477 (number-of-X-tics X-axis-leading-spaces
20478 &optional horizontal-step)
20479 "Print line of X-axis numbers"
20480 (let ((number X-axis-label-spacing)
20481 (horizontal-step (or horizontal-step 1)))
20482@end group
20483@group
20484 (insert X-axis-leading-spaces)
20485 ;; @r{Delete extra leading spaces.}
20486 (delete-char
20487 (- (1-
20488 (length (number-to-string horizontal-step)))))
20489 (insert (concat
20490 (make-string
20491@end group
20492@group
20493 ;; @r{Insert white space.}
20494 (- (* symbol-width
20495 X-axis-label-spacing)
20496 (1-
20497 (length
20498 (number-to-string horizontal-step)))
20499 2)
20500 ? )
20501 (number-to-string
20502 (* number horizontal-step))))
20503@end group
20504@group
20505 ;; @r{Insert remaining numbers.}
20506 (setq number (+ number X-axis-label-spacing))
20507 (while (> number-of-X-tics 1)
20508 (insert (X-axis-element
20509 (* number horizontal-step)))
20510 (setq number (+ number X-axis-label-spacing))
20511 (setq number-of-X-tics (1- number-of-X-tics)))))
20512@end group
20513@end smallexample
20514
20515@need 1500
20516If you are reading this in Info, you can see the new versions of
20517@code{print-X-axis} @code{print-graph} and evaluate them. If you are
20518reading this in a printed book, you can see the changed lines here
20519(the full text is too much to print).
20520
20521@iftex
20522@smallexample
20523@group
20524(defun print-X-axis (numbers-list horizontal-step)
20525 @dots{}
20526 (print-X-axis-numbered-line
20527 tic-number leading-spaces horizontal-step))
20528@end group
20529@end smallexample
20530
20531@smallexample
20532@group
20533(defun print-graph
20534 (numbers-list
20535 &optional vertical-step horizontal-step)
20536 @dots{}
20537 (print-X-axis numbers-list horizontal-step))
20538@end group
20539@end smallexample
20540@end iftex
20541
20542@ifnottex
20543@smallexample
20544@group
20545(defun print-X-axis (numbers-list horizontal-step)
20546 "Print X axis labels to length of NUMBERS-LIST.
20547Optionally, HORIZONTAL-STEP, a positive integer,
20548specifies how much an X axis label increments for
20549each column."
20550@end group
20551@group
20552;; Value of symbol-width and full-Y-label-width
20553;; are passed by `print-graph'.
20554 (let* ((leading-spaces
20555 (make-string full-Y-label-width ? ))
20556 ;; symbol-width @r{is provided by} graph-body-print
20557 (tic-width (* symbol-width X-axis-label-spacing))
20558 (X-length (length numbers-list))
20559@end group
20560@group
20561 (X-tic
20562 (concat
20563 (make-string
20564 ;; @r{Make a string of blanks.}
20565 (- (* symbol-width X-axis-label-spacing)
20566 (length X-axis-tic-symbol))
20567 ? )
20568@end group
20569@group
20570 ;; @r{Concatenate blanks with tic symbol.}
20571 X-axis-tic-symbol))
20572 (tic-number
20573 (if (zerop (% X-length tic-width))
20574 (/ X-length tic-width)
20575 (1+ (/ X-length tic-width)))))
20576@end group
20577
20578@group
20579 (print-X-axis-tic-line
20580 tic-number leading-spaces X-tic)
20581 (insert "\n")
20582 (print-X-axis-numbered-line
20583 tic-number leading-spaces horizontal-step)))
20584@end group
20585@end smallexample
20586
20587@smallexample
20588@group
20589(defun print-graph
20590 (numbers-list &optional vertical-step horizontal-step)
20591 "Print labelled bar graph of the NUMBERS-LIST.
20592The numbers-list consists of the Y-axis values.
20593@end group
20594
20595@group
20596Optionally, VERTICAL-STEP, a positive integer,
20597specifies how much a Y axis label increments for
20598each line. For example, a step of 5 means that
20599each row is five units.
20600@end group
20601
20602@group
20603Optionally, HORIZONTAL-STEP, a positive integer,
20604specifies how much an X axis label increments for
20605each column."
20606 (let* ((symbol-width (length graph-blank))
20607 ;; @code{height} @r{is both the largest number}
20608 ;; @r{and the number with the most digits.}
20609 (height (apply 'max numbers-list))
20610@end group
20611@group
20612 (height-of-top-line
20613 (if (zerop (% height Y-axis-label-spacing))
20614 height
20615 ;; @r{else}
20616 (* (1+ (/ height Y-axis-label-spacing))
20617 Y-axis-label-spacing)))
20618@end group
20619@group
20620 (vertical-step (or vertical-step 1))
20621 (full-Y-label-width
20622 (length
20623 (concat
20624 (number-to-string
20625 (* height-of-top-line vertical-step))
20626 Y-axis-tic))))
20627@end group
20628@group
20629 (print-Y-axis
20630 height-of-top-line full-Y-label-width vertical-step)
20631 (graph-body-print
20632 numbers-list height-of-top-line symbol-width)
20633 (print-X-axis numbers-list horizontal-step)))
20634@end group
20635@end smallexample
20636@end ifnottex
20637
20638@ignore
20639Graphing Definitions Re-listed
20640
20641@need 1250
20642Here are all the graphing definitions in their final form:
20643
20644@smallexample
20645@group
20646(defvar top-of-ranges
20647 '(10 20 30 40 50
20648 60 70 80 90 100
20649 110 120 130 140 150
20650 160 170 180 190 200
20651 210 220 230 240 250)
20652 "List specifying ranges for `defuns-per-range'.")
20653@end group
20654
20655@group
20656(defvar graph-symbol "*"
20657 "String used as symbol in graph, usually an asterisk.")
20658@end group
20659
20660@group
20661(defvar graph-blank " "
20662 "String used as blank in graph, usually a blank space.
20663graph-blank must be the same number of columns wide
20664as graph-symbol.")
20665@end group
20666
20667@group
20668(defvar Y-axis-tic " - "
20669 "String that follows number in a Y axis label.")
20670@end group
20671
20672@group
20673(defvar Y-axis-label-spacing 5
20674 "Number of lines from one Y axis label to next.")
20675@end group
20676
20677@group
20678(defvar X-axis-tic-symbol "|"
20679 "String to insert to point to a column in X axis.")
20680@end group
20681
20682@group
20683(defvar X-axis-label-spacing
20684 (if (boundp 'graph-blank)
20685 (* 5 (length graph-blank)) 5)
20686 "Number of units from one X axis label to next.")
20687@end group
20688@end smallexample
20689
20690@smallexample
20691@group
20692(defun count-words-in-defun ()
20693 "Return the number of words and symbols in a defun."
20694 (beginning-of-defun)
20695 (let ((count 0)
20696 (end (save-excursion (end-of-defun) (point))))
20697@end group
20698
20699@group
20700 (while
20701 (and (< (point) end)
20702 (re-search-forward
20703 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20704 end t))
20705 (setq count (1+ count)))
20706 count))
20707@end group
20708@end smallexample
20709
20710@smallexample
20711@group
20712(defun lengths-list-file (filename)
20713 "Return list of definitions' lengths within FILE.
20714The returned list is a list of numbers.
20715Each number is the number of words or
20716symbols in one function definition."
20717@end group
20718
20719@group
20720 (message "Working on `%s' ... " filename)
20721 (save-excursion
20722 (let ((buffer (find-file-noselect filename))
20723 (lengths-list))
20724 (set-buffer buffer)
20725 (setq buffer-read-only t)
20726 (widen)
20727 (goto-char (point-min))
20728@end group
20729
20730@group
20731 (while (re-search-forward "^(defun" nil t)
20732 (setq lengths-list
20733 (cons (count-words-in-defun) lengths-list)))
20734 (kill-buffer buffer)
20735 lengths-list)))
20736@end group
20737@end smallexample
20738
20739@smallexample
20740@group
20741(defun lengths-list-many-files (list-of-files)
20742 "Return list of lengths of defuns in LIST-OF-FILES."
20743 (let (lengths-list)
20744;;; @r{true-or-false-test}
20745 (while list-of-files
20746 (setq lengths-list
20747 (append
20748 lengths-list
20749@end group
20750@group
20751;;; @r{Generate a lengths' list.}
20752 (lengths-list-file
20753 (expand-file-name (car list-of-files)))))
20754;;; @r{Make files' list shorter.}
20755 (setq list-of-files (cdr list-of-files)))
20756;;; @r{Return final value of lengths' list.}
20757 lengths-list))
20758@end group
20759@end smallexample
20760
20761@smallexample
20762@group
20763(defun defuns-per-range (sorted-lengths top-of-ranges)
20764 "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20765 (let ((top-of-range (car top-of-ranges))
20766 (number-within-range 0)
20767 defuns-per-range-list)
20768@end group
20769
20770@group
20771 ;; @r{Outer loop.}
20772 (while top-of-ranges
20773
20774 ;; @r{Inner loop.}
20775 (while (and
20776 ;; @r{Need number for numeric test.}
20777 (car sorted-lengths)
20778 (< (car sorted-lengths) top-of-range))
20779
20780 ;; @r{Count number of definitions within current range.}
20781 (setq number-within-range (1+ number-within-range))
20782 (setq sorted-lengths (cdr sorted-lengths)))
20783@end group
20784
20785@group
20786 ;; @r{Exit inner loop but remain within outer loop.}
20787
20788 (setq defuns-per-range-list
20789 (cons number-within-range defuns-per-range-list))
20790 (setq number-within-range 0) ; @r{Reset count to zero.}
20791
20792 ;; @r{Move to next range.}
20793 (setq top-of-ranges (cdr top-of-ranges))
20794 ;; @r{Specify next top of range value.}
20795 (setq top-of-range (car top-of-ranges)))
20796@end group
20797
20798@group
20799 ;; @r{Exit outer loop and count the number of defuns larger than}
20800 ;; @r{ the largest top-of-range value.}
20801 (setq defuns-per-range-list
20802 (cons
20803 (length sorted-lengths)
20804 defuns-per-range-list))
20805
20806 ;; @r{Return a list of the number of definitions within each range,}
20807 ;; @r{ smallest to largest.}
20808 (nreverse defuns-per-range-list)))
20809@end group
20810@end smallexample
20811
20812@smallexample
20813@group
20814(defun column-of-graph (max-graph-height actual-height)
20815 "Return list of MAX-GRAPH-HEIGHT strings;
20816ACTUAL-HEIGHT are graph-symbols.
20817The graph-symbols are contiguous entries at the end
20818of the list.
20819The list will be inserted as one column of a graph.
20820The strings are either graph-blank or graph-symbol."
20821@end group
20822
20823@group
20824 (let ((insert-list nil)
20825 (number-of-top-blanks
20826 (- max-graph-height actual-height)))
20827
20828 ;; @r{Fill in @code{graph-symbols}.}
20829 (while (> actual-height 0)
20830 (setq insert-list (cons graph-symbol insert-list))
20831 (setq actual-height (1- actual-height)))
20832@end group
20833
20834@group
20835 ;; @r{Fill in @code{graph-blanks}.}
20836 (while (> number-of-top-blanks 0)
20837 (setq insert-list (cons graph-blank insert-list))
20838 (setq number-of-top-blanks
20839 (1- number-of-top-blanks)))
20840
20841 ;; @r{Return whole list.}
20842 insert-list))
20843@end group
20844@end smallexample
20845
20846@smallexample
20847@group
20848(defun Y-axis-element (number full-Y-label-width)
20849 "Construct a NUMBERed label element.
20850A numbered element looks like this ` 5 - ',
20851and is padded as needed so all line up with
20852the element for the largest number."
20853@end group
20854@group
20855 (let* ((leading-spaces
20856 (- full-Y-label-width
20857 (length
20858 (concat (number-to-string number)
20859 Y-axis-tic)))))
20860@end group
20861@group
20862 (concat
20863 (make-string leading-spaces ? )
20864 (number-to-string number)
20865 Y-axis-tic)))
20866@end group
20867@end smallexample
20868
20869@smallexample
20870@group
20871(defun print-Y-axis
20872 (height full-Y-label-width &optional vertical-step)
20873 "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20874Height must be the maximum height of the graph.
20875Full width is the width of the highest label element.
20876Optionally, print according to VERTICAL-STEP."
20877@end group
20878@group
20879;; Value of height and full-Y-label-width
20880;; are passed by `print-graph'.
20881 (let ((start (point)))
20882 (insert-rectangle
20883 (Y-axis-column height full-Y-label-width vertical-step))
20884@end group
20885@group
20886 ;; @r{Place point ready for inserting graph.}
20887 (goto-char start)
20888 ;; @r{Move point forward by value of} full-Y-label-width
20889 (forward-char full-Y-label-width)))
20890@end group
20891@end smallexample
20892
20893@smallexample
20894@group
20895(defun print-X-axis-tic-line
20896 (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20897 "Print tics for X axis."
20898 (insert X-axis-leading-spaces)
20899 (insert X-axis-tic-symbol) ; @r{Under first column.}
20900@end group
20901@group
20902 ;; @r{Insert second tic in the right spot.}
20903 (insert (concat
20904 (make-string
20905 (- (* symbol-width X-axis-label-spacing)
20906 ;; @r{Insert white space up to second tic symbol.}
20907 (* 2 (length X-axis-tic-symbol)))
20908 ? )
20909 X-axis-tic-symbol))
20910@end group
20911@group
20912 ;; @r{Insert remaining tics.}
20913 (while (> number-of-X-tics 1)
20914 (insert X-axis-tic-element)
20915 (setq number-of-X-tics (1- number-of-X-tics))))
20916@end group
20917@end smallexample
20918
20919@smallexample
20920@group
20921(defun X-axis-element (number)
20922 "Construct a numbered X axis element."
20923 (let ((leading-spaces
20924 (- (* symbol-width X-axis-label-spacing)
20925 (length (number-to-string number)))))
20926 (concat (make-string leading-spaces ? )
20927 (number-to-string number))))
20928@end group
20929@end smallexample
20930
20931@smallexample
20932@group
20933(defun graph-body-print (numbers-list height symbol-width)
20934 "Print a bar graph of the NUMBERS-LIST.
20935The numbers-list consists of the Y-axis values.
20936HEIGHT is maximum height of graph.
20937SYMBOL-WIDTH is number of each column."
20938@end group
20939@group
20940 (let (from-position)
20941 (while numbers-list
20942 (setq from-position (point))
20943 (insert-rectangle
20944 (column-of-graph height (car numbers-list)))
20945 (goto-char from-position)
20946 (forward-char symbol-width)
20947@end group
20948@group
20949 ;; @r{Draw graph column by column.}
20950 (sit-for 0)
20951 (setq numbers-list (cdr numbers-list)))
20952 ;; @r{Place point for X axis labels.}
20953 (forward-line height)
20954 (insert "\n")))
20955@end group
20956@end smallexample
20957
20958@smallexample
20959@group
20960(defun Y-axis-column
20961 (height width-of-label &optional vertical-step)
20962 "Construct list of labels for Y axis.
20963HEIGHT is maximum height of graph.
20964WIDTH-OF-LABEL is maximum width of label.
20965@end group
20966@group
20967VERTICAL-STEP, an option, is a positive integer
20968that specifies how much a Y axis label increments
20969for each line. For example, a step of 5 means
20970that each line is five units of the graph."
20971 (let (Y-axis
20972 (number-per-line (or vertical-step 1)))
20973@end group
20974@group
20975 (while (> height 1)
20976 (if (zerop (% height Y-axis-label-spacing))
20977 ;; @r{Insert label.}
20978 (setq Y-axis
20979 (cons
20980 (Y-axis-element
20981 (* height number-per-line)
20982 width-of-label)
20983 Y-axis))
20984@end group
20985@group
20986 ;; @r{Else, insert blanks.}
20987 (setq Y-axis
20988 (cons
20989 (make-string width-of-label ? )
20990 Y-axis)))
20991 (setq height (1- height)))
20992@end group
20993@group
20994 ;; @r{Insert base line.}
20995 (setq Y-axis (cons (Y-axis-element
20996 (or vertical-step 1)
20997 width-of-label)
20998 Y-axis))
20999 (nreverse Y-axis)))
21000@end group
21001@end smallexample
21002
21003@smallexample
21004@group
21005(defun print-X-axis-numbered-line
21006 (number-of-X-tics X-axis-leading-spaces
21007 &optional horizontal-step)
21008 "Print line of X-axis numbers"
21009 (let ((number X-axis-label-spacing)
21010 (horizontal-step (or horizontal-step 1)))
21011@end group
21012@group
21013 (insert X-axis-leading-spaces)
21014 ;; line up number
21015 (delete-char (- (1- (length (number-to-string horizontal-step)))))
21016 (insert (concat
21017 (make-string
21018 ;; @r{Insert white space up to next number.}
21019 (- (* symbol-width X-axis-label-spacing)
21020 (1- (length (number-to-string horizontal-step)))
21021 2)
21022 ? )
21023 (number-to-string (* number horizontal-step))))
21024@end group
21025@group
21026 ;; @r{Insert remaining numbers.}
21027 (setq number (+ number X-axis-label-spacing))
21028 (while (> number-of-X-tics 1)
21029 (insert (X-axis-element (* number horizontal-step)))
21030 (setq number (+ number X-axis-label-spacing))
21031 (setq number-of-X-tics (1- number-of-X-tics)))))
21032@end group
21033@end smallexample
21034
21035@smallexample
21036@group
21037(defun print-X-axis (numbers-list horizontal-step)
21038 "Print X axis labels to length of NUMBERS-LIST.
21039Optionally, HORIZONTAL-STEP, a positive integer,
21040specifies how much an X axis label increments for
21041each column."
21042@end group
21043@group
21044;; Value of symbol-width and full-Y-label-width
21045;; are passed by `print-graph'.
21046 (let* ((leading-spaces
21047 (make-string full-Y-label-width ? ))
21048 ;; symbol-width @r{is provided by} graph-body-print
21049 (tic-width (* symbol-width X-axis-label-spacing))
21050 (X-length (length numbers-list))
21051@end group
21052@group
21053 (X-tic
21054 (concat
21055 (make-string
21056 ;; @r{Make a string of blanks.}
21057 (- (* symbol-width X-axis-label-spacing)
21058 (length X-axis-tic-symbol))
21059 ? )
21060@end group
21061@group
21062 ;; @r{Concatenate blanks with tic symbol.}
21063 X-axis-tic-symbol))
21064 (tic-number
21065 (if (zerop (% X-length tic-width))
21066 (/ X-length tic-width)
21067 (1+ (/ X-length tic-width)))))
21068@end group
21069
21070@group
21071 (print-X-axis-tic-line
21072 tic-number leading-spaces X-tic)
21073 (insert "\n")
21074 (print-X-axis-numbered-line
21075 tic-number leading-spaces horizontal-step)))
21076@end group
21077@end smallexample
21078
21079@smallexample
21080@group
21081(defun one-fiftieth (full-range)
21082 "Return list, each number of which is 1/50th previous."
21083 (mapcar '(lambda (arg) (/ arg 50)) full-range))
21084@end group
21085@end smallexample
21086
21087@smallexample
21088@group
21089(defun print-graph
21090 (numbers-list &optional vertical-step horizontal-step)
21091 "Print labelled bar graph of the NUMBERS-LIST.
21092The numbers-list consists of the Y-axis values.
21093@end group
21094
21095@group
21096Optionally, VERTICAL-STEP, a positive integer,
21097specifies how much a Y axis label increments for
21098each line. For example, a step of 5 means that
21099each row is five units.
21100@end group
21101
21102@group
21103Optionally, HORIZONTAL-STEP, a positive integer,
21104specifies how much an X axis label increments for
21105each column."
21106 (let* ((symbol-width (length graph-blank))
21107 ;; @code{height} @r{is both the largest number}
21108 ;; @r{and the number with the most digits.}
21109 (height (apply 'max numbers-list))
21110@end group
21111@group
21112 (height-of-top-line
21113 (if (zerop (% height Y-axis-label-spacing))
21114 height
21115 ;; @r{else}
21116 (* (1+ (/ height Y-axis-label-spacing))
21117 Y-axis-label-spacing)))
21118@end group
21119@group
21120 (vertical-step (or vertical-step 1))
21121 (full-Y-label-width
21122 (length
21123 (concat
21124 (number-to-string
21125 (* height-of-top-line vertical-step))
21126 Y-axis-tic))))
21127@end group
21128@group
21129
21130 (print-Y-axis
21131 height-of-top-line full-Y-label-width vertical-step)
21132 (graph-body-print
21133 numbers-list height-of-top-line symbol-width)
21134 (print-X-axis numbers-list horizontal-step)))
21135@end group
21136@end smallexample
21137@end ignore
21138
21139@page
21140@node Final printed graph, , Another Bug, Print Whole Graph
21141@appendixsubsec The Printed Graph
21142
21143When made and installed, you can call the @code{print-graph} command
21144like this:
c6f54b06 21145@sp 1
8b096dce
EZ
21146
21147@smallexample
21148@group
21149(print-graph fiftieth-list-for-graph 50 10)
21150@end group
21151@end smallexample
c6f54b06 21152@sp 1
8b096dce 21153
c6f54b06 21154@noindent
8b096dce 21155Here is the graph:
8b096dce
EZ
21156@sp 2
21157
21158@smallexample
21159@group
211601000 - *
21161 **
21162 **
21163 **
21164 **
21165 750 - ***
21166 ***
21167 ***
21168 ***
21169 ****
21170 500 - *****
21171 ******
21172 ******
21173 ******
21174 *******
21175 250 - ********
21176 ********* *
21177 *********** *
21178 ************* *
21179 50 - ***************** * *
21180 | | | | | | | |
21181 10 50 100 150 200 250 300 350
21182@end group
21183@end smallexample
21184
21185@sp 2
21186
c6f54b06 21187@noindent
8b096dce
EZ
21188The largest group of functions contain 10 -- 19 words and symbols each.
21189
c6f54b06
RC
21190@node Free Software and Free Manuals, GNU Free Documentation License, Full Graph, Top
21191@appendix Free Software and Free Manuals
21192
21193@strong{by Richard M. Stallman}
21194@sp 1
21195
21196The biggest deficiency in free operating systems is not in the
21197software---it is the lack of good free manuals that we can include in
21198these systems. Many of our most important programs do not come with
21199full manuals. Documentation is an essential part of any software
21200package; when an important free software package does not come with a
21201free manual, that is a major gap. We have many such gaps today.
21202
21203Once upon a time, many years ago, I thought I would learn Perl. I got
21204a copy of a free manual, but I found it hard to read. When I asked
21205Perl users about alternatives, they told me that there were better
21206introductory manuals---but those were not free.
21207
21208Why was this? The authors of the good manuals had written them for
21209O'Reilly Associates, which published them with restrictive terms---no
21210copying, no modification, source files not available---which exclude
21211them from the free software community.
21212
21213That wasn't the first time this sort of thing has happened, and (to
21214our community's great loss) it was far from the last. Proprietary
21215manual publishers have enticed a great many authors to restrict their
21216manuals since then. Many times I have heard a GNU user eagerly tell me
21217about a manual that he is writing, with which he expects to help the
21218GNU project---and then had my hopes dashed, as he proceeded to explain
21219that he had signed a contract with a publisher that would restrict it
21220so that we cannot use it.
21221
21222Given that writing good English is a rare skill among programmers, we
21223can ill afford to lose manuals this way.
21224
21225@c (texinfo)uref
21226(The Free Software Foundation
21227@uref{http://www.gnu.org/doc/doc.html#DescriptionsOfGNUDocumentation, ,
21228sells printed copies} of free @uref{http://www.gnu.org/doc/doc.html,
21229GNU manuals}, too.)
21230
21231Free documentation, like free software, is a matter of freedom, not
21232price. The problem with these manuals was not that O'Reilly Associates
21233charged a price for printed copies---that in itself is fine. (The Free
21234Software Foundation sells printed copies of free GNU manuals, too.)
21235But GNU manuals are available in source code form, while these manuals
21236are available only on paper. GNU manuals come with permission to copy
21237and modify; the Perl manuals do not. These restrictions are the
21238problems.
21239
21240The criterion for a free manual is pretty much the same as for free
21241software: it is a matter of giving all users certain
21242freedoms. Redistribution (including commercial redistribution) must be
21243permitted, so that the manual can accompany every copy of the program,
21244on-line or on paper. Permission for modification is crucial too.
21245
21246As a general rule, I don't believe that it is essential for people to
21247have permission to modify all sorts of articles and books. The issues
21248for writings are not necessarily the same as those for software. For
21249example, I don't think you or I are obliged to give permission to
21250modify articles like this one, which describe our actions and our
21251views.
21252
21253But there is a particular reason why the freedom to modify is crucial
21254for documentation for free software. When people exercise their right
21255to modify the software, and add or change its features, if they are
21256conscientious they will change the manual too---so they can provide
21257accurate and usable documentation with the modified program. A manual
21258which forbids programmers to be conscientious and finish the job, or
21259more precisely requires them to write a new manual from scratch if
21260they change the program, does not fill our community's needs.
21261
21262While a blanket prohibition on modification is unacceptable, some
21263kinds of limits on the method of modification pose no problem. For
21264example, requirements to preserve the original author's copyright
21265notice, the distribution terms, or the list of authors, are ok. It is
21266also no problem to require modified versions to include notice that
21267they were modified, even to have entire sections that may not be
21268deleted or changed, as long as these sections deal with nontechnical
21269topics. (Some GNU manuals have them.)
21270
21271These kinds of restrictions are not a problem because, as a practical
21272matter, they don't stop the conscientious programmer from adapting the
21273manual to fit the modified program. In other words, they don't block
21274the free software community from making full use of the manual.
21275
21276However, it must be possible to modify all the technical content of
21277the manual, and then distribute the result in all the usual media,
21278through all the usual channels; otherwise, the restrictions do block
21279the community, the manual is not free, and so we need another manual.
21280
21281Unfortunately, it is often hard to find someone to write another
21282manual when a proprietary manual exists. The obstacle is that many
21283users think that a proprietary manual is good enough---so they don't
21284see the need to write a free manual. They do not see that the free
21285operating system has a gap that needs filling.
21286
21287Why do users think that proprietary manuals are good enough? Some have
21288not considered the issue. I hope this article will do something to
21289change that.
21290
21291Other users consider proprietary manuals acceptable for the same
21292reason so many people consider proprietary software acceptable: they
21293judge in purely practical terms, not using freedom as a
21294criterion. These people are entitled to their opinions, but since
21295those opinions spring from values which do not include freedom, they
21296are no guide for those of us who do value freedom.
21297
21298Please spread the word about this issue. We continue to lose manuals
21299to proprietary publishing. If we spread the word that proprietary
21300manuals are not sufficient, perhaps the next person who wants to help
21301GNU by writing documentation will realize, before it is too late, that
21302he must above all make it free.
21303
21304We can also encourage commercial publishers to sell free, copylefted
21305manuals instead of proprietary ones. One way you can help this is to
21306check the distribution terms of a manual before you buy it, and prefer
21307copylefted manuals to non-copylefted ones.
21308
21309@sp 2
21310@noindent
21311Note: The Free Software Foundation maintains a page on its Web site
21312that lists free books available from other publishers:@*
21313@uref{http://www.gnu.org/doc/other-free-books.html}
21314
21315
21316@node GNU Free Documentation License, Index, Free Software and Free Manuals, Top
8b096dce
EZ
21317@appendix GNU Free Documentation License
21318
21319@cindex FDL, GNU Free Documentation License
c6f54b06 21320@center Version 1.2, November 2002
8b096dce
EZ
21321
21322@display
c6f54b06 21323Copyright @copyright{} 2000,2001,2002 Free Software Foundation, Inc.
8b096dce
EZ
2132459 Temple Place, Suite 330, Boston, MA 02111-1307, USA
21325
21326Everyone is permitted to copy and distribute verbatim copies
21327of this license document, but changing it is not allowed.
21328@end display
21329
21330@enumerate 0
21331@item
21332PREAMBLE
21333
21334The purpose of this License is to make a manual, textbook, or other
c6f54b06
RC
21335functional and useful document @dfn{free} in the sense of freedom: to
21336assure everyone the effective freedom to copy and redistribute it,
21337with or without modifying it, either commercially or noncommercially.
21338Secondarily, this License preserves for the author and publisher a way
21339to get credit for their work, while not being considered responsible
21340for modifications made by others.
8b096dce
EZ
21341
21342This License is a kind of ``copyleft'', which means that derivative
21343works of the document must themselves be free in the same sense. It
21344complements the GNU General Public License, which is a copyleft
21345license designed for free software.
21346
21347We have designed this License in order to use it for manuals for free
21348software, because free software needs free documentation: a free
21349program should come with manuals providing the same freedoms that the
21350software does. But this License is not limited to software manuals;
21351it can be used for any textual work, regardless of subject matter or
21352whether it is published as a printed book. We recommend this License
21353principally for works whose purpose is instruction or reference.
21354
21355@item
21356APPLICABILITY AND DEFINITIONS
21357
c6f54b06
RC
21358This License applies to any manual or other work, in any medium, that
21359contains a notice placed by the copyright holder saying it can be
21360distributed under the terms of this License. Such a notice grants a
21361world-wide, royalty-free license, unlimited in duration, to use that
21362work under the conditions stated herein. The ``Document'', below,
21363refers to any such manual or work. Any member of the public is a
21364licensee, and is addressed as ``you''. You accept the license if you
21365copy, modify or distribute the work in a way requiring permission
21366under copyright law.
8b096dce
EZ
21367
21368A ``Modified Version'' of the Document means any work containing the
21369Document or a portion of it, either copied verbatim, or with
21370modifications and/or translated into another language.
21371
c6f54b06
RC
21372A ``Secondary Section'' is a named appendix or a front-matter section
21373of the Document that deals exclusively with the relationship of the
21374publishers or authors of the Document to the Document's overall
21375subject (or to related matters) and contains nothing that could fall
21376directly within that overall subject. (Thus, if the Document is in
21377part a textbook of mathematics, a Secondary Section may not explain
21378any mathematics.) The relationship could be a matter of historical
8b096dce
EZ
21379connection with the subject or with related matters, or of legal,
21380commercial, philosophical, ethical or political position regarding
21381them.
21382
21383The ``Invariant Sections'' are certain Secondary Sections whose titles
21384are designated, as being those of Invariant Sections, in the notice
c6f54b06
RC
21385that says that the Document is released under this License. If a
21386section does not fit the above definition of Secondary then it is not
21387allowed to be designated as Invariant. The Document may contain zero
21388Invariant Sections. If the Document does not identify any Invariant
21389Sections then there are none.
8b096dce
EZ
21390
21391The ``Cover Texts'' are certain short passages of text that are listed,
21392as Front-Cover Texts or Back-Cover Texts, in the notice that says that
c6f54b06
RC
21393the Document is released under this License. A Front-Cover Text may
21394be at most 5 words, and a Back-Cover Text may be at most 25 words.
8b096dce
EZ
21395
21396A ``Transparent'' copy of the Document means a machine-readable copy,
21397represented in a format whose specification is available to the
c6f54b06 21398general public, that is suitable for revising the document
8b096dce
EZ
21399straightforwardly with generic text editors or (for images composed of
21400pixels) generic paint programs or (for drawings) some widely available
21401drawing editor, and that is suitable for input to text formatters or
21402for automatic translation to a variety of formats suitable for input
21403to text formatters. A copy made in an otherwise Transparent file
c6f54b06
RC
21404format whose markup, or absence of markup, has been arranged to thwart
21405or discourage subsequent modification by readers is not Transparent.
21406An image format is not Transparent if used for any substantial amount
21407of text. A copy that is not ``Transparent'' is called ``Opaque''.
8b096dce
EZ
21408
21409Examples of suitable formats for Transparent copies include plain
c6f54b06
RC
21410@sc{ascii} without markup, Texinfo input format, La@TeX{} input
21411format, @acronym{SGML} or @acronym{XML} using a publicly available
21412@acronym{DTD}, and standard-conforming simple @acronym{HTML},
21413PostScript or @acronym{PDF} designed for human modification. Examples
21414of transparent image formats include @acronym{PNG}, @acronym{XCF} and
21415@acronym{JPG}. Opaque formats include proprietary formats that can be
21416read and edited only by proprietary word processors, @acronym{SGML} or
21417@acronym{XML} for which the @acronym{DTD} and/or processing tools are
21418not generally available, and the machine-generated @acronym{HTML},
21419PostScript or @acronym{PDF} produced by some word processors for
21420output purposes only.
8b096dce
EZ
21421
21422The ``Title Page'' means, for a printed book, the title page itself,
21423plus such following pages as are needed to hold, legibly, the material
21424this License requires to appear in the title page. For works in
21425formats which do not have any title page as such, ``Title Page'' means
21426the text near the most prominent appearance of the work's title,
21427preceding the beginning of the body of the text.
21428
c6f54b06
RC
21429A section ``Entitled XYZ'' means a named subunit of the Document whose
21430title either is precisely XYZ or contains XYZ in parentheses following
21431text that translates XYZ in another language. (Here XYZ stands for a
21432specific section name mentioned below, such as ``Acknowledgements'',
21433``Dedications'', ``Endorsements'', or ``History''.) To ``Preserve the Title''
21434of such a section when you modify the Document means that it remains a
21435section ``Entitled XYZ'' according to this definition.
21436
21437The Document may include Warranty Disclaimers next to the notice which
21438states that this License applies to the Document. These Warranty
21439Disclaimers are considered to be included by reference in this
21440License, but only as regards disclaiming warranties: any other
21441implication that these Warranty Disclaimers may have is void and has
21442no effect on the meaning of this License.
21443
8b096dce
EZ
21444@item
21445VERBATIM COPYING
21446
21447You may copy and distribute the Document in any medium, either
21448commercially or noncommercially, provided that this License, the
21449copyright notices, and the license notice saying this License applies
21450to the Document are reproduced in all copies, and that you add no other
21451conditions whatsoever to those of this License. You may not use
21452technical measures to obstruct or control the reading or further
21453copying of the copies you make or distribute. However, you may accept
21454compensation in exchange for copies. If you distribute a large enough
21455number of copies you must also follow the conditions in section 3.
21456
21457You may also lend copies, under the same conditions stated above, and
21458you may publicly display copies.
21459
21460@item
21461COPYING IN QUANTITY
21462
c6f54b06
RC
21463If you publish printed copies (or copies in media that commonly have
21464printed covers) of the Document, numbering more than 100, and the
21465Document's license notice requires Cover Texts, you must enclose the
21466copies in covers that carry, clearly and legibly, all these Cover
8b096dce
EZ
21467Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21468the back cover. Both covers must also clearly and legibly identify
21469you as the publisher of these copies. The front cover must present
21470the full title with all words of the title equally prominent and
21471visible. You may add other material on the covers in addition.
21472Copying with changes limited to the covers, as long as they preserve
21473the title of the Document and satisfy these conditions, can be treated
21474as verbatim copying in other respects.
21475
21476If the required texts for either cover are too voluminous to fit
21477legibly, you should put the first ones listed (as many as fit
21478reasonably) on the actual cover, and continue the rest onto adjacent
21479pages.
21480
21481If you publish or distribute Opaque copies of the Document numbering
21482more than 100, you must either include a machine-readable Transparent
21483copy along with each Opaque copy, or state in or with each Opaque copy
c6f54b06
RC
21484a computer-network location from which the general network-using
21485public has access to download using public-standard network protocols
21486a complete Transparent copy of the Document, free of added material.
21487If you use the latter option, you must take reasonably prudent steps,
21488when you begin distribution of Opaque copies in quantity, to ensure
21489that this Transparent copy will remain thus accessible at the stated
21490location until at least one year after the last time you distribute an
21491Opaque copy (directly or through your agents or retailers) of that
21492edition to the public.
8b096dce
EZ
21493
21494It is requested, but not required, that you contact the authors of the
21495Document well before redistributing any large number of copies, to give
21496them a chance to provide you with an updated version of the Document.
21497
21498@item
21499MODIFICATIONS
21500
21501You may copy and distribute a Modified Version of the Document under
21502the conditions of sections 2 and 3 above, provided that you release
21503the Modified Version under precisely this License, with the Modified
21504Version filling the role of the Document, thus licensing distribution
21505and modification of the Modified Version to whoever possesses a copy
21506of it. In addition, you must do these things in the Modified Version:
21507
21508@enumerate A
21509@item
21510Use in the Title Page (and on the covers, if any) a title distinct
21511from that of the Document, and from those of previous versions
21512(which should, if there were any, be listed in the History section
21513of the Document). You may use the same title as a previous version
21514if the original publisher of that version gives permission.
21515
21516@item
21517List on the Title Page, as authors, one or more persons or entities
21518responsible for authorship of the modifications in the Modified
21519Version, together with at least five of the principal authors of the
c6f54b06
RC
21520Document (all of its principal authors, if it has fewer than five),
21521unless they release you from this requirement.
8b096dce
EZ
21522
21523@item
21524State on the Title page the name of the publisher of the
21525Modified Version, as the publisher.
21526
21527@item
21528Preserve all the copyright notices of the Document.
21529
21530@item
21531Add an appropriate copyright notice for your modifications
21532adjacent to the other copyright notices.
21533
21534@item
21535Include, immediately after the copyright notices, a license notice
21536giving the public permission to use the Modified Version under the
21537terms of this License, in the form shown in the Addendum below.
21538
21539@item
21540Preserve in that license notice the full lists of Invariant Sections
21541and required Cover Texts given in the Document's license notice.
21542
21543@item
21544Include an unaltered copy of this License.
21545
21546@item
c6f54b06
RC
21547Preserve the section Entitled ``History'', Preserve its Title, and add
21548to it an item stating at least the title, year, new authors, and
8b096dce 21549publisher of the Modified Version as given on the Title Page. If
c6f54b06 21550there is no section Entitled ``History'' in the Document, create one
8b096dce
EZ
21551stating the title, year, authors, and publisher of the Document as
21552given on its Title Page, then add an item describing the Modified
21553Version as stated in the previous sentence.
21554
21555@item
21556Preserve the network location, if any, given in the Document for
21557public access to a Transparent copy of the Document, and likewise
21558the network locations given in the Document for previous versions
21559it was based on. These may be placed in the ``History'' section.
21560You may omit a network location for a work that was published at
21561least four years before the Document itself, or if the original
21562publisher of the version it refers to gives permission.
21563
21564@item
c6f54b06
RC
21565For any section Entitled ``Acknowledgements'' or ``Dedications'', Preserve
21566the Title of the section, and preserve in the section all the
21567substance and tone of each of the contributor acknowledgements and/or
21568dedications given therein.
8b096dce
EZ
21569
21570@item
21571Preserve all the Invariant Sections of the Document,
21572unaltered in their text and in their titles. Section numbers
21573or the equivalent are not considered part of the section titles.
21574
21575@item
c6f54b06 21576Delete any section Entitled ``Endorsements''. Such a section
8b096dce
EZ
21577may not be included in the Modified Version.
21578
21579@item
c6f54b06
RC
21580Do not retitle any existing section to be Entitled ``Endorsements'' or
21581to conflict in title with any Invariant Section.
21582
21583@item
21584Preserve any Warranty Disclaimers.
8b096dce
EZ
21585@end enumerate
21586
21587If the Modified Version includes new front-matter sections or
21588appendices that qualify as Secondary Sections and contain no material
21589copied from the Document, you may at your option designate some or all
21590of these sections as invariant. To do this, add their titles to the
21591list of Invariant Sections in the Modified Version's license notice.
21592These titles must be distinct from any other section titles.
21593
c6f54b06 21594You may add a section Entitled ``Endorsements'', provided it contains
8b096dce
EZ
21595nothing but endorsements of your Modified Version by various
21596parties---for example, statements of peer review or that the text has
21597been approved by an organization as the authoritative definition of a
21598standard.
21599
21600You may add a passage of up to five words as a Front-Cover Text, and a
21601passage of up to 25 words as a Back-Cover Text, to the end of the list
21602of Cover Texts in the Modified Version. Only one passage of
21603Front-Cover Text and one of Back-Cover Text may be added by (or
21604through arrangements made by) any one entity. If the Document already
21605includes a cover text for the same cover, previously added by you or
21606by arrangement made by the same entity you are acting on behalf of,
21607you may not add another; but you may replace the old one, on explicit
21608permission from the previous publisher that added the old one.
21609
21610The author(s) and publisher(s) of the Document do not by this License
21611give permission to use their names for publicity for or to assert or
21612imply endorsement of any Modified Version.
21613
21614@item
21615COMBINING DOCUMENTS
21616
21617You may combine the Document with other documents released under this
21618License, under the terms defined in section 4 above for modified
21619versions, provided that you include in the combination all of the
21620Invariant Sections of all of the original documents, unmodified, and
21621list them all as Invariant Sections of your combined work in its
c6f54b06 21622license notice, and that you preserve all their Warranty Disclaimers.
8b096dce
EZ
21623
21624The combined work need only contain one copy of this License, and
21625multiple identical Invariant Sections may be replaced with a single
21626copy. If there are multiple Invariant Sections with the same name but
21627different contents, make the title of each such section unique by
21628adding at the end of it, in parentheses, the name of the original
21629author or publisher of that section if known, or else a unique number.
21630Make the same adjustment to the section titles in the list of
21631Invariant Sections in the license notice of the combined work.
21632
c6f54b06
RC
21633In the combination, you must combine any sections Entitled ``History''
21634in the various original documents, forming one section Entitled
21635``History''; likewise combine any sections Entitled ``Acknowledgements'',
21636and any sections Entitled ``Dedications''. You must delete all
21637sections Entitled ``Endorsements.''
8b096dce
EZ
21638
21639@item
21640COLLECTIONS OF DOCUMENTS
21641
21642You may make a collection consisting of the Document and other documents
21643released under this License, and replace the individual copies of this
21644License in the various documents with a single copy that is included in
21645the collection, provided that you follow the rules of this License for
21646verbatim copying of each of the documents in all other respects.
21647
21648You may extract a single document from such a collection, and distribute
21649it individually under this License, provided you insert a copy of this
21650License into the extracted document, and follow this License in all
21651other respects regarding verbatim copying of that document.
21652
21653@item
21654AGGREGATION WITH INDEPENDENT WORKS
21655
21656A compilation of the Document or its derivatives with other separate
21657and independent documents or works, in or on a volume of a storage or
c6f54b06
RC
21658distribution medium, is called an ``aggregate'' if the copyright
21659resulting from the compilation is not used to limit the legal rights
21660of the compilation's users beyond what the individual works permit.
21661When the Document is included in an aggregate, this License does not
21662apply to the other works in the aggregate which are not themselves
21663derivative works of the Document.
8b096dce
EZ
21664
21665If the Cover Text requirement of section 3 is applicable to these
c6f54b06
RC
21666copies of the Document, then if the Document is less than one half of
21667the entire aggregate, the Document's Cover Texts may be placed on
21668covers that bracket the Document within the aggregate, or the
21669electronic equivalent of covers if the Document is in electronic form.
21670Otherwise they must appear on printed covers that bracket the whole
21671aggregate.
8b096dce
EZ
21672
21673@item
21674TRANSLATION
21675
21676Translation is considered a kind of modification, so you may
21677distribute translations of the Document under the terms of section 4.
21678Replacing Invariant Sections with translations requires special
21679permission from their copyright holders, but you may include
21680translations of some or all Invariant Sections in addition to the
21681original versions of these Invariant Sections. You may include a
c6f54b06
RC
21682translation of this License, and all the license notices in the
21683Document, and any Warranty Disclaimers, provided that you also include
21684the original English version of this License and the original versions
21685of those notices and disclaimers. In case of a disagreement between
21686the translation and the original version of this License or a notice
21687or disclaimer, the original version will prevail.
21688
21689If a section in the Document is Entitled ``Acknowledgements'',
21690``Dedications'', or ``History'', the requirement (section 4) to Preserve
21691its Title (section 1) will typically require changing the actual
21692title.
8b096dce
EZ
21693
21694@item
21695TERMINATION
21696
21697You may not copy, modify, sublicense, or distribute the Document except
21698as expressly provided for under this License. Any other attempt to
21699copy, modify, sublicense or distribute the Document is void, and will
21700automatically terminate your rights under this License. However,
21701parties who have received copies, or rights, from you under this
21702License will not have their licenses terminated so long as such
21703parties remain in full compliance.
21704
21705@item
21706FUTURE REVISIONS OF THIS LICENSE
21707
21708The Free Software Foundation may publish new, revised versions
21709of the GNU Free Documentation License from time to time. Such new
21710versions will be similar in spirit to the present version, but may
21711differ in detail to address new problems or concerns. See
21712@uref{http://www.gnu.org/copyleft/}.
21713
21714Each version of the License is given a distinguishing version number.
21715If the Document specifies that a particular numbered version of this
21716License ``or any later version'' applies to it, you have the option of
21717following the terms and conditions either of that specified version or
21718of any later version that has been published (not as a draft) by the
21719Free Software Foundation. If the Document does not specify a version
21720number of this License, you may choose any version ever published (not
21721as a draft) by the Free Software Foundation.
21722@end enumerate
21723
c6f54b06
RC
21724@page
21725@appendixsubsec ADDENDUM: How to use this License for your documents
21726
21727To use this License in a document you have written, include a copy of
21728the License in the document and put the following copyright and
21729license notices just after the title page:
21730
21731@smallexample
21732@group
21733Copyright (C) @var{year} @var{your name}.
21734Permission is granted to copy, distribute and/or modify this document
21735under the terms of the GNU Free Documentation License, Version 1.2
21736or any later version published by the Free Software Foundation;
21737with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
21738A copy of the license is included in the section entitled ``GNU
21739Free Documentation License''.
21740@end group
21741@end smallexample
21742
21743If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
21744replace the ``with...Texts.'' line with this:
21745
21746@smallexample
21747@group
21748with the Invariant Sections being @var{list their titles}, with
21749the Front-Cover Texts being @var{list}, and with the Back-Cover Texts
21750being @var{list}.
21751@end group
21752@end smallexample
21753
21754If you have Invariant Sections without Cover Texts, or some other
21755combination of the three, merge those two alternatives to suit the
21756situation.
21757
21758If your document contains nontrivial examples of program code, we
21759recommend releasing these examples in parallel under your choice of
21760free software license, such as the GNU General Public License,
21761to permit their use in free software.
21762
8b096dce
EZ
21763@node Index, About the Author, GNU Free Documentation License, Top
21764@comment node-name, next, previous, up
21765@unnumbered Index
21766
d586ab6c 21767@ignore
8b096dce 21768MENU ENTRY: NODE NAME.
d586ab6c 21769@end ignore
8b096dce
EZ
21770
21771@printindex cp
21772
21773@iftex
21774@c Place biographical information on right-hand (verso) page
21775
21776@tex
21777\ifodd\pageno
21778 \par\vfill\supereject
21779 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21780 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21781 \page\hbox{}\page
21782\else
21783 \par\vfill\supereject
21784 \par\vfill\supereject
21785 \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21786 \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21787 \page\hbox{}\page
21788 \page\hbox{}\page
21789\fi
21790@end tex
21791
21792@page
21793@w{ }
21794
21795@c ================ Biographical information ================
21796
21797@w{ }
21798@sp 8
21799@center About the Author
21800@sp 1
21801@end iftex
21802
21803@ifnottex
21804@node About the Author, , Index, Top
21805@unnumbered About the Author
21806@end ifnottex
21807
21808@quotation
21809Robert J. Chassell has worked with GNU Emacs since 1985. He writes
21810and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21811world on software freedom. Chassell was a founding Director and
21812Treasurer of the Free Software Foundation, Inc. He is co-author of
21813the @cite{Texinfo} manual, and has edited more than a dozen other
21814books. He graduated from Cambridge University, in England. He has an
21815abiding interest in social and economic history and flies his own
21816airplane.
21817@end quotation
21818
21819@page
21820@w{ }
21821
21822@c Prevent page number on blank verso, so eject it first.
21823@tex
21824\par\vfill\supereject
21825@end tex
21826
21827@iftex
21828@headings off
21829@evenheading @thispage @| @| @thistitle
21830@oddheading @| @| @thispage
21831@end iftex
21832
8b096dce 21833@bye
ab5796a9
MB
21834
21835@ignore
21836 arch-tag: da1a2154-531f-43a8-8e33-fc7faad10acf
21837@end ignore